xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision a1ac6efcb01ab8840d269056f01fb564b44c7ddc)
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                                                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, DI->getDebugLoc(), 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, Order);
1217   }
1218 }
1219 
1220 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1221                                                 const DIExpression *Expr) {
1222   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1223     DIVariable *DanglingVariable = DDI.getVariable();
1224     DIExpression *DanglingExpr = DDI.getExpression();
1225     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1226       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << DDI << "\n");
1227       return true;
1228     }
1229     return false;
1230   };
1231 
1232   for (auto &DDIMI : DanglingDebugInfoMap) {
1233     DanglingDebugInfoVector &DDIV = DDIMI.second;
1234 
1235     // If debug info is to be dropped, run it through final checks to see
1236     // whether it can be salvaged.
1237     for (auto &DDI : DDIV)
1238       if (isMatchingDbgValue(DDI))
1239         salvageUnresolvedDbgValue(DDI);
1240 
1241     erase_if(DDIV, isMatchingDbgValue);
1242   }
1243 }
1244 
1245 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1246 // generate the debug data structures now that we've seen its definition.
1247 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1248                                                    SDValue Val) {
1249   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1250   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1251     return;
1252 
1253   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1254   for (auto &DDI : DDIV) {
1255     DebugLoc DL = DDI.getDebugLoc();
1256     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1257     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1258     DILocalVariable *Variable = DDI.getVariable();
1259     DIExpression *Expr = DDI.getExpression();
1260     assert(Variable->isValidLocationForIntrinsic(DL) &&
1261            "Expected inlined-at fields to agree");
1262     SDDbgValue *SDV;
1263     if (Val.getNode()) {
1264       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1265       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1266       // we couldn't resolve it directly when examining the DbgValue intrinsic
1267       // in the first place we should not be more successful here). Unless we
1268       // have some test case that prove this to be correct we should avoid
1269       // calling EmitFuncArgumentDbgValue here.
1270       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1271                                     FuncArgumentDbgValueKind::Value, Val)) {
1272         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << DDI << "\n");
1273         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1274         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1275         // inserted after the definition of Val when emitting the instructions
1276         // after ISel. An alternative could be to teach
1277         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1278         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1279                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1280                    << ValSDNodeOrder << "\n");
1281         SDV = getDbgValue(Val, Variable, Expr, DL,
1282                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1283         DAG.AddDbgValue(SDV, false);
1284       } else
1285         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << DDI
1286                           << "in EmitFuncArgumentDbgValue\n");
1287     } else {
1288       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DDI << "\n");
1289       auto Undef = UndefValue::get(V->getType());
1290       auto SDV =
1291           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1292       DAG.AddDbgValue(SDV, false);
1293     }
1294   }
1295   DDIV.clear();
1296 }
1297 
1298 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1299   // TODO: For the variadic implementation, instead of only checking the fail
1300   // state of `handleDebugValue`, we need know specifically which values were
1301   // invalid, so that we attempt to salvage only those values when processing
1302   // a DIArgList.
1303   Value *V = DDI.getVariableLocationOp(0);
1304   Value *OrigV = V;
1305   DILocalVariable *Var = DDI.getVariable();
1306   DIExpression *Expr = DDI.getExpression();
1307   DebugLoc DL = DDI.getDebugLoc();
1308   unsigned SDOrder = DDI.getSDNodeOrder();
1309 
1310   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1311   // that DW_OP_stack_value is desired.
1312   bool StackValue = true;
1313 
1314   // Can this Value can be encoded without any further work?
1315   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1316     return;
1317 
1318   // Attempt to salvage back through as many instructions as possible. Bail if
1319   // a non-instruction is seen, such as a constant expression or global
1320   // variable. FIXME: Further work could recover those too.
1321   while (isa<Instruction>(V)) {
1322     Instruction &VAsInst = *cast<Instruction>(V);
1323     // Temporary "0", awaiting real implementation.
1324     SmallVector<uint64_t, 16> Ops;
1325     SmallVector<Value *, 4> AdditionalValues;
1326     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1327                              AdditionalValues);
1328     // If we cannot salvage any further, and haven't yet found a suitable debug
1329     // expression, bail out.
1330     if (!V)
1331       break;
1332 
1333     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1334     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1335     // here for variadic dbg_values, remove that condition.
1336     if (!AdditionalValues.empty())
1337       break;
1338 
1339     // New value and expr now represent this debuginfo.
1340     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1341 
1342     // Some kind of simplification occurred: check whether the operand of the
1343     // salvaged debug expression can be encoded in this DAG.
1344     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1345       LLVM_DEBUG(
1346           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1347                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1348       return;
1349     }
1350   }
1351 
1352   // This was the final opportunity to salvage this debug information, and it
1353   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1354   // any earlier variable location.
1355   assert(OrigV && "V shouldn't be null");
1356   auto *Undef = UndefValue::get(OrigV->getType());
1357   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1358   DAG.AddDbgValue(SDV, false);
1359   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI << "\n");
1360 }
1361 
1362 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1363                                            DILocalVariable *Var,
1364                                            DIExpression *Expr, DebugLoc DbgLoc,
1365                                            unsigned Order, bool IsVariadic) {
1366   if (Values.empty())
1367     return true;
1368   SmallVector<SDDbgOperand> LocationOps;
1369   SmallVector<SDNode *> Dependencies;
1370   for (const Value *V : Values) {
1371     // Constant value.
1372     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1373         isa<ConstantPointerNull>(V)) {
1374       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1375       continue;
1376     }
1377 
1378     // Look through IntToPtr constants.
1379     if (auto *CE = dyn_cast<ConstantExpr>(V))
1380       if (CE->getOpcode() == Instruction::IntToPtr) {
1381         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1382         continue;
1383       }
1384 
1385     // If the Value is a frame index, we can create a FrameIndex debug value
1386     // without relying on the DAG at all.
1387     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1388       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1389       if (SI != FuncInfo.StaticAllocaMap.end()) {
1390         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1391         continue;
1392       }
1393     }
1394 
1395     // Do not use getValue() in here; we don't want to generate code at
1396     // this point if it hasn't been done yet.
1397     SDValue N = NodeMap[V];
1398     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1399       N = UnusedArgNodeMap[V];
1400     if (N.getNode()) {
1401       // Only emit func arg dbg value for non-variadic dbg.values for now.
1402       if (!IsVariadic &&
1403           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1404                                    FuncArgumentDbgValueKind::Value, N))
1405         return true;
1406       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1407         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1408         // describe stack slot locations.
1409         //
1410         // Consider "int x = 0; int *px = &x;". There are two kinds of
1411         // interesting debug values here after optimization:
1412         //
1413         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1414         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1415         //
1416         // Both describe the direct values of their associated variables.
1417         Dependencies.push_back(N.getNode());
1418         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1419         continue;
1420       }
1421       LocationOps.emplace_back(
1422           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1423       continue;
1424     }
1425 
1426     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1427     // Special rules apply for the first dbg.values of parameter variables in a
1428     // function. Identify them by the fact they reference Argument Values, that
1429     // they're parameters, and they are parameters of the current function. We
1430     // need to let them dangle until they get an SDNode.
1431     bool IsParamOfFunc =
1432         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1433     if (IsParamOfFunc)
1434       return false;
1435 
1436     // The value is not used in this block yet (or it would have an SDNode).
1437     // We still want the value to appear for the user if possible -- if it has
1438     // an associated VReg, we can refer to that instead.
1439     auto VMI = FuncInfo.ValueMap.find(V);
1440     if (VMI != FuncInfo.ValueMap.end()) {
1441       unsigned Reg = VMI->second;
1442       // If this is a PHI node, it may be split up into several MI PHI nodes
1443       // (in FunctionLoweringInfo::set).
1444       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1445                        V->getType(), None);
1446       if (RFV.occupiesMultipleRegs()) {
1447         // FIXME: We could potentially support variadic dbg_values here.
1448         if (IsVariadic)
1449           return false;
1450         unsigned Offset = 0;
1451         unsigned BitsToDescribe = 0;
1452         if (auto VarSize = Var->getSizeInBits())
1453           BitsToDescribe = *VarSize;
1454         if (auto Fragment = Expr->getFragmentInfo())
1455           BitsToDescribe = Fragment->SizeInBits;
1456         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1457           // Bail out if all bits are described already.
1458           if (Offset >= BitsToDescribe)
1459             break;
1460           // TODO: handle scalable vectors.
1461           unsigned RegisterSize = RegAndSize.second;
1462           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1463                                       ? BitsToDescribe - Offset
1464                                       : RegisterSize;
1465           auto FragmentExpr = DIExpression::createFragmentExpression(
1466               Expr, Offset, FragmentSize);
1467           if (!FragmentExpr)
1468             continue;
1469           SDDbgValue *SDV = DAG.getVRegDbgValue(
1470               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1471           DAG.AddDbgValue(SDV, false);
1472           Offset += RegisterSize;
1473         }
1474         return true;
1475       }
1476       // We can use simple vreg locations for variadic dbg_values as well.
1477       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1478       continue;
1479     }
1480     // We failed to create a SDDbgOperand for V.
1481     return false;
1482   }
1483 
1484   // We have created a SDDbgOperand for each Value in Values.
1485   // Should use Order instead of SDNodeOrder?
1486   assert(!LocationOps.empty());
1487   SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1488                                         /*IsIndirect=*/false, DbgLoc,
1489                                         SDNodeOrder, IsVariadic);
1490   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1491   return true;
1492 }
1493 
1494 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1495   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1496   for (auto &Pair : DanglingDebugInfoMap)
1497     for (auto &DDI : Pair.second)
1498       salvageUnresolvedDbgValue(DDI);
1499   clearDanglingDebugInfo();
1500 }
1501 
1502 /// getCopyFromRegs - If there was virtual register allocated for the value V
1503 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1504 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1505   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1506   SDValue Result;
1507 
1508   if (It != FuncInfo.ValueMap.end()) {
1509     Register InReg = It->second;
1510 
1511     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1512                      DAG.getDataLayout(), InReg, Ty,
1513                      None); // This is not an ABI copy.
1514     SDValue Chain = DAG.getEntryNode();
1515     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1516                                  V);
1517     resolveDanglingDebugInfo(V, Result);
1518   }
1519 
1520   return Result;
1521 }
1522 
1523 /// getValue - Return an SDValue for the given Value.
1524 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1525   // If we already have an SDValue for this value, use it. It's important
1526   // to do this first, so that we don't create a CopyFromReg if we already
1527   // have a regular SDValue.
1528   SDValue &N = NodeMap[V];
1529   if (N.getNode()) return N;
1530 
1531   // If there's a virtual register allocated and initialized for this
1532   // value, use it.
1533   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1534     return copyFromReg;
1535 
1536   // Otherwise create a new SDValue and remember it.
1537   SDValue Val = getValueImpl(V);
1538   NodeMap[V] = Val;
1539   resolveDanglingDebugInfo(V, Val);
1540   return Val;
1541 }
1542 
1543 /// getNonRegisterValue - Return an SDValue for the given Value, but
1544 /// don't look in FuncInfo.ValueMap for a virtual register.
1545 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1546   // If we already have an SDValue for this value, use it.
1547   SDValue &N = NodeMap[V];
1548   if (N.getNode()) {
1549     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1550       // Remove the debug location from the node as the node is about to be used
1551       // in a location which may differ from the original debug location.  This
1552       // is relevant to Constant and ConstantFP nodes because they can appear
1553       // as constant expressions inside PHI nodes.
1554       N->setDebugLoc(DebugLoc());
1555     }
1556     return N;
1557   }
1558 
1559   // Otherwise create a new SDValue and remember it.
1560   SDValue Val = getValueImpl(V);
1561   NodeMap[V] = Val;
1562   resolveDanglingDebugInfo(V, Val);
1563   return Val;
1564 }
1565 
1566 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1567 /// Create an SDValue for the given value.
1568 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1569   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1570 
1571   if (const Constant *C = dyn_cast<Constant>(V)) {
1572     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1573 
1574     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1575       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1576 
1577     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1578       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1579 
1580     if (isa<ConstantPointerNull>(C)) {
1581       unsigned AS = V->getType()->getPointerAddressSpace();
1582       return DAG.getConstant(0, getCurSDLoc(),
1583                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1584     }
1585 
1586     if (match(C, m_VScale(DAG.getDataLayout())))
1587       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1588 
1589     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1590       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1591 
1592     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1593       return DAG.getUNDEF(VT);
1594 
1595     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1596       visit(CE->getOpcode(), *CE);
1597       SDValue N1 = NodeMap[V];
1598       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1599       return N1;
1600     }
1601 
1602     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1603       SmallVector<SDValue, 4> Constants;
1604       for (const Use &U : C->operands()) {
1605         SDNode *Val = getValue(U).getNode();
1606         // If the operand is an empty aggregate, there are no values.
1607         if (!Val) continue;
1608         // Add each leaf value from the operand to the Constants list
1609         // to form a flattened list of all the values.
1610         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1611           Constants.push_back(SDValue(Val, i));
1612       }
1613 
1614       return DAG.getMergeValues(Constants, getCurSDLoc());
1615     }
1616 
1617     if (const ConstantDataSequential *CDS =
1618           dyn_cast<ConstantDataSequential>(C)) {
1619       SmallVector<SDValue, 4> Ops;
1620       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1621         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1622         // Add each leaf value from the operand to the Constants list
1623         // to form a flattened list of all the values.
1624         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1625           Ops.push_back(SDValue(Val, i));
1626       }
1627 
1628       if (isa<ArrayType>(CDS->getType()))
1629         return DAG.getMergeValues(Ops, getCurSDLoc());
1630       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1631     }
1632 
1633     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1634       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1635              "Unknown struct or array constant!");
1636 
1637       SmallVector<EVT, 4> ValueVTs;
1638       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1639       unsigned NumElts = ValueVTs.size();
1640       if (NumElts == 0)
1641         return SDValue(); // empty struct
1642       SmallVector<SDValue, 4> Constants(NumElts);
1643       for (unsigned i = 0; i != NumElts; ++i) {
1644         EVT EltVT = ValueVTs[i];
1645         if (isa<UndefValue>(C))
1646           Constants[i] = DAG.getUNDEF(EltVT);
1647         else if (EltVT.isFloatingPoint())
1648           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1649         else
1650           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1651       }
1652 
1653       return DAG.getMergeValues(Constants, getCurSDLoc());
1654     }
1655 
1656     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1657       return DAG.getBlockAddress(BA, VT);
1658 
1659     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1660       return getValue(Equiv->getGlobalValue());
1661 
1662     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1663       return getValue(NC->getGlobalValue());
1664 
1665     VectorType *VecTy = cast<VectorType>(V->getType());
1666 
1667     // Now that we know the number and type of the elements, get that number of
1668     // elements into the Ops array based on what kind of constant it is.
1669     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1670       SmallVector<SDValue, 16> Ops;
1671       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1672       for (unsigned i = 0; i != NumElements; ++i)
1673         Ops.push_back(getValue(CV->getOperand(i)));
1674 
1675       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1676     }
1677 
1678     if (isa<ConstantAggregateZero>(C)) {
1679       EVT EltVT =
1680           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1681 
1682       SDValue Op;
1683       if (EltVT.isFloatingPoint())
1684         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1685       else
1686         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1687 
1688       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1689     }
1690 
1691     llvm_unreachable("Unknown vector constant");
1692   }
1693 
1694   // If this is a static alloca, generate it as the frameindex instead of
1695   // computation.
1696   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1697     DenseMap<const AllocaInst*, int>::iterator SI =
1698       FuncInfo.StaticAllocaMap.find(AI);
1699     if (SI != FuncInfo.StaticAllocaMap.end())
1700       return DAG.getFrameIndex(SI->second,
1701                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1702   }
1703 
1704   // If this is an instruction which fast-isel has deferred, select it now.
1705   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1706     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1707 
1708     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1709                      Inst->getType(), None);
1710     SDValue Chain = DAG.getEntryNode();
1711     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1712   }
1713 
1714   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1715     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1716 
1717   if (const auto *BB = dyn_cast<BasicBlock>(V))
1718     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1719 
1720   llvm_unreachable("Can't get register for value!");
1721 }
1722 
1723 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1724   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1725   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1726   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1727   bool IsSEH = isAsynchronousEHPersonality(Pers);
1728   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1729   if (!IsSEH)
1730     CatchPadMBB->setIsEHScopeEntry();
1731   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1732   if (IsMSVCCXX || IsCoreCLR)
1733     CatchPadMBB->setIsEHFuncletEntry();
1734 }
1735 
1736 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1737   // Update machine-CFG edge.
1738   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1739   FuncInfo.MBB->addSuccessor(TargetMBB);
1740   TargetMBB->setIsEHCatchretTarget(true);
1741   DAG.getMachineFunction().setHasEHCatchret(true);
1742 
1743   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1744   bool IsSEH = isAsynchronousEHPersonality(Pers);
1745   if (IsSEH) {
1746     // If this is not a fall-through branch or optimizations are switched off,
1747     // emit the branch.
1748     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1749         TM.getOptLevel() == CodeGenOpt::None)
1750       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1751                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1752     return;
1753   }
1754 
1755   // Figure out the funclet membership for the catchret's successor.
1756   // This will be used by the FuncletLayout pass to determine how to order the
1757   // BB's.
1758   // A 'catchret' returns to the outer scope's color.
1759   Value *ParentPad = I.getCatchSwitchParentPad();
1760   const BasicBlock *SuccessorColor;
1761   if (isa<ConstantTokenNone>(ParentPad))
1762     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1763   else
1764     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1765   assert(SuccessorColor && "No parent funclet for catchret!");
1766   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1767   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1768 
1769   // Create the terminator node.
1770   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1771                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1772                             DAG.getBasicBlock(SuccessorColorMBB));
1773   DAG.setRoot(Ret);
1774 }
1775 
1776 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1777   // Don't emit any special code for the cleanuppad instruction. It just marks
1778   // the start of an EH scope/funclet.
1779   FuncInfo.MBB->setIsEHScopeEntry();
1780   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1781   if (Pers != EHPersonality::Wasm_CXX) {
1782     FuncInfo.MBB->setIsEHFuncletEntry();
1783     FuncInfo.MBB->setIsCleanupFuncletEntry();
1784   }
1785 }
1786 
1787 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1788 // not match, it is OK to add only the first unwind destination catchpad to the
1789 // successors, because there will be at least one invoke instruction within the
1790 // catch scope that points to the next unwind destination, if one exists, so
1791 // CFGSort cannot mess up with BB sorting order.
1792 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1793 // call within them, and catchpads only consisting of 'catch (...)' have a
1794 // '__cxa_end_catch' call within them, both of which generate invokes in case
1795 // the next unwind destination exists, i.e., the next unwind destination is not
1796 // the caller.)
1797 //
1798 // Having at most one EH pad successor is also simpler and helps later
1799 // transformations.
1800 //
1801 // For example,
1802 // current:
1803 //   invoke void @foo to ... unwind label %catch.dispatch
1804 // catch.dispatch:
1805 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1806 // catch.start:
1807 //   ...
1808 //   ... in this BB or some other child BB dominated by this BB there will be an
1809 //   invoke that points to 'next' BB as an unwind destination
1810 //
1811 // next: ; We don't need to add this to 'current' BB's successor
1812 //   ...
1813 static void findWasmUnwindDestinations(
1814     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1815     BranchProbability Prob,
1816     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1817         &UnwindDests) {
1818   while (EHPadBB) {
1819     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1820     if (isa<CleanupPadInst>(Pad)) {
1821       // Stop on cleanup pads.
1822       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1823       UnwindDests.back().first->setIsEHScopeEntry();
1824       break;
1825     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1826       // Add the catchpad handlers to the possible destinations. We don't
1827       // continue to the unwind destination of the catchswitch for wasm.
1828       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1829         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1830         UnwindDests.back().first->setIsEHScopeEntry();
1831       }
1832       break;
1833     } else {
1834       continue;
1835     }
1836   }
1837 }
1838 
1839 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1840 /// many places it could ultimately go. In the IR, we have a single unwind
1841 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1842 /// This function skips over imaginary basic blocks that hold catchswitch
1843 /// instructions, and finds all the "real" machine
1844 /// basic block destinations. As those destinations may not be successors of
1845 /// EHPadBB, here we also calculate the edge probability to those destinations.
1846 /// The passed-in Prob is the edge probability to EHPadBB.
1847 static void findUnwindDestinations(
1848     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1849     BranchProbability Prob,
1850     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1851         &UnwindDests) {
1852   EHPersonality Personality =
1853     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1854   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1855   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1856   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1857   bool IsSEH = isAsynchronousEHPersonality(Personality);
1858 
1859   if (IsWasmCXX) {
1860     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1861     assert(UnwindDests.size() <= 1 &&
1862            "There should be at most one unwind destination for wasm");
1863     return;
1864   }
1865 
1866   while (EHPadBB) {
1867     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1868     BasicBlock *NewEHPadBB = nullptr;
1869     if (isa<LandingPadInst>(Pad)) {
1870       // Stop on landingpads. They are not funclets.
1871       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1872       break;
1873     } else if (isa<CleanupPadInst>(Pad)) {
1874       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1875       // personalities.
1876       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1877       UnwindDests.back().first->setIsEHScopeEntry();
1878       UnwindDests.back().first->setIsEHFuncletEntry();
1879       break;
1880     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1881       // Add the catchpad handlers to the possible destinations.
1882       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1883         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1884         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1885         if (IsMSVCCXX || IsCoreCLR)
1886           UnwindDests.back().first->setIsEHFuncletEntry();
1887         if (!IsSEH)
1888           UnwindDests.back().first->setIsEHScopeEntry();
1889       }
1890       NewEHPadBB = CatchSwitch->getUnwindDest();
1891     } else {
1892       continue;
1893     }
1894 
1895     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1896     if (BPI && NewEHPadBB)
1897       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1898     EHPadBB = NewEHPadBB;
1899   }
1900 }
1901 
1902 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1903   // Update successor info.
1904   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1905   auto UnwindDest = I.getUnwindDest();
1906   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1907   BranchProbability UnwindDestProb =
1908       (BPI && UnwindDest)
1909           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1910           : BranchProbability::getZero();
1911   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1912   for (auto &UnwindDest : UnwindDests) {
1913     UnwindDest.first->setIsEHPad();
1914     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1915   }
1916   FuncInfo.MBB->normalizeSuccProbs();
1917 
1918   // Create the terminator node.
1919   SDValue Ret =
1920       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1921   DAG.setRoot(Ret);
1922 }
1923 
1924 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1925   report_fatal_error("visitCatchSwitch not yet implemented!");
1926 }
1927 
1928 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1929   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1930   auto &DL = DAG.getDataLayout();
1931   SDValue Chain = getControlRoot();
1932   SmallVector<ISD::OutputArg, 8> Outs;
1933   SmallVector<SDValue, 8> OutVals;
1934 
1935   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1936   // lower
1937   //
1938   //   %val = call <ty> @llvm.experimental.deoptimize()
1939   //   ret <ty> %val
1940   //
1941   // differently.
1942   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1943     LowerDeoptimizingReturn();
1944     return;
1945   }
1946 
1947   if (!FuncInfo.CanLowerReturn) {
1948     unsigned DemoteReg = FuncInfo.DemoteRegister;
1949     const Function *F = I.getParent()->getParent();
1950 
1951     // Emit a store of the return value through the virtual register.
1952     // Leave Outs empty so that LowerReturn won't try to load return
1953     // registers the usual way.
1954     SmallVector<EVT, 1> PtrValueVTs;
1955     ComputeValueVTs(TLI, DL,
1956                     F->getReturnType()->getPointerTo(
1957                         DAG.getDataLayout().getAllocaAddrSpace()),
1958                     PtrValueVTs);
1959 
1960     SDValue RetPtr =
1961         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1962     SDValue RetOp = getValue(I.getOperand(0));
1963 
1964     SmallVector<EVT, 4> ValueVTs, MemVTs;
1965     SmallVector<uint64_t, 4> Offsets;
1966     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1967                     &Offsets);
1968     unsigned NumValues = ValueVTs.size();
1969 
1970     SmallVector<SDValue, 4> Chains(NumValues);
1971     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1972     for (unsigned i = 0; i != NumValues; ++i) {
1973       // An aggregate return value cannot wrap around the address space, so
1974       // offsets to its parts don't wrap either.
1975       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1976                                            TypeSize::Fixed(Offsets[i]));
1977 
1978       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1979       if (MemVTs[i] != ValueVTs[i])
1980         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1981       Chains[i] = DAG.getStore(
1982           Chain, getCurSDLoc(), Val,
1983           // FIXME: better loc info would be nice.
1984           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1985           commonAlignment(BaseAlign, Offsets[i]));
1986     }
1987 
1988     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1989                         MVT::Other, Chains);
1990   } else if (I.getNumOperands() != 0) {
1991     SmallVector<EVT, 4> ValueVTs;
1992     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1993     unsigned NumValues = ValueVTs.size();
1994     if (NumValues) {
1995       SDValue RetOp = getValue(I.getOperand(0));
1996 
1997       const Function *F = I.getParent()->getParent();
1998 
1999       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2000           I.getOperand(0)->getType(), F->getCallingConv(),
2001           /*IsVarArg*/ false, DL);
2002 
2003       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2004       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2005         ExtendKind = ISD::SIGN_EXTEND;
2006       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2007         ExtendKind = ISD::ZERO_EXTEND;
2008 
2009       LLVMContext &Context = F->getContext();
2010       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2011 
2012       for (unsigned j = 0; j != NumValues; ++j) {
2013         EVT VT = ValueVTs[j];
2014 
2015         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2016           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2017 
2018         CallingConv::ID CC = F->getCallingConv();
2019 
2020         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2021         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2022         SmallVector<SDValue, 4> Parts(NumParts);
2023         getCopyToParts(DAG, getCurSDLoc(),
2024                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2025                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2026 
2027         // 'inreg' on function refers to return value
2028         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2029         if (RetInReg)
2030           Flags.setInReg();
2031 
2032         if (I.getOperand(0)->getType()->isPointerTy()) {
2033           Flags.setPointer();
2034           Flags.setPointerAddrSpace(
2035               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2036         }
2037 
2038         if (NeedsRegBlock) {
2039           Flags.setInConsecutiveRegs();
2040           if (j == NumValues - 1)
2041             Flags.setInConsecutiveRegsLast();
2042         }
2043 
2044         // Propagate extension type if any
2045         if (ExtendKind == ISD::SIGN_EXTEND)
2046           Flags.setSExt();
2047         else if (ExtendKind == ISD::ZERO_EXTEND)
2048           Flags.setZExt();
2049 
2050         for (unsigned i = 0; i < NumParts; ++i) {
2051           Outs.push_back(ISD::OutputArg(Flags,
2052                                         Parts[i].getValueType().getSimpleVT(),
2053                                         VT, /*isfixed=*/true, 0, 0));
2054           OutVals.push_back(Parts[i]);
2055         }
2056       }
2057     }
2058   }
2059 
2060   // Push in swifterror virtual register as the last element of Outs. This makes
2061   // sure swifterror virtual register will be returned in the swifterror
2062   // physical register.
2063   const Function *F = I.getParent()->getParent();
2064   if (TLI.supportSwiftError() &&
2065       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2066     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2067     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2068     Flags.setSwiftError();
2069     Outs.push_back(ISD::OutputArg(
2070         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2071         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2072     // Create SDNode for the swifterror virtual register.
2073     OutVals.push_back(
2074         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2075                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2076                         EVT(TLI.getPointerTy(DL))));
2077   }
2078 
2079   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2080   CallingConv::ID CallConv =
2081     DAG.getMachineFunction().getFunction().getCallingConv();
2082   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2083       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2084 
2085   // Verify that the target's LowerReturn behaved as expected.
2086   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2087          "LowerReturn didn't return a valid chain!");
2088 
2089   // Update the DAG with the new chain value resulting from return lowering.
2090   DAG.setRoot(Chain);
2091 }
2092 
2093 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2094 /// created for it, emit nodes to copy the value into the virtual
2095 /// registers.
2096 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2097   // Skip empty types
2098   if (V->getType()->isEmptyTy())
2099     return;
2100 
2101   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2102   if (VMI != FuncInfo.ValueMap.end()) {
2103     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2104     CopyValueToVirtualRegister(V, VMI->second);
2105   }
2106 }
2107 
2108 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2109 /// the current basic block, add it to ValueMap now so that we'll get a
2110 /// CopyTo/FromReg.
2111 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2112   // No need to export constants.
2113   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2114 
2115   // Already exported?
2116   if (FuncInfo.isExportedInst(V)) return;
2117 
2118   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2119   CopyValueToVirtualRegister(V, Reg);
2120 }
2121 
2122 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2123                                                      const BasicBlock *FromBB) {
2124   // The operands of the setcc have to be in this block.  We don't know
2125   // how to export them from some other block.
2126   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2127     // Can export from current BB.
2128     if (VI->getParent() == FromBB)
2129       return true;
2130 
2131     // Is already exported, noop.
2132     return FuncInfo.isExportedInst(V);
2133   }
2134 
2135   // If this is an argument, we can export it if the BB is the entry block or
2136   // if it is already exported.
2137   if (isa<Argument>(V)) {
2138     if (FromBB->isEntryBlock())
2139       return true;
2140 
2141     // Otherwise, can only export this if it is already exported.
2142     return FuncInfo.isExportedInst(V);
2143   }
2144 
2145   // Otherwise, constants can always be exported.
2146   return true;
2147 }
2148 
2149 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2150 BranchProbability
2151 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2152                                         const MachineBasicBlock *Dst) const {
2153   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2154   const BasicBlock *SrcBB = Src->getBasicBlock();
2155   const BasicBlock *DstBB = Dst->getBasicBlock();
2156   if (!BPI) {
2157     // If BPI is not available, set the default probability as 1 / N, where N is
2158     // the number of successors.
2159     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2160     return BranchProbability(1, SuccSize);
2161   }
2162   return BPI->getEdgeProbability(SrcBB, DstBB);
2163 }
2164 
2165 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2166                                                MachineBasicBlock *Dst,
2167                                                BranchProbability Prob) {
2168   if (!FuncInfo.BPI)
2169     Src->addSuccessorWithoutProb(Dst);
2170   else {
2171     if (Prob.isUnknown())
2172       Prob = getEdgeProbability(Src, Dst);
2173     Src->addSuccessor(Dst, Prob);
2174   }
2175 }
2176 
2177 static bool InBlock(const Value *V, const BasicBlock *BB) {
2178   if (const Instruction *I = dyn_cast<Instruction>(V))
2179     return I->getParent() == BB;
2180   return true;
2181 }
2182 
2183 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2184 /// This function emits a branch and is used at the leaves of an OR or an
2185 /// AND operator tree.
2186 void
2187 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2188                                                   MachineBasicBlock *TBB,
2189                                                   MachineBasicBlock *FBB,
2190                                                   MachineBasicBlock *CurBB,
2191                                                   MachineBasicBlock *SwitchBB,
2192                                                   BranchProbability TProb,
2193                                                   BranchProbability FProb,
2194                                                   bool InvertCond) {
2195   const BasicBlock *BB = CurBB->getBasicBlock();
2196 
2197   // If the leaf of the tree is a comparison, merge the condition into
2198   // the caseblock.
2199   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2200     // The operands of the cmp have to be in this block.  We don't know
2201     // how to export them from some other block.  If this is the first block
2202     // of the sequence, no exporting is needed.
2203     if (CurBB == SwitchBB ||
2204         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2205          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2206       ISD::CondCode Condition;
2207       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2208         ICmpInst::Predicate Pred =
2209             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2210         Condition = getICmpCondCode(Pred);
2211       } else {
2212         const FCmpInst *FC = cast<FCmpInst>(Cond);
2213         FCmpInst::Predicate Pred =
2214             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2215         Condition = getFCmpCondCode(Pred);
2216         if (TM.Options.NoNaNsFPMath)
2217           Condition = getFCmpCodeWithoutNaN(Condition);
2218       }
2219 
2220       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2221                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2222       SL->SwitchCases.push_back(CB);
2223       return;
2224     }
2225   }
2226 
2227   // Create a CaseBlock record representing this branch.
2228   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2229   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2230                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2231   SL->SwitchCases.push_back(CB);
2232 }
2233 
2234 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2235                                                MachineBasicBlock *TBB,
2236                                                MachineBasicBlock *FBB,
2237                                                MachineBasicBlock *CurBB,
2238                                                MachineBasicBlock *SwitchBB,
2239                                                Instruction::BinaryOps Opc,
2240                                                BranchProbability TProb,
2241                                                BranchProbability FProb,
2242                                                bool InvertCond) {
2243   // Skip over not part of the tree and remember to invert op and operands at
2244   // next level.
2245   Value *NotCond;
2246   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2247       InBlock(NotCond, CurBB->getBasicBlock())) {
2248     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2249                          !InvertCond);
2250     return;
2251   }
2252 
2253   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2254   const Value *BOpOp0, *BOpOp1;
2255   // Compute the effective opcode for Cond, taking into account whether it needs
2256   // to be inverted, e.g.
2257   //   and (not (or A, B)), C
2258   // gets lowered as
2259   //   and (and (not A, not B), C)
2260   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2261   if (BOp) {
2262     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2263                ? Instruction::And
2264                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2265                       ? Instruction::Or
2266                       : (Instruction::BinaryOps)0);
2267     if (InvertCond) {
2268       if (BOpc == Instruction::And)
2269         BOpc = Instruction::Or;
2270       else if (BOpc == Instruction::Or)
2271         BOpc = Instruction::And;
2272     }
2273   }
2274 
2275   // If this node is not part of the or/and tree, emit it as a branch.
2276   // Note that all nodes in the tree should have same opcode.
2277   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2278   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2279       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2280       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2281     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2282                                  TProb, FProb, InvertCond);
2283     return;
2284   }
2285 
2286   //  Create TmpBB after CurBB.
2287   MachineFunction::iterator BBI(CurBB);
2288   MachineFunction &MF = DAG.getMachineFunction();
2289   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2290   CurBB->getParent()->insert(++BBI, TmpBB);
2291 
2292   if (Opc == Instruction::Or) {
2293     // Codegen X | Y as:
2294     // BB1:
2295     //   jmp_if_X TBB
2296     //   jmp TmpBB
2297     // TmpBB:
2298     //   jmp_if_Y TBB
2299     //   jmp FBB
2300     //
2301 
2302     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2303     // The requirement is that
2304     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2305     //     = TrueProb for original BB.
2306     // Assuming the original probabilities are A and B, one choice is to set
2307     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2308     // A/(1+B) and 2B/(1+B). This choice assumes that
2309     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2310     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2311     // TmpBB, but the math is more complicated.
2312 
2313     auto NewTrueProb = TProb / 2;
2314     auto NewFalseProb = TProb / 2 + FProb;
2315     // Emit the LHS condition.
2316     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2317                          NewFalseProb, InvertCond);
2318 
2319     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2320     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2321     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2322     // Emit the RHS condition into TmpBB.
2323     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2324                          Probs[1], InvertCond);
2325   } else {
2326     assert(Opc == Instruction::And && "Unknown merge op!");
2327     // Codegen X & Y as:
2328     // BB1:
2329     //   jmp_if_X TmpBB
2330     //   jmp FBB
2331     // TmpBB:
2332     //   jmp_if_Y TBB
2333     //   jmp FBB
2334     //
2335     //  This requires creation of TmpBB after CurBB.
2336 
2337     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2338     // The requirement is that
2339     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2340     //     = FalseProb for original BB.
2341     // Assuming the original probabilities are A and B, one choice is to set
2342     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2343     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2344     // TrueProb for BB1 * FalseProb for TmpBB.
2345 
2346     auto NewTrueProb = TProb + FProb / 2;
2347     auto NewFalseProb = FProb / 2;
2348     // Emit the LHS condition.
2349     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2350                          NewFalseProb, InvertCond);
2351 
2352     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2353     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2354     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2355     // Emit the RHS condition into TmpBB.
2356     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2357                          Probs[1], InvertCond);
2358   }
2359 }
2360 
2361 /// If the set of cases should be emitted as a series of branches, return true.
2362 /// If we should emit this as a bunch of and/or'd together conditions, return
2363 /// false.
2364 bool
2365 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2366   if (Cases.size() != 2) return true;
2367 
2368   // If this is two comparisons of the same values or'd or and'd together, they
2369   // will get folded into a single comparison, so don't emit two blocks.
2370   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2371        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2372       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2373        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2374     return false;
2375   }
2376 
2377   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2378   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2379   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2380       Cases[0].CC == Cases[1].CC &&
2381       isa<Constant>(Cases[0].CmpRHS) &&
2382       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2383     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2384       return false;
2385     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2386       return false;
2387   }
2388 
2389   return true;
2390 }
2391 
2392 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2393   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2394 
2395   // Update machine-CFG edges.
2396   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2397 
2398   if (I.isUnconditional()) {
2399     // Update machine-CFG edges.
2400     BrMBB->addSuccessor(Succ0MBB);
2401 
2402     // If this is not a fall-through branch or optimizations are switched off,
2403     // emit the branch.
2404     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2405       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2406                               MVT::Other, getControlRoot(),
2407                               DAG.getBasicBlock(Succ0MBB)));
2408 
2409     return;
2410   }
2411 
2412   // If this condition is one of the special cases we handle, do special stuff
2413   // now.
2414   const Value *CondVal = I.getCondition();
2415   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2416 
2417   // If this is a series of conditions that are or'd or and'd together, emit
2418   // this as a sequence of branches instead of setcc's with and/or operations.
2419   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2420   // unpredictable branches, and vector extracts because those jumps are likely
2421   // expensive for any target), this should improve performance.
2422   // For example, instead of something like:
2423   //     cmp A, B
2424   //     C = seteq
2425   //     cmp D, E
2426   //     F = setle
2427   //     or C, F
2428   //     jnz foo
2429   // Emit:
2430   //     cmp A, B
2431   //     je foo
2432   //     cmp D, E
2433   //     jle foo
2434   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2435   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2436       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2437     Value *Vec;
2438     const Value *BOp0, *BOp1;
2439     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2440     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2441       Opcode = Instruction::And;
2442     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2443       Opcode = Instruction::Or;
2444 
2445     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2446                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2447       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2448                            getEdgeProbability(BrMBB, Succ0MBB),
2449                            getEdgeProbability(BrMBB, Succ1MBB),
2450                            /*InvertCond=*/false);
2451       // If the compares in later blocks need to use values not currently
2452       // exported from this block, export them now.  This block should always
2453       // be the first entry.
2454       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2455 
2456       // Allow some cases to be rejected.
2457       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2458         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2459           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2460           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2461         }
2462 
2463         // Emit the branch for this block.
2464         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2465         SL->SwitchCases.erase(SL->SwitchCases.begin());
2466         return;
2467       }
2468 
2469       // Okay, we decided not to do this, remove any inserted MBB's and clear
2470       // SwitchCases.
2471       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2472         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2473 
2474       SL->SwitchCases.clear();
2475     }
2476   }
2477 
2478   // Create a CaseBlock record representing this branch.
2479   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2480                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2481 
2482   // Use visitSwitchCase to actually insert the fast branch sequence for this
2483   // cond branch.
2484   visitSwitchCase(CB, BrMBB);
2485 }
2486 
2487 /// visitSwitchCase - Emits the necessary code to represent a single node in
2488 /// the binary search tree resulting from lowering a switch instruction.
2489 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2490                                           MachineBasicBlock *SwitchBB) {
2491   SDValue Cond;
2492   SDValue CondLHS = getValue(CB.CmpLHS);
2493   SDLoc dl = CB.DL;
2494 
2495   if (CB.CC == ISD::SETTRUE) {
2496     // Branch or fall through to TrueBB.
2497     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2498     SwitchBB->normalizeSuccProbs();
2499     if (CB.TrueBB != NextBlock(SwitchBB)) {
2500       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2501                               DAG.getBasicBlock(CB.TrueBB)));
2502     }
2503     return;
2504   }
2505 
2506   auto &TLI = DAG.getTargetLoweringInfo();
2507   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2508 
2509   // Build the setcc now.
2510   if (!CB.CmpMHS) {
2511     // Fold "(X == true)" to X and "(X == false)" to !X to
2512     // handle common cases produced by branch lowering.
2513     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2514         CB.CC == ISD::SETEQ)
2515       Cond = CondLHS;
2516     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2517              CB.CC == ISD::SETEQ) {
2518       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2519       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2520     } else {
2521       SDValue CondRHS = getValue(CB.CmpRHS);
2522 
2523       // If a pointer's DAG type is larger than its memory type then the DAG
2524       // values are zero-extended. This breaks signed comparisons so truncate
2525       // back to the underlying type before doing the compare.
2526       if (CondLHS.getValueType() != MemVT) {
2527         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2528         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2529       }
2530       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2531     }
2532   } else {
2533     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2534 
2535     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2536     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2537 
2538     SDValue CmpOp = getValue(CB.CmpMHS);
2539     EVT VT = CmpOp.getValueType();
2540 
2541     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2542       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2543                           ISD::SETLE);
2544     } else {
2545       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2546                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2547       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2548                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2549     }
2550   }
2551 
2552   // Update successor info
2553   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2554   // TrueBB and FalseBB are always different unless the incoming IR is
2555   // degenerate. This only happens when running llc on weird IR.
2556   if (CB.TrueBB != CB.FalseBB)
2557     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2558   SwitchBB->normalizeSuccProbs();
2559 
2560   // If the lhs block is the next block, invert the condition so that we can
2561   // fall through to the lhs instead of the rhs block.
2562   if (CB.TrueBB == NextBlock(SwitchBB)) {
2563     std::swap(CB.TrueBB, CB.FalseBB);
2564     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2565     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2566   }
2567 
2568   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2569                                MVT::Other, getControlRoot(), Cond,
2570                                DAG.getBasicBlock(CB.TrueBB));
2571 
2572   setValue(CurInst, BrCond);
2573 
2574   // Insert the false branch. Do this even if it's a fall through branch,
2575   // this makes it easier to do DAG optimizations which require inverting
2576   // the branch condition.
2577   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2578                        DAG.getBasicBlock(CB.FalseBB));
2579 
2580   DAG.setRoot(BrCond);
2581 }
2582 
2583 /// visitJumpTable - Emit JumpTable node in the current MBB
2584 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2585   // Emit the code for the jump table
2586   assert(JT.Reg != -1U && "Should lower JT Header first!");
2587   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2588   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2589                                      JT.Reg, PTy);
2590   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2591   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2592                                     MVT::Other, Index.getValue(1),
2593                                     Table, Index);
2594   DAG.setRoot(BrJumpTable);
2595 }
2596 
2597 /// visitJumpTableHeader - This function emits necessary code to produce index
2598 /// in the JumpTable from switch case.
2599 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2600                                                JumpTableHeader &JTH,
2601                                                MachineBasicBlock *SwitchBB) {
2602   SDLoc dl = getCurSDLoc();
2603 
2604   // Subtract the lowest switch case value from the value being switched on.
2605   SDValue SwitchOp = getValue(JTH.SValue);
2606   EVT VT = SwitchOp.getValueType();
2607   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2608                             DAG.getConstant(JTH.First, dl, VT));
2609 
2610   // The SDNode we just created, which holds the value being switched on minus
2611   // the smallest case value, needs to be copied to a virtual register so it
2612   // can be used as an index into the jump table in a subsequent basic block.
2613   // This value may be smaller or larger than the target's pointer type, and
2614   // therefore require extension or truncating.
2615   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2616   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2617 
2618   unsigned JumpTableReg =
2619       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2620   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2621                                     JumpTableReg, SwitchOp);
2622   JT.Reg = JumpTableReg;
2623 
2624   if (!JTH.FallthroughUnreachable) {
2625     // Emit the range check for the jump table, and branch to the default block
2626     // for the switch statement if the value being switched on exceeds the
2627     // largest case in the switch.
2628     SDValue CMP = DAG.getSetCC(
2629         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2630                                    Sub.getValueType()),
2631         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2632 
2633     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2634                                  MVT::Other, CopyTo, CMP,
2635                                  DAG.getBasicBlock(JT.Default));
2636 
2637     // Avoid emitting unnecessary branches to the next block.
2638     if (JT.MBB != NextBlock(SwitchBB))
2639       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2640                            DAG.getBasicBlock(JT.MBB));
2641 
2642     DAG.setRoot(BrCond);
2643   } else {
2644     // Avoid emitting unnecessary branches to the next block.
2645     if (JT.MBB != NextBlock(SwitchBB))
2646       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2647                               DAG.getBasicBlock(JT.MBB)));
2648     else
2649       DAG.setRoot(CopyTo);
2650   }
2651 }
2652 
2653 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2654 /// variable if there exists one.
2655 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2656                                  SDValue &Chain) {
2657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2658   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2659   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2660   MachineFunction &MF = DAG.getMachineFunction();
2661   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2662   MachineSDNode *Node =
2663       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2664   if (Global) {
2665     MachinePointerInfo MPInfo(Global);
2666     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2667                  MachineMemOperand::MODereferenceable;
2668     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2669         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2670     DAG.setNodeMemRefs(Node, {MemRef});
2671   }
2672   if (PtrTy != PtrMemTy)
2673     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2674   return SDValue(Node, 0);
2675 }
2676 
2677 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2678 /// tail spliced into a stack protector check success bb.
2679 ///
2680 /// For a high level explanation of how this fits into the stack protector
2681 /// generation see the comment on the declaration of class
2682 /// StackProtectorDescriptor.
2683 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2684                                                   MachineBasicBlock *ParentBB) {
2685 
2686   // First create the loads to the guard/stack slot for the comparison.
2687   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2688   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2689   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2690 
2691   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2692   int FI = MFI.getStackProtectorIndex();
2693 
2694   SDValue Guard;
2695   SDLoc dl = getCurSDLoc();
2696   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2697   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2698   Align Align =
2699       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2700 
2701   // Generate code to load the content of the guard slot.
2702   SDValue GuardVal = DAG.getLoad(
2703       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2704       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2705       MachineMemOperand::MOVolatile);
2706 
2707   if (TLI.useStackGuardXorFP())
2708     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2709 
2710   // Retrieve guard check function, nullptr if instrumentation is inlined.
2711   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2712     // The target provides a guard check function to validate the guard value.
2713     // Generate a call to that function with the content of the guard slot as
2714     // argument.
2715     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2716     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2717 
2718     TargetLowering::ArgListTy Args;
2719     TargetLowering::ArgListEntry Entry;
2720     Entry.Node = GuardVal;
2721     Entry.Ty = FnTy->getParamType(0);
2722     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2723       Entry.IsInReg = true;
2724     Args.push_back(Entry);
2725 
2726     TargetLowering::CallLoweringInfo CLI(DAG);
2727     CLI.setDebugLoc(getCurSDLoc())
2728         .setChain(DAG.getEntryNode())
2729         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2730                    getValue(GuardCheckFn), std::move(Args));
2731 
2732     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2733     DAG.setRoot(Result.second);
2734     return;
2735   }
2736 
2737   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2738   // Otherwise, emit a volatile load to retrieve the stack guard value.
2739   SDValue Chain = DAG.getEntryNode();
2740   if (TLI.useLoadStackGuardNode()) {
2741     Guard = getLoadStackGuard(DAG, dl, Chain);
2742   } else {
2743     const Value *IRGuard = TLI.getSDagStackGuard(M);
2744     SDValue GuardPtr = getValue(IRGuard);
2745 
2746     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2747                         MachinePointerInfo(IRGuard, 0), Align,
2748                         MachineMemOperand::MOVolatile);
2749   }
2750 
2751   // Perform the comparison via a getsetcc.
2752   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2753                                                         *DAG.getContext(),
2754                                                         Guard.getValueType()),
2755                              Guard, GuardVal, ISD::SETNE);
2756 
2757   // If the guard/stackslot do not equal, branch to failure MBB.
2758   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2759                                MVT::Other, GuardVal.getOperand(0),
2760                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2761   // Otherwise branch to success MBB.
2762   SDValue Br = DAG.getNode(ISD::BR, dl,
2763                            MVT::Other, BrCond,
2764                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2765 
2766   DAG.setRoot(Br);
2767 }
2768 
2769 /// Codegen the failure basic block for a stack protector check.
2770 ///
2771 /// A failure stack protector machine basic block consists simply of a call to
2772 /// __stack_chk_fail().
2773 ///
2774 /// For a high level explanation of how this fits into the stack protector
2775 /// generation see the comment on the declaration of class
2776 /// StackProtectorDescriptor.
2777 void
2778 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2779   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2780   TargetLowering::MakeLibCallOptions CallOptions;
2781   CallOptions.setDiscardResult(true);
2782   SDValue Chain =
2783       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2784                       None, CallOptions, getCurSDLoc()).second;
2785   // On PS4/PS5, the "return address" must still be within the calling
2786   // function, even if it's at the very end, so emit an explicit TRAP here.
2787   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2788   if (TM.getTargetTriple().isPS())
2789     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2790   // WebAssembly needs an unreachable instruction after a non-returning call,
2791   // because the function return type can be different from __stack_chk_fail's
2792   // return type (void).
2793   if (TM.getTargetTriple().isWasm())
2794     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2795 
2796   DAG.setRoot(Chain);
2797 }
2798 
2799 /// visitBitTestHeader - This function emits necessary code to produce value
2800 /// suitable for "bit tests"
2801 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2802                                              MachineBasicBlock *SwitchBB) {
2803   SDLoc dl = getCurSDLoc();
2804 
2805   // Subtract the minimum value.
2806   SDValue SwitchOp = getValue(B.SValue);
2807   EVT VT = SwitchOp.getValueType();
2808   SDValue RangeSub =
2809       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2810 
2811   // Determine the type of the test operands.
2812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2813   bool UsePtrType = false;
2814   if (!TLI.isTypeLegal(VT)) {
2815     UsePtrType = true;
2816   } else {
2817     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2818       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2819         // Switch table case range are encoded into series of masks.
2820         // Just use pointer type, it's guaranteed to fit.
2821         UsePtrType = true;
2822         break;
2823       }
2824   }
2825   SDValue Sub = RangeSub;
2826   if (UsePtrType) {
2827     VT = TLI.getPointerTy(DAG.getDataLayout());
2828     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2829   }
2830 
2831   B.RegVT = VT.getSimpleVT();
2832   B.Reg = FuncInfo.CreateReg(B.RegVT);
2833   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2834 
2835   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2836 
2837   if (!B.FallthroughUnreachable)
2838     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2839   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2840   SwitchBB->normalizeSuccProbs();
2841 
2842   SDValue Root = CopyTo;
2843   if (!B.FallthroughUnreachable) {
2844     // Conditional branch to the default block.
2845     SDValue RangeCmp = DAG.getSetCC(dl,
2846         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2847                                RangeSub.getValueType()),
2848         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2849         ISD::SETUGT);
2850 
2851     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2852                        DAG.getBasicBlock(B.Default));
2853   }
2854 
2855   // Avoid emitting unnecessary branches to the next block.
2856   if (MBB != NextBlock(SwitchBB))
2857     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2858 
2859   DAG.setRoot(Root);
2860 }
2861 
2862 /// visitBitTestCase - this function produces one "bit test"
2863 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2864                                            MachineBasicBlock* NextMBB,
2865                                            BranchProbability BranchProbToNext,
2866                                            unsigned Reg,
2867                                            BitTestCase &B,
2868                                            MachineBasicBlock *SwitchBB) {
2869   SDLoc dl = getCurSDLoc();
2870   MVT VT = BB.RegVT;
2871   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2872   SDValue Cmp;
2873   unsigned PopCount = countPopulation(B.Mask);
2874   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2875   if (PopCount == 1) {
2876     // Testing for a single bit; just compare the shift count with what it
2877     // would need to be to shift a 1 bit in that position.
2878     Cmp = DAG.getSetCC(
2879         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2880         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2881         ISD::SETEQ);
2882   } else if (PopCount == BB.Range) {
2883     // There is only one zero bit in the range, test for it directly.
2884     Cmp = DAG.getSetCC(
2885         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2886         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2887         ISD::SETNE);
2888   } else {
2889     // Make desired shift
2890     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2891                                     DAG.getConstant(1, dl, VT), ShiftOp);
2892 
2893     // Emit bit tests and jumps
2894     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2895                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2896     Cmp = DAG.getSetCC(
2897         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2898         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2899   }
2900 
2901   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2902   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2903   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2904   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2905   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2906   // one as they are relative probabilities (and thus work more like weights),
2907   // and hence we need to normalize them to let the sum of them become one.
2908   SwitchBB->normalizeSuccProbs();
2909 
2910   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2911                               MVT::Other, getControlRoot(),
2912                               Cmp, DAG.getBasicBlock(B.TargetBB));
2913 
2914   // Avoid emitting unnecessary branches to the next block.
2915   if (NextMBB != NextBlock(SwitchBB))
2916     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2917                         DAG.getBasicBlock(NextMBB));
2918 
2919   DAG.setRoot(BrAnd);
2920 }
2921 
2922 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2923   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2924 
2925   // Retrieve successors. Look through artificial IR level blocks like
2926   // catchswitch for successors.
2927   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2928   const BasicBlock *EHPadBB = I.getSuccessor(1);
2929 
2930   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2931   // have to do anything here to lower funclet bundles.
2932   assert(!I.hasOperandBundlesOtherThan(
2933              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2934               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2935               LLVMContext::OB_cfguardtarget,
2936               LLVMContext::OB_clang_arc_attachedcall}) &&
2937          "Cannot lower invokes with arbitrary operand bundles yet!");
2938 
2939   const Value *Callee(I.getCalledOperand());
2940   const Function *Fn = dyn_cast<Function>(Callee);
2941   if (isa<InlineAsm>(Callee))
2942     visitInlineAsm(I, EHPadBB);
2943   else if (Fn && Fn->isIntrinsic()) {
2944     switch (Fn->getIntrinsicID()) {
2945     default:
2946       llvm_unreachable("Cannot invoke this intrinsic");
2947     case Intrinsic::donothing:
2948       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2949     case Intrinsic::seh_try_begin:
2950     case Intrinsic::seh_scope_begin:
2951     case Intrinsic::seh_try_end:
2952     case Intrinsic::seh_scope_end:
2953       break;
2954     case Intrinsic::experimental_patchpoint_void:
2955     case Intrinsic::experimental_patchpoint_i64:
2956       visitPatchpoint(I, EHPadBB);
2957       break;
2958     case Intrinsic::experimental_gc_statepoint:
2959       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2960       break;
2961     case Intrinsic::wasm_rethrow: {
2962       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2963       // special because it can be invoked, so we manually lower it to a DAG
2964       // node here.
2965       SmallVector<SDValue, 8> Ops;
2966       Ops.push_back(getRoot()); // inchain
2967       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2968       Ops.push_back(
2969           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2970                                 TLI.getPointerTy(DAG.getDataLayout())));
2971       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2972       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2973       break;
2974     }
2975     }
2976   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2977     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2978     // Eventually we will support lowering the @llvm.experimental.deoptimize
2979     // intrinsic, and right now there are no plans to support other intrinsics
2980     // with deopt state.
2981     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2982   } else {
2983     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2984   }
2985 
2986   // If the value of the invoke is used outside of its defining block, make it
2987   // available as a virtual register.
2988   // We already took care of the exported value for the statepoint instruction
2989   // during call to the LowerStatepoint.
2990   if (!isa<GCStatepointInst>(I)) {
2991     CopyToExportRegsIfNeeded(&I);
2992   }
2993 
2994   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2995   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2996   BranchProbability EHPadBBProb =
2997       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2998           : BranchProbability::getZero();
2999   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3000 
3001   // Update successor info.
3002   addSuccessorWithProb(InvokeMBB, Return);
3003   for (auto &UnwindDest : UnwindDests) {
3004     UnwindDest.first->setIsEHPad();
3005     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3006   }
3007   InvokeMBB->normalizeSuccProbs();
3008 
3009   // Drop into normal successor.
3010   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3011                           DAG.getBasicBlock(Return)));
3012 }
3013 
3014 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3015   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3016 
3017   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3018   // have to do anything here to lower funclet bundles.
3019   assert(!I.hasOperandBundlesOtherThan(
3020              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3021          "Cannot lower callbrs with arbitrary operand bundles yet!");
3022 
3023   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3024   visitInlineAsm(I);
3025   CopyToExportRegsIfNeeded(&I);
3026 
3027   // Retrieve successors.
3028   SmallPtrSet<BasicBlock *, 8> Dests;
3029   Dests.insert(I.getDefaultDest());
3030   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3031 
3032   // Update successor info.
3033   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3034   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3035     BasicBlock *Dest = I.getIndirectDest(i);
3036     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3037     Target->setIsInlineAsmBrIndirectTarget();
3038     Target->setMachineBlockAddressTaken();
3039     Target->setLabelMustBeEmitted();
3040     // Don't add duplicate machine successors.
3041     if (Dests.insert(Dest).second)
3042       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3043   }
3044   CallBrMBB->normalizeSuccProbs();
3045 
3046   // Drop into default successor.
3047   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3048                           MVT::Other, getControlRoot(),
3049                           DAG.getBasicBlock(Return)));
3050 }
3051 
3052 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3053   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3054 }
3055 
3056 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3057   assert(FuncInfo.MBB->isEHPad() &&
3058          "Call to landingpad not in landing pad!");
3059 
3060   // If there aren't registers to copy the values into (e.g., during SjLj
3061   // exceptions), then don't bother to create these DAG nodes.
3062   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3063   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3064   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3065       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3066     return;
3067 
3068   // If landingpad's return type is token type, we don't create DAG nodes
3069   // for its exception pointer and selector value. The extraction of exception
3070   // pointer or selector value from token type landingpads is not currently
3071   // supported.
3072   if (LP.getType()->isTokenTy())
3073     return;
3074 
3075   SmallVector<EVT, 2> ValueVTs;
3076   SDLoc dl = getCurSDLoc();
3077   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3078   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3079 
3080   // Get the two live-in registers as SDValues. The physregs have already been
3081   // copied into virtual registers.
3082   SDValue Ops[2];
3083   if (FuncInfo.ExceptionPointerVirtReg) {
3084     Ops[0] = DAG.getZExtOrTrunc(
3085         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3086                            FuncInfo.ExceptionPointerVirtReg,
3087                            TLI.getPointerTy(DAG.getDataLayout())),
3088         dl, ValueVTs[0]);
3089   } else {
3090     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3091   }
3092   Ops[1] = DAG.getZExtOrTrunc(
3093       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3094                          FuncInfo.ExceptionSelectorVirtReg,
3095                          TLI.getPointerTy(DAG.getDataLayout())),
3096       dl, ValueVTs[1]);
3097 
3098   // Merge into one.
3099   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3100                             DAG.getVTList(ValueVTs), Ops);
3101   setValue(&LP, Res);
3102 }
3103 
3104 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3105                                            MachineBasicBlock *Last) {
3106   // Update JTCases.
3107   for (JumpTableBlock &JTB : SL->JTCases)
3108     if (JTB.first.HeaderBB == First)
3109       JTB.first.HeaderBB = Last;
3110 
3111   // Update BitTestCases.
3112   for (BitTestBlock &BTB : SL->BitTestCases)
3113     if (BTB.Parent == First)
3114       BTB.Parent = Last;
3115 }
3116 
3117 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3118   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3119 
3120   // Update machine-CFG edges with unique successors.
3121   SmallSet<BasicBlock*, 32> Done;
3122   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3123     BasicBlock *BB = I.getSuccessor(i);
3124     bool Inserted = Done.insert(BB).second;
3125     if (!Inserted)
3126         continue;
3127 
3128     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3129     addSuccessorWithProb(IndirectBrMBB, Succ);
3130   }
3131   IndirectBrMBB->normalizeSuccProbs();
3132 
3133   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3134                           MVT::Other, getControlRoot(),
3135                           getValue(I.getAddress())));
3136 }
3137 
3138 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3139   if (!DAG.getTarget().Options.TrapUnreachable)
3140     return;
3141 
3142   // We may be able to ignore unreachable behind a noreturn call.
3143   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3144     const BasicBlock &BB = *I.getParent();
3145     if (&I != &BB.front()) {
3146       BasicBlock::const_iterator PredI =
3147         std::prev(BasicBlock::const_iterator(&I));
3148       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3149         if (Call->doesNotReturn())
3150           return;
3151       }
3152     }
3153   }
3154 
3155   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3156 }
3157 
3158 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3159   SDNodeFlags Flags;
3160   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3161     Flags.copyFMF(*FPOp);
3162 
3163   SDValue Op = getValue(I.getOperand(0));
3164   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3165                                     Op, Flags);
3166   setValue(&I, UnNodeValue);
3167 }
3168 
3169 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3170   SDNodeFlags Flags;
3171   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3172     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3173     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3174   }
3175   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3176     Flags.setExact(ExactOp->isExact());
3177   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3178     Flags.copyFMF(*FPOp);
3179 
3180   SDValue Op1 = getValue(I.getOperand(0));
3181   SDValue Op2 = getValue(I.getOperand(1));
3182   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3183                                      Op1, Op2, Flags);
3184   setValue(&I, BinNodeValue);
3185 }
3186 
3187 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3188   SDValue Op1 = getValue(I.getOperand(0));
3189   SDValue Op2 = getValue(I.getOperand(1));
3190 
3191   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3192       Op1.getValueType(), DAG.getDataLayout());
3193 
3194   // Coerce the shift amount to the right type if we can. This exposes the
3195   // truncate or zext to optimization early.
3196   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3197     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3198            "Unexpected shift type");
3199     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3200   }
3201 
3202   bool nuw = false;
3203   bool nsw = false;
3204   bool exact = false;
3205 
3206   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3207 
3208     if (const OverflowingBinaryOperator *OFBinOp =
3209             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3210       nuw = OFBinOp->hasNoUnsignedWrap();
3211       nsw = OFBinOp->hasNoSignedWrap();
3212     }
3213     if (const PossiblyExactOperator *ExactOp =
3214             dyn_cast<const PossiblyExactOperator>(&I))
3215       exact = ExactOp->isExact();
3216   }
3217   SDNodeFlags Flags;
3218   Flags.setExact(exact);
3219   Flags.setNoSignedWrap(nsw);
3220   Flags.setNoUnsignedWrap(nuw);
3221   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3222                             Flags);
3223   setValue(&I, Res);
3224 }
3225 
3226 void SelectionDAGBuilder::visitSDiv(const User &I) {
3227   SDValue Op1 = getValue(I.getOperand(0));
3228   SDValue Op2 = getValue(I.getOperand(1));
3229 
3230   SDNodeFlags Flags;
3231   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3232                  cast<PossiblyExactOperator>(&I)->isExact());
3233   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3234                            Op2, Flags));
3235 }
3236 
3237 void SelectionDAGBuilder::visitICmp(const User &I) {
3238   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3239   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3240     predicate = IC->getPredicate();
3241   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3242     predicate = ICmpInst::Predicate(IC->getPredicate());
3243   SDValue Op1 = getValue(I.getOperand(0));
3244   SDValue Op2 = getValue(I.getOperand(1));
3245   ISD::CondCode Opcode = getICmpCondCode(predicate);
3246 
3247   auto &TLI = DAG.getTargetLoweringInfo();
3248   EVT MemVT =
3249       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3250 
3251   // If a pointer's DAG type is larger than its memory type then the DAG values
3252   // are zero-extended. This breaks signed comparisons so truncate back to the
3253   // underlying type before doing the compare.
3254   if (Op1.getValueType() != MemVT) {
3255     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3256     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3257   }
3258 
3259   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3260                                                         I.getType());
3261   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3262 }
3263 
3264 void SelectionDAGBuilder::visitFCmp(const User &I) {
3265   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3266   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3267     predicate = FC->getPredicate();
3268   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3269     predicate = FCmpInst::Predicate(FC->getPredicate());
3270   SDValue Op1 = getValue(I.getOperand(0));
3271   SDValue Op2 = getValue(I.getOperand(1));
3272 
3273   ISD::CondCode Condition = getFCmpCondCode(predicate);
3274   auto *FPMO = cast<FPMathOperator>(&I);
3275   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3276     Condition = getFCmpCodeWithoutNaN(Condition);
3277 
3278   SDNodeFlags Flags;
3279   Flags.copyFMF(*FPMO);
3280   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3281 
3282   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3283                                                         I.getType());
3284   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3285 }
3286 
3287 // Check if the condition of the select has one use or two users that are both
3288 // selects with the same condition.
3289 static bool hasOnlySelectUsers(const Value *Cond) {
3290   return llvm::all_of(Cond->users(), [](const Value *V) {
3291     return isa<SelectInst>(V);
3292   });
3293 }
3294 
3295 void SelectionDAGBuilder::visitSelect(const User &I) {
3296   SmallVector<EVT, 4> ValueVTs;
3297   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3298                   ValueVTs);
3299   unsigned NumValues = ValueVTs.size();
3300   if (NumValues == 0) return;
3301 
3302   SmallVector<SDValue, 4> Values(NumValues);
3303   SDValue Cond     = getValue(I.getOperand(0));
3304   SDValue LHSVal   = getValue(I.getOperand(1));
3305   SDValue RHSVal   = getValue(I.getOperand(2));
3306   SmallVector<SDValue, 1> BaseOps(1, Cond);
3307   ISD::NodeType OpCode =
3308       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3309 
3310   bool IsUnaryAbs = false;
3311   bool Negate = false;
3312 
3313   SDNodeFlags Flags;
3314   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3315     Flags.copyFMF(*FPOp);
3316 
3317   // Min/max matching is only viable if all output VTs are the same.
3318   if (all_equal(ValueVTs)) {
3319     EVT VT = ValueVTs[0];
3320     LLVMContext &Ctx = *DAG.getContext();
3321     auto &TLI = DAG.getTargetLoweringInfo();
3322 
3323     // We care about the legality of the operation after it has been type
3324     // legalized.
3325     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3326       VT = TLI.getTypeToTransformTo(Ctx, VT);
3327 
3328     // If the vselect is legal, assume we want to leave this as a vector setcc +
3329     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3330     // min/max is legal on the scalar type.
3331     bool UseScalarMinMax = VT.isVector() &&
3332       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3333 
3334     Value *LHS, *RHS;
3335     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3336     ISD::NodeType Opc = ISD::DELETED_NODE;
3337     switch (SPR.Flavor) {
3338     case SPF_UMAX:    Opc = ISD::UMAX; break;
3339     case SPF_UMIN:    Opc = ISD::UMIN; break;
3340     case SPF_SMAX:    Opc = ISD::SMAX; break;
3341     case SPF_SMIN:    Opc = ISD::SMIN; break;
3342     case SPF_FMINNUM:
3343       switch (SPR.NaNBehavior) {
3344       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3345       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3346       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3347       case SPNB_RETURNS_ANY: {
3348         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3349           Opc = ISD::FMINNUM;
3350         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3351           Opc = ISD::FMINIMUM;
3352         else if (UseScalarMinMax)
3353           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3354             ISD::FMINNUM : ISD::FMINIMUM;
3355         break;
3356       }
3357       }
3358       break;
3359     case SPF_FMAXNUM:
3360       switch (SPR.NaNBehavior) {
3361       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3362       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3363       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3364       case SPNB_RETURNS_ANY:
3365 
3366         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3367           Opc = ISD::FMAXNUM;
3368         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3369           Opc = ISD::FMAXIMUM;
3370         else if (UseScalarMinMax)
3371           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3372             ISD::FMAXNUM : ISD::FMAXIMUM;
3373         break;
3374       }
3375       break;
3376     case SPF_NABS:
3377       Negate = true;
3378       [[fallthrough]];
3379     case SPF_ABS:
3380       IsUnaryAbs = true;
3381       Opc = ISD::ABS;
3382       break;
3383     default: break;
3384     }
3385 
3386     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3387         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3388          (UseScalarMinMax &&
3389           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3390         // If the underlying comparison instruction is used by any other
3391         // instruction, the consumed instructions won't be destroyed, so it is
3392         // not profitable to convert to a min/max.
3393         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3394       OpCode = Opc;
3395       LHSVal = getValue(LHS);
3396       RHSVal = getValue(RHS);
3397       BaseOps.clear();
3398     }
3399 
3400     if (IsUnaryAbs) {
3401       OpCode = Opc;
3402       LHSVal = getValue(LHS);
3403       BaseOps.clear();
3404     }
3405   }
3406 
3407   if (IsUnaryAbs) {
3408     for (unsigned i = 0; i != NumValues; ++i) {
3409       SDLoc dl = getCurSDLoc();
3410       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3411       Values[i] =
3412           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3413       if (Negate)
3414         Values[i] = DAG.getNegative(Values[i], dl, VT);
3415     }
3416   } else {
3417     for (unsigned i = 0; i != NumValues; ++i) {
3418       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3419       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3420       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3421       Values[i] = DAG.getNode(
3422           OpCode, getCurSDLoc(),
3423           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3424     }
3425   }
3426 
3427   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3428                            DAG.getVTList(ValueVTs), Values));
3429 }
3430 
3431 void SelectionDAGBuilder::visitTrunc(const User &I) {
3432   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3433   SDValue N = getValue(I.getOperand(0));
3434   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3435                                                         I.getType());
3436   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3437 }
3438 
3439 void SelectionDAGBuilder::visitZExt(const User &I) {
3440   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3441   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3442   SDValue N = getValue(I.getOperand(0));
3443   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3444                                                         I.getType());
3445   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3446 }
3447 
3448 void SelectionDAGBuilder::visitSExt(const User &I) {
3449   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3450   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3451   SDValue N = getValue(I.getOperand(0));
3452   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3453                                                         I.getType());
3454   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3455 }
3456 
3457 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3458   // FPTrunc is never a no-op cast, no need to check
3459   SDValue N = getValue(I.getOperand(0));
3460   SDLoc dl = getCurSDLoc();
3461   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3462   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3463   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3464                            DAG.getTargetConstant(
3465                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3466 }
3467 
3468 void SelectionDAGBuilder::visitFPExt(const User &I) {
3469   // FPExt is never a no-op cast, no need to check
3470   SDValue N = getValue(I.getOperand(0));
3471   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3472                                                         I.getType());
3473   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3474 }
3475 
3476 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3477   // FPToUI 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_TO_UINT, getCurSDLoc(), DestVT, N));
3482 }
3483 
3484 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3485   // FPToSI 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_SINT, getCurSDLoc(), DestVT, N));
3490 }
3491 
3492 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3493   // UIToFP 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::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3498 }
3499 
3500 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3501   // SIToFP 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::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3506 }
3507 
3508 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3509   // What to do depends on the size of the integer and the size of the pointer.
3510   // We can either truncate, zero extend, or no-op, accordingly.
3511   SDValue N = getValue(I.getOperand(0));
3512   auto &TLI = DAG.getTargetLoweringInfo();
3513   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3514                                                         I.getType());
3515   EVT PtrMemVT =
3516       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3517   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3518   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3519   setValue(&I, N);
3520 }
3521 
3522 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3523   // What to do depends on the size of the integer and the size of the pointer.
3524   // We can either truncate, zero extend, or no-op, accordingly.
3525   SDValue N = getValue(I.getOperand(0));
3526   auto &TLI = DAG.getTargetLoweringInfo();
3527   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3528   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3529   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3530   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3531   setValue(&I, N);
3532 }
3533 
3534 void SelectionDAGBuilder::visitBitCast(const User &I) {
3535   SDValue N = getValue(I.getOperand(0));
3536   SDLoc dl = getCurSDLoc();
3537   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3538                                                         I.getType());
3539 
3540   // BitCast assures us that source and destination are the same size so this is
3541   // either a BITCAST or a no-op.
3542   if (DestVT != N.getValueType())
3543     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3544                              DestVT, N)); // convert types.
3545   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3546   // might fold any kind of constant expression to an integer constant and that
3547   // is not what we are looking for. Only recognize a bitcast of a genuine
3548   // constant integer as an opaque constant.
3549   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3550     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3551                                  /*isOpaque*/true));
3552   else
3553     setValue(&I, N);            // noop cast.
3554 }
3555 
3556 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3557   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3558   const Value *SV = I.getOperand(0);
3559   SDValue N = getValue(SV);
3560   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3561 
3562   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3563   unsigned DestAS = I.getType()->getPointerAddressSpace();
3564 
3565   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3566     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3567 
3568   setValue(&I, N);
3569 }
3570 
3571 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3572   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3573   SDValue InVec = getValue(I.getOperand(0));
3574   SDValue InVal = getValue(I.getOperand(1));
3575   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3576                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3577   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3578                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3579                            InVec, InVal, InIdx));
3580 }
3581 
3582 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3584   SDValue InVec = getValue(I.getOperand(0));
3585   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3586                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3587   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3588                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3589                            InVec, InIdx));
3590 }
3591 
3592 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3593   SDValue Src1 = getValue(I.getOperand(0));
3594   SDValue Src2 = getValue(I.getOperand(1));
3595   ArrayRef<int> Mask;
3596   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3597     Mask = SVI->getShuffleMask();
3598   else
3599     Mask = cast<ConstantExpr>(I).getShuffleMask();
3600   SDLoc DL = getCurSDLoc();
3601   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3602   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3603   EVT SrcVT = Src1.getValueType();
3604 
3605   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3606       VT.isScalableVector()) {
3607     // Canonical splat form of first element of first input vector.
3608     SDValue FirstElt =
3609         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3610                     DAG.getVectorIdxConstant(0, DL));
3611     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3612     return;
3613   }
3614 
3615   // For now, we only handle splats for scalable vectors.
3616   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3617   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3618   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3619 
3620   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3621   unsigned MaskNumElts = Mask.size();
3622 
3623   if (SrcNumElts == MaskNumElts) {
3624     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3625     return;
3626   }
3627 
3628   // Normalize the shuffle vector since mask and vector length don't match.
3629   if (SrcNumElts < MaskNumElts) {
3630     // Mask is longer than the source vectors. We can use concatenate vector to
3631     // make the mask and vectors lengths match.
3632 
3633     if (MaskNumElts % SrcNumElts == 0) {
3634       // Mask length is a multiple of the source vector length.
3635       // Check if the shuffle is some kind of concatenation of the input
3636       // vectors.
3637       unsigned NumConcat = MaskNumElts / SrcNumElts;
3638       bool IsConcat = true;
3639       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3640       for (unsigned i = 0; i != MaskNumElts; ++i) {
3641         int Idx = Mask[i];
3642         if (Idx < 0)
3643           continue;
3644         // Ensure the indices in each SrcVT sized piece are sequential and that
3645         // the same source is used for the whole piece.
3646         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3647             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3648              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3649           IsConcat = false;
3650           break;
3651         }
3652         // Remember which source this index came from.
3653         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3654       }
3655 
3656       // The shuffle is concatenating multiple vectors together. Just emit
3657       // a CONCAT_VECTORS operation.
3658       if (IsConcat) {
3659         SmallVector<SDValue, 8> ConcatOps;
3660         for (auto Src : ConcatSrcs) {
3661           if (Src < 0)
3662             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3663           else if (Src == 0)
3664             ConcatOps.push_back(Src1);
3665           else
3666             ConcatOps.push_back(Src2);
3667         }
3668         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3669         return;
3670       }
3671     }
3672 
3673     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3674     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3675     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3676                                     PaddedMaskNumElts);
3677 
3678     // Pad both vectors with undefs to make them the same length as the mask.
3679     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3680 
3681     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3682     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3683     MOps1[0] = Src1;
3684     MOps2[0] = Src2;
3685 
3686     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3687     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3688 
3689     // Readjust mask for new input vector length.
3690     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3691     for (unsigned i = 0; i != MaskNumElts; ++i) {
3692       int Idx = Mask[i];
3693       if (Idx >= (int)SrcNumElts)
3694         Idx -= SrcNumElts - PaddedMaskNumElts;
3695       MappedOps[i] = Idx;
3696     }
3697 
3698     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3699 
3700     // If the concatenated vector was padded, extract a subvector with the
3701     // correct number of elements.
3702     if (MaskNumElts != PaddedMaskNumElts)
3703       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3704                            DAG.getVectorIdxConstant(0, DL));
3705 
3706     setValue(&I, Result);
3707     return;
3708   }
3709 
3710   if (SrcNumElts > MaskNumElts) {
3711     // Analyze the access pattern of the vector to see if we can extract
3712     // two subvectors and do the shuffle.
3713     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3714     bool CanExtract = true;
3715     for (int Idx : Mask) {
3716       unsigned Input = 0;
3717       if (Idx < 0)
3718         continue;
3719 
3720       if (Idx >= (int)SrcNumElts) {
3721         Input = 1;
3722         Idx -= SrcNumElts;
3723       }
3724 
3725       // If all the indices come from the same MaskNumElts sized portion of
3726       // the sources we can use extract. Also make sure the extract wouldn't
3727       // extract past the end of the source.
3728       int NewStartIdx = alignDown(Idx, MaskNumElts);
3729       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3730           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3731         CanExtract = false;
3732       // Make sure we always update StartIdx as we use it to track if all
3733       // elements are undef.
3734       StartIdx[Input] = NewStartIdx;
3735     }
3736 
3737     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3738       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3739       return;
3740     }
3741     if (CanExtract) {
3742       // Extract appropriate subvector and generate a vector shuffle
3743       for (unsigned Input = 0; Input < 2; ++Input) {
3744         SDValue &Src = Input == 0 ? Src1 : Src2;
3745         if (StartIdx[Input] < 0)
3746           Src = DAG.getUNDEF(VT);
3747         else {
3748           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3749                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3750         }
3751       }
3752 
3753       // Calculate new mask.
3754       SmallVector<int, 8> MappedOps(Mask);
3755       for (int &Idx : MappedOps) {
3756         if (Idx >= (int)SrcNumElts)
3757           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3758         else if (Idx >= 0)
3759           Idx -= StartIdx[0];
3760       }
3761 
3762       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3763       return;
3764     }
3765   }
3766 
3767   // We can't use either concat vectors or extract subvectors so fall back to
3768   // replacing the shuffle with extract and build vector.
3769   // to insert and build vector.
3770   EVT EltVT = VT.getVectorElementType();
3771   SmallVector<SDValue,8> Ops;
3772   for (int Idx : Mask) {
3773     SDValue Res;
3774 
3775     if (Idx < 0) {
3776       Res = DAG.getUNDEF(EltVT);
3777     } else {
3778       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3779       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3780 
3781       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3782                         DAG.getVectorIdxConstant(Idx, DL));
3783     }
3784 
3785     Ops.push_back(Res);
3786   }
3787 
3788   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3789 }
3790 
3791 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3792   ArrayRef<unsigned> Indices = I.getIndices();
3793   const Value *Op0 = I.getOperand(0);
3794   const Value *Op1 = I.getOperand(1);
3795   Type *AggTy = I.getType();
3796   Type *ValTy = Op1->getType();
3797   bool IntoUndef = isa<UndefValue>(Op0);
3798   bool FromUndef = isa<UndefValue>(Op1);
3799 
3800   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3801 
3802   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3803   SmallVector<EVT, 4> AggValueVTs;
3804   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3805   SmallVector<EVT, 4> ValValueVTs;
3806   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3807 
3808   unsigned NumAggValues = AggValueVTs.size();
3809   unsigned NumValValues = ValValueVTs.size();
3810   SmallVector<SDValue, 4> Values(NumAggValues);
3811 
3812   // Ignore an insertvalue that produces an empty object
3813   if (!NumAggValues) {
3814     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3815     return;
3816   }
3817 
3818   SDValue Agg = getValue(Op0);
3819   unsigned i = 0;
3820   // Copy the beginning value(s) from the original aggregate.
3821   for (; i != LinearIndex; ++i)
3822     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3823                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3824   // Copy values from the inserted value(s).
3825   if (NumValValues) {
3826     SDValue Val = getValue(Op1);
3827     for (; i != LinearIndex + NumValValues; ++i)
3828       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3829                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3830   }
3831   // Copy remaining value(s) from the original aggregate.
3832   for (; i != NumAggValues; ++i)
3833     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3834                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3835 
3836   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3837                            DAG.getVTList(AggValueVTs), Values));
3838 }
3839 
3840 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3841   ArrayRef<unsigned> Indices = I.getIndices();
3842   const Value *Op0 = I.getOperand(0);
3843   Type *AggTy = Op0->getType();
3844   Type *ValTy = I.getType();
3845   bool OutOfUndef = isa<UndefValue>(Op0);
3846 
3847   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3848 
3849   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3850   SmallVector<EVT, 4> ValValueVTs;
3851   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3852 
3853   unsigned NumValValues = ValValueVTs.size();
3854 
3855   // Ignore a extractvalue that produces an empty object
3856   if (!NumValValues) {
3857     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3858     return;
3859   }
3860 
3861   SmallVector<SDValue, 4> Values(NumValValues);
3862 
3863   SDValue Agg = getValue(Op0);
3864   // Copy out the selected value(s).
3865   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3866     Values[i - LinearIndex] =
3867       OutOfUndef ?
3868         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3869         SDValue(Agg.getNode(), Agg.getResNo() + i);
3870 
3871   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3872                            DAG.getVTList(ValValueVTs), Values));
3873 }
3874 
3875 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3876   Value *Op0 = I.getOperand(0);
3877   // Note that the pointer operand may be a vector of pointers. Take the scalar
3878   // element which holds a pointer.
3879   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3880   SDValue N = getValue(Op0);
3881   SDLoc dl = getCurSDLoc();
3882   auto &TLI = DAG.getTargetLoweringInfo();
3883 
3884   // Normalize Vector GEP - all scalar operands should be converted to the
3885   // splat vector.
3886   bool IsVectorGEP = I.getType()->isVectorTy();
3887   ElementCount VectorElementCount =
3888       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3889                   : ElementCount::getFixed(0);
3890 
3891   if (IsVectorGEP && !N.getValueType().isVector()) {
3892     LLVMContext &Context = *DAG.getContext();
3893     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3894     N = DAG.getSplat(VT, dl, N);
3895   }
3896 
3897   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3898        GTI != E; ++GTI) {
3899     const Value *Idx = GTI.getOperand();
3900     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3901       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3902       if (Field) {
3903         // N = N + Offset
3904         uint64_t Offset =
3905             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3906 
3907         // In an inbounds GEP with an offset that is nonnegative even when
3908         // interpreted as signed, assume there is no unsigned overflow.
3909         SDNodeFlags Flags;
3910         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3911           Flags.setNoUnsignedWrap(true);
3912 
3913         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3914                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3915       }
3916     } else {
3917       // IdxSize is the width of the arithmetic according to IR semantics.
3918       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3919       // (and fix up the result later).
3920       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3921       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3922       TypeSize ElementSize =
3923           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3924       // We intentionally mask away the high bits here; ElementSize may not
3925       // fit in IdxTy.
3926       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3927       bool ElementScalable = ElementSize.isScalable();
3928 
3929       // If this is a scalar constant or a splat vector of constants,
3930       // handle it quickly.
3931       const auto *C = dyn_cast<Constant>(Idx);
3932       if (C && isa<VectorType>(C->getType()))
3933         C = C->getSplatValue();
3934 
3935       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3936       if (CI && CI->isZero())
3937         continue;
3938       if (CI && !ElementScalable) {
3939         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3940         LLVMContext &Context = *DAG.getContext();
3941         SDValue OffsVal;
3942         if (IsVectorGEP)
3943           OffsVal = DAG.getConstant(
3944               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3945         else
3946           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3947 
3948         // In an inbounds GEP with an offset that is nonnegative even when
3949         // interpreted as signed, assume there is no unsigned overflow.
3950         SDNodeFlags Flags;
3951         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3952           Flags.setNoUnsignedWrap(true);
3953 
3954         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3955 
3956         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3957         continue;
3958       }
3959 
3960       // N = N + Idx * ElementMul;
3961       SDValue IdxN = getValue(Idx);
3962 
3963       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3964         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3965                                   VectorElementCount);
3966         IdxN = DAG.getSplat(VT, dl, IdxN);
3967       }
3968 
3969       // If the index is smaller or larger than intptr_t, truncate or extend
3970       // it.
3971       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3972 
3973       if (ElementScalable) {
3974         EVT VScaleTy = N.getValueType().getScalarType();
3975         SDValue VScale = DAG.getNode(
3976             ISD::VSCALE, dl, VScaleTy,
3977             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3978         if (IsVectorGEP)
3979           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3980         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3981       } else {
3982         // If this is a multiply by a power of two, turn it into a shl
3983         // immediately.  This is a very common case.
3984         if (ElementMul != 1) {
3985           if (ElementMul.isPowerOf2()) {
3986             unsigned Amt = ElementMul.logBase2();
3987             IdxN = DAG.getNode(ISD::SHL, dl,
3988                                N.getValueType(), IdxN,
3989                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3990           } else {
3991             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3992                                             IdxN.getValueType());
3993             IdxN = DAG.getNode(ISD::MUL, dl,
3994                                N.getValueType(), IdxN, Scale);
3995           }
3996         }
3997       }
3998 
3999       N = DAG.getNode(ISD::ADD, dl,
4000                       N.getValueType(), N, IdxN);
4001     }
4002   }
4003 
4004   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4005   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4006   if (IsVectorGEP) {
4007     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4008     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4009   }
4010 
4011   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4012     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4013 
4014   setValue(&I, N);
4015 }
4016 
4017 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4018   // If this is a fixed sized alloca in the entry block of the function,
4019   // allocate it statically on the stack.
4020   if (FuncInfo.StaticAllocaMap.count(&I))
4021     return;   // getValue will auto-populate this.
4022 
4023   SDLoc dl = getCurSDLoc();
4024   Type *Ty = I.getAllocatedType();
4025   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4026   auto &DL = DAG.getDataLayout();
4027   TypeSize TySize = DL.getTypeAllocSize(Ty);
4028   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4029 
4030   SDValue AllocSize = getValue(I.getArraySize());
4031 
4032   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4033   if (AllocSize.getValueType() != IntPtr)
4034     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4035 
4036   if (TySize.isScalable())
4037     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4038                             DAG.getVScale(dl, IntPtr,
4039                                           APInt(IntPtr.getScalarSizeInBits(),
4040                                                 TySize.getKnownMinValue())));
4041   else
4042     AllocSize =
4043         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4044                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4045 
4046   // Handle alignment.  If the requested alignment is less than or equal to
4047   // the stack alignment, ignore it.  If the size is greater than or equal to
4048   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4049   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4050   if (*Alignment <= StackAlign)
4051     Alignment = None;
4052 
4053   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4054   // Round the size of the allocation up to the stack alignment size
4055   // by add SA-1 to the size. This doesn't overflow because we're computing
4056   // an address inside an alloca.
4057   SDNodeFlags Flags;
4058   Flags.setNoUnsignedWrap(true);
4059   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4060                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4061 
4062   // Mask out the low bits for alignment purposes.
4063   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4064                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4065 
4066   SDValue Ops[] = {
4067       getRoot(), AllocSize,
4068       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4069   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4070   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4071   setValue(&I, DSA);
4072   DAG.setRoot(DSA.getValue(1));
4073 
4074   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4075 }
4076 
4077 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4078   if (I.isAtomic())
4079     return visitAtomicLoad(I);
4080 
4081   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4082   const Value *SV = I.getOperand(0);
4083   if (TLI.supportSwiftError()) {
4084     // Swifterror values can come from either a function parameter with
4085     // swifterror attribute or an alloca with swifterror attribute.
4086     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4087       if (Arg->hasSwiftErrorAttr())
4088         return visitLoadFromSwiftError(I);
4089     }
4090 
4091     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4092       if (Alloca->isSwiftError())
4093         return visitLoadFromSwiftError(I);
4094     }
4095   }
4096 
4097   SDValue Ptr = getValue(SV);
4098 
4099   Type *Ty = I.getType();
4100   SmallVector<EVT, 4> ValueVTs, MemVTs;
4101   SmallVector<uint64_t, 4> Offsets;
4102   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4103   unsigned NumValues = ValueVTs.size();
4104   if (NumValues == 0)
4105     return;
4106 
4107   Align Alignment = I.getAlign();
4108   AAMDNodes AAInfo = I.getAAMetadata();
4109   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4110   bool isVolatile = I.isVolatile();
4111   MachineMemOperand::Flags MMOFlags =
4112       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4113 
4114   SDValue Root;
4115   bool ConstantMemory = false;
4116   if (isVolatile)
4117     // Serialize volatile loads with other side effects.
4118     Root = getRoot();
4119   else if (NumValues > MaxParallelChains)
4120     Root = getMemoryRoot();
4121   else if (AA &&
4122            AA->pointsToConstantMemory(MemoryLocation(
4123                SV,
4124                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4125                AAInfo))) {
4126     // Do not serialize (non-volatile) loads of constant memory with anything.
4127     Root = DAG.getEntryNode();
4128     ConstantMemory = true;
4129     MMOFlags |= MachineMemOperand::MOInvariant;
4130   } else {
4131     // Do not serialize non-volatile loads against each other.
4132     Root = DAG.getRoot();
4133   }
4134 
4135   if (isDereferenceableAndAlignedPointer(SV, Ty, Alignment, DAG.getDataLayout(),
4136                                          &I, AC, nullptr, LibInfo))
4137     MMOFlags |= MachineMemOperand::MODereferenceable;
4138 
4139   SDLoc dl = getCurSDLoc();
4140 
4141   if (isVolatile)
4142     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4143 
4144   // An aggregate load cannot wrap around the address space, so offsets to its
4145   // parts don't wrap either.
4146   SDNodeFlags Flags;
4147   Flags.setNoUnsignedWrap(true);
4148 
4149   SmallVector<SDValue, 4> Values(NumValues);
4150   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4151   EVT PtrVT = Ptr.getValueType();
4152 
4153   unsigned ChainI = 0;
4154   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4155     // Serializing loads here may result in excessive register pressure, and
4156     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4157     // could recover a bit by hoisting nodes upward in the chain by recognizing
4158     // they are side-effect free or do not alias. The optimizer should really
4159     // avoid this case by converting large object/array copies to llvm.memcpy
4160     // (MaxParallelChains should always remain as failsafe).
4161     if (ChainI == MaxParallelChains) {
4162       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4163       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4164                                   makeArrayRef(Chains.data(), ChainI));
4165       Root = Chain;
4166       ChainI = 0;
4167     }
4168     SDValue A = DAG.getNode(ISD::ADD, dl,
4169                             PtrVT, Ptr,
4170                             DAG.getConstant(Offsets[i], dl, PtrVT),
4171                             Flags);
4172 
4173     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4174                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4175                             MMOFlags, AAInfo, Ranges);
4176     Chains[ChainI] = L.getValue(1);
4177 
4178     if (MemVTs[i] != ValueVTs[i])
4179       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4180 
4181     Values[i] = L;
4182   }
4183 
4184   if (!ConstantMemory) {
4185     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4186                                 makeArrayRef(Chains.data(), ChainI));
4187     if (isVolatile)
4188       DAG.setRoot(Chain);
4189     else
4190       PendingLoads.push_back(Chain);
4191   }
4192 
4193   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4194                            DAG.getVTList(ValueVTs), Values));
4195 }
4196 
4197 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4198   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4199          "call visitStoreToSwiftError when backend supports swifterror");
4200 
4201   SmallVector<EVT, 4> ValueVTs;
4202   SmallVector<uint64_t, 4> Offsets;
4203   const Value *SrcV = I.getOperand(0);
4204   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4205                   SrcV->getType(), ValueVTs, &Offsets);
4206   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4207          "expect a single EVT for swifterror");
4208 
4209   SDValue Src = getValue(SrcV);
4210   // Create a virtual register, then update the virtual register.
4211   Register VReg =
4212       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4213   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4214   // Chain can be getRoot or getControlRoot.
4215   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4216                                       SDValue(Src.getNode(), Src.getResNo()));
4217   DAG.setRoot(CopyNode);
4218 }
4219 
4220 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4221   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4222          "call visitLoadFromSwiftError when backend supports swifterror");
4223 
4224   assert(!I.isVolatile() &&
4225          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4226          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4227          "Support volatile, non temporal, invariant for load_from_swift_error");
4228 
4229   const Value *SV = I.getOperand(0);
4230   Type *Ty = I.getType();
4231   assert(
4232       (!AA ||
4233        !AA->pointsToConstantMemory(MemoryLocation(
4234            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4235            I.getAAMetadata()))) &&
4236       "load_from_swift_error should not be constant memory");
4237 
4238   SmallVector<EVT, 4> ValueVTs;
4239   SmallVector<uint64_t, 4> Offsets;
4240   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4241                   ValueVTs, &Offsets);
4242   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4243          "expect a single EVT for swifterror");
4244 
4245   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4246   SDValue L = DAG.getCopyFromReg(
4247       getRoot(), getCurSDLoc(),
4248       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4249 
4250   setValue(&I, L);
4251 }
4252 
4253 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4254   if (I.isAtomic())
4255     return visitAtomicStore(I);
4256 
4257   const Value *SrcV = I.getOperand(0);
4258   const Value *PtrV = I.getOperand(1);
4259 
4260   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4261   if (TLI.supportSwiftError()) {
4262     // Swifterror values can come from either a function parameter with
4263     // swifterror attribute or an alloca with swifterror attribute.
4264     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4265       if (Arg->hasSwiftErrorAttr())
4266         return visitStoreToSwiftError(I);
4267     }
4268 
4269     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4270       if (Alloca->isSwiftError())
4271         return visitStoreToSwiftError(I);
4272     }
4273   }
4274 
4275   SmallVector<EVT, 4> ValueVTs, MemVTs;
4276   SmallVector<uint64_t, 4> Offsets;
4277   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4278                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4279   unsigned NumValues = ValueVTs.size();
4280   if (NumValues == 0)
4281     return;
4282 
4283   // Get the lowered operands. Note that we do this after
4284   // checking if NumResults is zero, because with zero results
4285   // the operands won't have values in the map.
4286   SDValue Src = getValue(SrcV);
4287   SDValue Ptr = getValue(PtrV);
4288 
4289   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4290   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4291   SDLoc dl = getCurSDLoc();
4292   Align Alignment = I.getAlign();
4293   AAMDNodes AAInfo = I.getAAMetadata();
4294 
4295   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4296 
4297   // An aggregate load cannot wrap around the address space, so offsets to its
4298   // parts don't wrap either.
4299   SDNodeFlags Flags;
4300   Flags.setNoUnsignedWrap(true);
4301 
4302   unsigned ChainI = 0;
4303   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4304     // See visitLoad comments.
4305     if (ChainI == MaxParallelChains) {
4306       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4307                                   makeArrayRef(Chains.data(), ChainI));
4308       Root = Chain;
4309       ChainI = 0;
4310     }
4311     SDValue Add =
4312         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4313     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4314     if (MemVTs[i] != ValueVTs[i])
4315       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4316     SDValue St =
4317         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4318                      Alignment, MMOFlags, AAInfo);
4319     Chains[ChainI] = St;
4320   }
4321 
4322   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4323                                   makeArrayRef(Chains.data(), ChainI));
4324   setValue(&I, StoreNode);
4325   DAG.setRoot(StoreNode);
4326 }
4327 
4328 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4329                                            bool IsCompressing) {
4330   SDLoc sdl = getCurSDLoc();
4331 
4332   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4333                                MaybeAlign &Alignment) {
4334     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4335     Src0 = I.getArgOperand(0);
4336     Ptr = I.getArgOperand(1);
4337     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4338     Mask = I.getArgOperand(3);
4339   };
4340   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4341                                     MaybeAlign &Alignment) {
4342     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4343     Src0 = I.getArgOperand(0);
4344     Ptr = I.getArgOperand(1);
4345     Mask = I.getArgOperand(2);
4346     Alignment = None;
4347   };
4348 
4349   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4350   MaybeAlign Alignment;
4351   if (IsCompressing)
4352     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4353   else
4354     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4355 
4356   SDValue Ptr = getValue(PtrOperand);
4357   SDValue Src0 = getValue(Src0Operand);
4358   SDValue Mask = getValue(MaskOperand);
4359   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4360 
4361   EVT VT = Src0.getValueType();
4362   if (!Alignment)
4363     Alignment = DAG.getEVTAlign(VT);
4364 
4365   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4366       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4367       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4368   SDValue StoreNode =
4369       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4370                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4371   DAG.setRoot(StoreNode);
4372   setValue(&I, StoreNode);
4373 }
4374 
4375 // Get a uniform base for the Gather/Scatter intrinsic.
4376 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4377 // We try to represent it as a base pointer + vector of indices.
4378 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4379 // The first operand of the GEP may be a single pointer or a vector of pointers
4380 // Example:
4381 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4382 //  or
4383 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4384 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4385 //
4386 // When the first GEP operand is a single pointer - it is the uniform base we
4387 // are looking for. If first operand of the GEP is a splat vector - we
4388 // extract the splat value and use it as a uniform base.
4389 // In all other cases the function returns 'false'.
4390 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4391                            ISD::MemIndexType &IndexType, SDValue &Scale,
4392                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4393                            uint64_t ElemSize) {
4394   SelectionDAG& DAG = SDB->DAG;
4395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4396   const DataLayout &DL = DAG.getDataLayout();
4397 
4398   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4399 
4400   // Handle splat constant pointer.
4401   if (auto *C = dyn_cast<Constant>(Ptr)) {
4402     C = C->getSplatValue();
4403     if (!C)
4404       return false;
4405 
4406     Base = SDB->getValue(C);
4407 
4408     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4409     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4410     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4411     IndexType = ISD::SIGNED_SCALED;
4412     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4413     return true;
4414   }
4415 
4416   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4417   if (!GEP || GEP->getParent() != CurBB)
4418     return false;
4419 
4420   if (GEP->getNumOperands() != 2)
4421     return false;
4422 
4423   const Value *BasePtr = GEP->getPointerOperand();
4424   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4425 
4426   // Make sure the base is scalar and the index is a vector.
4427   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4428     return false;
4429 
4430   uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4431 
4432   // Target may not support the required addressing mode.
4433   if (ScaleVal != 1 &&
4434       !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize))
4435     return false;
4436 
4437   Base = SDB->getValue(BasePtr);
4438   Index = SDB->getValue(IndexVal);
4439   IndexType = ISD::SIGNED_SCALED;
4440 
4441   Scale =
4442       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4443   return true;
4444 }
4445 
4446 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4447   SDLoc sdl = getCurSDLoc();
4448 
4449   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4450   const Value *Ptr = I.getArgOperand(1);
4451   SDValue Src0 = getValue(I.getArgOperand(0));
4452   SDValue Mask = getValue(I.getArgOperand(3));
4453   EVT VT = Src0.getValueType();
4454   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4455                         ->getMaybeAlignValue()
4456                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4457   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4458 
4459   SDValue Base;
4460   SDValue Index;
4461   ISD::MemIndexType IndexType;
4462   SDValue Scale;
4463   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4464                                     I.getParent(), VT.getScalarStoreSize());
4465 
4466   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4467   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4468       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4469       // TODO: Make MachineMemOperands aware of scalable
4470       // vectors.
4471       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4472   if (!UniformBase) {
4473     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4474     Index = getValue(Ptr);
4475     IndexType = ISD::SIGNED_SCALED;
4476     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4477   }
4478 
4479   EVT IdxVT = Index.getValueType();
4480   EVT EltTy = IdxVT.getVectorElementType();
4481   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4482     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4483     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4484   }
4485 
4486   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4487   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4488                                          Ops, MMO, IndexType, false);
4489   DAG.setRoot(Scatter);
4490   setValue(&I, Scatter);
4491 }
4492 
4493 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4494   SDLoc sdl = getCurSDLoc();
4495 
4496   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4497                               MaybeAlign &Alignment) {
4498     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4499     Ptr = I.getArgOperand(0);
4500     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4501     Mask = I.getArgOperand(2);
4502     Src0 = I.getArgOperand(3);
4503   };
4504   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4505                                  MaybeAlign &Alignment) {
4506     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4507     Ptr = I.getArgOperand(0);
4508     Alignment = None;
4509     Mask = I.getArgOperand(1);
4510     Src0 = I.getArgOperand(2);
4511   };
4512 
4513   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4514   MaybeAlign Alignment;
4515   if (IsExpanding)
4516     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4517   else
4518     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4519 
4520   SDValue Ptr = getValue(PtrOperand);
4521   SDValue Src0 = getValue(Src0Operand);
4522   SDValue Mask = getValue(MaskOperand);
4523   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4524 
4525   EVT VT = Src0.getValueType();
4526   if (!Alignment)
4527     Alignment = DAG.getEVTAlign(VT);
4528 
4529   AAMDNodes AAInfo = I.getAAMetadata();
4530   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4531 
4532   // Do not serialize masked loads of constant memory with anything.
4533   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4534   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4535 
4536   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4537 
4538   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4539       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4540       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4541 
4542   SDValue Load =
4543       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4544                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4545   if (AddToChain)
4546     PendingLoads.push_back(Load.getValue(1));
4547   setValue(&I, Load);
4548 }
4549 
4550 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4551   SDLoc sdl = getCurSDLoc();
4552 
4553   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4554   const Value *Ptr = I.getArgOperand(0);
4555   SDValue Src0 = getValue(I.getArgOperand(3));
4556   SDValue Mask = getValue(I.getArgOperand(2));
4557 
4558   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4559   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4560   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4561                         ->getMaybeAlignValue()
4562                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4563 
4564   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4565 
4566   SDValue Root = DAG.getRoot();
4567   SDValue Base;
4568   SDValue Index;
4569   ISD::MemIndexType IndexType;
4570   SDValue Scale;
4571   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4572                                     I.getParent(), VT.getScalarStoreSize());
4573   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4574   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4575       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4576       // TODO: Make MachineMemOperands aware of scalable
4577       // vectors.
4578       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4579 
4580   if (!UniformBase) {
4581     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4582     Index = getValue(Ptr);
4583     IndexType = ISD::SIGNED_SCALED;
4584     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4585   }
4586 
4587   EVT IdxVT = Index.getValueType();
4588   EVT EltTy = IdxVT.getVectorElementType();
4589   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4590     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4591     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4592   }
4593 
4594   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4595   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4596                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4597 
4598   PendingLoads.push_back(Gather.getValue(1));
4599   setValue(&I, Gather);
4600 }
4601 
4602 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4603   SDLoc dl = getCurSDLoc();
4604   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4605   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4606   SyncScope::ID SSID = I.getSyncScopeID();
4607 
4608   SDValue InChain = getRoot();
4609 
4610   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4611   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4612 
4613   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4614   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4615 
4616   MachineFunction &MF = DAG.getMachineFunction();
4617   MachineMemOperand *MMO = MF.getMachineMemOperand(
4618       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4619       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4620       FailureOrdering);
4621 
4622   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4623                                    dl, MemVT, VTs, InChain,
4624                                    getValue(I.getPointerOperand()),
4625                                    getValue(I.getCompareOperand()),
4626                                    getValue(I.getNewValOperand()), MMO);
4627 
4628   SDValue OutChain = L.getValue(2);
4629 
4630   setValue(&I, L);
4631   DAG.setRoot(OutChain);
4632 }
4633 
4634 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4635   SDLoc dl = getCurSDLoc();
4636   ISD::NodeType NT;
4637   switch (I.getOperation()) {
4638   default: llvm_unreachable("Unknown atomicrmw operation");
4639   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4640   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4641   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4642   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4643   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4644   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4645   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4646   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4647   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4648   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4649   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4650   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4651   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4652   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4653   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4654   }
4655   AtomicOrdering Ordering = I.getOrdering();
4656   SyncScope::ID SSID = I.getSyncScopeID();
4657 
4658   SDValue InChain = getRoot();
4659 
4660   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4661   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4662   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4663 
4664   MachineFunction &MF = DAG.getMachineFunction();
4665   MachineMemOperand *MMO = MF.getMachineMemOperand(
4666       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4667       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4668 
4669   SDValue L =
4670     DAG.getAtomic(NT, dl, MemVT, InChain,
4671                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4672                   MMO);
4673 
4674   SDValue OutChain = L.getValue(1);
4675 
4676   setValue(&I, L);
4677   DAG.setRoot(OutChain);
4678 }
4679 
4680 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4681   SDLoc dl = getCurSDLoc();
4682   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4683   SDValue Ops[3];
4684   Ops[0] = getRoot();
4685   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4686                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4687   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4688                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4689   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4690   setValue(&I, N);
4691   DAG.setRoot(N);
4692 }
4693 
4694 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4695   SDLoc dl = getCurSDLoc();
4696   AtomicOrdering Order = I.getOrdering();
4697   SyncScope::ID SSID = I.getSyncScopeID();
4698 
4699   SDValue InChain = getRoot();
4700 
4701   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4702   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4703   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4704 
4705   if (!TLI.supportsUnalignedAtomics() &&
4706       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4707     report_fatal_error("Cannot generate unaligned atomic load");
4708 
4709   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4710 
4711   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4712       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4713       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4714 
4715   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4716 
4717   SDValue Ptr = getValue(I.getPointerOperand());
4718 
4719   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4720     // TODO: Once this is better exercised by tests, it should be merged with
4721     // the normal path for loads to prevent future divergence.
4722     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4723     if (MemVT != VT)
4724       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4725 
4726     setValue(&I, L);
4727     SDValue OutChain = L.getValue(1);
4728     if (!I.isUnordered())
4729       DAG.setRoot(OutChain);
4730     else
4731       PendingLoads.push_back(OutChain);
4732     return;
4733   }
4734 
4735   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4736                             Ptr, MMO);
4737 
4738   SDValue OutChain = L.getValue(1);
4739   if (MemVT != VT)
4740     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4741 
4742   setValue(&I, L);
4743   DAG.setRoot(OutChain);
4744 }
4745 
4746 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4747   SDLoc dl = getCurSDLoc();
4748 
4749   AtomicOrdering Ordering = I.getOrdering();
4750   SyncScope::ID SSID = I.getSyncScopeID();
4751 
4752   SDValue InChain = getRoot();
4753 
4754   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4755   EVT MemVT =
4756       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4757 
4758   if (!TLI.supportsUnalignedAtomics() &&
4759       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4760     report_fatal_error("Cannot generate unaligned atomic store");
4761 
4762   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4763 
4764   MachineFunction &MF = DAG.getMachineFunction();
4765   MachineMemOperand *MMO = MF.getMachineMemOperand(
4766       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4767       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4768 
4769   SDValue Val = getValue(I.getValueOperand());
4770   if (Val.getValueType() != MemVT)
4771     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4772   SDValue Ptr = getValue(I.getPointerOperand());
4773 
4774   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4775     // TODO: Once this is better exercised by tests, it should be merged with
4776     // the normal path for stores to prevent future divergence.
4777     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4778     setValue(&I, S);
4779     DAG.setRoot(S);
4780     return;
4781   }
4782   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4783                                    Ptr, Val, MMO);
4784 
4785   setValue(&I, OutChain);
4786   DAG.setRoot(OutChain);
4787 }
4788 
4789 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4790 /// node.
4791 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4792                                                unsigned Intrinsic) {
4793   // Ignore the callsite's attributes. A specific call site may be marked with
4794   // readnone, but the lowering code will expect the chain based on the
4795   // definition.
4796   const Function *F = I.getCalledFunction();
4797   bool HasChain = !F->doesNotAccessMemory();
4798   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4799 
4800   // Build the operand list.
4801   SmallVector<SDValue, 8> Ops;
4802   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4803     if (OnlyLoad) {
4804       // We don't need to serialize loads against other loads.
4805       Ops.push_back(DAG.getRoot());
4806     } else {
4807       Ops.push_back(getRoot());
4808     }
4809   }
4810 
4811   // Info is set by getTgtMemIntrinsic
4812   TargetLowering::IntrinsicInfo Info;
4813   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4814   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4815                                                DAG.getMachineFunction(),
4816                                                Intrinsic);
4817 
4818   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4819   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4820       Info.opc == ISD::INTRINSIC_W_CHAIN)
4821     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4822                                         TLI.getPointerTy(DAG.getDataLayout())));
4823 
4824   // Add all operands of the call to the operand list.
4825   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4826     const Value *Arg = I.getArgOperand(i);
4827     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4828       Ops.push_back(getValue(Arg));
4829       continue;
4830     }
4831 
4832     // Use TargetConstant instead of a regular constant for immarg.
4833     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4834     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4835       assert(CI->getBitWidth() <= 64 &&
4836              "large intrinsic immediates not handled");
4837       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4838     } else {
4839       Ops.push_back(
4840           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4841     }
4842   }
4843 
4844   SmallVector<EVT, 4> ValueVTs;
4845   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4846 
4847   if (HasChain)
4848     ValueVTs.push_back(MVT::Other);
4849 
4850   SDVTList VTs = DAG.getVTList(ValueVTs);
4851 
4852   // Propagate fast-math-flags from IR to node(s).
4853   SDNodeFlags Flags;
4854   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4855     Flags.copyFMF(*FPMO);
4856   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4857 
4858   // Create the node.
4859   SDValue Result;
4860   // In some cases, custom collection of operands from CallInst I may be needed.
4861   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4862   if (IsTgtIntrinsic) {
4863     // This is target intrinsic that touches memory
4864     Result =
4865         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4866                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4867                                 Info.align, Info.flags, Info.size,
4868                                 I.getAAMetadata());
4869   } else if (!HasChain) {
4870     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4871   } else if (!I.getType()->isVoidTy()) {
4872     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4873   } else {
4874     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4875   }
4876 
4877   if (HasChain) {
4878     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4879     if (OnlyLoad)
4880       PendingLoads.push_back(Chain);
4881     else
4882       DAG.setRoot(Chain);
4883   }
4884 
4885   if (!I.getType()->isVoidTy()) {
4886     if (!isa<VectorType>(I.getType()))
4887       Result = lowerRangeToAssertZExt(DAG, I, Result);
4888 
4889     MaybeAlign Alignment = I.getRetAlign();
4890     if (!Alignment)
4891       Alignment = F->getAttributes().getRetAlignment();
4892     // Insert `assertalign` node if there's an alignment.
4893     if (InsertAssertAlign && Alignment) {
4894       Result =
4895           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4896     }
4897 
4898     setValue(&I, Result);
4899   }
4900 }
4901 
4902 /// GetSignificand - Get the significand and build it into a floating-point
4903 /// number with exponent of 1:
4904 ///
4905 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4906 ///
4907 /// where Op is the hexadecimal representation of floating point value.
4908 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4909   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4910                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4911   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4912                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4913   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4914 }
4915 
4916 /// GetExponent - Get the exponent:
4917 ///
4918 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4919 ///
4920 /// where Op is the hexadecimal representation of floating point value.
4921 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4922                            const TargetLowering &TLI, const SDLoc &dl) {
4923   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4924                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4925   SDValue t1 = DAG.getNode(
4926       ISD::SRL, dl, MVT::i32, t0,
4927       DAG.getConstant(23, dl,
4928                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
4929   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4930                            DAG.getConstant(127, dl, MVT::i32));
4931   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4932 }
4933 
4934 /// getF32Constant - Get 32-bit floating point constant.
4935 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4936                               const SDLoc &dl) {
4937   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4938                            MVT::f32);
4939 }
4940 
4941 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4942                                        SelectionDAG &DAG) {
4943   // TODO: What fast-math-flags should be set on the floating-point nodes?
4944 
4945   //   IntegerPartOfX = ((int32_t)(t0);
4946   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4947 
4948   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4949   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4950   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4951 
4952   //   IntegerPartOfX <<= 23;
4953   IntegerPartOfX =
4954       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4955                   DAG.getConstant(23, dl,
4956                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
4957                                       MVT::i32, DAG.getDataLayout())));
4958 
4959   SDValue TwoToFractionalPartOfX;
4960   if (LimitFloatPrecision <= 6) {
4961     // For floating-point precision of 6:
4962     //
4963     //   TwoToFractionalPartOfX =
4964     //     0.997535578f +
4965     //       (0.735607626f + 0.252464424f * x) * x;
4966     //
4967     // error 0.0144103317, which is 6 bits
4968     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4969                              getF32Constant(DAG, 0x3e814304, dl));
4970     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4971                              getF32Constant(DAG, 0x3f3c50c8, dl));
4972     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4973     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4974                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4975   } else if (LimitFloatPrecision <= 12) {
4976     // For floating-point precision of 12:
4977     //
4978     //   TwoToFractionalPartOfX =
4979     //     0.999892986f +
4980     //       (0.696457318f +
4981     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4982     //
4983     // error 0.000107046256, which is 13 to 14 bits
4984     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4985                              getF32Constant(DAG, 0x3da235e3, dl));
4986     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4987                              getF32Constant(DAG, 0x3e65b8f3, dl));
4988     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4989     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4990                              getF32Constant(DAG, 0x3f324b07, dl));
4991     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4992     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4993                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4994   } else { // LimitFloatPrecision <= 18
4995     // For floating-point precision of 18:
4996     //
4997     //   TwoToFractionalPartOfX =
4998     //     0.999999982f +
4999     //       (0.693148872f +
5000     //         (0.240227044f +
5001     //           (0.554906021e-1f +
5002     //             (0.961591928e-2f +
5003     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5004     // error 2.47208000*10^(-7), which is better than 18 bits
5005     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5006                              getF32Constant(DAG, 0x3924b03e, dl));
5007     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5008                              getF32Constant(DAG, 0x3ab24b87, dl));
5009     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5010     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5011                              getF32Constant(DAG, 0x3c1d8c17, dl));
5012     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5013     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5014                              getF32Constant(DAG, 0x3d634a1d, dl));
5015     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5016     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5017                              getF32Constant(DAG, 0x3e75fe14, dl));
5018     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5019     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5020                               getF32Constant(DAG, 0x3f317234, dl));
5021     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5022     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5023                                          getF32Constant(DAG, 0x3f800000, dl));
5024   }
5025 
5026   // Add the exponent into the result in integer domain.
5027   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5028   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5029                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5030 }
5031 
5032 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5033 /// limited-precision mode.
5034 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5035                          const TargetLowering &TLI, SDNodeFlags Flags) {
5036   if (Op.getValueType() == MVT::f32 &&
5037       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5038 
5039     // Put the exponent in the right bit position for later addition to the
5040     // final result:
5041     //
5042     // t0 = Op * log2(e)
5043 
5044     // TODO: What fast-math-flags should be set here?
5045     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5046                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5047     return getLimitedPrecisionExp2(t0, dl, DAG);
5048   }
5049 
5050   // No special expansion.
5051   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5052 }
5053 
5054 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5055 /// limited-precision mode.
5056 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5057                          const TargetLowering &TLI, SDNodeFlags Flags) {
5058   // TODO: What fast-math-flags should be set on the floating-point nodes?
5059 
5060   if (Op.getValueType() == MVT::f32 &&
5061       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5062     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5063 
5064     // Scale the exponent by log(2).
5065     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5066     SDValue LogOfExponent =
5067         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5068                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5069 
5070     // Get the significand and build it into a floating-point number with
5071     // exponent of 1.
5072     SDValue X = GetSignificand(DAG, Op1, dl);
5073 
5074     SDValue LogOfMantissa;
5075     if (LimitFloatPrecision <= 6) {
5076       // For floating-point precision of 6:
5077       //
5078       //   LogofMantissa =
5079       //     -1.1609546f +
5080       //       (1.4034025f - 0.23903021f * x) * x;
5081       //
5082       // error 0.0034276066, which is better than 8 bits
5083       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5084                                getF32Constant(DAG, 0xbe74c456, dl));
5085       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5086                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5087       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5088       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5089                                   getF32Constant(DAG, 0x3f949a29, dl));
5090     } else if (LimitFloatPrecision <= 12) {
5091       // For floating-point precision of 12:
5092       //
5093       //   LogOfMantissa =
5094       //     -1.7417939f +
5095       //       (2.8212026f +
5096       //         (-1.4699568f +
5097       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5098       //
5099       // error 0.000061011436, which is 14 bits
5100       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5101                                getF32Constant(DAG, 0xbd67b6d6, dl));
5102       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5103                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5104       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5105       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5106                                getF32Constant(DAG, 0x3fbc278b, dl));
5107       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5108       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5109                                getF32Constant(DAG, 0x40348e95, dl));
5110       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5111       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5112                                   getF32Constant(DAG, 0x3fdef31a, dl));
5113     } else { // LimitFloatPrecision <= 18
5114       // For floating-point precision of 18:
5115       //
5116       //   LogOfMantissa =
5117       //     -2.1072184f +
5118       //       (4.2372794f +
5119       //         (-3.7029485f +
5120       //           (2.2781945f +
5121       //             (-0.87823314f +
5122       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5123       //
5124       // error 0.0000023660568, which is better than 18 bits
5125       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5126                                getF32Constant(DAG, 0xbc91e5ac, dl));
5127       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5128                                getF32Constant(DAG, 0x3e4350aa, dl));
5129       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5130       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5131                                getF32Constant(DAG, 0x3f60d3e3, dl));
5132       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5133       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5134                                getF32Constant(DAG, 0x4011cdf0, dl));
5135       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5136       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5137                                getF32Constant(DAG, 0x406cfd1c, dl));
5138       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5139       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5140                                getF32Constant(DAG, 0x408797cb, dl));
5141       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5142       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5143                                   getF32Constant(DAG, 0x4006dcab, dl));
5144     }
5145 
5146     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5147   }
5148 
5149   // No special expansion.
5150   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5151 }
5152 
5153 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5154 /// limited-precision mode.
5155 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5156                           const TargetLowering &TLI, SDNodeFlags Flags) {
5157   // TODO: What fast-math-flags should be set on the floating-point nodes?
5158 
5159   if (Op.getValueType() == MVT::f32 &&
5160       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5161     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5162 
5163     // Get the exponent.
5164     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5165 
5166     // Get the significand and build it into a floating-point number with
5167     // exponent of 1.
5168     SDValue X = GetSignificand(DAG, Op1, dl);
5169 
5170     // Different possible minimax approximations of significand in
5171     // floating-point for various degrees of accuracy over [1,2].
5172     SDValue Log2ofMantissa;
5173     if (LimitFloatPrecision <= 6) {
5174       // For floating-point precision of 6:
5175       //
5176       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5177       //
5178       // error 0.0049451742, which is more than 7 bits
5179       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5180                                getF32Constant(DAG, 0xbeb08fe0, dl));
5181       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5182                                getF32Constant(DAG, 0x40019463, dl));
5183       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5184       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5185                                    getF32Constant(DAG, 0x3fd6633d, dl));
5186     } else if (LimitFloatPrecision <= 12) {
5187       // For floating-point precision of 12:
5188       //
5189       //   Log2ofMantissa =
5190       //     -2.51285454f +
5191       //       (4.07009056f +
5192       //         (-2.12067489f +
5193       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5194       //
5195       // error 0.0000876136000, which is better than 13 bits
5196       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5197                                getF32Constant(DAG, 0xbda7262e, dl));
5198       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5199                                getF32Constant(DAG, 0x3f25280b, dl));
5200       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5201       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5202                                getF32Constant(DAG, 0x4007b923, dl));
5203       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5204       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5205                                getF32Constant(DAG, 0x40823e2f, dl));
5206       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5207       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5208                                    getF32Constant(DAG, 0x4020d29c, dl));
5209     } else { // LimitFloatPrecision <= 18
5210       // For floating-point precision of 18:
5211       //
5212       //   Log2ofMantissa =
5213       //     -3.0400495f +
5214       //       (6.1129976f +
5215       //         (-5.3420409f +
5216       //           (3.2865683f +
5217       //             (-1.2669343f +
5218       //               (0.27515199f -
5219       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5220       //
5221       // error 0.0000018516, which is better than 18 bits
5222       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5223                                getF32Constant(DAG, 0xbcd2769e, dl));
5224       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5225                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5226       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5227       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5228                                getF32Constant(DAG, 0x3fa22ae7, dl));
5229       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5230       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5231                                getF32Constant(DAG, 0x40525723, dl));
5232       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5233       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5234                                getF32Constant(DAG, 0x40aaf200, dl));
5235       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5236       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5237                                getF32Constant(DAG, 0x40c39dad, dl));
5238       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5239       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5240                                    getF32Constant(DAG, 0x4042902c, dl));
5241     }
5242 
5243     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5244   }
5245 
5246   // No special expansion.
5247   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5248 }
5249 
5250 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5251 /// limited-precision mode.
5252 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5253                            const TargetLowering &TLI, SDNodeFlags Flags) {
5254   // TODO: What fast-math-flags should be set on the floating-point nodes?
5255 
5256   if (Op.getValueType() == MVT::f32 &&
5257       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5258     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5259 
5260     // Scale the exponent by log10(2) [0.30102999f].
5261     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5262     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5263                                         getF32Constant(DAG, 0x3e9a209a, dl));
5264 
5265     // Get the significand and build it into a floating-point number with
5266     // exponent of 1.
5267     SDValue X = GetSignificand(DAG, Op1, dl);
5268 
5269     SDValue Log10ofMantissa;
5270     if (LimitFloatPrecision <= 6) {
5271       // For floating-point precision of 6:
5272       //
5273       //   Log10ofMantissa =
5274       //     -0.50419619f +
5275       //       (0.60948995f - 0.10380950f * x) * x;
5276       //
5277       // error 0.0014886165, which is 6 bits
5278       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5279                                getF32Constant(DAG, 0xbdd49a13, dl));
5280       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5281                                getF32Constant(DAG, 0x3f1c0789, dl));
5282       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5283       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5284                                     getF32Constant(DAG, 0x3f011300, dl));
5285     } else if (LimitFloatPrecision <= 12) {
5286       // For floating-point precision of 12:
5287       //
5288       //   Log10ofMantissa =
5289       //     -0.64831180f +
5290       //       (0.91751397f +
5291       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5292       //
5293       // error 0.00019228036, which is better than 12 bits
5294       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5295                                getF32Constant(DAG, 0x3d431f31, dl));
5296       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5297                                getF32Constant(DAG, 0x3ea21fb2, dl));
5298       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5299       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5300                                getF32Constant(DAG, 0x3f6ae232, dl));
5301       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5302       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5303                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5304     } else { // LimitFloatPrecision <= 18
5305       // For floating-point precision of 18:
5306       //
5307       //   Log10ofMantissa =
5308       //     -0.84299375f +
5309       //       (1.5327582f +
5310       //         (-1.0688956f +
5311       //           (0.49102474f +
5312       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5313       //
5314       // error 0.0000037995730, which is better than 18 bits
5315       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5316                                getF32Constant(DAG, 0x3c5d51ce, dl));
5317       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5318                                getF32Constant(DAG, 0x3e00685a, dl));
5319       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5320       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5321                                getF32Constant(DAG, 0x3efb6798, dl));
5322       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5323       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5324                                getF32Constant(DAG, 0x3f88d192, dl));
5325       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5326       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5327                                getF32Constant(DAG, 0x3fc4316c, dl));
5328       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5329       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5330                                     getF32Constant(DAG, 0x3f57ce70, dl));
5331     }
5332 
5333     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5334   }
5335 
5336   // No special expansion.
5337   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5338 }
5339 
5340 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5341 /// limited-precision mode.
5342 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5343                           const TargetLowering &TLI, SDNodeFlags Flags) {
5344   if (Op.getValueType() == MVT::f32 &&
5345       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5346     return getLimitedPrecisionExp2(Op, dl, DAG);
5347 
5348   // No special expansion.
5349   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5350 }
5351 
5352 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5353 /// limited-precision mode with x == 10.0f.
5354 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5355                          SelectionDAG &DAG, const TargetLowering &TLI,
5356                          SDNodeFlags Flags) {
5357   bool IsExp10 = false;
5358   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5359       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5360     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5361       APFloat Ten(10.0f);
5362       IsExp10 = LHSC->isExactlyValue(Ten);
5363     }
5364   }
5365 
5366   // TODO: What fast-math-flags should be set on the FMUL node?
5367   if (IsExp10) {
5368     // Put the exponent in the right bit position for later addition to the
5369     // final result:
5370     //
5371     //   #define LOG2OF10 3.3219281f
5372     //   t0 = Op * LOG2OF10;
5373     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5374                              getF32Constant(DAG, 0x40549a78, dl));
5375     return getLimitedPrecisionExp2(t0, dl, DAG);
5376   }
5377 
5378   // No special expansion.
5379   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5380 }
5381 
5382 /// ExpandPowI - Expand a llvm.powi intrinsic.
5383 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5384                           SelectionDAG &DAG) {
5385   // If RHS is a constant, we can expand this out to a multiplication tree if
5386   // it's beneficial on the target, otherwise we end up lowering to a call to
5387   // __powidf2 (for example).
5388   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5389     unsigned Val = RHSC->getSExtValue();
5390 
5391     // powi(x, 0) -> 1.0
5392     if (Val == 0)
5393       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5394 
5395     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5396             Val, DAG.shouldOptForSize())) {
5397       // Get the exponent as a positive value.
5398       if ((int)Val < 0)
5399         Val = -Val;
5400       // We use the simple binary decomposition method to generate the multiply
5401       // sequence.  There are more optimal ways to do this (for example,
5402       // powi(x,15) generates one more multiply than it should), but this has
5403       // the benefit of being both really simple and much better than a libcall.
5404       SDValue Res; // Logically starts equal to 1.0
5405       SDValue CurSquare = LHS;
5406       // TODO: Intrinsics should have fast-math-flags that propagate to these
5407       // nodes.
5408       while (Val) {
5409         if (Val & 1) {
5410           if (Res.getNode())
5411             Res =
5412                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5413           else
5414             Res = CurSquare; // 1.0*CurSquare.
5415         }
5416 
5417         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5418                                 CurSquare, CurSquare);
5419         Val >>= 1;
5420       }
5421 
5422       // If the original was negative, invert the result, producing 1/(x*x*x).
5423       if (RHSC->getSExtValue() < 0)
5424         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5425                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5426       return Res;
5427     }
5428   }
5429 
5430   // Otherwise, expand to a libcall.
5431   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5432 }
5433 
5434 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5435                             SDValue LHS, SDValue RHS, SDValue Scale,
5436                             SelectionDAG &DAG, const TargetLowering &TLI) {
5437   EVT VT = LHS.getValueType();
5438   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5439   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5440   LLVMContext &Ctx = *DAG.getContext();
5441 
5442   // If the type is legal but the operation isn't, this node might survive all
5443   // the way to operation legalization. If we end up there and we do not have
5444   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5445   // node.
5446 
5447   // Coax the legalizer into expanding the node during type legalization instead
5448   // by bumping the size by one bit. This will force it to Promote, enabling the
5449   // early expansion and avoiding the need to expand later.
5450 
5451   // We don't have to do this if Scale is 0; that can always be expanded, unless
5452   // it's a saturating signed operation. Those can experience true integer
5453   // division overflow, a case which we must avoid.
5454 
5455   // FIXME: We wouldn't have to do this (or any of the early
5456   // expansion/promotion) if it was possible to expand a libcall of an
5457   // illegal type during operation legalization. But it's not, so things
5458   // get a bit hacky.
5459   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5460   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5461       (TLI.isTypeLegal(VT) ||
5462        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5463     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5464         Opcode, VT, ScaleInt);
5465     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5466       EVT PromVT;
5467       if (VT.isScalarInteger())
5468         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5469       else if (VT.isVector()) {
5470         PromVT = VT.getVectorElementType();
5471         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5472         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5473       } else
5474         llvm_unreachable("Wrong VT for DIVFIX?");
5475       if (Signed) {
5476         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5477         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5478       } else {
5479         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5480         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5481       }
5482       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5483       // For saturating operations, we need to shift up the LHS to get the
5484       // proper saturation width, and then shift down again afterwards.
5485       if (Saturating)
5486         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5487                           DAG.getConstant(1, DL, ShiftTy));
5488       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5489       if (Saturating)
5490         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5491                           DAG.getConstant(1, DL, ShiftTy));
5492       return DAG.getZExtOrTrunc(Res, DL, VT);
5493     }
5494   }
5495 
5496   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5497 }
5498 
5499 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5500 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5501 static void
5502 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5503                      const SDValue &N) {
5504   switch (N.getOpcode()) {
5505   case ISD::CopyFromReg: {
5506     SDValue Op = N.getOperand(1);
5507     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5508                       Op.getValueType().getSizeInBits());
5509     return;
5510   }
5511   case ISD::BITCAST:
5512   case ISD::AssertZext:
5513   case ISD::AssertSext:
5514   case ISD::TRUNCATE:
5515     getUnderlyingArgRegs(Regs, N.getOperand(0));
5516     return;
5517   case ISD::BUILD_PAIR:
5518   case ISD::BUILD_VECTOR:
5519   case ISD::CONCAT_VECTORS:
5520     for (SDValue Op : N->op_values())
5521       getUnderlyingArgRegs(Regs, Op);
5522     return;
5523   default:
5524     return;
5525   }
5526 }
5527 
5528 /// If the DbgValueInst is a dbg_value of a function argument, create the
5529 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5530 /// instruction selection, they will be inserted to the entry BB.
5531 /// We don't currently support this for variadic dbg_values, as they shouldn't
5532 /// appear for function arguments or in the prologue.
5533 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5534     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5535     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5536   const Argument *Arg = dyn_cast<Argument>(V);
5537   if (!Arg)
5538     return false;
5539 
5540   MachineFunction &MF = DAG.getMachineFunction();
5541   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5542 
5543   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5544   // we've been asked to pursue.
5545   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5546                               bool Indirect) {
5547     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5548       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5549       // pointing at the VReg, which will be patched up later.
5550       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5551       auto MIB = BuildMI(MF, DL, Inst);
5552       MIB.addReg(Reg);
5553       MIB.addImm(0);
5554       MIB.addMetadata(Variable);
5555       auto *NewDIExpr = FragExpr;
5556       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5557       // the DIExpression.
5558       if (Indirect)
5559         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5560       MIB.addMetadata(NewDIExpr);
5561       return MIB;
5562     } else {
5563       // Create a completely standard DBG_VALUE.
5564       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5565       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5566     }
5567   };
5568 
5569   if (Kind == FuncArgumentDbgValueKind::Value) {
5570     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5571     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5572     // the entry block.
5573     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5574     if (!IsInEntryBlock)
5575       return false;
5576 
5577     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5578     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5579     // variable that also is a param.
5580     //
5581     // Although, if we are at the top of the entry block already, we can still
5582     // emit using ArgDbgValue. This might catch some situations when the
5583     // dbg.value refers to an argument that isn't used in the entry block, so
5584     // any CopyToReg node would be optimized out and the only way to express
5585     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5586     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5587     // we should only emit as ArgDbgValue if the Variable is an argument to the
5588     // current function, and the dbg.value intrinsic is found in the entry
5589     // block.
5590     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5591         !DL->getInlinedAt();
5592     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5593     if (!IsInPrologue && !VariableIsFunctionInputArg)
5594       return false;
5595 
5596     // Here we assume that a function argument on IR level only can be used to
5597     // describe one input parameter on source level. If we for example have
5598     // source code like this
5599     //
5600     //    struct A { long x, y; };
5601     //    void foo(struct A a, long b) {
5602     //      ...
5603     //      b = a.x;
5604     //      ...
5605     //    }
5606     //
5607     // and IR like this
5608     //
5609     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5610     //  entry:
5611     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5612     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5613     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5614     //    ...
5615     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5616     //    ...
5617     //
5618     // then the last dbg.value is describing a parameter "b" using a value that
5619     // is an argument. But since we already has used %a1 to describe a parameter
5620     // we should not handle that last dbg.value here (that would result in an
5621     // incorrect hoisting of the DBG_VALUE to the function entry).
5622     // Notice that we allow one dbg.value per IR level argument, to accommodate
5623     // for the situation with fragments above.
5624     if (VariableIsFunctionInputArg) {
5625       unsigned ArgNo = Arg->getArgNo();
5626       if (ArgNo >= FuncInfo.DescribedArgs.size())
5627         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5628       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5629         return false;
5630       FuncInfo.DescribedArgs.set(ArgNo);
5631     }
5632   }
5633 
5634   bool IsIndirect = false;
5635   Optional<MachineOperand> Op;
5636   // Some arguments' frame index is recorded during argument lowering.
5637   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5638   if (FI != std::numeric_limits<int>::max())
5639     Op = MachineOperand::CreateFI(FI);
5640 
5641   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5642   if (!Op && N.getNode()) {
5643     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5644     Register Reg;
5645     if (ArgRegsAndSizes.size() == 1)
5646       Reg = ArgRegsAndSizes.front().first;
5647 
5648     if (Reg && Reg.isVirtual()) {
5649       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5650       Register PR = RegInfo.getLiveInPhysReg(Reg);
5651       if (PR)
5652         Reg = PR;
5653     }
5654     if (Reg) {
5655       Op = MachineOperand::CreateReg(Reg, false);
5656       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5657     }
5658   }
5659 
5660   if (!Op && N.getNode()) {
5661     // Check if frame index is available.
5662     SDValue LCandidate = peekThroughBitcasts(N);
5663     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5664       if (FrameIndexSDNode *FINode =
5665           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5666         Op = MachineOperand::CreateFI(FINode->getIndex());
5667   }
5668 
5669   if (!Op) {
5670     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5671     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5672                                          SplitRegs) {
5673       unsigned Offset = 0;
5674       for (const auto &RegAndSize : SplitRegs) {
5675         // If the expression is already a fragment, the current register
5676         // offset+size might extend beyond the fragment. In this case, only
5677         // the register bits that are inside the fragment are relevant.
5678         int RegFragmentSizeInBits = RegAndSize.second;
5679         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5680           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5681           // The register is entirely outside the expression fragment,
5682           // so is irrelevant for debug info.
5683           if (Offset >= ExprFragmentSizeInBits)
5684             break;
5685           // The register is partially outside the expression fragment, only
5686           // the low bits within the fragment are relevant for debug info.
5687           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5688             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5689           }
5690         }
5691 
5692         auto FragmentExpr = DIExpression::createFragmentExpression(
5693             Expr, Offset, RegFragmentSizeInBits);
5694         Offset += RegAndSize.second;
5695         // If a valid fragment expression cannot be created, the variable's
5696         // correct value cannot be determined and so it is set as Undef.
5697         if (!FragmentExpr) {
5698           SDDbgValue *SDV = DAG.getConstantDbgValue(
5699               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5700           DAG.AddDbgValue(SDV, false);
5701           continue;
5702         }
5703         MachineInstr *NewMI =
5704             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5705                              Kind != FuncArgumentDbgValueKind::Value);
5706         FuncInfo.ArgDbgValues.push_back(NewMI);
5707       }
5708     };
5709 
5710     // Check if ValueMap has reg number.
5711     DenseMap<const Value *, Register>::const_iterator
5712       VMI = FuncInfo.ValueMap.find(V);
5713     if (VMI != FuncInfo.ValueMap.end()) {
5714       const auto &TLI = DAG.getTargetLoweringInfo();
5715       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5716                        V->getType(), None);
5717       if (RFV.occupiesMultipleRegs()) {
5718         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5719         return true;
5720       }
5721 
5722       Op = MachineOperand::CreateReg(VMI->second, false);
5723       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5724     } else if (ArgRegsAndSizes.size() > 1) {
5725       // This was split due to the calling convention, and no virtual register
5726       // mapping exists for the value.
5727       splitMultiRegDbgValue(ArgRegsAndSizes);
5728       return true;
5729     }
5730   }
5731 
5732   if (!Op)
5733     return false;
5734 
5735   assert(Variable->isValidLocationForIntrinsic(DL) &&
5736          "Expected inlined-at fields to agree");
5737   MachineInstr *NewMI = nullptr;
5738 
5739   if (Op->isReg())
5740     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5741   else
5742     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5743                     Variable, Expr);
5744 
5745   // Otherwise, use ArgDbgValues.
5746   FuncInfo.ArgDbgValues.push_back(NewMI);
5747   return true;
5748 }
5749 
5750 /// Return the appropriate SDDbgValue based on N.
5751 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5752                                              DILocalVariable *Variable,
5753                                              DIExpression *Expr,
5754                                              const DebugLoc &dl,
5755                                              unsigned DbgSDNodeOrder) {
5756   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5757     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5758     // stack slot locations.
5759     //
5760     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5761     // debug values here after optimization:
5762     //
5763     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5764     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5765     //
5766     // Both describe the direct values of their associated variables.
5767     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5768                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5769   }
5770   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5771                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5772 }
5773 
5774 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5775   switch (Intrinsic) {
5776   case Intrinsic::smul_fix:
5777     return ISD::SMULFIX;
5778   case Intrinsic::umul_fix:
5779     return ISD::UMULFIX;
5780   case Intrinsic::smul_fix_sat:
5781     return ISD::SMULFIXSAT;
5782   case Intrinsic::umul_fix_sat:
5783     return ISD::UMULFIXSAT;
5784   case Intrinsic::sdiv_fix:
5785     return ISD::SDIVFIX;
5786   case Intrinsic::udiv_fix:
5787     return ISD::UDIVFIX;
5788   case Intrinsic::sdiv_fix_sat:
5789     return ISD::SDIVFIXSAT;
5790   case Intrinsic::udiv_fix_sat:
5791     return ISD::UDIVFIXSAT;
5792   default:
5793     llvm_unreachable("Unhandled fixed point intrinsic");
5794   }
5795 }
5796 
5797 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5798                                            const char *FunctionName) {
5799   assert(FunctionName && "FunctionName must not be nullptr");
5800   SDValue Callee = DAG.getExternalSymbol(
5801       FunctionName,
5802       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5803   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5804 }
5805 
5806 /// Given a @llvm.call.preallocated.setup, return the corresponding
5807 /// preallocated call.
5808 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5809   assert(cast<CallBase>(PreallocatedSetup)
5810                  ->getCalledFunction()
5811                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5812          "expected call_preallocated_setup Value");
5813   for (const auto *U : PreallocatedSetup->users()) {
5814     auto *UseCall = cast<CallBase>(U);
5815     const Function *Fn = UseCall->getCalledFunction();
5816     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5817       return UseCall;
5818     }
5819   }
5820   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5821 }
5822 
5823 /// Lower the call to the specified intrinsic function.
5824 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5825                                              unsigned Intrinsic) {
5826   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5827   SDLoc sdl = getCurSDLoc();
5828   DebugLoc dl = getCurDebugLoc();
5829   SDValue Res;
5830 
5831   SDNodeFlags Flags;
5832   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5833     Flags.copyFMF(*FPOp);
5834 
5835   switch (Intrinsic) {
5836   default:
5837     // By default, turn this into a target intrinsic node.
5838     visitTargetIntrinsic(I, Intrinsic);
5839     return;
5840   case Intrinsic::vscale: {
5841     match(&I, m_VScale(DAG.getDataLayout()));
5842     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5843     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5844     return;
5845   }
5846   case Intrinsic::vastart:  visitVAStart(I); return;
5847   case Intrinsic::vaend:    visitVAEnd(I); return;
5848   case Intrinsic::vacopy:   visitVACopy(I); return;
5849   case Intrinsic::returnaddress:
5850     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5851                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5852                              getValue(I.getArgOperand(0))));
5853     return;
5854   case Intrinsic::addressofreturnaddress:
5855     setValue(&I,
5856              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5857                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5858     return;
5859   case Intrinsic::sponentry:
5860     setValue(&I,
5861              DAG.getNode(ISD::SPONENTRY, sdl,
5862                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5863     return;
5864   case Intrinsic::frameaddress:
5865     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5866                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5867                              getValue(I.getArgOperand(0))));
5868     return;
5869   case Intrinsic::read_volatile_register:
5870   case Intrinsic::read_register: {
5871     Value *Reg = I.getArgOperand(0);
5872     SDValue Chain = getRoot();
5873     SDValue RegName =
5874         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5875     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5876     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5877       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5878     setValue(&I, Res);
5879     DAG.setRoot(Res.getValue(1));
5880     return;
5881   }
5882   case Intrinsic::write_register: {
5883     Value *Reg = I.getArgOperand(0);
5884     Value *RegValue = I.getArgOperand(1);
5885     SDValue Chain = getRoot();
5886     SDValue RegName =
5887         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5888     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5889                             RegName, getValue(RegValue)));
5890     return;
5891   }
5892   case Intrinsic::memcpy: {
5893     const auto &MCI = cast<MemCpyInst>(I);
5894     SDValue Op1 = getValue(I.getArgOperand(0));
5895     SDValue Op2 = getValue(I.getArgOperand(1));
5896     SDValue Op3 = getValue(I.getArgOperand(2));
5897     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5898     Align DstAlign = MCI.getDestAlign().valueOrOne();
5899     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5900     Align Alignment = std::min(DstAlign, SrcAlign);
5901     bool isVol = MCI.isVolatile();
5902     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5903     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5904     // node.
5905     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5906     SDValue MC = DAG.getMemcpy(
5907         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5908         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
5909         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5910     updateDAGForMaybeTailCall(MC);
5911     return;
5912   }
5913   case Intrinsic::memcpy_inline: {
5914     const auto &MCI = cast<MemCpyInlineInst>(I);
5915     SDValue Dst = getValue(I.getArgOperand(0));
5916     SDValue Src = getValue(I.getArgOperand(1));
5917     SDValue Size = getValue(I.getArgOperand(2));
5918     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5919     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5920     Align DstAlign = MCI.getDestAlign().valueOrOne();
5921     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5922     Align Alignment = std::min(DstAlign, SrcAlign);
5923     bool isVol = MCI.isVolatile();
5924     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5925     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5926     // node.
5927     SDValue MC = DAG.getMemcpy(
5928         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5929         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
5930         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5931     updateDAGForMaybeTailCall(MC);
5932     return;
5933   }
5934   case Intrinsic::memset: {
5935     const auto &MSI = cast<MemSetInst>(I);
5936     SDValue Op1 = getValue(I.getArgOperand(0));
5937     SDValue Op2 = getValue(I.getArgOperand(1));
5938     SDValue Op3 = getValue(I.getArgOperand(2));
5939     // @llvm.memset defines 0 and 1 to both mean no alignment.
5940     Align Alignment = MSI.getDestAlign().valueOrOne();
5941     bool isVol = MSI.isVolatile();
5942     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5943     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5944     SDValue MS = DAG.getMemset(
5945         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
5946         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
5947     updateDAGForMaybeTailCall(MS);
5948     return;
5949   }
5950   case Intrinsic::memset_inline: {
5951     const auto &MSII = cast<MemSetInlineInst>(I);
5952     SDValue Dst = getValue(I.getArgOperand(0));
5953     SDValue Value = getValue(I.getArgOperand(1));
5954     SDValue Size = getValue(I.getArgOperand(2));
5955     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
5956     // @llvm.memset defines 0 and 1 to both mean no alignment.
5957     Align DstAlign = MSII.getDestAlign().valueOrOne();
5958     bool isVol = MSII.isVolatile();
5959     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5960     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5961     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
5962                                /* AlwaysInline */ true, isTC,
5963                                MachinePointerInfo(I.getArgOperand(0)),
5964                                I.getAAMetadata());
5965     updateDAGForMaybeTailCall(MC);
5966     return;
5967   }
5968   case Intrinsic::memmove: {
5969     const auto &MMI = cast<MemMoveInst>(I);
5970     SDValue Op1 = getValue(I.getArgOperand(0));
5971     SDValue Op2 = getValue(I.getArgOperand(1));
5972     SDValue Op3 = getValue(I.getArgOperand(2));
5973     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5974     Align DstAlign = MMI.getDestAlign().valueOrOne();
5975     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5976     Align Alignment = std::min(DstAlign, SrcAlign);
5977     bool isVol = MMI.isVolatile();
5978     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5979     // FIXME: Support passing different dest/src alignments to the memmove DAG
5980     // node.
5981     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5982     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5983                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5984                                 MachinePointerInfo(I.getArgOperand(1)),
5985                                 I.getAAMetadata(), AA);
5986     updateDAGForMaybeTailCall(MM);
5987     return;
5988   }
5989   case Intrinsic::memcpy_element_unordered_atomic: {
5990     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5991     SDValue Dst = getValue(MI.getRawDest());
5992     SDValue Src = getValue(MI.getRawSource());
5993     SDValue Length = getValue(MI.getLength());
5994 
5995     Type *LengthTy = MI.getLength()->getType();
5996     unsigned ElemSz = MI.getElementSizeInBytes();
5997     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5998     SDValue MC =
5999         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6000                             isTC, MachinePointerInfo(MI.getRawDest()),
6001                             MachinePointerInfo(MI.getRawSource()));
6002     updateDAGForMaybeTailCall(MC);
6003     return;
6004   }
6005   case Intrinsic::memmove_element_unordered_atomic: {
6006     auto &MI = cast<AtomicMemMoveInst>(I);
6007     SDValue Dst = getValue(MI.getRawDest());
6008     SDValue Src = getValue(MI.getRawSource());
6009     SDValue Length = getValue(MI.getLength());
6010 
6011     Type *LengthTy = MI.getLength()->getType();
6012     unsigned ElemSz = MI.getElementSizeInBytes();
6013     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6014     SDValue MC =
6015         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6016                              isTC, MachinePointerInfo(MI.getRawDest()),
6017                              MachinePointerInfo(MI.getRawSource()));
6018     updateDAGForMaybeTailCall(MC);
6019     return;
6020   }
6021   case Intrinsic::memset_element_unordered_atomic: {
6022     auto &MI = cast<AtomicMemSetInst>(I);
6023     SDValue Dst = getValue(MI.getRawDest());
6024     SDValue Val = getValue(MI.getValue());
6025     SDValue Length = getValue(MI.getLength());
6026 
6027     Type *LengthTy = MI.getLength()->getType();
6028     unsigned ElemSz = MI.getElementSizeInBytes();
6029     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6030     SDValue MC =
6031         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6032                             isTC, MachinePointerInfo(MI.getRawDest()));
6033     updateDAGForMaybeTailCall(MC);
6034     return;
6035   }
6036   case Intrinsic::call_preallocated_setup: {
6037     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6038     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6039     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6040                               getRoot(), SrcValue);
6041     setValue(&I, Res);
6042     DAG.setRoot(Res);
6043     return;
6044   }
6045   case Intrinsic::call_preallocated_arg: {
6046     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6047     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6048     SDValue Ops[3];
6049     Ops[0] = getRoot();
6050     Ops[1] = SrcValue;
6051     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6052                                    MVT::i32); // arg index
6053     SDValue Res = DAG.getNode(
6054         ISD::PREALLOCATED_ARG, sdl,
6055         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6056     setValue(&I, Res);
6057     DAG.setRoot(Res.getValue(1));
6058     return;
6059   }
6060   case Intrinsic::dbg_addr:
6061   case Intrinsic::dbg_declare: {
6062     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6063     // they are non-variadic.
6064     const auto &DI = cast<DbgVariableIntrinsic>(I);
6065     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6066     DILocalVariable *Variable = DI.getVariable();
6067     DIExpression *Expression = DI.getExpression();
6068     dropDanglingDebugInfo(Variable, Expression);
6069     assert(Variable && "Missing variable");
6070     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6071                       << "\n");
6072     // Check if address has undef value.
6073     const Value *Address = DI.getVariableLocationOp(0);
6074     if (!Address || isa<UndefValue>(Address) ||
6075         (Address->use_empty() && !isa<Argument>(Address))) {
6076       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6077                         << " (bad/undef/unused-arg address)\n");
6078       return;
6079     }
6080 
6081     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6082 
6083     // Check if this variable can be described by a frame index, typically
6084     // either as a static alloca or a byval parameter.
6085     int FI = std::numeric_limits<int>::max();
6086     if (const auto *AI =
6087             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6088       if (AI->isStaticAlloca()) {
6089         auto I = FuncInfo.StaticAllocaMap.find(AI);
6090         if (I != FuncInfo.StaticAllocaMap.end())
6091           FI = I->second;
6092       }
6093     } else if (const auto *Arg = dyn_cast<Argument>(
6094                    Address->stripInBoundsConstantOffsets())) {
6095       FI = FuncInfo.getArgumentFrameIndex(Arg);
6096     }
6097 
6098     // llvm.dbg.addr is control dependent and always generates indirect
6099     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6100     // the MachineFunction variable table.
6101     if (FI != std::numeric_limits<int>::max()) {
6102       if (Intrinsic == Intrinsic::dbg_addr) {
6103         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6104             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6105             dl, SDNodeOrder);
6106         DAG.AddDbgValue(SDV, isParameter);
6107       } else {
6108         LLVM_DEBUG(dbgs() << "Skipping " << DI
6109                           << " (variable info stashed in MF side table)\n");
6110       }
6111       return;
6112     }
6113 
6114     SDValue &N = NodeMap[Address];
6115     if (!N.getNode() && isa<Argument>(Address))
6116       // Check unused arguments map.
6117       N = UnusedArgNodeMap[Address];
6118     SDDbgValue *SDV;
6119     if (N.getNode()) {
6120       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6121         Address = BCI->getOperand(0);
6122       // Parameters are handled specially.
6123       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6124       if (isParameter && FINode) {
6125         // Byval parameter. We have a frame index at this point.
6126         SDV =
6127             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6128                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6129       } else if (isa<Argument>(Address)) {
6130         // Address is an argument, so try to emit its dbg value using
6131         // virtual register info from the FuncInfo.ValueMap.
6132         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6133                                  FuncArgumentDbgValueKind::Declare, N);
6134         return;
6135       } else {
6136         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6137                               true, dl, SDNodeOrder);
6138       }
6139       DAG.AddDbgValue(SDV, isParameter);
6140     } else {
6141       // If Address is an argument then try to emit its dbg value using
6142       // virtual register info from the FuncInfo.ValueMap.
6143       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6144                                     FuncArgumentDbgValueKind::Declare, N)) {
6145         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6146                           << " (could not emit func-arg dbg_value)\n");
6147       }
6148     }
6149     return;
6150   }
6151   case Intrinsic::dbg_label: {
6152     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6153     DILabel *Label = DI.getLabel();
6154     assert(Label && "Missing label");
6155 
6156     SDDbgLabel *SDV;
6157     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6158     DAG.AddDbgLabel(SDV);
6159     return;
6160   }
6161   case Intrinsic::dbg_value: {
6162     const DbgValueInst &DI = cast<DbgValueInst>(I);
6163     assert(DI.getVariable() && "Missing variable");
6164 
6165     DILocalVariable *Variable = DI.getVariable();
6166     DIExpression *Expression = DI.getExpression();
6167     dropDanglingDebugInfo(Variable, Expression);
6168     SmallVector<Value *, 4> Values(DI.getValues());
6169     if (Values.empty())
6170       return;
6171 
6172     if (llvm::is_contained(Values, nullptr))
6173       return;
6174 
6175     bool IsVariadic = DI.hasArgList();
6176     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6177                           SDNodeOrder, IsVariadic))
6178       addDanglingDebugInfo(&DI, SDNodeOrder);
6179     return;
6180   }
6181 
6182   case Intrinsic::eh_typeid_for: {
6183     // Find the type id for the given typeinfo.
6184     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6185     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6186     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6187     setValue(&I, Res);
6188     return;
6189   }
6190 
6191   case Intrinsic::eh_return_i32:
6192   case Intrinsic::eh_return_i64:
6193     DAG.getMachineFunction().setCallsEHReturn(true);
6194     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6195                             MVT::Other,
6196                             getControlRoot(),
6197                             getValue(I.getArgOperand(0)),
6198                             getValue(I.getArgOperand(1))));
6199     return;
6200   case Intrinsic::eh_unwind_init:
6201     DAG.getMachineFunction().setCallsUnwindInit(true);
6202     return;
6203   case Intrinsic::eh_dwarf_cfa:
6204     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6205                              TLI.getPointerTy(DAG.getDataLayout()),
6206                              getValue(I.getArgOperand(0))));
6207     return;
6208   case Intrinsic::eh_sjlj_callsite: {
6209     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6210     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6211     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6212 
6213     MMI.setCurrentCallSite(CI->getZExtValue());
6214     return;
6215   }
6216   case Intrinsic::eh_sjlj_functioncontext: {
6217     // Get and store the index of the function context.
6218     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6219     AllocaInst *FnCtx =
6220       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6221     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6222     MFI.setFunctionContextIndex(FI);
6223     return;
6224   }
6225   case Intrinsic::eh_sjlj_setjmp: {
6226     SDValue Ops[2];
6227     Ops[0] = getRoot();
6228     Ops[1] = getValue(I.getArgOperand(0));
6229     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6230                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6231     setValue(&I, Op.getValue(0));
6232     DAG.setRoot(Op.getValue(1));
6233     return;
6234   }
6235   case Intrinsic::eh_sjlj_longjmp:
6236     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6237                             getRoot(), getValue(I.getArgOperand(0))));
6238     return;
6239   case Intrinsic::eh_sjlj_setup_dispatch:
6240     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6241                             getRoot()));
6242     return;
6243   case Intrinsic::masked_gather:
6244     visitMaskedGather(I);
6245     return;
6246   case Intrinsic::masked_load:
6247     visitMaskedLoad(I);
6248     return;
6249   case Intrinsic::masked_scatter:
6250     visitMaskedScatter(I);
6251     return;
6252   case Intrinsic::masked_store:
6253     visitMaskedStore(I);
6254     return;
6255   case Intrinsic::masked_expandload:
6256     visitMaskedLoad(I, true /* IsExpanding */);
6257     return;
6258   case Intrinsic::masked_compressstore:
6259     visitMaskedStore(I, true /* IsCompressing */);
6260     return;
6261   case Intrinsic::powi:
6262     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6263                             getValue(I.getArgOperand(1)), DAG));
6264     return;
6265   case Intrinsic::log:
6266     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6267     return;
6268   case Intrinsic::log2:
6269     setValue(&I,
6270              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6271     return;
6272   case Intrinsic::log10:
6273     setValue(&I,
6274              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6275     return;
6276   case Intrinsic::exp:
6277     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6278     return;
6279   case Intrinsic::exp2:
6280     setValue(&I,
6281              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6282     return;
6283   case Intrinsic::pow:
6284     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6285                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6286     return;
6287   case Intrinsic::sqrt:
6288   case Intrinsic::fabs:
6289   case Intrinsic::sin:
6290   case Intrinsic::cos:
6291   case Intrinsic::floor:
6292   case Intrinsic::ceil:
6293   case Intrinsic::trunc:
6294   case Intrinsic::rint:
6295   case Intrinsic::nearbyint:
6296   case Intrinsic::round:
6297   case Intrinsic::roundeven:
6298   case Intrinsic::canonicalize: {
6299     unsigned Opcode;
6300     switch (Intrinsic) {
6301     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6302     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6303     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6304     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6305     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6306     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6307     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6308     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6309     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6310     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6311     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6312     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6313     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6314     }
6315 
6316     setValue(&I, DAG.getNode(Opcode, sdl,
6317                              getValue(I.getArgOperand(0)).getValueType(),
6318                              getValue(I.getArgOperand(0)), Flags));
6319     return;
6320   }
6321   case Intrinsic::lround:
6322   case Intrinsic::llround:
6323   case Intrinsic::lrint:
6324   case Intrinsic::llrint: {
6325     unsigned Opcode;
6326     switch (Intrinsic) {
6327     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6328     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6329     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6330     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6331     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6332     }
6333 
6334     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6335     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6336                              getValue(I.getArgOperand(0))));
6337     return;
6338   }
6339   case Intrinsic::minnum:
6340     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6341                              getValue(I.getArgOperand(0)).getValueType(),
6342                              getValue(I.getArgOperand(0)),
6343                              getValue(I.getArgOperand(1)), Flags));
6344     return;
6345   case Intrinsic::maxnum:
6346     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6347                              getValue(I.getArgOperand(0)).getValueType(),
6348                              getValue(I.getArgOperand(0)),
6349                              getValue(I.getArgOperand(1)), Flags));
6350     return;
6351   case Intrinsic::minimum:
6352     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6353                              getValue(I.getArgOperand(0)).getValueType(),
6354                              getValue(I.getArgOperand(0)),
6355                              getValue(I.getArgOperand(1)), Flags));
6356     return;
6357   case Intrinsic::maximum:
6358     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6359                              getValue(I.getArgOperand(0)).getValueType(),
6360                              getValue(I.getArgOperand(0)),
6361                              getValue(I.getArgOperand(1)), Flags));
6362     return;
6363   case Intrinsic::copysign:
6364     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6365                              getValue(I.getArgOperand(0)).getValueType(),
6366                              getValue(I.getArgOperand(0)),
6367                              getValue(I.getArgOperand(1)), Flags));
6368     return;
6369   case Intrinsic::arithmetic_fence: {
6370     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6371                              getValue(I.getArgOperand(0)).getValueType(),
6372                              getValue(I.getArgOperand(0)), Flags));
6373     return;
6374   }
6375   case Intrinsic::fma:
6376     setValue(&I, DAG.getNode(
6377                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6378                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6379                      getValue(I.getArgOperand(2)), Flags));
6380     return;
6381 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6382   case Intrinsic::INTRINSIC:
6383 #include "llvm/IR/ConstrainedOps.def"
6384     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6385     return;
6386 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6387 #include "llvm/IR/VPIntrinsics.def"
6388     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6389     return;
6390   case Intrinsic::fptrunc_round: {
6391     // Get the last argument, the metadata and convert it to an integer in the
6392     // call
6393     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6394     Optional<RoundingMode> RoundMode =
6395         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6396 
6397     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6398 
6399     // Propagate fast-math-flags from IR to node(s).
6400     SDNodeFlags Flags;
6401     Flags.copyFMF(*cast<FPMathOperator>(&I));
6402     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6403 
6404     SDValue Result;
6405     Result = DAG.getNode(
6406         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6407         DAG.getTargetConstant((int)*RoundMode, sdl,
6408                               TLI.getPointerTy(DAG.getDataLayout())));
6409     setValue(&I, Result);
6410 
6411     return;
6412   }
6413   case Intrinsic::fmuladd: {
6414     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6415     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6416         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6417       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6418                                getValue(I.getArgOperand(0)).getValueType(),
6419                                getValue(I.getArgOperand(0)),
6420                                getValue(I.getArgOperand(1)),
6421                                getValue(I.getArgOperand(2)), Flags));
6422     } else {
6423       // TODO: Intrinsic calls should have fast-math-flags.
6424       SDValue Mul = DAG.getNode(
6425           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6426           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6427       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6428                                 getValue(I.getArgOperand(0)).getValueType(),
6429                                 Mul, getValue(I.getArgOperand(2)), Flags);
6430       setValue(&I, Add);
6431     }
6432     return;
6433   }
6434   case Intrinsic::convert_to_fp16:
6435     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6436                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6437                                          getValue(I.getArgOperand(0)),
6438                                          DAG.getTargetConstant(0, sdl,
6439                                                                MVT::i32))));
6440     return;
6441   case Intrinsic::convert_from_fp16:
6442     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6443                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6444                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6445                                          getValue(I.getArgOperand(0)))));
6446     return;
6447   case Intrinsic::fptosi_sat: {
6448     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6449     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6450                              getValue(I.getArgOperand(0)),
6451                              DAG.getValueType(VT.getScalarType())));
6452     return;
6453   }
6454   case Intrinsic::fptoui_sat: {
6455     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6456     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6457                              getValue(I.getArgOperand(0)),
6458                              DAG.getValueType(VT.getScalarType())));
6459     return;
6460   }
6461   case Intrinsic::set_rounding:
6462     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6463                       {getRoot(), getValue(I.getArgOperand(0))});
6464     setValue(&I, Res);
6465     DAG.setRoot(Res.getValue(0));
6466     return;
6467   case Intrinsic::is_fpclass: {
6468     const DataLayout DLayout = DAG.getDataLayout();
6469     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6470     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6471     unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6472     MachineFunction &MF = DAG.getMachineFunction();
6473     const Function &F = MF.getFunction();
6474     SDValue Op = getValue(I.getArgOperand(0));
6475     SDNodeFlags Flags;
6476     Flags.setNoFPExcept(
6477         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6478     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6479     // expansion can use illegal types. Making expansion early allows
6480     // legalizing these types prior to selection.
6481     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6482       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6483       setValue(&I, Result);
6484       return;
6485     }
6486 
6487     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6488     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6489     setValue(&I, V);
6490     return;
6491   }
6492   case Intrinsic::pcmarker: {
6493     SDValue Tmp = getValue(I.getArgOperand(0));
6494     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6495     return;
6496   }
6497   case Intrinsic::readcyclecounter: {
6498     SDValue Op = getRoot();
6499     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6500                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6501     setValue(&I, Res);
6502     DAG.setRoot(Res.getValue(1));
6503     return;
6504   }
6505   case Intrinsic::bitreverse:
6506     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6507                              getValue(I.getArgOperand(0)).getValueType(),
6508                              getValue(I.getArgOperand(0))));
6509     return;
6510   case Intrinsic::bswap:
6511     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6512                              getValue(I.getArgOperand(0)).getValueType(),
6513                              getValue(I.getArgOperand(0))));
6514     return;
6515   case Intrinsic::cttz: {
6516     SDValue Arg = getValue(I.getArgOperand(0));
6517     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6518     EVT Ty = Arg.getValueType();
6519     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6520                              sdl, Ty, Arg));
6521     return;
6522   }
6523   case Intrinsic::ctlz: {
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::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6528                              sdl, Ty, Arg));
6529     return;
6530   }
6531   case Intrinsic::ctpop: {
6532     SDValue Arg = getValue(I.getArgOperand(0));
6533     EVT Ty = Arg.getValueType();
6534     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6535     return;
6536   }
6537   case Intrinsic::fshl:
6538   case Intrinsic::fshr: {
6539     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6540     SDValue X = getValue(I.getArgOperand(0));
6541     SDValue Y = getValue(I.getArgOperand(1));
6542     SDValue Z = getValue(I.getArgOperand(2));
6543     EVT VT = X.getValueType();
6544 
6545     if (X == Y) {
6546       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6547       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6548     } else {
6549       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6550       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6551     }
6552     return;
6553   }
6554   case Intrinsic::sadd_sat: {
6555     SDValue Op1 = getValue(I.getArgOperand(0));
6556     SDValue Op2 = getValue(I.getArgOperand(1));
6557     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6558     return;
6559   }
6560   case Intrinsic::uadd_sat: {
6561     SDValue Op1 = getValue(I.getArgOperand(0));
6562     SDValue Op2 = getValue(I.getArgOperand(1));
6563     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6564     return;
6565   }
6566   case Intrinsic::ssub_sat: {
6567     SDValue Op1 = getValue(I.getArgOperand(0));
6568     SDValue Op2 = getValue(I.getArgOperand(1));
6569     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6570     return;
6571   }
6572   case Intrinsic::usub_sat: {
6573     SDValue Op1 = getValue(I.getArgOperand(0));
6574     SDValue Op2 = getValue(I.getArgOperand(1));
6575     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6576     return;
6577   }
6578   case Intrinsic::sshl_sat: {
6579     SDValue Op1 = getValue(I.getArgOperand(0));
6580     SDValue Op2 = getValue(I.getArgOperand(1));
6581     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6582     return;
6583   }
6584   case Intrinsic::ushl_sat: {
6585     SDValue Op1 = getValue(I.getArgOperand(0));
6586     SDValue Op2 = getValue(I.getArgOperand(1));
6587     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6588     return;
6589   }
6590   case Intrinsic::smul_fix:
6591   case Intrinsic::umul_fix:
6592   case Intrinsic::smul_fix_sat:
6593   case Intrinsic::umul_fix_sat: {
6594     SDValue Op1 = getValue(I.getArgOperand(0));
6595     SDValue Op2 = getValue(I.getArgOperand(1));
6596     SDValue Op3 = getValue(I.getArgOperand(2));
6597     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6598                              Op1.getValueType(), Op1, Op2, Op3));
6599     return;
6600   }
6601   case Intrinsic::sdiv_fix:
6602   case Intrinsic::udiv_fix:
6603   case Intrinsic::sdiv_fix_sat:
6604   case Intrinsic::udiv_fix_sat: {
6605     SDValue Op1 = getValue(I.getArgOperand(0));
6606     SDValue Op2 = getValue(I.getArgOperand(1));
6607     SDValue Op3 = getValue(I.getArgOperand(2));
6608     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6609                               Op1, Op2, Op3, DAG, TLI));
6610     return;
6611   }
6612   case Intrinsic::smax: {
6613     SDValue Op1 = getValue(I.getArgOperand(0));
6614     SDValue Op2 = getValue(I.getArgOperand(1));
6615     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6616     return;
6617   }
6618   case Intrinsic::smin: {
6619     SDValue Op1 = getValue(I.getArgOperand(0));
6620     SDValue Op2 = getValue(I.getArgOperand(1));
6621     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6622     return;
6623   }
6624   case Intrinsic::umax: {
6625     SDValue Op1 = getValue(I.getArgOperand(0));
6626     SDValue Op2 = getValue(I.getArgOperand(1));
6627     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6628     return;
6629   }
6630   case Intrinsic::umin: {
6631     SDValue Op1 = getValue(I.getArgOperand(0));
6632     SDValue Op2 = getValue(I.getArgOperand(1));
6633     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6634     return;
6635   }
6636   case Intrinsic::abs: {
6637     // TODO: Preserve "int min is poison" arg in SDAG?
6638     SDValue Op1 = getValue(I.getArgOperand(0));
6639     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6640     return;
6641   }
6642   case Intrinsic::stacksave: {
6643     SDValue Op = getRoot();
6644     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6645     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6646     setValue(&I, Res);
6647     DAG.setRoot(Res.getValue(1));
6648     return;
6649   }
6650   case Intrinsic::stackrestore:
6651     Res = getValue(I.getArgOperand(0));
6652     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6653     return;
6654   case Intrinsic::get_dynamic_area_offset: {
6655     SDValue Op = getRoot();
6656     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6657     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6658     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6659     // target.
6660     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6661       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6662                          " intrinsic!");
6663     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6664                       Op);
6665     DAG.setRoot(Op);
6666     setValue(&I, Res);
6667     return;
6668   }
6669   case Intrinsic::stackguard: {
6670     MachineFunction &MF = DAG.getMachineFunction();
6671     const Module &M = *MF.getFunction().getParent();
6672     SDValue Chain = getRoot();
6673     if (TLI.useLoadStackGuardNode()) {
6674       Res = getLoadStackGuard(DAG, sdl, Chain);
6675     } else {
6676       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6677       const Value *Global = TLI.getSDagStackGuard(M);
6678       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6679       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6680                         MachinePointerInfo(Global, 0), Align,
6681                         MachineMemOperand::MOVolatile);
6682     }
6683     if (TLI.useStackGuardXorFP())
6684       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6685     DAG.setRoot(Chain);
6686     setValue(&I, Res);
6687     return;
6688   }
6689   case Intrinsic::stackprotector: {
6690     // Emit code into the DAG to store the stack guard onto the stack.
6691     MachineFunction &MF = DAG.getMachineFunction();
6692     MachineFrameInfo &MFI = MF.getFrameInfo();
6693     SDValue Src, Chain = getRoot();
6694 
6695     if (TLI.useLoadStackGuardNode())
6696       Src = getLoadStackGuard(DAG, sdl, Chain);
6697     else
6698       Src = getValue(I.getArgOperand(0));   // The guard's value.
6699 
6700     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6701 
6702     int FI = FuncInfo.StaticAllocaMap[Slot];
6703     MFI.setStackProtectorIndex(FI);
6704     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6705 
6706     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6707 
6708     // Store the stack protector onto the stack.
6709     Res = DAG.getStore(
6710         Chain, sdl, Src, FIN,
6711         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6712         MaybeAlign(), MachineMemOperand::MOVolatile);
6713     setValue(&I, Res);
6714     DAG.setRoot(Res);
6715     return;
6716   }
6717   case Intrinsic::objectsize:
6718     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6719 
6720   case Intrinsic::is_constant:
6721     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6722 
6723   case Intrinsic::annotation:
6724   case Intrinsic::ptr_annotation:
6725   case Intrinsic::launder_invariant_group:
6726   case Intrinsic::strip_invariant_group:
6727     // Drop the intrinsic, but forward the value
6728     setValue(&I, getValue(I.getOperand(0)));
6729     return;
6730 
6731   case Intrinsic::assume:
6732   case Intrinsic::experimental_noalias_scope_decl:
6733   case Intrinsic::var_annotation:
6734   case Intrinsic::sideeffect:
6735     // Discard annotate attributes, noalias scope declarations, assumptions, and
6736     // artificial side-effects.
6737     return;
6738 
6739   case Intrinsic::codeview_annotation: {
6740     // Emit a label associated with this metadata.
6741     MachineFunction &MF = DAG.getMachineFunction();
6742     MCSymbol *Label =
6743         MF.getMMI().getContext().createTempSymbol("annotation", true);
6744     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6745     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6746     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6747     DAG.setRoot(Res);
6748     return;
6749   }
6750 
6751   case Intrinsic::init_trampoline: {
6752     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6753 
6754     SDValue Ops[6];
6755     Ops[0] = getRoot();
6756     Ops[1] = getValue(I.getArgOperand(0));
6757     Ops[2] = getValue(I.getArgOperand(1));
6758     Ops[3] = getValue(I.getArgOperand(2));
6759     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6760     Ops[5] = DAG.getSrcValue(F);
6761 
6762     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6763 
6764     DAG.setRoot(Res);
6765     return;
6766   }
6767   case Intrinsic::adjust_trampoline:
6768     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6769                              TLI.getPointerTy(DAG.getDataLayout()),
6770                              getValue(I.getArgOperand(0))));
6771     return;
6772   case Intrinsic::gcroot: {
6773     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6774            "only valid in functions with gc specified, enforced by Verifier");
6775     assert(GFI && "implied by previous");
6776     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6777     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6778 
6779     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6780     GFI->addStackRoot(FI->getIndex(), TypeMap);
6781     return;
6782   }
6783   case Intrinsic::gcread:
6784   case Intrinsic::gcwrite:
6785     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6786   case Intrinsic::flt_rounds:
6787     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6788     setValue(&I, Res);
6789     DAG.setRoot(Res.getValue(1));
6790     return;
6791 
6792   case Intrinsic::expect:
6793     // Just replace __builtin_expect(exp, c) with EXP.
6794     setValue(&I, getValue(I.getArgOperand(0)));
6795     return;
6796 
6797   case Intrinsic::ubsantrap:
6798   case Intrinsic::debugtrap:
6799   case Intrinsic::trap: {
6800     StringRef TrapFuncName =
6801         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6802     if (TrapFuncName.empty()) {
6803       switch (Intrinsic) {
6804       case Intrinsic::trap:
6805         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6806         break;
6807       case Intrinsic::debugtrap:
6808         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6809         break;
6810       case Intrinsic::ubsantrap:
6811         DAG.setRoot(DAG.getNode(
6812             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6813             DAG.getTargetConstant(
6814                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6815                 MVT::i32)));
6816         break;
6817       default: llvm_unreachable("unknown trap intrinsic");
6818       }
6819       return;
6820     }
6821     TargetLowering::ArgListTy Args;
6822     if (Intrinsic == Intrinsic::ubsantrap) {
6823       Args.push_back(TargetLoweringBase::ArgListEntry());
6824       Args[0].Val = I.getArgOperand(0);
6825       Args[0].Node = getValue(Args[0].Val);
6826       Args[0].Ty = Args[0].Val->getType();
6827     }
6828 
6829     TargetLowering::CallLoweringInfo CLI(DAG);
6830     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6831         CallingConv::C, I.getType(),
6832         DAG.getExternalSymbol(TrapFuncName.data(),
6833                               TLI.getPointerTy(DAG.getDataLayout())),
6834         std::move(Args));
6835 
6836     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6837     DAG.setRoot(Result.second);
6838     return;
6839   }
6840 
6841   case Intrinsic::uadd_with_overflow:
6842   case Intrinsic::sadd_with_overflow:
6843   case Intrinsic::usub_with_overflow:
6844   case Intrinsic::ssub_with_overflow:
6845   case Intrinsic::umul_with_overflow:
6846   case Intrinsic::smul_with_overflow: {
6847     ISD::NodeType Op;
6848     switch (Intrinsic) {
6849     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6850     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6851     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6852     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6853     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6854     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6855     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6856     }
6857     SDValue Op1 = getValue(I.getArgOperand(0));
6858     SDValue Op2 = getValue(I.getArgOperand(1));
6859 
6860     EVT ResultVT = Op1.getValueType();
6861     EVT OverflowVT = MVT::i1;
6862     if (ResultVT.isVector())
6863       OverflowVT = EVT::getVectorVT(
6864           *Context, OverflowVT, ResultVT.getVectorElementCount());
6865 
6866     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6867     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6868     return;
6869   }
6870   case Intrinsic::prefetch: {
6871     SDValue Ops[5];
6872     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6873     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6874     Ops[0] = DAG.getRoot();
6875     Ops[1] = getValue(I.getArgOperand(0));
6876     Ops[2] = getValue(I.getArgOperand(1));
6877     Ops[3] = getValue(I.getArgOperand(2));
6878     Ops[4] = getValue(I.getArgOperand(3));
6879     SDValue Result = DAG.getMemIntrinsicNode(
6880         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6881         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6882         /* align */ None, Flags);
6883 
6884     // Chain the prefetch in parallell with any pending loads, to stay out of
6885     // the way of later optimizations.
6886     PendingLoads.push_back(Result);
6887     Result = getRoot();
6888     DAG.setRoot(Result);
6889     return;
6890   }
6891   case Intrinsic::lifetime_start:
6892   case Intrinsic::lifetime_end: {
6893     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6894     // Stack coloring is not enabled in O0, discard region information.
6895     if (TM.getOptLevel() == CodeGenOpt::None)
6896       return;
6897 
6898     const int64_t ObjectSize =
6899         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6900     Value *const ObjectPtr = I.getArgOperand(1);
6901     SmallVector<const Value *, 4> Allocas;
6902     getUnderlyingObjects(ObjectPtr, Allocas);
6903 
6904     for (const Value *Alloca : Allocas) {
6905       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6906 
6907       // Could not find an Alloca.
6908       if (!LifetimeObject)
6909         continue;
6910 
6911       // First check that the Alloca is static, otherwise it won't have a
6912       // valid frame index.
6913       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6914       if (SI == FuncInfo.StaticAllocaMap.end())
6915         return;
6916 
6917       const int FrameIndex = SI->second;
6918       int64_t Offset;
6919       if (GetPointerBaseWithConstantOffset(
6920               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6921         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6922       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6923                                 Offset);
6924       DAG.setRoot(Res);
6925     }
6926     return;
6927   }
6928   case Intrinsic::pseudoprobe: {
6929     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6930     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6931     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6932     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6933     DAG.setRoot(Res);
6934     return;
6935   }
6936   case Intrinsic::invariant_start:
6937     // Discard region information.
6938     setValue(&I,
6939              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
6940     return;
6941   case Intrinsic::invariant_end:
6942     // Discard region information.
6943     return;
6944   case Intrinsic::clear_cache:
6945     /// FunctionName may be null.
6946     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6947       lowerCallToExternalSymbol(I, FunctionName);
6948     return;
6949   case Intrinsic::donothing:
6950   case Intrinsic::seh_try_begin:
6951   case Intrinsic::seh_scope_begin:
6952   case Intrinsic::seh_try_end:
6953   case Intrinsic::seh_scope_end:
6954     // ignore
6955     return;
6956   case Intrinsic::experimental_stackmap:
6957     visitStackmap(I);
6958     return;
6959   case Intrinsic::experimental_patchpoint_void:
6960   case Intrinsic::experimental_patchpoint_i64:
6961     visitPatchpoint(I);
6962     return;
6963   case Intrinsic::experimental_gc_statepoint:
6964     LowerStatepoint(cast<GCStatepointInst>(I));
6965     return;
6966   case Intrinsic::experimental_gc_result:
6967     visitGCResult(cast<GCResultInst>(I));
6968     return;
6969   case Intrinsic::experimental_gc_relocate:
6970     visitGCRelocate(cast<GCRelocateInst>(I));
6971     return;
6972   case Intrinsic::instrprof_cover:
6973     llvm_unreachable("instrprof failed to lower a cover");
6974   case Intrinsic::instrprof_increment:
6975     llvm_unreachable("instrprof failed to lower an increment");
6976   case Intrinsic::instrprof_value_profile:
6977     llvm_unreachable("instrprof failed to lower a value profiling call");
6978   case Intrinsic::localescape: {
6979     MachineFunction &MF = DAG.getMachineFunction();
6980     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6981 
6982     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6983     // is the same on all targets.
6984     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
6985       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6986       if (isa<ConstantPointerNull>(Arg))
6987         continue; // Skip null pointers. They represent a hole in index space.
6988       AllocaInst *Slot = cast<AllocaInst>(Arg);
6989       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6990              "can only escape static allocas");
6991       int FI = FuncInfo.StaticAllocaMap[Slot];
6992       MCSymbol *FrameAllocSym =
6993           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6994               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6995       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6996               TII->get(TargetOpcode::LOCAL_ESCAPE))
6997           .addSym(FrameAllocSym)
6998           .addFrameIndex(FI);
6999     }
7000 
7001     return;
7002   }
7003 
7004   case Intrinsic::localrecover: {
7005     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7006     MachineFunction &MF = DAG.getMachineFunction();
7007 
7008     // Get the symbol that defines the frame offset.
7009     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7010     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7011     unsigned IdxVal =
7012         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7013     MCSymbol *FrameAllocSym =
7014         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7015             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7016 
7017     Value *FP = I.getArgOperand(1);
7018     SDValue FPVal = getValue(FP);
7019     EVT PtrVT = FPVal.getValueType();
7020 
7021     // Create a MCSymbol for the label to avoid any target lowering
7022     // that would make this PC relative.
7023     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7024     SDValue OffsetVal =
7025         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7026 
7027     // Add the offset to the FP.
7028     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7029     setValue(&I, Add);
7030 
7031     return;
7032   }
7033 
7034   case Intrinsic::eh_exceptionpointer:
7035   case Intrinsic::eh_exceptioncode: {
7036     // Get the exception pointer vreg, copy from it, and resize it to fit.
7037     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7038     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7039     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7040     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7041     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7042     if (Intrinsic == Intrinsic::eh_exceptioncode)
7043       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7044     setValue(&I, N);
7045     return;
7046   }
7047   case Intrinsic::xray_customevent: {
7048     // Here we want to make sure that the intrinsic behaves as if it has a
7049     // specific calling convention, and only for x86_64.
7050     // FIXME: Support other platforms later.
7051     const auto &Triple = DAG.getTarget().getTargetTriple();
7052     if (Triple.getArch() != Triple::x86_64)
7053       return;
7054 
7055     SmallVector<SDValue, 8> Ops;
7056 
7057     // We want to say that we always want the arguments in registers.
7058     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7059     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7060     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7061     SDValue Chain = getRoot();
7062     Ops.push_back(LogEntryVal);
7063     Ops.push_back(StrSizeVal);
7064     Ops.push_back(Chain);
7065 
7066     // We need to enforce the calling convention for the callsite, so that
7067     // argument ordering is enforced correctly, and that register allocation can
7068     // see that some registers may be assumed clobbered and have to preserve
7069     // them across calls to the intrinsic.
7070     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7071                                            sdl, NodeTys, Ops);
7072     SDValue patchableNode = SDValue(MN, 0);
7073     DAG.setRoot(patchableNode);
7074     setValue(&I, patchableNode);
7075     return;
7076   }
7077   case Intrinsic::xray_typedevent: {
7078     // Here we want to make sure that the intrinsic behaves as if it has a
7079     // specific calling convention, and only for x86_64.
7080     // FIXME: Support other platforms later.
7081     const auto &Triple = DAG.getTarget().getTargetTriple();
7082     if (Triple.getArch() != Triple::x86_64)
7083       return;
7084 
7085     SmallVector<SDValue, 8> Ops;
7086 
7087     // We want to say that we always want the arguments in registers.
7088     // It's unclear to me how manipulating the selection DAG here forces callers
7089     // to provide arguments in registers instead of on the stack.
7090     SDValue LogTypeId = getValue(I.getArgOperand(0));
7091     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7092     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7093     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7094     SDValue Chain = getRoot();
7095     Ops.push_back(LogTypeId);
7096     Ops.push_back(LogEntryVal);
7097     Ops.push_back(StrSizeVal);
7098     Ops.push_back(Chain);
7099 
7100     // We need to enforce the calling convention for the callsite, so that
7101     // argument ordering is enforced correctly, and that register allocation can
7102     // see that some registers may be assumed clobbered and have to preserve
7103     // them across calls to the intrinsic.
7104     MachineSDNode *MN = DAG.getMachineNode(
7105         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7106     SDValue patchableNode = SDValue(MN, 0);
7107     DAG.setRoot(patchableNode);
7108     setValue(&I, patchableNode);
7109     return;
7110   }
7111   case Intrinsic::experimental_deoptimize:
7112     LowerDeoptimizeCall(&I);
7113     return;
7114   case Intrinsic::experimental_stepvector:
7115     visitStepVector(I);
7116     return;
7117   case Intrinsic::vector_reduce_fadd:
7118   case Intrinsic::vector_reduce_fmul:
7119   case Intrinsic::vector_reduce_add:
7120   case Intrinsic::vector_reduce_mul:
7121   case Intrinsic::vector_reduce_and:
7122   case Intrinsic::vector_reduce_or:
7123   case Intrinsic::vector_reduce_xor:
7124   case Intrinsic::vector_reduce_smax:
7125   case Intrinsic::vector_reduce_smin:
7126   case Intrinsic::vector_reduce_umax:
7127   case Intrinsic::vector_reduce_umin:
7128   case Intrinsic::vector_reduce_fmax:
7129   case Intrinsic::vector_reduce_fmin:
7130     visitVectorReduce(I, Intrinsic);
7131     return;
7132 
7133   case Intrinsic::icall_branch_funnel: {
7134     SmallVector<SDValue, 16> Ops;
7135     Ops.push_back(getValue(I.getArgOperand(0)));
7136 
7137     int64_t Offset;
7138     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7139         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7140     if (!Base)
7141       report_fatal_error(
7142           "llvm.icall.branch.funnel operand must be a GlobalValue");
7143     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7144 
7145     struct BranchFunnelTarget {
7146       int64_t Offset;
7147       SDValue Target;
7148     };
7149     SmallVector<BranchFunnelTarget, 8> Targets;
7150 
7151     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7152       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7153           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7154       if (ElemBase != Base)
7155         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7156                            "to the same GlobalValue");
7157 
7158       SDValue Val = getValue(I.getArgOperand(Op + 1));
7159       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7160       if (!GA)
7161         report_fatal_error(
7162             "llvm.icall.branch.funnel operand must be a GlobalValue");
7163       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7164                                      GA->getGlobal(), sdl, Val.getValueType(),
7165                                      GA->getOffset())});
7166     }
7167     llvm::sort(Targets,
7168                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7169                  return T1.Offset < T2.Offset;
7170                });
7171 
7172     for (auto &T : Targets) {
7173       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7174       Ops.push_back(T.Target);
7175     }
7176 
7177     Ops.push_back(DAG.getRoot()); // Chain
7178     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7179                                  MVT::Other, Ops),
7180               0);
7181     DAG.setRoot(N);
7182     setValue(&I, N);
7183     HasTailCall = true;
7184     return;
7185   }
7186 
7187   case Intrinsic::wasm_landingpad_index:
7188     // Information this intrinsic contained has been transferred to
7189     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7190     // delete it now.
7191     return;
7192 
7193   case Intrinsic::aarch64_settag:
7194   case Intrinsic::aarch64_settag_zero: {
7195     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7196     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7197     SDValue Val = TSI.EmitTargetCodeForSetTag(
7198         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7199         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7200         ZeroMemory);
7201     DAG.setRoot(Val);
7202     setValue(&I, Val);
7203     return;
7204   }
7205   case Intrinsic::ptrmask: {
7206     SDValue Ptr = getValue(I.getOperand(0));
7207     SDValue Const = getValue(I.getOperand(1));
7208 
7209     EVT PtrVT = Ptr.getValueType();
7210     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7211                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7212     return;
7213   }
7214   case Intrinsic::threadlocal_address: {
7215     setValue(&I, getValue(I.getOperand(0)));
7216     return;
7217   }
7218   case Intrinsic::get_active_lane_mask: {
7219     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7220     SDValue Index = getValue(I.getOperand(0));
7221     EVT ElementVT = Index.getValueType();
7222 
7223     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7224       visitTargetIntrinsic(I, Intrinsic);
7225       return;
7226     }
7227 
7228     SDValue TripCount = getValue(I.getOperand(1));
7229     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7230 
7231     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7232     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7233     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7234     SDValue VectorInduction = DAG.getNode(
7235         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7236     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7237                                  VectorTripCount, ISD::CondCode::SETULT);
7238     setValue(&I, SetCC);
7239     return;
7240   }
7241   case Intrinsic::vector_insert: {
7242     SDValue Vec = getValue(I.getOperand(0));
7243     SDValue SubVec = getValue(I.getOperand(1));
7244     SDValue Index = getValue(I.getOperand(2));
7245 
7246     // The intrinsic's index type is i64, but the SDNode requires an index type
7247     // suitable for the target. Convert the index as required.
7248     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7249     if (Index.getValueType() != VectorIdxTy)
7250       Index = DAG.getVectorIdxConstant(
7251           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7252 
7253     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7254     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7255                              Index));
7256     return;
7257   }
7258   case Intrinsic::vector_extract: {
7259     SDValue Vec = getValue(I.getOperand(0));
7260     SDValue Index = getValue(I.getOperand(1));
7261     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7262 
7263     // The intrinsic's index type is i64, but the SDNode requires an index type
7264     // suitable for the target. Convert the index as required.
7265     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7266     if (Index.getValueType() != VectorIdxTy)
7267       Index = DAG.getVectorIdxConstant(
7268           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7269 
7270     setValue(&I,
7271              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7272     return;
7273   }
7274   case Intrinsic::experimental_vector_reverse:
7275     visitVectorReverse(I);
7276     return;
7277   case Intrinsic::experimental_vector_splice:
7278     visitVectorSplice(I);
7279     return;
7280   }
7281 }
7282 
7283 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7284     const ConstrainedFPIntrinsic &FPI) {
7285   SDLoc sdl = getCurSDLoc();
7286 
7287   // We do not need to serialize constrained FP intrinsics against
7288   // each other or against (nonvolatile) loads, so they can be
7289   // chained like loads.
7290   SDValue Chain = DAG.getRoot();
7291   SmallVector<SDValue, 4> Opers;
7292   Opers.push_back(Chain);
7293   if (FPI.isUnaryOp()) {
7294     Opers.push_back(getValue(FPI.getArgOperand(0)));
7295   } else if (FPI.isTernaryOp()) {
7296     Opers.push_back(getValue(FPI.getArgOperand(0)));
7297     Opers.push_back(getValue(FPI.getArgOperand(1)));
7298     Opers.push_back(getValue(FPI.getArgOperand(2)));
7299   } else {
7300     Opers.push_back(getValue(FPI.getArgOperand(0)));
7301     Opers.push_back(getValue(FPI.getArgOperand(1)));
7302   }
7303 
7304   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7305     assert(Result.getNode()->getNumValues() == 2);
7306 
7307     // Push node to the appropriate list so that future instructions can be
7308     // chained up correctly.
7309     SDValue OutChain = Result.getValue(1);
7310     switch (EB) {
7311     case fp::ExceptionBehavior::ebIgnore:
7312       // The only reason why ebIgnore nodes still need to be chained is that
7313       // they might depend on the current rounding mode, and therefore must
7314       // not be moved across instruction that may change that mode.
7315       [[fallthrough]];
7316     case fp::ExceptionBehavior::ebMayTrap:
7317       // These must not be moved across calls or instructions that may change
7318       // floating-point exception masks.
7319       PendingConstrainedFP.push_back(OutChain);
7320       break;
7321     case fp::ExceptionBehavior::ebStrict:
7322       // These must not be moved across calls or instructions that may change
7323       // floating-point exception masks or read floating-point exception flags.
7324       // In addition, they cannot be optimized out even if unused.
7325       PendingConstrainedFPStrict.push_back(OutChain);
7326       break;
7327     }
7328   };
7329 
7330   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7331   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7332   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7333   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7334 
7335   SDNodeFlags Flags;
7336   if (EB == fp::ExceptionBehavior::ebIgnore)
7337     Flags.setNoFPExcept(true);
7338 
7339   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7340     Flags.copyFMF(*FPOp);
7341 
7342   unsigned Opcode;
7343   switch (FPI.getIntrinsicID()) {
7344   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7345 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7346   case Intrinsic::INTRINSIC:                                                   \
7347     Opcode = ISD::STRICT_##DAGN;                                               \
7348     break;
7349 #include "llvm/IR/ConstrainedOps.def"
7350   case Intrinsic::experimental_constrained_fmuladd: {
7351     Opcode = ISD::STRICT_FMA;
7352     // Break fmuladd into fmul and fadd.
7353     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7354         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7355       Opers.pop_back();
7356       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7357       pushOutChain(Mul, EB);
7358       Opcode = ISD::STRICT_FADD;
7359       Opers.clear();
7360       Opers.push_back(Mul.getValue(1));
7361       Opers.push_back(Mul.getValue(0));
7362       Opers.push_back(getValue(FPI.getArgOperand(2)));
7363     }
7364     break;
7365   }
7366   }
7367 
7368   // A few strict DAG nodes carry additional operands that are not
7369   // set up by the default code above.
7370   switch (Opcode) {
7371   default: break;
7372   case ISD::STRICT_FP_ROUND:
7373     Opers.push_back(
7374         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7375     break;
7376   case ISD::STRICT_FSETCC:
7377   case ISD::STRICT_FSETCCS: {
7378     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7379     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7380     if (TM.Options.NoNaNsFPMath)
7381       Condition = getFCmpCodeWithoutNaN(Condition);
7382     Opers.push_back(DAG.getCondCode(Condition));
7383     break;
7384   }
7385   }
7386 
7387   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7388   pushOutChain(Result, EB);
7389 
7390   SDValue FPResult = Result.getValue(0);
7391   setValue(&FPI, FPResult);
7392 }
7393 
7394 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7395   Optional<unsigned> ResOPC;
7396   switch (VPIntrin.getIntrinsicID()) {
7397 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7398   case Intrinsic::VPID:                                                        \
7399     ResOPC = ISD::VPSD;                                                        \
7400     break;
7401 #include "llvm/IR/VPIntrinsics.def"
7402   }
7403 
7404   if (!ResOPC)
7405     llvm_unreachable(
7406         "Inconsistency: no SDNode available for this VPIntrinsic!");
7407 
7408   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7409       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7410     if (VPIntrin.getFastMathFlags().allowReassoc())
7411       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7412                                                 : ISD::VP_REDUCE_FMUL;
7413   }
7414 
7415   return *ResOPC;
7416 }
7417 
7418 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT,
7419                                       SmallVector<SDValue, 7> &OpValues) {
7420   SDLoc DL = getCurSDLoc();
7421   Value *PtrOperand = VPIntrin.getArgOperand(0);
7422   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7423   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7424   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7425   SDValue LD;
7426   bool AddToChain = true;
7427   // Do not serialize variable-length loads of constant memory with
7428   // anything.
7429   if (!Alignment)
7430     Alignment = DAG.getEVTAlign(VT);
7431   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7432   AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7433   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7434   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7435       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7436       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7437   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7438                      MMO, false /*IsExpanding */);
7439   if (AddToChain)
7440     PendingLoads.push_back(LD.getValue(1));
7441   setValue(&VPIntrin, LD);
7442 }
7443 
7444 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT,
7445                                         SmallVector<SDValue, 7> &OpValues) {
7446   SDLoc DL = getCurSDLoc();
7447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7448   Value *PtrOperand = VPIntrin.getArgOperand(0);
7449   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7450   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7451   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7452   SDValue LD;
7453   if (!Alignment)
7454     Alignment = DAG.getEVTAlign(VT.getScalarType());
7455   unsigned AS =
7456     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7457   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7458      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7459      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7460   SDValue Base, Index, Scale;
7461   ISD::MemIndexType IndexType;
7462   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7463                                     this, VPIntrin.getParent(),
7464                                     VT.getScalarStoreSize());
7465   if (!UniformBase) {
7466     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7467     Index = getValue(PtrOperand);
7468     IndexType = ISD::SIGNED_SCALED;
7469     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7470   }
7471   EVT IdxVT = Index.getValueType();
7472   EVT EltTy = IdxVT.getVectorElementType();
7473   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7474     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7475     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7476   }
7477   LD = DAG.getGatherVP(
7478       DAG.getVTList(VT, MVT::Other), VT, DL,
7479       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7480       IndexType);
7481   PendingLoads.push_back(LD.getValue(1));
7482   setValue(&VPIntrin, LD);
7483 }
7484 
7485 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin,
7486                                        SmallVector<SDValue, 7> &OpValues) {
7487   SDLoc DL = getCurSDLoc();
7488   Value *PtrOperand = VPIntrin.getArgOperand(1);
7489   EVT VT = OpValues[0].getValueType();
7490   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7491   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7492   SDValue ST;
7493   if (!Alignment)
7494     Alignment = DAG.getEVTAlign(VT);
7495   SDValue Ptr = OpValues[1];
7496   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7497   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7498       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7499       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7500   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7501                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7502                       /* IsTruncating */ false, /*IsCompressing*/ false);
7503   DAG.setRoot(ST);
7504   setValue(&VPIntrin, ST);
7505 }
7506 
7507 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin,
7508                                               SmallVector<SDValue, 7> &OpValues) {
7509   SDLoc DL = getCurSDLoc();
7510   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7511   Value *PtrOperand = VPIntrin.getArgOperand(1);
7512   EVT VT = OpValues[0].getValueType();
7513   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7514   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7515   SDValue ST;
7516   if (!Alignment)
7517     Alignment = DAG.getEVTAlign(VT.getScalarType());
7518   unsigned AS =
7519       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7520   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7521       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7522       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7523   SDValue Base, Index, Scale;
7524   ISD::MemIndexType IndexType;
7525   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7526                                     this, VPIntrin.getParent(),
7527                                     VT.getScalarStoreSize());
7528   if (!UniformBase) {
7529     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7530     Index = getValue(PtrOperand);
7531     IndexType = ISD::SIGNED_SCALED;
7532     Scale =
7533       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7534   }
7535   EVT IdxVT = Index.getValueType();
7536   EVT EltTy = IdxVT.getVectorElementType();
7537   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7538     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7539     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7540   }
7541   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7542                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7543                          OpValues[2], OpValues[3]},
7544                         MMO, IndexType);
7545   DAG.setRoot(ST);
7546   setValue(&VPIntrin, ST);
7547 }
7548 
7549 void SelectionDAGBuilder::visitVPStridedLoad(
7550     const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) {
7551   SDLoc DL = getCurSDLoc();
7552   Value *PtrOperand = VPIntrin.getArgOperand(0);
7553   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7554   if (!Alignment)
7555     Alignment = DAG.getEVTAlign(VT.getScalarType());
7556   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7557   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7558   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7559   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7560   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7561   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7562       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7563       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7564 
7565   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7566                                     OpValues[2], OpValues[3], MMO,
7567                                     false /*IsExpanding*/);
7568 
7569   if (AddToChain)
7570     PendingLoads.push_back(LD.getValue(1));
7571   setValue(&VPIntrin, LD);
7572 }
7573 
7574 void SelectionDAGBuilder::visitVPStridedStore(
7575     const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) {
7576   SDLoc DL = getCurSDLoc();
7577   Value *PtrOperand = VPIntrin.getArgOperand(1);
7578   EVT VT = OpValues[0].getValueType();
7579   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7580   if (!Alignment)
7581     Alignment = DAG.getEVTAlign(VT.getScalarType());
7582   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7583   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7584       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7585       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7586 
7587   SDValue ST = DAG.getStridedStoreVP(
7588       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7589       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7590       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7591       /*IsCompressing*/ false);
7592 
7593   DAG.setRoot(ST);
7594   setValue(&VPIntrin, ST);
7595 }
7596 
7597 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7598   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7599   SDLoc DL = getCurSDLoc();
7600 
7601   ISD::CondCode Condition;
7602   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7603   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7604   if (IsFP) {
7605     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7606     // flags, but calls that don't return floating-point types can't be
7607     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7608     Condition = getFCmpCondCode(CondCode);
7609     if (TM.Options.NoNaNsFPMath)
7610       Condition = getFCmpCodeWithoutNaN(Condition);
7611   } else {
7612     Condition = getICmpCondCode(CondCode);
7613   }
7614 
7615   SDValue Op1 = getValue(VPIntrin.getOperand(0));
7616   SDValue Op2 = getValue(VPIntrin.getOperand(1));
7617   // #2 is the condition code
7618   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7619   SDValue EVL = getValue(VPIntrin.getOperand(4));
7620   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7621   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7622          "Unexpected target EVL type");
7623   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7624 
7625   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7626                                                         VPIntrin.getType());
7627   setValue(&VPIntrin,
7628            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7629 }
7630 
7631 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7632     const VPIntrinsic &VPIntrin) {
7633   SDLoc DL = getCurSDLoc();
7634   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7635 
7636   auto IID = VPIntrin.getIntrinsicID();
7637 
7638   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7639     return visitVPCmp(*CmpI);
7640 
7641   SmallVector<EVT, 4> ValueVTs;
7642   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7643   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7644   SDVTList VTs = DAG.getVTList(ValueVTs);
7645 
7646   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
7647 
7648   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7649   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7650          "Unexpected target EVL type");
7651 
7652   // Request operands.
7653   SmallVector<SDValue, 7> OpValues;
7654   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7655     auto Op = getValue(VPIntrin.getArgOperand(I));
7656     if (I == EVLParamPos)
7657       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7658     OpValues.push_back(Op);
7659   }
7660 
7661   switch (Opcode) {
7662   default: {
7663     SDNodeFlags SDFlags;
7664     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7665       SDFlags.copyFMF(*FPMO);
7666     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
7667     setValue(&VPIntrin, Result);
7668     break;
7669   }
7670   case ISD::VP_LOAD:
7671     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
7672     break;
7673   case ISD::VP_GATHER:
7674     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
7675     break;
7676   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7677     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7678     break;
7679   case ISD::VP_STORE:
7680     visitVPStore(VPIntrin, OpValues);
7681     break;
7682   case ISD::VP_SCATTER:
7683     visitVPScatter(VPIntrin, OpValues);
7684     break;
7685   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7686     visitVPStridedStore(VPIntrin, OpValues);
7687     break;
7688   case ISD::VP_FMULADD: {
7689     assert(OpValues.size() == 5 && "Unexpected number of operands");
7690     SDNodeFlags SDFlags;
7691     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7692       SDFlags.copyFMF(*FPMO);
7693     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7694         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
7695       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
7696     } else {
7697       SDValue Mul = DAG.getNode(
7698           ISD::VP_FMUL, DL, VTs,
7699           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
7700       SDValue Add =
7701           DAG.getNode(ISD::VP_FADD, DL, VTs,
7702                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
7703       setValue(&VPIntrin, Add);
7704     }
7705     break;
7706   }
7707   }
7708 }
7709 
7710 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7711                                           const BasicBlock *EHPadBB,
7712                                           MCSymbol *&BeginLabel) {
7713   MachineFunction &MF = DAG.getMachineFunction();
7714   MachineModuleInfo &MMI = MF.getMMI();
7715 
7716   // Insert a label before the invoke call to mark the try range.  This can be
7717   // used to detect deletion of the invoke via the MachineModuleInfo.
7718   BeginLabel = MMI.getContext().createTempSymbol();
7719 
7720   // For SjLj, keep track of which landing pads go with which invokes
7721   // so as to maintain the ordering of pads in the LSDA.
7722   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7723   if (CallSiteIndex) {
7724     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7725     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7726 
7727     // Now that the call site is handled, stop tracking it.
7728     MMI.setCurrentCallSite(0);
7729   }
7730 
7731   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7732 }
7733 
7734 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7735                                         const BasicBlock *EHPadBB,
7736                                         MCSymbol *BeginLabel) {
7737   assert(BeginLabel && "BeginLabel should've been set");
7738 
7739   MachineFunction &MF = DAG.getMachineFunction();
7740   MachineModuleInfo &MMI = MF.getMMI();
7741 
7742   // Insert a label at the end of the invoke call to mark the try range.  This
7743   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7744   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7745   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7746 
7747   // Inform MachineModuleInfo of range.
7748   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7749   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7750   // actually use outlined funclets and their LSDA info style.
7751   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7752     assert(II && "II should've been set");
7753     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7754     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7755   } else if (!isScopedEHPersonality(Pers)) {
7756     assert(EHPadBB);
7757     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7758   }
7759 
7760   return Chain;
7761 }
7762 
7763 std::pair<SDValue, SDValue>
7764 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7765                                     const BasicBlock *EHPadBB) {
7766   MCSymbol *BeginLabel = nullptr;
7767 
7768   if (EHPadBB) {
7769     // Both PendingLoads and PendingExports must be flushed here;
7770     // this call might not return.
7771     (void)getRoot();
7772     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7773     CLI.setChain(getRoot());
7774   }
7775 
7776   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7777   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7778 
7779   assert((CLI.IsTailCall || Result.second.getNode()) &&
7780          "Non-null chain expected with non-tail call!");
7781   assert((Result.second.getNode() || !Result.first.getNode()) &&
7782          "Null value expected with tail call!");
7783 
7784   if (!Result.second.getNode()) {
7785     // As a special case, a null chain means that a tail call has been emitted
7786     // and the DAG root is already updated.
7787     HasTailCall = true;
7788 
7789     // Since there's no actual continuation from this block, nothing can be
7790     // relying on us setting vregs for them.
7791     PendingExports.clear();
7792   } else {
7793     DAG.setRoot(Result.second);
7794   }
7795 
7796   if (EHPadBB) {
7797     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7798                            BeginLabel));
7799   }
7800 
7801   return Result;
7802 }
7803 
7804 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7805                                       bool isTailCall,
7806                                       bool isMustTailCall,
7807                                       const BasicBlock *EHPadBB) {
7808   auto &DL = DAG.getDataLayout();
7809   FunctionType *FTy = CB.getFunctionType();
7810   Type *RetTy = CB.getType();
7811 
7812   TargetLowering::ArgListTy Args;
7813   Args.reserve(CB.arg_size());
7814 
7815   const Value *SwiftErrorVal = nullptr;
7816   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7817 
7818   if (isTailCall) {
7819     // Avoid emitting tail calls in functions with the disable-tail-calls
7820     // attribute.
7821     auto *Caller = CB.getParent()->getParent();
7822     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7823         "true" && !isMustTailCall)
7824       isTailCall = false;
7825 
7826     // We can't tail call inside a function with a swifterror argument. Lowering
7827     // does not support this yet. It would have to move into the swifterror
7828     // register before the call.
7829     if (TLI.supportSwiftError() &&
7830         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7831       isTailCall = false;
7832   }
7833 
7834   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7835     TargetLowering::ArgListEntry Entry;
7836     const Value *V = *I;
7837 
7838     // Skip empty types
7839     if (V->getType()->isEmptyTy())
7840       continue;
7841 
7842     SDValue ArgNode = getValue(V);
7843     Entry.Node = ArgNode; Entry.Ty = V->getType();
7844 
7845     Entry.setAttributes(&CB, I - CB.arg_begin());
7846 
7847     // Use swifterror virtual register as input to the call.
7848     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7849       SwiftErrorVal = V;
7850       // We find the virtual register for the actual swifterror argument.
7851       // Instead of using the Value, we use the virtual register instead.
7852       Entry.Node =
7853           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7854                           EVT(TLI.getPointerTy(DL)));
7855     }
7856 
7857     Args.push_back(Entry);
7858 
7859     // If we have an explicit sret argument that is an Instruction, (i.e., it
7860     // might point to function-local memory), we can't meaningfully tail-call.
7861     if (Entry.IsSRet && isa<Instruction>(V))
7862       isTailCall = false;
7863   }
7864 
7865   // If call site has a cfguardtarget operand bundle, create and add an
7866   // additional ArgListEntry.
7867   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7868     TargetLowering::ArgListEntry Entry;
7869     Value *V = Bundle->Inputs[0];
7870     SDValue ArgNode = getValue(V);
7871     Entry.Node = ArgNode;
7872     Entry.Ty = V->getType();
7873     Entry.IsCFGuardTarget = true;
7874     Args.push_back(Entry);
7875   }
7876 
7877   // Check if target-independent constraints permit a tail call here.
7878   // Target-dependent constraints are checked within TLI->LowerCallTo.
7879   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7880     isTailCall = false;
7881 
7882   // Disable tail calls if there is an swifterror argument. Targets have not
7883   // been updated to support tail calls.
7884   if (TLI.supportSwiftError() && SwiftErrorVal)
7885     isTailCall = false;
7886 
7887   ConstantInt *CFIType = nullptr;
7888   if (CB.isIndirectCall()) {
7889     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
7890       if (!TLI.supportKCFIBundles())
7891         report_fatal_error(
7892             "Target doesn't support calls with kcfi operand bundles.");
7893       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
7894       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
7895     }
7896   }
7897 
7898   TargetLowering::CallLoweringInfo CLI(DAG);
7899   CLI.setDebugLoc(getCurSDLoc())
7900       .setChain(getRoot())
7901       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7902       .setTailCall(isTailCall)
7903       .setConvergent(CB.isConvergent())
7904       .setIsPreallocated(
7905           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
7906       .setCFIType(CFIType);
7907   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7908 
7909   if (Result.first.getNode()) {
7910     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7911     setValue(&CB, Result.first);
7912   }
7913 
7914   // The last element of CLI.InVals has the SDValue for swifterror return.
7915   // Here we copy it to a virtual register and update SwiftErrorMap for
7916   // book-keeping.
7917   if (SwiftErrorVal && TLI.supportSwiftError()) {
7918     // Get the last element of InVals.
7919     SDValue Src = CLI.InVals.back();
7920     Register VReg =
7921         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7922     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7923     DAG.setRoot(CopyNode);
7924   }
7925 }
7926 
7927 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7928                              SelectionDAGBuilder &Builder) {
7929   // Check to see if this load can be trivially constant folded, e.g. if the
7930   // input is from a string literal.
7931   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7932     // Cast pointer to the type we really want to load.
7933     Type *LoadTy =
7934         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7935     if (LoadVT.isVector())
7936       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7937 
7938     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7939                                          PointerType::getUnqual(LoadTy));
7940 
7941     if (const Constant *LoadCst =
7942             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
7943                                          LoadTy, Builder.DAG.getDataLayout()))
7944       return Builder.getValue(LoadCst);
7945   }
7946 
7947   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7948   // still constant memory, the input chain can be the entry node.
7949   SDValue Root;
7950   bool ConstantMemory = false;
7951 
7952   // Do not serialize (non-volatile) loads of constant memory with anything.
7953   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7954     Root = Builder.DAG.getEntryNode();
7955     ConstantMemory = true;
7956   } else {
7957     // Do not serialize non-volatile loads against each other.
7958     Root = Builder.DAG.getRoot();
7959   }
7960 
7961   SDValue Ptr = Builder.getValue(PtrVal);
7962   SDValue LoadVal =
7963       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7964                           MachinePointerInfo(PtrVal), Align(1));
7965 
7966   if (!ConstantMemory)
7967     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7968   return LoadVal;
7969 }
7970 
7971 /// Record the value for an instruction that produces an integer result,
7972 /// converting the type where necessary.
7973 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7974                                                   SDValue Value,
7975                                                   bool IsSigned) {
7976   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7977                                                     I.getType(), true);
7978   if (IsSigned)
7979     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7980   else
7981     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7982   setValue(&I, Value);
7983 }
7984 
7985 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7986 /// true and lower it. Otherwise return false, and it will be lowered like a
7987 /// normal call.
7988 /// The caller already checked that \p I calls the appropriate LibFunc with a
7989 /// correct prototype.
7990 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7991   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7992   const Value *Size = I.getArgOperand(2);
7993   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
7994   if (CSize && CSize->getZExtValue() == 0) {
7995     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7996                                                           I.getType(), true);
7997     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7998     return true;
7999   }
8000 
8001   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8002   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8003       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8004       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8005   if (Res.first.getNode()) {
8006     processIntegerCallValue(I, Res.first, true);
8007     PendingLoads.push_back(Res.second);
8008     return true;
8009   }
8010 
8011   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8012   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8013   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8014     return false;
8015 
8016   // If the target has a fast compare for the given size, it will return a
8017   // preferred load type for that size. Require that the load VT is legal and
8018   // that the target supports unaligned loads of that type. Otherwise, return
8019   // INVALID.
8020   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8021     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8022     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8023     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8024       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8025       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8026       // TODO: Check alignment of src and dest ptrs.
8027       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8028       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8029       if (!TLI.isTypeLegal(LVT) ||
8030           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8031           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8032         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8033     }
8034 
8035     return LVT;
8036   };
8037 
8038   // This turns into unaligned loads. We only do this if the target natively
8039   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8040   // we'll only produce a small number of byte loads.
8041   MVT LoadVT;
8042   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8043   switch (NumBitsToCompare) {
8044   default:
8045     return false;
8046   case 16:
8047     LoadVT = MVT::i16;
8048     break;
8049   case 32:
8050     LoadVT = MVT::i32;
8051     break;
8052   case 64:
8053   case 128:
8054   case 256:
8055     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8056     break;
8057   }
8058 
8059   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8060     return false;
8061 
8062   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8063   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8064 
8065   // Bitcast to a wide integer type if the loads are vectors.
8066   if (LoadVT.isVector()) {
8067     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8068     LoadL = DAG.getBitcast(CmpVT, LoadL);
8069     LoadR = DAG.getBitcast(CmpVT, LoadR);
8070   }
8071 
8072   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8073   processIntegerCallValue(I, Cmp, false);
8074   return true;
8075 }
8076 
8077 /// See if we can lower a memchr call into an optimized form. If so, return
8078 /// true and lower it. Otherwise return false, and it will be lowered like a
8079 /// normal call.
8080 /// The caller already checked that \p I calls the appropriate LibFunc with a
8081 /// correct prototype.
8082 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8083   const Value *Src = I.getArgOperand(0);
8084   const Value *Char = I.getArgOperand(1);
8085   const Value *Length = I.getArgOperand(2);
8086 
8087   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8088   std::pair<SDValue, SDValue> Res =
8089     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8090                                 getValue(Src), getValue(Char), getValue(Length),
8091                                 MachinePointerInfo(Src));
8092   if (Res.first.getNode()) {
8093     setValue(&I, Res.first);
8094     PendingLoads.push_back(Res.second);
8095     return true;
8096   }
8097 
8098   return false;
8099 }
8100 
8101 /// See if we can lower a mempcpy call into an optimized form. If so, return
8102 /// true and lower it. Otherwise return false, and it will be lowered like a
8103 /// normal call.
8104 /// The caller already checked that \p I calls the appropriate LibFunc with a
8105 /// correct prototype.
8106 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8107   SDValue Dst = getValue(I.getArgOperand(0));
8108   SDValue Src = getValue(I.getArgOperand(1));
8109   SDValue Size = getValue(I.getArgOperand(2));
8110 
8111   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8112   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8113   // DAG::getMemcpy needs Alignment to be defined.
8114   Align Alignment = std::min(DstAlign, SrcAlign);
8115 
8116   bool isVol = false;
8117   SDLoc sdl = getCurSDLoc();
8118 
8119   // In the mempcpy context we need to pass in a false value for isTailCall
8120   // because the return pointer needs to be adjusted by the size of
8121   // the copied memory.
8122   SDValue Root = isVol ? getRoot() : getMemoryRoot();
8123   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
8124                              /*isTailCall=*/false,
8125                              MachinePointerInfo(I.getArgOperand(0)),
8126                              MachinePointerInfo(I.getArgOperand(1)),
8127                              I.getAAMetadata());
8128   assert(MC.getNode() != nullptr &&
8129          "** memcpy should not be lowered as TailCall in mempcpy context **");
8130   DAG.setRoot(MC);
8131 
8132   // Check if Size needs to be truncated or extended.
8133   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8134 
8135   // Adjust return pointer to point just past the last dst byte.
8136   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8137                                     Dst, Size);
8138   setValue(&I, DstPlusSize);
8139   return true;
8140 }
8141 
8142 /// See if we can lower a strcpy call into an optimized form.  If so, return
8143 /// true and lower it, otherwise return false and it will be lowered like a
8144 /// normal call.
8145 /// The caller already checked that \p I calls the appropriate LibFunc with a
8146 /// correct prototype.
8147 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8148   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8149 
8150   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8151   std::pair<SDValue, SDValue> Res =
8152     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8153                                 getValue(Arg0), getValue(Arg1),
8154                                 MachinePointerInfo(Arg0),
8155                                 MachinePointerInfo(Arg1), isStpcpy);
8156   if (Res.first.getNode()) {
8157     setValue(&I, Res.first);
8158     DAG.setRoot(Res.second);
8159     return true;
8160   }
8161 
8162   return false;
8163 }
8164 
8165 /// See if we can lower a strcmp call into an optimized form.  If so, return
8166 /// true and lower it, otherwise return false and it will be lowered like a
8167 /// normal call.
8168 /// The caller already checked that \p I calls the appropriate LibFunc with a
8169 /// correct prototype.
8170 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8171   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8172 
8173   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8174   std::pair<SDValue, SDValue> Res =
8175     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8176                                 getValue(Arg0), getValue(Arg1),
8177                                 MachinePointerInfo(Arg0),
8178                                 MachinePointerInfo(Arg1));
8179   if (Res.first.getNode()) {
8180     processIntegerCallValue(I, Res.first, true);
8181     PendingLoads.push_back(Res.second);
8182     return true;
8183   }
8184 
8185   return false;
8186 }
8187 
8188 /// See if we can lower a strlen call into an optimized form.  If so, return
8189 /// true and lower it, otherwise return false and it will be lowered like a
8190 /// normal call.
8191 /// The caller already checked that \p I calls the appropriate LibFunc with a
8192 /// correct prototype.
8193 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8194   const Value *Arg0 = I.getArgOperand(0);
8195 
8196   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8197   std::pair<SDValue, SDValue> Res =
8198     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8199                                 getValue(Arg0), MachinePointerInfo(Arg0));
8200   if (Res.first.getNode()) {
8201     processIntegerCallValue(I, Res.first, false);
8202     PendingLoads.push_back(Res.second);
8203     return true;
8204   }
8205 
8206   return false;
8207 }
8208 
8209 /// See if we can lower a strnlen call into an optimized form.  If so, return
8210 /// true and lower it, otherwise return false and it will be lowered like a
8211 /// normal call.
8212 /// The caller already checked that \p I calls the appropriate LibFunc with a
8213 /// correct prototype.
8214 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8215   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8216 
8217   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8218   std::pair<SDValue, SDValue> Res =
8219     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8220                                  getValue(Arg0), getValue(Arg1),
8221                                  MachinePointerInfo(Arg0));
8222   if (Res.first.getNode()) {
8223     processIntegerCallValue(I, Res.first, false);
8224     PendingLoads.push_back(Res.second);
8225     return true;
8226   }
8227 
8228   return false;
8229 }
8230 
8231 /// See if we can lower a unary floating-point operation into an SDNode with
8232 /// the specified Opcode.  If so, return true and lower it, otherwise return
8233 /// false and it will be lowered like a normal call.
8234 /// The caller already checked that \p I calls the appropriate LibFunc with a
8235 /// correct prototype.
8236 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8237                                               unsigned Opcode) {
8238   // We already checked this call's prototype; verify it doesn't modify errno.
8239   if (!I.onlyReadsMemory())
8240     return false;
8241 
8242   SDNodeFlags Flags;
8243   Flags.copyFMF(cast<FPMathOperator>(I));
8244 
8245   SDValue Tmp = getValue(I.getArgOperand(0));
8246   setValue(&I,
8247            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8248   return true;
8249 }
8250 
8251 /// See if we can lower a binary floating-point operation into an SDNode with
8252 /// the specified Opcode. If so, return true and lower it. Otherwise return
8253 /// false, and it will be lowered like a normal call.
8254 /// The caller already checked that \p I calls the appropriate LibFunc with a
8255 /// correct prototype.
8256 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8257                                                unsigned Opcode) {
8258   // We already checked this call's prototype; verify it doesn't modify errno.
8259   if (!I.onlyReadsMemory())
8260     return false;
8261 
8262   SDNodeFlags Flags;
8263   Flags.copyFMF(cast<FPMathOperator>(I));
8264 
8265   SDValue Tmp0 = getValue(I.getArgOperand(0));
8266   SDValue Tmp1 = getValue(I.getArgOperand(1));
8267   EVT VT = Tmp0.getValueType();
8268   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8269   return true;
8270 }
8271 
8272 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8273   // Handle inline assembly differently.
8274   if (I.isInlineAsm()) {
8275     visitInlineAsm(I);
8276     return;
8277   }
8278 
8279   if (Function *F = I.getCalledFunction()) {
8280     diagnoseDontCall(I);
8281 
8282     if (F->isDeclaration()) {
8283       // Is this an LLVM intrinsic or a target-specific intrinsic?
8284       unsigned IID = F->getIntrinsicID();
8285       if (!IID)
8286         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8287           IID = II->getIntrinsicID(F);
8288 
8289       if (IID) {
8290         visitIntrinsicCall(I, IID);
8291         return;
8292       }
8293     }
8294 
8295     // Check for well-known libc/libm calls.  If the function is internal, it
8296     // can't be a library call.  Don't do the check if marked as nobuiltin for
8297     // some reason or the call site requires strict floating point semantics.
8298     LibFunc Func;
8299     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8300         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8301         LibInfo->hasOptimizedCodeGen(Func)) {
8302       switch (Func) {
8303       default: break;
8304       case LibFunc_bcmp:
8305         if (visitMemCmpBCmpCall(I))
8306           return;
8307         break;
8308       case LibFunc_copysign:
8309       case LibFunc_copysignf:
8310       case LibFunc_copysignl:
8311         // We already checked this call's prototype; verify it doesn't modify
8312         // errno.
8313         if (I.onlyReadsMemory()) {
8314           SDValue LHS = getValue(I.getArgOperand(0));
8315           SDValue RHS = getValue(I.getArgOperand(1));
8316           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8317                                    LHS.getValueType(), LHS, RHS));
8318           return;
8319         }
8320         break;
8321       case LibFunc_fabs:
8322       case LibFunc_fabsf:
8323       case LibFunc_fabsl:
8324         if (visitUnaryFloatCall(I, ISD::FABS))
8325           return;
8326         break;
8327       case LibFunc_fmin:
8328       case LibFunc_fminf:
8329       case LibFunc_fminl:
8330         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8331           return;
8332         break;
8333       case LibFunc_fmax:
8334       case LibFunc_fmaxf:
8335       case LibFunc_fmaxl:
8336         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8337           return;
8338         break;
8339       case LibFunc_sin:
8340       case LibFunc_sinf:
8341       case LibFunc_sinl:
8342         if (visitUnaryFloatCall(I, ISD::FSIN))
8343           return;
8344         break;
8345       case LibFunc_cos:
8346       case LibFunc_cosf:
8347       case LibFunc_cosl:
8348         if (visitUnaryFloatCall(I, ISD::FCOS))
8349           return;
8350         break;
8351       case LibFunc_sqrt:
8352       case LibFunc_sqrtf:
8353       case LibFunc_sqrtl:
8354       case LibFunc_sqrt_finite:
8355       case LibFunc_sqrtf_finite:
8356       case LibFunc_sqrtl_finite:
8357         if (visitUnaryFloatCall(I, ISD::FSQRT))
8358           return;
8359         break;
8360       case LibFunc_floor:
8361       case LibFunc_floorf:
8362       case LibFunc_floorl:
8363         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8364           return;
8365         break;
8366       case LibFunc_nearbyint:
8367       case LibFunc_nearbyintf:
8368       case LibFunc_nearbyintl:
8369         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8370           return;
8371         break;
8372       case LibFunc_ceil:
8373       case LibFunc_ceilf:
8374       case LibFunc_ceill:
8375         if (visitUnaryFloatCall(I, ISD::FCEIL))
8376           return;
8377         break;
8378       case LibFunc_rint:
8379       case LibFunc_rintf:
8380       case LibFunc_rintl:
8381         if (visitUnaryFloatCall(I, ISD::FRINT))
8382           return;
8383         break;
8384       case LibFunc_round:
8385       case LibFunc_roundf:
8386       case LibFunc_roundl:
8387         if (visitUnaryFloatCall(I, ISD::FROUND))
8388           return;
8389         break;
8390       case LibFunc_trunc:
8391       case LibFunc_truncf:
8392       case LibFunc_truncl:
8393         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8394           return;
8395         break;
8396       case LibFunc_log2:
8397       case LibFunc_log2f:
8398       case LibFunc_log2l:
8399         if (visitUnaryFloatCall(I, ISD::FLOG2))
8400           return;
8401         break;
8402       case LibFunc_exp2:
8403       case LibFunc_exp2f:
8404       case LibFunc_exp2l:
8405         if (visitUnaryFloatCall(I, ISD::FEXP2))
8406           return;
8407         break;
8408       case LibFunc_memcmp:
8409         if (visitMemCmpBCmpCall(I))
8410           return;
8411         break;
8412       case LibFunc_mempcpy:
8413         if (visitMemPCpyCall(I))
8414           return;
8415         break;
8416       case LibFunc_memchr:
8417         if (visitMemChrCall(I))
8418           return;
8419         break;
8420       case LibFunc_strcpy:
8421         if (visitStrCpyCall(I, false))
8422           return;
8423         break;
8424       case LibFunc_stpcpy:
8425         if (visitStrCpyCall(I, true))
8426           return;
8427         break;
8428       case LibFunc_strcmp:
8429         if (visitStrCmpCall(I))
8430           return;
8431         break;
8432       case LibFunc_strlen:
8433         if (visitStrLenCall(I))
8434           return;
8435         break;
8436       case LibFunc_strnlen:
8437         if (visitStrNLenCall(I))
8438           return;
8439         break;
8440       }
8441     }
8442   }
8443 
8444   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8445   // have to do anything here to lower funclet bundles.
8446   // CFGuardTarget bundles are lowered in LowerCallTo.
8447   assert(!I.hasOperandBundlesOtherThan(
8448              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8449               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8450               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8451          "Cannot lower calls with arbitrary operand bundles!");
8452 
8453   SDValue Callee = getValue(I.getCalledOperand());
8454 
8455   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8456     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8457   else
8458     // Check if we can potentially perform a tail call. More detailed checking
8459     // is be done within LowerCallTo, after more information about the call is
8460     // known.
8461     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8462 }
8463 
8464 namespace {
8465 
8466 /// AsmOperandInfo - This contains information for each constraint that we are
8467 /// lowering.
8468 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8469 public:
8470   /// CallOperand - If this is the result output operand or a clobber
8471   /// this is null, otherwise it is the incoming operand to the CallInst.
8472   /// This gets modified as the asm is processed.
8473   SDValue CallOperand;
8474 
8475   /// AssignedRegs - If this is a register or register class operand, this
8476   /// contains the set of register corresponding to the operand.
8477   RegsForValue AssignedRegs;
8478 
8479   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8480     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8481   }
8482 
8483   /// Whether or not this operand accesses memory
8484   bool hasMemory(const TargetLowering &TLI) const {
8485     // Indirect operand accesses access memory.
8486     if (isIndirect)
8487       return true;
8488 
8489     for (const auto &Code : Codes)
8490       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8491         return true;
8492 
8493     return false;
8494   }
8495 };
8496 
8497 
8498 } // end anonymous namespace
8499 
8500 /// Make sure that the output operand \p OpInfo and its corresponding input
8501 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8502 /// out).
8503 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8504                                SDISelAsmOperandInfo &MatchingOpInfo,
8505                                SelectionDAG &DAG) {
8506   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8507     return;
8508 
8509   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8510   const auto &TLI = DAG.getTargetLoweringInfo();
8511 
8512   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8513       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8514                                        OpInfo.ConstraintVT);
8515   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8516       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8517                                        MatchingOpInfo.ConstraintVT);
8518   if ((OpInfo.ConstraintVT.isInteger() !=
8519        MatchingOpInfo.ConstraintVT.isInteger()) ||
8520       (MatchRC.second != InputRC.second)) {
8521     // FIXME: error out in a more elegant fashion
8522     report_fatal_error("Unsupported asm: input constraint"
8523                        " with a matching output constraint of"
8524                        " incompatible type!");
8525   }
8526   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8527 }
8528 
8529 /// Get a direct memory input to behave well as an indirect operand.
8530 /// This may introduce stores, hence the need for a \p Chain.
8531 /// \return The (possibly updated) chain.
8532 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8533                                         SDISelAsmOperandInfo &OpInfo,
8534                                         SelectionDAG &DAG) {
8535   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8536 
8537   // If we don't have an indirect input, put it in the constpool if we can,
8538   // otherwise spill it to a stack slot.
8539   // TODO: This isn't quite right. We need to handle these according to
8540   // the addressing mode that the constraint wants. Also, this may take
8541   // an additional register for the computation and we don't want that
8542   // either.
8543 
8544   // If the operand is a float, integer, or vector constant, spill to a
8545   // constant pool entry to get its address.
8546   const Value *OpVal = OpInfo.CallOperandVal;
8547   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8548       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8549     OpInfo.CallOperand = DAG.getConstantPool(
8550         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8551     return Chain;
8552   }
8553 
8554   // Otherwise, create a stack slot and emit a store to it before the asm.
8555   Type *Ty = OpVal->getType();
8556   auto &DL = DAG.getDataLayout();
8557   uint64_t TySize = DL.getTypeAllocSize(Ty);
8558   MachineFunction &MF = DAG.getMachineFunction();
8559   int SSFI = MF.getFrameInfo().CreateStackObject(
8560       TySize, DL.getPrefTypeAlign(Ty), false);
8561   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8562   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8563                             MachinePointerInfo::getFixedStack(MF, SSFI),
8564                             TLI.getMemValueType(DL, Ty));
8565   OpInfo.CallOperand = StackSlot;
8566 
8567   return Chain;
8568 }
8569 
8570 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8571 /// specified operand.  We prefer to assign virtual registers, to allow the
8572 /// register allocator to handle the assignment process.  However, if the asm
8573 /// uses features that we can't model on machineinstrs, we have SDISel do the
8574 /// allocation.  This produces generally horrible, but correct, code.
8575 ///
8576 ///   OpInfo describes the operand
8577 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8578 static llvm::Optional<unsigned>
8579 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8580                      SDISelAsmOperandInfo &OpInfo,
8581                      SDISelAsmOperandInfo &RefOpInfo) {
8582   LLVMContext &Context = *DAG.getContext();
8583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8584 
8585   MachineFunction &MF = DAG.getMachineFunction();
8586   SmallVector<unsigned, 4> Regs;
8587   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8588 
8589   // No work to do for memory/address operands.
8590   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8591       OpInfo.ConstraintType == TargetLowering::C_Address)
8592     return None;
8593 
8594   // If this is a constraint for a single physreg, or a constraint for a
8595   // register class, find it.
8596   unsigned AssignedReg;
8597   const TargetRegisterClass *RC;
8598   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8599       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8600   // RC is unset only on failure. Return immediately.
8601   if (!RC)
8602     return None;
8603 
8604   // Get the actual register value type.  This is important, because the user
8605   // may have asked for (e.g.) the AX register in i32 type.  We need to
8606   // remember that AX is actually i16 to get the right extension.
8607   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8608 
8609   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8610     // If this is an FP operand in an integer register (or visa versa), or more
8611     // generally if the operand value disagrees with the register class we plan
8612     // to stick it in, fix the operand type.
8613     //
8614     // If this is an input value, the bitcast to the new type is done now.
8615     // Bitcast for output value is done at the end of visitInlineAsm().
8616     if ((OpInfo.Type == InlineAsm::isOutput ||
8617          OpInfo.Type == InlineAsm::isInput) &&
8618         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8619       // Try to convert to the first EVT that the reg class contains.  If the
8620       // types are identical size, use a bitcast to convert (e.g. two differing
8621       // vector types).  Note: output bitcast is done at the end of
8622       // visitInlineAsm().
8623       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8624         // Exclude indirect inputs while they are unsupported because the code
8625         // to perform the load is missing and thus OpInfo.CallOperand still
8626         // refers to the input address rather than the pointed-to value.
8627         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8628           OpInfo.CallOperand =
8629               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8630         OpInfo.ConstraintVT = RegVT;
8631         // If the operand is an FP value and we want it in integer registers,
8632         // use the corresponding integer type. This turns an f64 value into
8633         // i64, which can be passed with two i32 values on a 32-bit machine.
8634       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8635         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8636         if (OpInfo.Type == InlineAsm::isInput)
8637           OpInfo.CallOperand =
8638               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8639         OpInfo.ConstraintVT = VT;
8640       }
8641     }
8642   }
8643 
8644   // No need to allocate a matching input constraint since the constraint it's
8645   // matching to has already been allocated.
8646   if (OpInfo.isMatchingInputConstraint())
8647     return None;
8648 
8649   EVT ValueVT = OpInfo.ConstraintVT;
8650   if (OpInfo.ConstraintVT == MVT::Other)
8651     ValueVT = RegVT;
8652 
8653   // Initialize NumRegs.
8654   unsigned NumRegs = 1;
8655   if (OpInfo.ConstraintVT != MVT::Other)
8656     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8657 
8658   // If this is a constraint for a specific physical register, like {r17},
8659   // assign it now.
8660 
8661   // If this associated to a specific register, initialize iterator to correct
8662   // place. If virtual, make sure we have enough registers
8663 
8664   // Initialize iterator if necessary
8665   TargetRegisterClass::iterator I = RC->begin();
8666   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8667 
8668   // Do not check for single registers.
8669   if (AssignedReg) {
8670     I = std::find(I, RC->end(), AssignedReg);
8671     if (I == RC->end()) {
8672       // RC does not contain the selected register, which indicates a
8673       // mismatch between the register and the required type/bitwidth.
8674       return {AssignedReg};
8675     }
8676   }
8677 
8678   for (; NumRegs; --NumRegs, ++I) {
8679     assert(I != RC->end() && "Ran out of registers to allocate!");
8680     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8681     Regs.push_back(R);
8682   }
8683 
8684   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8685   return None;
8686 }
8687 
8688 static unsigned
8689 findMatchingInlineAsmOperand(unsigned OperandNo,
8690                              const std::vector<SDValue> &AsmNodeOperands) {
8691   // Scan until we find the definition we already emitted of this operand.
8692   unsigned CurOp = InlineAsm::Op_FirstOperand;
8693   for (; OperandNo; --OperandNo) {
8694     // Advance to the next operand.
8695     unsigned OpFlag =
8696         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8697     assert((InlineAsm::isRegDefKind(OpFlag) ||
8698             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8699             InlineAsm::isMemKind(OpFlag)) &&
8700            "Skipped past definitions?");
8701     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8702   }
8703   return CurOp;
8704 }
8705 
8706 namespace {
8707 
8708 class ExtraFlags {
8709   unsigned Flags = 0;
8710 
8711 public:
8712   explicit ExtraFlags(const CallBase &Call) {
8713     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8714     if (IA->hasSideEffects())
8715       Flags |= InlineAsm::Extra_HasSideEffects;
8716     if (IA->isAlignStack())
8717       Flags |= InlineAsm::Extra_IsAlignStack;
8718     if (Call.isConvergent())
8719       Flags |= InlineAsm::Extra_IsConvergent;
8720     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8721   }
8722 
8723   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8724     // Ideally, we would only check against memory constraints.  However, the
8725     // meaning of an Other constraint can be target-specific and we can't easily
8726     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8727     // for Other constraints as well.
8728     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8729         OpInfo.ConstraintType == TargetLowering::C_Other) {
8730       if (OpInfo.Type == InlineAsm::isInput)
8731         Flags |= InlineAsm::Extra_MayLoad;
8732       else if (OpInfo.Type == InlineAsm::isOutput)
8733         Flags |= InlineAsm::Extra_MayStore;
8734       else if (OpInfo.Type == InlineAsm::isClobber)
8735         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8736     }
8737   }
8738 
8739   unsigned get() const { return Flags; }
8740 };
8741 
8742 } // end anonymous namespace
8743 
8744 static bool isFunction(SDValue Op) {
8745   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
8746     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8747       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
8748 
8749       // In normal "call dllimport func" instruction (non-inlineasm) it force
8750       // indirect access by specifing call opcode. And usually specially print
8751       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
8752       // not do in this way now. (In fact, this is similar with "Data Access"
8753       // action). So here we ignore dllimport function.
8754       if (Fn && !Fn->hasDLLImportStorageClass())
8755         return true;
8756     }
8757   }
8758   return false;
8759 }
8760 
8761 /// visitInlineAsm - Handle a call to an InlineAsm object.
8762 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8763                                          const BasicBlock *EHPadBB) {
8764   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8765 
8766   /// ConstraintOperands - Information about all of the constraints.
8767   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8768 
8769   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8770   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8771       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8772 
8773   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8774   // AsmDialect, MayLoad, MayStore).
8775   bool HasSideEffect = IA->hasSideEffects();
8776   ExtraFlags ExtraInfo(Call);
8777 
8778   for (auto &T : TargetConstraints) {
8779     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8780     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8781 
8782     if (OpInfo.CallOperandVal)
8783       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8784 
8785     if (!HasSideEffect)
8786       HasSideEffect = OpInfo.hasMemory(TLI);
8787 
8788     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8789     // FIXME: Could we compute this on OpInfo rather than T?
8790 
8791     // Compute the constraint code and ConstraintType to use.
8792     TLI.ComputeConstraintToUse(T, SDValue());
8793 
8794     if (T.ConstraintType == TargetLowering::C_Immediate &&
8795         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8796       // We've delayed emitting a diagnostic like the "n" constraint because
8797       // inlining could cause an integer showing up.
8798       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8799                                           "' expects an integer constant "
8800                                           "expression");
8801 
8802     ExtraInfo.update(T);
8803   }
8804 
8805   // We won't need to flush pending loads if this asm doesn't touch
8806   // memory and is nonvolatile.
8807   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8808 
8809   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8810   if (EmitEHLabels) {
8811     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8812   }
8813   bool IsCallBr = isa<CallBrInst>(Call);
8814 
8815   if (IsCallBr || EmitEHLabels) {
8816     // If this is a callbr or invoke we need to flush pending exports since
8817     // inlineasm_br and invoke are terminators.
8818     // We need to do this before nodes are glued to the inlineasm_br node.
8819     Chain = getControlRoot();
8820   }
8821 
8822   MCSymbol *BeginLabel = nullptr;
8823   if (EmitEHLabels) {
8824     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8825   }
8826 
8827   int OpNo = -1;
8828   SmallVector<StringRef> AsmStrs;
8829   IA->collectAsmStrs(AsmStrs);
8830 
8831   // Second pass over the constraints: compute which constraint option to use.
8832   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8833     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
8834       OpNo++;
8835 
8836     // If this is an output operand with a matching input operand, look up the
8837     // matching input. If their types mismatch, e.g. one is an integer, the
8838     // other is floating point, or their sizes are different, flag it as an
8839     // error.
8840     if (OpInfo.hasMatchingInput()) {
8841       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8842       patchMatchingInput(OpInfo, Input, DAG);
8843     }
8844 
8845     // Compute the constraint code and ConstraintType to use.
8846     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8847 
8848     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
8849          OpInfo.Type == InlineAsm::isClobber) ||
8850         OpInfo.ConstraintType == TargetLowering::C_Address)
8851       continue;
8852 
8853     // In Linux PIC model, there are 4 cases about value/label addressing:
8854     //
8855     // 1: Function call or Label jmp inside the module.
8856     // 2: Data access (such as global variable, static variable) inside module.
8857     // 3: Function call or Label jmp outside the module.
8858     // 4: Data access (such as global variable) outside the module.
8859     //
8860     // Due to current llvm inline asm architecture designed to not "recognize"
8861     // the asm code, there are quite troubles for us to treat mem addressing
8862     // differently for same value/adress used in different instuctions.
8863     // For example, in pic model, call a func may in plt way or direclty
8864     // pc-related, but lea/mov a function adress may use got.
8865     //
8866     // Here we try to "recognize" function call for the case 1 and case 3 in
8867     // inline asm. And try to adjust the constraint for them.
8868     //
8869     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
8870     // label, so here we don't handle jmp function label now, but we need to
8871     // enhance it (especilly in PIC model) if we meet meaningful requirements.
8872     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
8873         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
8874         TM.getCodeModel() != CodeModel::Large) {
8875       OpInfo.isIndirect = false;
8876       OpInfo.ConstraintType = TargetLowering::C_Address;
8877     }
8878 
8879     // If this is a memory input, and if the operand is not indirect, do what we
8880     // need to provide an address for the memory input.
8881     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8882         !OpInfo.isIndirect) {
8883       assert((OpInfo.isMultipleAlternative ||
8884               (OpInfo.Type == InlineAsm::isInput)) &&
8885              "Can only indirectify direct input operands!");
8886 
8887       // Memory operands really want the address of the value.
8888       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8889 
8890       // There is no longer a Value* corresponding to this operand.
8891       OpInfo.CallOperandVal = nullptr;
8892 
8893       // It is now an indirect operand.
8894       OpInfo.isIndirect = true;
8895     }
8896 
8897   }
8898 
8899   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8900   std::vector<SDValue> AsmNodeOperands;
8901   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8902   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8903       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8904 
8905   // If we have a !srcloc metadata node associated with it, we want to attach
8906   // this to the ultimately generated inline asm machineinstr.  To do this, we
8907   // pass in the third operand as this (potentially null) inline asm MDNode.
8908   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8909   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8910 
8911   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8912   // bits as operand 3.
8913   AsmNodeOperands.push_back(DAG.getTargetConstant(
8914       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8915 
8916   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8917   // this, assign virtual and physical registers for inputs and otput.
8918   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8919     // Assign Registers.
8920     SDISelAsmOperandInfo &RefOpInfo =
8921         OpInfo.isMatchingInputConstraint()
8922             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8923             : OpInfo;
8924     const auto RegError =
8925         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8926     if (RegError) {
8927       const MachineFunction &MF = DAG.getMachineFunction();
8928       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8929       const char *RegName = TRI.getName(RegError.value());
8930       emitInlineAsmError(Call, "register '" + Twine(RegName) +
8931                                    "' allocated for constraint '" +
8932                                    Twine(OpInfo.ConstraintCode) +
8933                                    "' does not match required type");
8934       return;
8935     }
8936 
8937     auto DetectWriteToReservedRegister = [&]() {
8938       const MachineFunction &MF = DAG.getMachineFunction();
8939       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8940       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8941         if (Register::isPhysicalRegister(Reg) &&
8942             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8943           const char *RegName = TRI.getName(Reg);
8944           emitInlineAsmError(Call, "write to reserved register '" +
8945                                        Twine(RegName) + "'");
8946           return true;
8947         }
8948       }
8949       return false;
8950     };
8951     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
8952             (OpInfo.Type == InlineAsm::isInput &&
8953              !OpInfo.isMatchingInputConstraint())) &&
8954            "Only address as input operand is allowed.");
8955 
8956     switch (OpInfo.Type) {
8957     case InlineAsm::isOutput:
8958       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8959         unsigned ConstraintID =
8960             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8961         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8962                "Failed to convert memory constraint code to constraint id.");
8963 
8964         // Add information to the INLINEASM node to know about this output.
8965         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8966         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8967         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8968                                                         MVT::i32));
8969         AsmNodeOperands.push_back(OpInfo.CallOperand);
8970       } else {
8971         // Otherwise, this outputs to a register (directly for C_Register /
8972         // C_RegisterClass, and a target-defined fashion for
8973         // C_Immediate/C_Other). Find a register that we can use.
8974         if (OpInfo.AssignedRegs.Regs.empty()) {
8975           emitInlineAsmError(
8976               Call, "couldn't allocate output register for constraint '" +
8977                         Twine(OpInfo.ConstraintCode) + "'");
8978           return;
8979         }
8980 
8981         if (DetectWriteToReservedRegister())
8982           return;
8983 
8984         // Add information to the INLINEASM node to know that this register is
8985         // set.
8986         OpInfo.AssignedRegs.AddInlineAsmOperands(
8987             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8988                                   : InlineAsm::Kind_RegDef,
8989             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8990       }
8991       break;
8992 
8993     case InlineAsm::isInput:
8994     case InlineAsm::isLabel: {
8995       SDValue InOperandVal = OpInfo.CallOperand;
8996 
8997       if (OpInfo.isMatchingInputConstraint()) {
8998         // If this is required to match an output register we have already set,
8999         // just use its register.
9000         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9001                                                   AsmNodeOperands);
9002         unsigned OpFlag =
9003           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
9004         if (InlineAsm::isRegDefKind(OpFlag) ||
9005             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
9006           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
9007           if (OpInfo.isIndirect) {
9008             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9009             emitInlineAsmError(Call, "inline asm not supported yet: "
9010                                      "don't know how to handle tied "
9011                                      "indirect register inputs");
9012             return;
9013           }
9014 
9015           SmallVector<unsigned, 4> Regs;
9016           MachineFunction &MF = DAG.getMachineFunction();
9017           MachineRegisterInfo &MRI = MF.getRegInfo();
9018           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9019           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9020           Register TiedReg = R->getReg();
9021           MVT RegVT = R->getSimpleValueType(0);
9022           const TargetRegisterClass *RC =
9023               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9024               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9025                                       : TRI.getMinimalPhysRegClass(TiedReg);
9026           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
9027           for (unsigned i = 0; i != NumRegs; ++i)
9028             Regs.push_back(MRI.createVirtualRegister(RC));
9029 
9030           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9031 
9032           SDLoc dl = getCurSDLoc();
9033           // Use the produced MatchedRegs object to
9034           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
9035           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
9036                                            true, OpInfo.getMatchedOperand(), dl,
9037                                            DAG, AsmNodeOperands);
9038           break;
9039         }
9040 
9041         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
9042         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
9043                "Unexpected number of operands");
9044         // Add information to the INLINEASM node to know about this input.
9045         // See InlineAsm.h isUseOperandTiedToDef.
9046         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
9047         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
9048                                                     OpInfo.getMatchedOperand());
9049         AsmNodeOperands.push_back(DAG.getTargetConstant(
9050             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9051         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9052         break;
9053       }
9054 
9055       // Treat indirect 'X' constraint as memory.
9056       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9057           OpInfo.isIndirect)
9058         OpInfo.ConstraintType = TargetLowering::C_Memory;
9059 
9060       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9061           OpInfo.ConstraintType == TargetLowering::C_Other) {
9062         std::vector<SDValue> Ops;
9063         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9064                                           Ops, DAG);
9065         if (Ops.empty()) {
9066           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9067             if (isa<ConstantSDNode>(InOperandVal)) {
9068               emitInlineAsmError(Call, "value out of range for constraint '" +
9069                                            Twine(OpInfo.ConstraintCode) + "'");
9070               return;
9071             }
9072 
9073           emitInlineAsmError(Call,
9074                              "invalid operand for inline asm constraint '" +
9075                                  Twine(OpInfo.ConstraintCode) + "'");
9076           return;
9077         }
9078 
9079         // Add information to the INLINEASM node to know about this input.
9080         unsigned ResOpType =
9081           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
9082         AsmNodeOperands.push_back(DAG.getTargetConstant(
9083             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9084         llvm::append_range(AsmNodeOperands, Ops);
9085         break;
9086       }
9087 
9088       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9089         assert((OpInfo.isIndirect ||
9090                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9091                "Operand must be indirect to be a mem!");
9092         assert(InOperandVal.getValueType() ==
9093                    TLI.getPointerTy(DAG.getDataLayout()) &&
9094                "Memory operands expect pointer values");
9095 
9096         unsigned ConstraintID =
9097             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9098         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9099                "Failed to convert memory constraint code to constraint id.");
9100 
9101         // Add information to the INLINEASM node to know about this input.
9102         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9103         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9104         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9105                                                         getCurSDLoc(),
9106                                                         MVT::i32));
9107         AsmNodeOperands.push_back(InOperandVal);
9108         break;
9109       }
9110 
9111       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9112         assert(InOperandVal.getValueType() ==
9113                    TLI.getPointerTy(DAG.getDataLayout()) &&
9114                "Address operands expect pointer values");
9115 
9116         unsigned ConstraintID =
9117             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9118         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9119                "Failed to convert memory constraint code to constraint id.");
9120 
9121         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9122 
9123         SDValue AsmOp = InOperandVal;
9124         if (isFunction(InOperandVal)) {
9125           auto *GA = dyn_cast<GlobalAddressSDNode>(InOperandVal);
9126           ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1);
9127           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9128                                              InOperandVal.getValueType(),
9129                                              GA->getOffset());
9130         }
9131 
9132         // Add information to the INLINEASM node to know about this input.
9133         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9134 
9135         AsmNodeOperands.push_back(
9136             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9137 
9138         AsmNodeOperands.push_back(AsmOp);
9139         break;
9140       }
9141 
9142       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9143               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9144              "Unknown constraint type!");
9145 
9146       // TODO: Support this.
9147       if (OpInfo.isIndirect) {
9148         emitInlineAsmError(
9149             Call, "Don't know how to handle indirect register inputs yet "
9150                   "for constraint '" +
9151                       Twine(OpInfo.ConstraintCode) + "'");
9152         return;
9153       }
9154 
9155       // Copy the input into the appropriate registers.
9156       if (OpInfo.AssignedRegs.Regs.empty()) {
9157         emitInlineAsmError(Call,
9158                            "couldn't allocate input reg for constraint '" +
9159                                Twine(OpInfo.ConstraintCode) + "'");
9160         return;
9161       }
9162 
9163       if (DetectWriteToReservedRegister())
9164         return;
9165 
9166       SDLoc dl = getCurSDLoc();
9167 
9168       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
9169                                         &Call);
9170 
9171       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
9172                                                dl, DAG, AsmNodeOperands);
9173       break;
9174     }
9175     case InlineAsm::isClobber:
9176       // Add the clobbered value to the operand list, so that the register
9177       // allocator is aware that the physreg got clobbered.
9178       if (!OpInfo.AssignedRegs.Regs.empty())
9179         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
9180                                                  false, 0, getCurSDLoc(), DAG,
9181                                                  AsmNodeOperands);
9182       break;
9183     }
9184   }
9185 
9186   // Finish up input operands.  Set the input chain and add the flag last.
9187   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9188   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
9189 
9190   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9191   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9192                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9193   Flag = Chain.getValue(1);
9194 
9195   // Do additional work to generate outputs.
9196 
9197   SmallVector<EVT, 1> ResultVTs;
9198   SmallVector<SDValue, 1> ResultValues;
9199   SmallVector<SDValue, 8> OutChains;
9200 
9201   llvm::Type *CallResultType = Call.getType();
9202   ArrayRef<Type *> ResultTypes;
9203   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9204     ResultTypes = StructResult->elements();
9205   else if (!CallResultType->isVoidTy())
9206     ResultTypes = makeArrayRef(CallResultType);
9207 
9208   auto CurResultType = ResultTypes.begin();
9209   auto handleRegAssign = [&](SDValue V) {
9210     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9211     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9212     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9213     ++CurResultType;
9214     // If the type of the inline asm call site return value is different but has
9215     // same size as the type of the asm output bitcast it.  One example of this
9216     // is for vectors with different width / number of elements.  This can
9217     // happen for register classes that can contain multiple different value
9218     // types.  The preg or vreg allocated may not have the same VT as was
9219     // expected.
9220     //
9221     // This can also happen for a return value that disagrees with the register
9222     // class it is put in, eg. a double in a general-purpose register on a
9223     // 32-bit machine.
9224     if (ResultVT != V.getValueType() &&
9225         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9226       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9227     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9228              V.getValueType().isInteger()) {
9229       // If a result value was tied to an input value, the computed result
9230       // may have a wider width than the expected result.  Extract the
9231       // relevant portion.
9232       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9233     }
9234     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9235     ResultVTs.push_back(ResultVT);
9236     ResultValues.push_back(V);
9237   };
9238 
9239   // Deal with output operands.
9240   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9241     if (OpInfo.Type == InlineAsm::isOutput) {
9242       SDValue Val;
9243       // Skip trivial output operands.
9244       if (OpInfo.AssignedRegs.Regs.empty())
9245         continue;
9246 
9247       switch (OpInfo.ConstraintType) {
9248       case TargetLowering::C_Register:
9249       case TargetLowering::C_RegisterClass:
9250         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9251                                                   Chain, &Flag, &Call);
9252         break;
9253       case TargetLowering::C_Immediate:
9254       case TargetLowering::C_Other:
9255         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9256                                               OpInfo, DAG);
9257         break;
9258       case TargetLowering::C_Memory:
9259         break; // Already handled.
9260       case TargetLowering::C_Address:
9261         break; // Silence warning.
9262       case TargetLowering::C_Unknown:
9263         assert(false && "Unexpected unknown constraint");
9264       }
9265 
9266       // Indirect output manifest as stores. Record output chains.
9267       if (OpInfo.isIndirect) {
9268         const Value *Ptr = OpInfo.CallOperandVal;
9269         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9270         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9271                                      MachinePointerInfo(Ptr));
9272         OutChains.push_back(Store);
9273       } else {
9274         // generate CopyFromRegs to associated registers.
9275         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9276         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9277           for (const SDValue &V : Val->op_values())
9278             handleRegAssign(V);
9279         } else
9280           handleRegAssign(Val);
9281       }
9282     }
9283   }
9284 
9285   // Set results.
9286   if (!ResultValues.empty()) {
9287     assert(CurResultType == ResultTypes.end() &&
9288            "Mismatch in number of ResultTypes");
9289     assert(ResultValues.size() == ResultTypes.size() &&
9290            "Mismatch in number of output operands in asm result");
9291 
9292     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9293                             DAG.getVTList(ResultVTs), ResultValues);
9294     setValue(&Call, V);
9295   }
9296 
9297   // Collect store chains.
9298   if (!OutChains.empty())
9299     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9300 
9301   if (EmitEHLabels) {
9302     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9303   }
9304 
9305   // Only Update Root if inline assembly has a memory effect.
9306   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9307       EmitEHLabels)
9308     DAG.setRoot(Chain);
9309 }
9310 
9311 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9312                                              const Twine &Message) {
9313   LLVMContext &Ctx = *DAG.getContext();
9314   Ctx.emitError(&Call, Message);
9315 
9316   // Make sure we leave the DAG in a valid state
9317   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9318   SmallVector<EVT, 1> ValueVTs;
9319   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9320 
9321   if (ValueVTs.empty())
9322     return;
9323 
9324   SmallVector<SDValue, 1> Ops;
9325   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9326     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9327 
9328   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9329 }
9330 
9331 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9332   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9333                           MVT::Other, getRoot(),
9334                           getValue(I.getArgOperand(0)),
9335                           DAG.getSrcValue(I.getArgOperand(0))));
9336 }
9337 
9338 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9339   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9340   const DataLayout &DL = DAG.getDataLayout();
9341   SDValue V = DAG.getVAArg(
9342       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9343       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9344       DL.getABITypeAlign(I.getType()).value());
9345   DAG.setRoot(V.getValue(1));
9346 
9347   if (I.getType()->isPointerTy())
9348     V = DAG.getPtrExtOrTrunc(
9349         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9350   setValue(&I, V);
9351 }
9352 
9353 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9354   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9355                           MVT::Other, getRoot(),
9356                           getValue(I.getArgOperand(0)),
9357                           DAG.getSrcValue(I.getArgOperand(0))));
9358 }
9359 
9360 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9361   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9362                           MVT::Other, getRoot(),
9363                           getValue(I.getArgOperand(0)),
9364                           getValue(I.getArgOperand(1)),
9365                           DAG.getSrcValue(I.getArgOperand(0)),
9366                           DAG.getSrcValue(I.getArgOperand(1))));
9367 }
9368 
9369 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9370                                                     const Instruction &I,
9371                                                     SDValue Op) {
9372   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9373   if (!Range)
9374     return Op;
9375 
9376   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9377   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9378     return Op;
9379 
9380   APInt Lo = CR.getUnsignedMin();
9381   if (!Lo.isMinValue())
9382     return Op;
9383 
9384   APInt Hi = CR.getUnsignedMax();
9385   unsigned Bits = std::max(Hi.getActiveBits(),
9386                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9387 
9388   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9389 
9390   SDLoc SL = getCurSDLoc();
9391 
9392   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9393                              DAG.getValueType(SmallVT));
9394   unsigned NumVals = Op.getNode()->getNumValues();
9395   if (NumVals == 1)
9396     return ZExt;
9397 
9398   SmallVector<SDValue, 4> Ops;
9399 
9400   Ops.push_back(ZExt);
9401   for (unsigned I = 1; I != NumVals; ++I)
9402     Ops.push_back(Op.getValue(I));
9403 
9404   return DAG.getMergeValues(Ops, SL);
9405 }
9406 
9407 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9408 /// the call being lowered.
9409 ///
9410 /// This is a helper for lowering intrinsics that follow a target calling
9411 /// convention or require stack pointer adjustment. Only a subset of the
9412 /// intrinsic's operands need to participate in the calling convention.
9413 void SelectionDAGBuilder::populateCallLoweringInfo(
9414     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9415     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9416     bool IsPatchPoint) {
9417   TargetLowering::ArgListTy Args;
9418   Args.reserve(NumArgs);
9419 
9420   // Populate the argument list.
9421   // Attributes for args start at offset 1, after the return attribute.
9422   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9423        ArgI != ArgE; ++ArgI) {
9424     const Value *V = Call->getOperand(ArgI);
9425 
9426     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9427 
9428     TargetLowering::ArgListEntry Entry;
9429     Entry.Node = getValue(V);
9430     Entry.Ty = V->getType();
9431     Entry.setAttributes(Call, ArgI);
9432     Args.push_back(Entry);
9433   }
9434 
9435   CLI.setDebugLoc(getCurSDLoc())
9436       .setChain(getRoot())
9437       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9438       .setDiscardResult(Call->use_empty())
9439       .setIsPatchPoint(IsPatchPoint)
9440       .setIsPreallocated(
9441           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9442 }
9443 
9444 /// Add a stack map intrinsic call's live variable operands to a stackmap
9445 /// or patchpoint target node's operand list.
9446 ///
9447 /// Constants are converted to TargetConstants purely as an optimization to
9448 /// avoid constant materialization and register allocation.
9449 ///
9450 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9451 /// generate addess computation nodes, and so FinalizeISel can convert the
9452 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9453 /// address materialization and register allocation, but may also be required
9454 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9455 /// alloca in the entry block, then the runtime may assume that the alloca's
9456 /// StackMap location can be read immediately after compilation and that the
9457 /// location is valid at any point during execution (this is similar to the
9458 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9459 /// only available in a register, then the runtime would need to trap when
9460 /// execution reaches the StackMap in order to read the alloca's location.
9461 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9462                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9463                                 SelectionDAGBuilder &Builder) {
9464   SelectionDAG &DAG = Builder.DAG;
9465   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9466     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9467 
9468     // Things on the stack are pointer-typed, meaning that they are already
9469     // legal and can be emitted directly to target nodes.
9470     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9471       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9472     } else {
9473       // Otherwise emit a target independent node to be legalised.
9474       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9475     }
9476   }
9477 }
9478 
9479 /// Lower llvm.experimental.stackmap.
9480 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9481   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9482   //                                  [live variables...])
9483 
9484   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9485 
9486   SDValue Chain, InFlag, Callee;
9487   SmallVector<SDValue, 32> Ops;
9488 
9489   SDLoc DL = getCurSDLoc();
9490   Callee = getValue(CI.getCalledOperand());
9491 
9492   // The stackmap intrinsic only records the live variables (the arguments
9493   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9494   // intrinsic, this won't be lowered to a function call. This means we don't
9495   // have to worry about calling conventions and target specific lowering code.
9496   // Instead we perform the call lowering right here.
9497   //
9498   // chain, flag = CALLSEQ_START(chain, 0, 0)
9499   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9500   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9501   //
9502   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9503   InFlag = Chain.getValue(1);
9504 
9505   // Add the STACKMAP operands, starting with DAG house-keeping.
9506   Ops.push_back(Chain);
9507   Ops.push_back(InFlag);
9508 
9509   // Add the <id>, <numShadowBytes> operands.
9510   //
9511   // These do not require legalisation, and can be emitted directly to target
9512   // constant nodes.
9513   SDValue ID = getValue(CI.getArgOperand(0));
9514   assert(ID.getValueType() == MVT::i64);
9515   SDValue IDConst = DAG.getTargetConstant(
9516       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9517   Ops.push_back(IDConst);
9518 
9519   SDValue Shad = getValue(CI.getArgOperand(1));
9520   assert(Shad.getValueType() == MVT::i32);
9521   SDValue ShadConst = DAG.getTargetConstant(
9522       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9523   Ops.push_back(ShadConst);
9524 
9525   // Add the live variables.
9526   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9527 
9528   // Create the STACKMAP node.
9529   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9530   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9531   InFlag = Chain.getValue(1);
9532 
9533   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL);
9534 
9535   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9536 
9537   // Set the root to the target-lowered call chain.
9538   DAG.setRoot(Chain);
9539 
9540   // Inform the Frame Information that we have a stackmap in this function.
9541   FuncInfo.MF->getFrameInfo().setHasStackMap();
9542 }
9543 
9544 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9545 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9546                                           const BasicBlock *EHPadBB) {
9547   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9548   //                                                 i32 <numBytes>,
9549   //                                                 i8* <target>,
9550   //                                                 i32 <numArgs>,
9551   //                                                 [Args...],
9552   //                                                 [live variables...])
9553 
9554   CallingConv::ID CC = CB.getCallingConv();
9555   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9556   bool HasDef = !CB.getType()->isVoidTy();
9557   SDLoc dl = getCurSDLoc();
9558   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9559 
9560   // Handle immediate and symbolic callees.
9561   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9562     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9563                                    /*isTarget=*/true);
9564   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9565     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9566                                          SDLoc(SymbolicCallee),
9567                                          SymbolicCallee->getValueType(0));
9568 
9569   // Get the real number of arguments participating in the call <numArgs>
9570   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9571   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9572 
9573   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9574   // Intrinsics include all meta-operands up to but not including CC.
9575   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9576   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9577          "Not enough arguments provided to the patchpoint intrinsic");
9578 
9579   // For AnyRegCC the arguments are lowered later on manually.
9580   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9581   Type *ReturnTy =
9582       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9583 
9584   TargetLowering::CallLoweringInfo CLI(DAG);
9585   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9586                            ReturnTy, true);
9587   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9588 
9589   SDNode *CallEnd = Result.second.getNode();
9590   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9591     CallEnd = CallEnd->getOperand(0).getNode();
9592 
9593   /// Get a call instruction from the call sequence chain.
9594   /// Tail calls are not allowed.
9595   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9596          "Expected a callseq node.");
9597   SDNode *Call = CallEnd->getOperand(0).getNode();
9598   bool HasGlue = Call->getGluedNode();
9599 
9600   // Replace the target specific call node with the patchable intrinsic.
9601   SmallVector<SDValue, 8> Ops;
9602 
9603   // Push the chain.
9604   Ops.push_back(*(Call->op_begin()));
9605 
9606   // Optionally, push the glue (if any).
9607   if (HasGlue)
9608     Ops.push_back(*(Call->op_end() - 1));
9609 
9610   // Push the register mask info.
9611   if (HasGlue)
9612     Ops.push_back(*(Call->op_end() - 2));
9613   else
9614     Ops.push_back(*(Call->op_end() - 1));
9615 
9616   // Add the <id> and <numBytes> constants.
9617   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9618   Ops.push_back(DAG.getTargetConstant(
9619                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9620   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9621   Ops.push_back(DAG.getTargetConstant(
9622                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9623                   MVT::i32));
9624 
9625   // Add the callee.
9626   Ops.push_back(Callee);
9627 
9628   // Adjust <numArgs> to account for any arguments that have been passed on the
9629   // stack instead.
9630   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9631   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9632   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9633   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9634 
9635   // Add the calling convention
9636   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9637 
9638   // Add the arguments we omitted previously. The register allocator should
9639   // place these in any free register.
9640   if (IsAnyRegCC)
9641     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9642       Ops.push_back(getValue(CB.getArgOperand(i)));
9643 
9644   // Push the arguments from the call instruction.
9645   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9646   Ops.append(Call->op_begin() + 2, e);
9647 
9648   // Push live variables for the stack map.
9649   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9650 
9651   SDVTList NodeTys;
9652   if (IsAnyRegCC && HasDef) {
9653     // Create the return types based on the intrinsic definition
9654     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9655     SmallVector<EVT, 3> ValueVTs;
9656     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9657     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9658 
9659     // There is always a chain and a glue type at the end
9660     ValueVTs.push_back(MVT::Other);
9661     ValueVTs.push_back(MVT::Glue);
9662     NodeTys = DAG.getVTList(ValueVTs);
9663   } else
9664     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9665 
9666   // Replace the target specific call node with a PATCHPOINT node.
9667   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
9668 
9669   // Update the NodeMap.
9670   if (HasDef) {
9671     if (IsAnyRegCC)
9672       setValue(&CB, SDValue(PPV.getNode(), 0));
9673     else
9674       setValue(&CB, Result.first);
9675   }
9676 
9677   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9678   // call sequence. Furthermore the location of the chain and glue can change
9679   // when the AnyReg calling convention is used and the intrinsic returns a
9680   // value.
9681   if (IsAnyRegCC && HasDef) {
9682     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9683     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
9684     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9685   } else
9686     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
9687   DAG.DeleteNode(Call);
9688 
9689   // Inform the Frame Information that we have a patchpoint in this function.
9690   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9691 }
9692 
9693 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9694                                             unsigned Intrinsic) {
9695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9696   SDValue Op1 = getValue(I.getArgOperand(0));
9697   SDValue Op2;
9698   if (I.arg_size() > 1)
9699     Op2 = getValue(I.getArgOperand(1));
9700   SDLoc dl = getCurSDLoc();
9701   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9702   SDValue Res;
9703   SDNodeFlags SDFlags;
9704   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9705     SDFlags.copyFMF(*FPMO);
9706 
9707   switch (Intrinsic) {
9708   case Intrinsic::vector_reduce_fadd:
9709     if (SDFlags.hasAllowReassociation())
9710       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9711                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9712                         SDFlags);
9713     else
9714       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9715     break;
9716   case Intrinsic::vector_reduce_fmul:
9717     if (SDFlags.hasAllowReassociation())
9718       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9719                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9720                         SDFlags);
9721     else
9722       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9723     break;
9724   case Intrinsic::vector_reduce_add:
9725     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9726     break;
9727   case Intrinsic::vector_reduce_mul:
9728     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9729     break;
9730   case Intrinsic::vector_reduce_and:
9731     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9732     break;
9733   case Intrinsic::vector_reduce_or:
9734     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9735     break;
9736   case Intrinsic::vector_reduce_xor:
9737     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9738     break;
9739   case Intrinsic::vector_reduce_smax:
9740     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9741     break;
9742   case Intrinsic::vector_reduce_smin:
9743     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9744     break;
9745   case Intrinsic::vector_reduce_umax:
9746     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9747     break;
9748   case Intrinsic::vector_reduce_umin:
9749     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9750     break;
9751   case Intrinsic::vector_reduce_fmax:
9752     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9753     break;
9754   case Intrinsic::vector_reduce_fmin:
9755     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9756     break;
9757   default:
9758     llvm_unreachable("Unhandled vector reduce intrinsic");
9759   }
9760   setValue(&I, Res);
9761 }
9762 
9763 /// Returns an AttributeList representing the attributes applied to the return
9764 /// value of the given call.
9765 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9766   SmallVector<Attribute::AttrKind, 2> Attrs;
9767   if (CLI.RetSExt)
9768     Attrs.push_back(Attribute::SExt);
9769   if (CLI.RetZExt)
9770     Attrs.push_back(Attribute::ZExt);
9771   if (CLI.IsInReg)
9772     Attrs.push_back(Attribute::InReg);
9773 
9774   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9775                             Attrs);
9776 }
9777 
9778 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9779 /// implementation, which just calls LowerCall.
9780 /// FIXME: When all targets are
9781 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9782 std::pair<SDValue, SDValue>
9783 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9784   // Handle the incoming return values from the call.
9785   CLI.Ins.clear();
9786   Type *OrigRetTy = CLI.RetTy;
9787   SmallVector<EVT, 4> RetTys;
9788   SmallVector<uint64_t, 4> Offsets;
9789   auto &DL = CLI.DAG.getDataLayout();
9790   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9791 
9792   if (CLI.IsPostTypeLegalization) {
9793     // If we are lowering a libcall after legalization, split the return type.
9794     SmallVector<EVT, 4> OldRetTys;
9795     SmallVector<uint64_t, 4> OldOffsets;
9796     RetTys.swap(OldRetTys);
9797     Offsets.swap(OldOffsets);
9798 
9799     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9800       EVT RetVT = OldRetTys[i];
9801       uint64_t Offset = OldOffsets[i];
9802       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9803       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9804       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9805       RetTys.append(NumRegs, RegisterVT);
9806       for (unsigned j = 0; j != NumRegs; ++j)
9807         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9808     }
9809   }
9810 
9811   SmallVector<ISD::OutputArg, 4> Outs;
9812   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9813 
9814   bool CanLowerReturn =
9815       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9816                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9817 
9818   SDValue DemoteStackSlot;
9819   int DemoteStackIdx = -100;
9820   if (!CanLowerReturn) {
9821     // FIXME: equivalent assert?
9822     // assert(!CS.hasInAllocaArgument() &&
9823     //        "sret demotion is incompatible with inalloca");
9824     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9825     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9826     MachineFunction &MF = CLI.DAG.getMachineFunction();
9827     DemoteStackIdx =
9828         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9829     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9830                                               DL.getAllocaAddrSpace());
9831 
9832     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9833     ArgListEntry Entry;
9834     Entry.Node = DemoteStackSlot;
9835     Entry.Ty = StackSlotPtrType;
9836     Entry.IsSExt = false;
9837     Entry.IsZExt = false;
9838     Entry.IsInReg = false;
9839     Entry.IsSRet = true;
9840     Entry.IsNest = false;
9841     Entry.IsByVal = false;
9842     Entry.IsByRef = false;
9843     Entry.IsReturned = false;
9844     Entry.IsSwiftSelf = false;
9845     Entry.IsSwiftAsync = false;
9846     Entry.IsSwiftError = false;
9847     Entry.IsCFGuardTarget = false;
9848     Entry.Alignment = Alignment;
9849     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9850     CLI.NumFixedArgs += 1;
9851     CLI.getArgs()[0].IndirectType = CLI.RetTy;
9852     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9853 
9854     // sret demotion isn't compatible with tail-calls, since the sret argument
9855     // points into the callers stack frame.
9856     CLI.IsTailCall = false;
9857   } else {
9858     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9859         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9860     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9861       ISD::ArgFlagsTy Flags;
9862       if (NeedsRegBlock) {
9863         Flags.setInConsecutiveRegs();
9864         if (I == RetTys.size() - 1)
9865           Flags.setInConsecutiveRegsLast();
9866       }
9867       EVT VT = RetTys[I];
9868       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9869                                                      CLI.CallConv, VT);
9870       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9871                                                        CLI.CallConv, VT);
9872       for (unsigned i = 0; i != NumRegs; ++i) {
9873         ISD::InputArg MyFlags;
9874         MyFlags.Flags = Flags;
9875         MyFlags.VT = RegisterVT;
9876         MyFlags.ArgVT = VT;
9877         MyFlags.Used = CLI.IsReturnValueUsed;
9878         if (CLI.RetTy->isPointerTy()) {
9879           MyFlags.Flags.setPointer();
9880           MyFlags.Flags.setPointerAddrSpace(
9881               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9882         }
9883         if (CLI.RetSExt)
9884           MyFlags.Flags.setSExt();
9885         if (CLI.RetZExt)
9886           MyFlags.Flags.setZExt();
9887         if (CLI.IsInReg)
9888           MyFlags.Flags.setInReg();
9889         CLI.Ins.push_back(MyFlags);
9890       }
9891     }
9892   }
9893 
9894   // We push in swifterror return as the last element of CLI.Ins.
9895   ArgListTy &Args = CLI.getArgs();
9896   if (supportSwiftError()) {
9897     for (const ArgListEntry &Arg : Args) {
9898       if (Arg.IsSwiftError) {
9899         ISD::InputArg MyFlags;
9900         MyFlags.VT = getPointerTy(DL);
9901         MyFlags.ArgVT = EVT(getPointerTy(DL));
9902         MyFlags.Flags.setSwiftError();
9903         CLI.Ins.push_back(MyFlags);
9904       }
9905     }
9906   }
9907 
9908   // Handle all of the outgoing arguments.
9909   CLI.Outs.clear();
9910   CLI.OutVals.clear();
9911   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9912     SmallVector<EVT, 4> ValueVTs;
9913     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9914     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9915     Type *FinalType = Args[i].Ty;
9916     if (Args[i].IsByVal)
9917       FinalType = Args[i].IndirectType;
9918     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9919         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9920     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9921          ++Value) {
9922       EVT VT = ValueVTs[Value];
9923       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9924       SDValue Op = SDValue(Args[i].Node.getNode(),
9925                            Args[i].Node.getResNo() + Value);
9926       ISD::ArgFlagsTy Flags;
9927 
9928       // Certain targets (such as MIPS), may have a different ABI alignment
9929       // for a type depending on the context. Give the target a chance to
9930       // specify the alignment it wants.
9931       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9932       Flags.setOrigAlign(OriginalAlignment);
9933 
9934       if (Args[i].Ty->isPointerTy()) {
9935         Flags.setPointer();
9936         Flags.setPointerAddrSpace(
9937             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9938       }
9939       if (Args[i].IsZExt)
9940         Flags.setZExt();
9941       if (Args[i].IsSExt)
9942         Flags.setSExt();
9943       if (Args[i].IsInReg) {
9944         // If we are using vectorcall calling convention, a structure that is
9945         // passed InReg - is surely an HVA
9946         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9947             isa<StructType>(FinalType)) {
9948           // The first value of a structure is marked
9949           if (0 == Value)
9950             Flags.setHvaStart();
9951           Flags.setHva();
9952         }
9953         // Set InReg Flag
9954         Flags.setInReg();
9955       }
9956       if (Args[i].IsSRet)
9957         Flags.setSRet();
9958       if (Args[i].IsSwiftSelf)
9959         Flags.setSwiftSelf();
9960       if (Args[i].IsSwiftAsync)
9961         Flags.setSwiftAsync();
9962       if (Args[i].IsSwiftError)
9963         Flags.setSwiftError();
9964       if (Args[i].IsCFGuardTarget)
9965         Flags.setCFGuardTarget();
9966       if (Args[i].IsByVal)
9967         Flags.setByVal();
9968       if (Args[i].IsByRef)
9969         Flags.setByRef();
9970       if (Args[i].IsPreallocated) {
9971         Flags.setPreallocated();
9972         // Set the byval flag for CCAssignFn callbacks that don't know about
9973         // preallocated.  This way we can know how many bytes we should've
9974         // allocated and how many bytes a callee cleanup function will pop.  If
9975         // we port preallocated to more targets, we'll have to add custom
9976         // preallocated handling in the various CC lowering callbacks.
9977         Flags.setByVal();
9978       }
9979       if (Args[i].IsInAlloca) {
9980         Flags.setInAlloca();
9981         // Set the byval flag for CCAssignFn callbacks that don't know about
9982         // inalloca.  This way we can know how many bytes we should've allocated
9983         // and how many bytes a callee cleanup function will pop.  If we port
9984         // inalloca to more targets, we'll have to add custom inalloca handling
9985         // in the various CC lowering callbacks.
9986         Flags.setByVal();
9987       }
9988       Align MemAlign;
9989       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9990         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9991         Flags.setByValSize(FrameSize);
9992 
9993         // info is not there but there are cases it cannot get right.
9994         if (auto MA = Args[i].Alignment)
9995           MemAlign = *MA;
9996         else
9997           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
9998       } else if (auto MA = Args[i].Alignment) {
9999         MemAlign = *MA;
10000       } else {
10001         MemAlign = OriginalAlignment;
10002       }
10003       Flags.setMemAlign(MemAlign);
10004       if (Args[i].IsNest)
10005         Flags.setNest();
10006       if (NeedsRegBlock)
10007         Flags.setInConsecutiveRegs();
10008 
10009       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10010                                                  CLI.CallConv, VT);
10011       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10012                                                         CLI.CallConv, VT);
10013       SmallVector<SDValue, 4> Parts(NumParts);
10014       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10015 
10016       if (Args[i].IsSExt)
10017         ExtendKind = ISD::SIGN_EXTEND;
10018       else if (Args[i].IsZExt)
10019         ExtendKind = ISD::ZERO_EXTEND;
10020 
10021       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10022       // for now.
10023       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10024           CanLowerReturn) {
10025         assert((CLI.RetTy == Args[i].Ty ||
10026                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10027                  CLI.RetTy->getPointerAddressSpace() ==
10028                      Args[i].Ty->getPointerAddressSpace())) &&
10029                RetTys.size() == NumValues && "unexpected use of 'returned'");
10030         // Before passing 'returned' to the target lowering code, ensure that
10031         // either the register MVT and the actual EVT are the same size or that
10032         // the return value and argument are extended in the same way; in these
10033         // cases it's safe to pass the argument register value unchanged as the
10034         // return register value (although it's at the target's option whether
10035         // to do so)
10036         // TODO: allow code generation to take advantage of partially preserved
10037         // registers rather than clobbering the entire register when the
10038         // parameter extension method is not compatible with the return
10039         // extension method
10040         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10041             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10042              CLI.RetZExt == Args[i].IsZExt))
10043           Flags.setReturned();
10044       }
10045 
10046       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10047                      CLI.CallConv, ExtendKind);
10048 
10049       for (unsigned j = 0; j != NumParts; ++j) {
10050         // if it isn't first piece, alignment must be 1
10051         // For scalable vectors the scalable part is currently handled
10052         // by individual targets, so we just use the known minimum size here.
10053         ISD::OutputArg MyFlags(
10054             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10055             i < CLI.NumFixedArgs, i,
10056             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
10057         if (NumParts > 1 && j == 0)
10058           MyFlags.Flags.setSplit();
10059         else if (j != 0) {
10060           MyFlags.Flags.setOrigAlign(Align(1));
10061           if (j == NumParts - 1)
10062             MyFlags.Flags.setSplitEnd();
10063         }
10064 
10065         CLI.Outs.push_back(MyFlags);
10066         CLI.OutVals.push_back(Parts[j]);
10067       }
10068 
10069       if (NeedsRegBlock && Value == NumValues - 1)
10070         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10071     }
10072   }
10073 
10074   SmallVector<SDValue, 4> InVals;
10075   CLI.Chain = LowerCall(CLI, InVals);
10076 
10077   // Update CLI.InVals to use outside of this function.
10078   CLI.InVals = InVals;
10079 
10080   // Verify that the target's LowerCall behaved as expected.
10081   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10082          "LowerCall didn't return a valid chain!");
10083   assert((!CLI.IsTailCall || InVals.empty()) &&
10084          "LowerCall emitted a return value for a tail call!");
10085   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10086          "LowerCall didn't emit the correct number of values!");
10087 
10088   // For a tail call, the return value is merely live-out and there aren't
10089   // any nodes in the DAG representing it. Return a special value to
10090   // indicate that a tail call has been emitted and no more Instructions
10091   // should be processed in the current block.
10092   if (CLI.IsTailCall) {
10093     CLI.DAG.setRoot(CLI.Chain);
10094     return std::make_pair(SDValue(), SDValue());
10095   }
10096 
10097 #ifndef NDEBUG
10098   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10099     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10100     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10101            "LowerCall emitted a value with the wrong type!");
10102   }
10103 #endif
10104 
10105   SmallVector<SDValue, 4> ReturnValues;
10106   if (!CanLowerReturn) {
10107     // The instruction result is the result of loading from the
10108     // hidden sret parameter.
10109     SmallVector<EVT, 1> PVTs;
10110     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
10111 
10112     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10113     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10114     EVT PtrVT = PVTs[0];
10115 
10116     unsigned NumValues = RetTys.size();
10117     ReturnValues.resize(NumValues);
10118     SmallVector<SDValue, 4> Chains(NumValues);
10119 
10120     // An aggregate return value cannot wrap around the address space, so
10121     // offsets to its parts don't wrap either.
10122     SDNodeFlags Flags;
10123     Flags.setNoUnsignedWrap(true);
10124 
10125     MachineFunction &MF = CLI.DAG.getMachineFunction();
10126     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10127     for (unsigned i = 0; i < NumValues; ++i) {
10128       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10129                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10130                                                         PtrVT), Flags);
10131       SDValue L = CLI.DAG.getLoad(
10132           RetTys[i], CLI.DL, CLI.Chain, Add,
10133           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10134                                             DemoteStackIdx, Offsets[i]),
10135           HiddenSRetAlign);
10136       ReturnValues[i] = L;
10137       Chains[i] = L.getValue(1);
10138     }
10139 
10140     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10141   } else {
10142     // Collect the legal value parts into potentially illegal values
10143     // that correspond to the original function's return values.
10144     Optional<ISD::NodeType> AssertOp;
10145     if (CLI.RetSExt)
10146       AssertOp = ISD::AssertSext;
10147     else if (CLI.RetZExt)
10148       AssertOp = ISD::AssertZext;
10149     unsigned CurReg = 0;
10150     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10151       EVT VT = RetTys[I];
10152       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10153                                                      CLI.CallConv, VT);
10154       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10155                                                        CLI.CallConv, VT);
10156 
10157       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10158                                               NumRegs, RegisterVT, VT, nullptr,
10159                                               CLI.CallConv, AssertOp));
10160       CurReg += NumRegs;
10161     }
10162 
10163     // For a function returning void, there is no return value. We can't create
10164     // such a node, so we just return a null return value in that case. In
10165     // that case, nothing will actually look at the value.
10166     if (ReturnValues.empty())
10167       return std::make_pair(SDValue(), CLI.Chain);
10168   }
10169 
10170   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10171                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10172   return std::make_pair(Res, CLI.Chain);
10173 }
10174 
10175 /// Places new result values for the node in Results (their number
10176 /// and types must exactly match those of the original return values of
10177 /// the node), or leaves Results empty, which indicates that the node is not
10178 /// to be custom lowered after all.
10179 void TargetLowering::LowerOperationWrapper(SDNode *N,
10180                                            SmallVectorImpl<SDValue> &Results,
10181                                            SelectionDAG &DAG) const {
10182   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10183 
10184   if (!Res.getNode())
10185     return;
10186 
10187   // If the original node has one result, take the return value from
10188   // LowerOperation as is. It might not be result number 0.
10189   if (N->getNumValues() == 1) {
10190     Results.push_back(Res);
10191     return;
10192   }
10193 
10194   // If the original node has multiple results, then the return node should
10195   // have the same number of results.
10196   assert((N->getNumValues() == Res->getNumValues()) &&
10197       "Lowering returned the wrong number of results!");
10198 
10199   // Places new result values base on N result number.
10200   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10201     Results.push_back(Res.getValue(I));
10202 }
10203 
10204 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10205   llvm_unreachable("LowerOperation not implemented for this target!");
10206 }
10207 
10208 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10209                                                      unsigned Reg,
10210                                                      ISD::NodeType ExtendType) {
10211   SDValue Op = getNonRegisterValue(V);
10212   assert((Op.getOpcode() != ISD::CopyFromReg ||
10213           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10214          "Copy from a reg to the same reg!");
10215   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10216 
10217   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10218   // If this is an InlineAsm we have to match the registers required, not the
10219   // notional registers required by the type.
10220 
10221   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10222                    None); // This is not an ABI copy.
10223   SDValue Chain = DAG.getEntryNode();
10224 
10225   if (ExtendType == ISD::ANY_EXTEND) {
10226     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10227     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10228       ExtendType = PreferredExtendIt->second;
10229   }
10230   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10231   PendingExports.push_back(Chain);
10232 }
10233 
10234 #include "llvm/CodeGen/SelectionDAGISel.h"
10235 
10236 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10237 /// entry block, return true.  This includes arguments used by switches, since
10238 /// the switch may expand into multiple basic blocks.
10239 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10240   // With FastISel active, we may be splitting blocks, so force creation
10241   // of virtual registers for all non-dead arguments.
10242   if (FastISel)
10243     return A->use_empty();
10244 
10245   const BasicBlock &Entry = A->getParent()->front();
10246   for (const User *U : A->users())
10247     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10248       return false;  // Use not in entry block.
10249 
10250   return true;
10251 }
10252 
10253 using ArgCopyElisionMapTy =
10254     DenseMap<const Argument *,
10255              std::pair<const AllocaInst *, const StoreInst *>>;
10256 
10257 /// Scan the entry block of the function in FuncInfo for arguments that look
10258 /// like copies into a local alloca. Record any copied arguments in
10259 /// ArgCopyElisionCandidates.
10260 static void
10261 findArgumentCopyElisionCandidates(const DataLayout &DL,
10262                                   FunctionLoweringInfo *FuncInfo,
10263                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10264   // Record the state of every static alloca used in the entry block. Argument
10265   // allocas are all used in the entry block, so we need approximately as many
10266   // entries as we have arguments.
10267   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10268   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10269   unsigned NumArgs = FuncInfo->Fn->arg_size();
10270   StaticAllocas.reserve(NumArgs * 2);
10271 
10272   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10273     if (!V)
10274       return nullptr;
10275     V = V->stripPointerCasts();
10276     const auto *AI = dyn_cast<AllocaInst>(V);
10277     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10278       return nullptr;
10279     auto Iter = StaticAllocas.insert({AI, Unknown});
10280     return &Iter.first->second;
10281   };
10282 
10283   // Look for stores of arguments to static allocas. Look through bitcasts and
10284   // GEPs to handle type coercions, as long as the alloca is fully initialized
10285   // by the store. Any non-store use of an alloca escapes it and any subsequent
10286   // unanalyzed store might write it.
10287   // FIXME: Handle structs initialized with multiple stores.
10288   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10289     // Look for stores, and handle non-store uses conservatively.
10290     const auto *SI = dyn_cast<StoreInst>(&I);
10291     if (!SI) {
10292       // We will look through cast uses, so ignore them completely.
10293       if (I.isCast())
10294         continue;
10295       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10296       // to allocas.
10297       if (I.isDebugOrPseudoInst())
10298         continue;
10299       // This is an unknown instruction. Assume it escapes or writes to all
10300       // static alloca operands.
10301       for (const Use &U : I.operands()) {
10302         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10303           *Info = StaticAllocaInfo::Clobbered;
10304       }
10305       continue;
10306     }
10307 
10308     // If the stored value is a static alloca, mark it as escaped.
10309     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10310       *Info = StaticAllocaInfo::Clobbered;
10311 
10312     // Check if the destination is a static alloca.
10313     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10314     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10315     if (!Info)
10316       continue;
10317     const AllocaInst *AI = cast<AllocaInst>(Dst);
10318 
10319     // Skip allocas that have been initialized or clobbered.
10320     if (*Info != StaticAllocaInfo::Unknown)
10321       continue;
10322 
10323     // Check if the stored value is an argument, and that this store fully
10324     // initializes the alloca.
10325     // If the argument type has padding bits we can't directly forward a pointer
10326     // as the upper bits may contain garbage.
10327     // Don't elide copies from the same argument twice.
10328     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10329     const auto *Arg = dyn_cast<Argument>(Val);
10330     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10331         Arg->getType()->isEmptyTy() ||
10332         DL.getTypeStoreSize(Arg->getType()) !=
10333             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10334         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10335         ArgCopyElisionCandidates.count(Arg)) {
10336       *Info = StaticAllocaInfo::Clobbered;
10337       continue;
10338     }
10339 
10340     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10341                       << '\n');
10342 
10343     // Mark this alloca and store for argument copy elision.
10344     *Info = StaticAllocaInfo::Elidable;
10345     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10346 
10347     // Stop scanning if we've seen all arguments. This will happen early in -O0
10348     // builds, which is useful, because -O0 builds have large entry blocks and
10349     // many allocas.
10350     if (ArgCopyElisionCandidates.size() == NumArgs)
10351       break;
10352   }
10353 }
10354 
10355 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10356 /// ArgVal is a load from a suitable fixed stack object.
10357 static void tryToElideArgumentCopy(
10358     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10359     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10360     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10361     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10362     SDValue ArgVal, bool &ArgHasUses) {
10363   // Check if this is a load from a fixed stack object.
10364   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10365   if (!LNode)
10366     return;
10367   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10368   if (!FINode)
10369     return;
10370 
10371   // Check that the fixed stack object is the right size and alignment.
10372   // Look at the alignment that the user wrote on the alloca instead of looking
10373   // at the stack object.
10374   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10375   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10376   const AllocaInst *AI = ArgCopyIter->second.first;
10377   int FixedIndex = FINode->getIndex();
10378   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10379   int OldIndex = AllocaIndex;
10380   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10381   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10382     LLVM_DEBUG(
10383         dbgs() << "  argument copy elision failed due to bad fixed stack "
10384                   "object size\n");
10385     return;
10386   }
10387   Align RequiredAlignment = AI->getAlign();
10388   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10389     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10390                          "greater than stack argument alignment ("
10391                       << DebugStr(RequiredAlignment) << " vs "
10392                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10393     return;
10394   }
10395 
10396   // Perform the elision. Delete the old stack object and replace its only use
10397   // in the variable info map. Mark the stack object as mutable.
10398   LLVM_DEBUG({
10399     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10400            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10401            << '\n';
10402   });
10403   MFI.RemoveStackObject(OldIndex);
10404   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10405   AllocaIndex = FixedIndex;
10406   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10407   Chains.push_back(ArgVal.getValue(1));
10408 
10409   // Avoid emitting code for the store implementing the copy.
10410   const StoreInst *SI = ArgCopyIter->second.second;
10411   ElidedArgCopyInstrs.insert(SI);
10412 
10413   // Check for uses of the argument again so that we can avoid exporting ArgVal
10414   // if it is't used by anything other than the store.
10415   for (const Value *U : Arg.users()) {
10416     if (U != SI) {
10417       ArgHasUses = true;
10418       break;
10419     }
10420   }
10421 }
10422 
10423 void SelectionDAGISel::LowerArguments(const Function &F) {
10424   SelectionDAG &DAG = SDB->DAG;
10425   SDLoc dl = SDB->getCurSDLoc();
10426   const DataLayout &DL = DAG.getDataLayout();
10427   SmallVector<ISD::InputArg, 16> Ins;
10428 
10429   // In Naked functions we aren't going to save any registers.
10430   if (F.hasFnAttribute(Attribute::Naked))
10431     return;
10432 
10433   if (!FuncInfo->CanLowerReturn) {
10434     // Put in an sret pointer parameter before all the other parameters.
10435     SmallVector<EVT, 1> ValueVTs;
10436     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10437                     F.getReturnType()->getPointerTo(
10438                         DAG.getDataLayout().getAllocaAddrSpace()),
10439                     ValueVTs);
10440 
10441     // NOTE: Assuming that a pointer will never break down to more than one VT
10442     // or one register.
10443     ISD::ArgFlagsTy Flags;
10444     Flags.setSRet();
10445     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10446     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10447                          ISD::InputArg::NoArgIndex, 0);
10448     Ins.push_back(RetArg);
10449   }
10450 
10451   // Look for stores of arguments to static allocas. Mark such arguments with a
10452   // flag to ask the target to give us the memory location of that argument if
10453   // available.
10454   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10455   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10456                                     ArgCopyElisionCandidates);
10457 
10458   // Set up the incoming argument description vector.
10459   for (const Argument &Arg : F.args()) {
10460     unsigned ArgNo = Arg.getArgNo();
10461     SmallVector<EVT, 4> ValueVTs;
10462     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10463     bool isArgValueUsed = !Arg.use_empty();
10464     unsigned PartBase = 0;
10465     Type *FinalType = Arg.getType();
10466     if (Arg.hasAttribute(Attribute::ByVal))
10467       FinalType = Arg.getParamByValType();
10468     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10469         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10470     for (unsigned Value = 0, NumValues = ValueVTs.size();
10471          Value != NumValues; ++Value) {
10472       EVT VT = ValueVTs[Value];
10473       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10474       ISD::ArgFlagsTy Flags;
10475 
10476 
10477       if (Arg.getType()->isPointerTy()) {
10478         Flags.setPointer();
10479         Flags.setPointerAddrSpace(
10480             cast<PointerType>(Arg.getType())->getAddressSpace());
10481       }
10482       if (Arg.hasAttribute(Attribute::ZExt))
10483         Flags.setZExt();
10484       if (Arg.hasAttribute(Attribute::SExt))
10485         Flags.setSExt();
10486       if (Arg.hasAttribute(Attribute::InReg)) {
10487         // If we are using vectorcall calling convention, a structure that is
10488         // passed InReg - is surely an HVA
10489         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10490             isa<StructType>(Arg.getType())) {
10491           // The first value of a structure is marked
10492           if (0 == Value)
10493             Flags.setHvaStart();
10494           Flags.setHva();
10495         }
10496         // Set InReg Flag
10497         Flags.setInReg();
10498       }
10499       if (Arg.hasAttribute(Attribute::StructRet))
10500         Flags.setSRet();
10501       if (Arg.hasAttribute(Attribute::SwiftSelf))
10502         Flags.setSwiftSelf();
10503       if (Arg.hasAttribute(Attribute::SwiftAsync))
10504         Flags.setSwiftAsync();
10505       if (Arg.hasAttribute(Attribute::SwiftError))
10506         Flags.setSwiftError();
10507       if (Arg.hasAttribute(Attribute::ByVal))
10508         Flags.setByVal();
10509       if (Arg.hasAttribute(Attribute::ByRef))
10510         Flags.setByRef();
10511       if (Arg.hasAttribute(Attribute::InAlloca)) {
10512         Flags.setInAlloca();
10513         // Set the byval flag for CCAssignFn callbacks that don't know about
10514         // inalloca.  This way we can know how many bytes we should've allocated
10515         // and how many bytes a callee cleanup function will pop.  If we port
10516         // inalloca to more targets, we'll have to add custom inalloca handling
10517         // in the various CC lowering callbacks.
10518         Flags.setByVal();
10519       }
10520       if (Arg.hasAttribute(Attribute::Preallocated)) {
10521         Flags.setPreallocated();
10522         // Set the byval flag for CCAssignFn callbacks that don't know about
10523         // preallocated.  This way we can know how many bytes we should've
10524         // allocated and how many bytes a callee cleanup function will pop.  If
10525         // we port preallocated to more targets, we'll have to add custom
10526         // preallocated handling in the various CC lowering callbacks.
10527         Flags.setByVal();
10528       }
10529 
10530       // Certain targets (such as MIPS), may have a different ABI alignment
10531       // for a type depending on the context. Give the target a chance to
10532       // specify the alignment it wants.
10533       const Align OriginalAlignment(
10534           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10535       Flags.setOrigAlign(OriginalAlignment);
10536 
10537       Align MemAlign;
10538       Type *ArgMemTy = nullptr;
10539       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10540           Flags.isByRef()) {
10541         if (!ArgMemTy)
10542           ArgMemTy = Arg.getPointeeInMemoryValueType();
10543 
10544         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10545 
10546         // For in-memory arguments, size and alignment should be passed from FE.
10547         // BE will guess if this info is not there but there are cases it cannot
10548         // get right.
10549         if (auto ParamAlign = Arg.getParamStackAlign())
10550           MemAlign = *ParamAlign;
10551         else if ((ParamAlign = Arg.getParamAlign()))
10552           MemAlign = *ParamAlign;
10553         else
10554           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10555         if (Flags.isByRef())
10556           Flags.setByRefSize(MemSize);
10557         else
10558           Flags.setByValSize(MemSize);
10559       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10560         MemAlign = *ParamAlign;
10561       } else {
10562         MemAlign = OriginalAlignment;
10563       }
10564       Flags.setMemAlign(MemAlign);
10565 
10566       if (Arg.hasAttribute(Attribute::Nest))
10567         Flags.setNest();
10568       if (NeedsRegBlock)
10569         Flags.setInConsecutiveRegs();
10570       if (ArgCopyElisionCandidates.count(&Arg))
10571         Flags.setCopyElisionCandidate();
10572       if (Arg.hasAttribute(Attribute::Returned))
10573         Flags.setReturned();
10574 
10575       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10576           *CurDAG->getContext(), F.getCallingConv(), VT);
10577       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10578           *CurDAG->getContext(), F.getCallingConv(), VT);
10579       for (unsigned i = 0; i != NumRegs; ++i) {
10580         // For scalable vectors, use the minimum size; individual targets
10581         // are responsible for handling scalable vector arguments and
10582         // return values.
10583         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10584                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10585         if (NumRegs > 1 && i == 0)
10586           MyFlags.Flags.setSplit();
10587         // if it isn't first piece, alignment must be 1
10588         else if (i > 0) {
10589           MyFlags.Flags.setOrigAlign(Align(1));
10590           if (i == NumRegs - 1)
10591             MyFlags.Flags.setSplitEnd();
10592         }
10593         Ins.push_back(MyFlags);
10594       }
10595       if (NeedsRegBlock && Value == NumValues - 1)
10596         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10597       PartBase += VT.getStoreSize().getKnownMinSize();
10598     }
10599   }
10600 
10601   // Call the target to set up the argument values.
10602   SmallVector<SDValue, 8> InVals;
10603   SDValue NewRoot = TLI->LowerFormalArguments(
10604       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10605 
10606   // Verify that the target's LowerFormalArguments behaved as expected.
10607   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10608          "LowerFormalArguments didn't return a valid chain!");
10609   assert(InVals.size() == Ins.size() &&
10610          "LowerFormalArguments didn't emit the correct number of values!");
10611   LLVM_DEBUG({
10612     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10613       assert(InVals[i].getNode() &&
10614              "LowerFormalArguments emitted a null value!");
10615       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10616              "LowerFormalArguments emitted a value with the wrong type!");
10617     }
10618   });
10619 
10620   // Update the DAG with the new chain value resulting from argument lowering.
10621   DAG.setRoot(NewRoot);
10622 
10623   // Set up the argument values.
10624   unsigned i = 0;
10625   if (!FuncInfo->CanLowerReturn) {
10626     // Create a virtual register for the sret pointer, and put in a copy
10627     // from the sret argument into it.
10628     SmallVector<EVT, 1> ValueVTs;
10629     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10630                     F.getReturnType()->getPointerTo(
10631                         DAG.getDataLayout().getAllocaAddrSpace()),
10632                     ValueVTs);
10633     MVT VT = ValueVTs[0].getSimpleVT();
10634     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10635     Optional<ISD::NodeType> AssertOp;
10636     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10637                                         nullptr, F.getCallingConv(), AssertOp);
10638 
10639     MachineFunction& MF = SDB->DAG.getMachineFunction();
10640     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10641     Register SRetReg =
10642         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10643     FuncInfo->DemoteRegister = SRetReg;
10644     NewRoot =
10645         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10646     DAG.setRoot(NewRoot);
10647 
10648     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10649     ++i;
10650   }
10651 
10652   SmallVector<SDValue, 4> Chains;
10653   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10654   for (const Argument &Arg : F.args()) {
10655     SmallVector<SDValue, 4> ArgValues;
10656     SmallVector<EVT, 4> ValueVTs;
10657     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10658     unsigned NumValues = ValueVTs.size();
10659     if (NumValues == 0)
10660       continue;
10661 
10662     bool ArgHasUses = !Arg.use_empty();
10663 
10664     // Elide the copying store if the target loaded this argument from a
10665     // suitable fixed stack object.
10666     if (Ins[i].Flags.isCopyElisionCandidate()) {
10667       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10668                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10669                              InVals[i], ArgHasUses);
10670     }
10671 
10672     // If this argument is unused then remember its value. It is used to generate
10673     // debugging information.
10674     bool isSwiftErrorArg =
10675         TLI->supportSwiftError() &&
10676         Arg.hasAttribute(Attribute::SwiftError);
10677     if (!ArgHasUses && !isSwiftErrorArg) {
10678       SDB->setUnusedArgValue(&Arg, InVals[i]);
10679 
10680       // Also remember any frame index for use in FastISel.
10681       if (FrameIndexSDNode *FI =
10682           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10683         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10684     }
10685 
10686     for (unsigned Val = 0; Val != NumValues; ++Val) {
10687       EVT VT = ValueVTs[Val];
10688       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10689                                                       F.getCallingConv(), VT);
10690       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10691           *CurDAG->getContext(), F.getCallingConv(), VT);
10692 
10693       // Even an apparent 'unused' swifterror argument needs to be returned. So
10694       // we do generate a copy for it that can be used on return from the
10695       // function.
10696       if (ArgHasUses || isSwiftErrorArg) {
10697         Optional<ISD::NodeType> AssertOp;
10698         if (Arg.hasAttribute(Attribute::SExt))
10699           AssertOp = ISD::AssertSext;
10700         else if (Arg.hasAttribute(Attribute::ZExt))
10701           AssertOp = ISD::AssertZext;
10702 
10703         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10704                                              PartVT, VT, nullptr,
10705                                              F.getCallingConv(), AssertOp));
10706       }
10707 
10708       i += NumParts;
10709     }
10710 
10711     // We don't need to do anything else for unused arguments.
10712     if (ArgValues.empty())
10713       continue;
10714 
10715     // Note down frame index.
10716     if (FrameIndexSDNode *FI =
10717         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10718       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10719 
10720     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10721                                      SDB->getCurSDLoc());
10722 
10723     SDB->setValue(&Arg, Res);
10724     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10725       // We want to associate the argument with the frame index, among
10726       // involved operands, that correspond to the lowest address. The
10727       // getCopyFromParts function, called earlier, is swapping the order of
10728       // the operands to BUILD_PAIR depending on endianness. The result of
10729       // that swapping is that the least significant bits of the argument will
10730       // be in the first operand of the BUILD_PAIR node, and the most
10731       // significant bits will be in the second operand.
10732       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10733       if (LoadSDNode *LNode =
10734           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10735         if (FrameIndexSDNode *FI =
10736             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10737           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10738     }
10739 
10740     // Analyses past this point are naive and don't expect an assertion.
10741     if (Res.getOpcode() == ISD::AssertZext)
10742       Res = Res.getOperand(0);
10743 
10744     // Update the SwiftErrorVRegDefMap.
10745     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10746       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10747       if (Register::isVirtualRegister(Reg))
10748         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10749                                    Reg);
10750     }
10751 
10752     // If this argument is live outside of the entry block, insert a copy from
10753     // wherever we got it to the vreg that other BB's will reference it as.
10754     if (Res.getOpcode() == ISD::CopyFromReg) {
10755       // If we can, though, try to skip creating an unnecessary vreg.
10756       // FIXME: This isn't very clean... it would be nice to make this more
10757       // general.
10758       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10759       if (Register::isVirtualRegister(Reg)) {
10760         FuncInfo->ValueMap[&Arg] = Reg;
10761         continue;
10762       }
10763     }
10764     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10765       FuncInfo->InitializeRegForValue(&Arg);
10766       SDB->CopyToExportRegsIfNeeded(&Arg);
10767     }
10768   }
10769 
10770   if (!Chains.empty()) {
10771     Chains.push_back(NewRoot);
10772     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10773   }
10774 
10775   DAG.setRoot(NewRoot);
10776 
10777   assert(i == InVals.size() && "Argument register count mismatch!");
10778 
10779   // If any argument copy elisions occurred and we have debug info, update the
10780   // stale frame indices used in the dbg.declare variable info table.
10781   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10782   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10783     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10784       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10785       if (I != ArgCopyElisionFrameIndexMap.end())
10786         VI.Slot = I->second;
10787     }
10788   }
10789 
10790   // Finally, if the target has anything special to do, allow it to do so.
10791   emitFunctionEntryCode();
10792 }
10793 
10794 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10795 /// ensure constants are generated when needed.  Remember the virtual registers
10796 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10797 /// directly add them, because expansion might result in multiple MBB's for one
10798 /// BB.  As such, the start of the BB might correspond to a different MBB than
10799 /// the end.
10800 void
10801 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10802   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10803 
10804   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10805 
10806   // Check PHI nodes in successors that expect a value to be available from this
10807   // block.
10808   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
10809     if (!isa<PHINode>(SuccBB->begin())) continue;
10810     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10811 
10812     // If this terminator has multiple identical successors (common for
10813     // switches), only handle each succ once.
10814     if (!SuccsHandled.insert(SuccMBB).second)
10815       continue;
10816 
10817     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10818 
10819     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10820     // nodes and Machine PHI nodes, but the incoming operands have not been
10821     // emitted yet.
10822     for (const PHINode &PN : SuccBB->phis()) {
10823       // Ignore dead phi's.
10824       if (PN.use_empty())
10825         continue;
10826 
10827       // Skip empty types
10828       if (PN.getType()->isEmptyTy())
10829         continue;
10830 
10831       unsigned Reg;
10832       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10833 
10834       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
10835         unsigned &RegOut = ConstantsOut[C];
10836         if (RegOut == 0) {
10837           RegOut = FuncInfo.CreateRegs(C);
10838           // We need to zero/sign extend ConstantInt phi operands to match
10839           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
10840           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
10841           if (auto *CI = dyn_cast<ConstantInt>(C))
10842             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
10843                                                     : ISD::ZERO_EXTEND;
10844           CopyValueToVirtualRegister(C, RegOut, ExtendType);
10845         }
10846         Reg = RegOut;
10847       } else {
10848         DenseMap<const Value *, Register>::iterator I =
10849           FuncInfo.ValueMap.find(PHIOp);
10850         if (I != FuncInfo.ValueMap.end())
10851           Reg = I->second;
10852         else {
10853           assert(isa<AllocaInst>(PHIOp) &&
10854                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10855                  "Didn't codegen value into a register!??");
10856           Reg = FuncInfo.CreateRegs(PHIOp);
10857           CopyValueToVirtualRegister(PHIOp, Reg);
10858         }
10859       }
10860 
10861       // Remember that this register needs to added to the machine PHI node as
10862       // the input for this MBB.
10863       SmallVector<EVT, 4> ValueVTs;
10864       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10865       for (EVT VT : ValueVTs) {
10866         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10867         for (unsigned i = 0; i != NumRegisters; ++i)
10868           FuncInfo.PHINodesToUpdate.push_back(
10869               std::make_pair(&*MBBI++, Reg + i));
10870         Reg += NumRegisters;
10871       }
10872     }
10873   }
10874 
10875   ConstantsOut.clear();
10876 }
10877 
10878 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10879   MachineFunction::iterator I(MBB);
10880   if (++I == FuncInfo.MF->end())
10881     return nullptr;
10882   return &*I;
10883 }
10884 
10885 /// During lowering new call nodes can be created (such as memset, etc.).
10886 /// Those will become new roots of the current DAG, but complications arise
10887 /// when they are tail calls. In such cases, the call lowering will update
10888 /// the root, but the builder still needs to know that a tail call has been
10889 /// lowered in order to avoid generating an additional return.
10890 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10891   // If the node is null, we do have a tail call.
10892   if (MaybeTC.getNode() != nullptr)
10893     DAG.setRoot(MaybeTC);
10894   else
10895     HasTailCall = true;
10896 }
10897 
10898 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10899                                         MachineBasicBlock *SwitchMBB,
10900                                         MachineBasicBlock *DefaultMBB) {
10901   MachineFunction *CurMF = FuncInfo.MF;
10902   MachineBasicBlock *NextMBB = nullptr;
10903   MachineFunction::iterator BBI(W.MBB);
10904   if (++BBI != FuncInfo.MF->end())
10905     NextMBB = &*BBI;
10906 
10907   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10908 
10909   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10910 
10911   if (Size == 2 && W.MBB == SwitchMBB) {
10912     // If any two of the cases has the same destination, and if one value
10913     // is the same as the other, but has one bit unset that the other has set,
10914     // use bit manipulation to do two compares at once.  For example:
10915     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10916     // TODO: This could be extended to merge any 2 cases in switches with 3
10917     // cases.
10918     // TODO: Handle cases where W.CaseBB != SwitchBB.
10919     CaseCluster &Small = *W.FirstCluster;
10920     CaseCluster &Big = *W.LastCluster;
10921 
10922     if (Small.Low == Small.High && Big.Low == Big.High &&
10923         Small.MBB == Big.MBB) {
10924       const APInt &SmallValue = Small.Low->getValue();
10925       const APInt &BigValue = Big.Low->getValue();
10926 
10927       // Check that there is only one bit different.
10928       APInt CommonBit = BigValue ^ SmallValue;
10929       if (CommonBit.isPowerOf2()) {
10930         SDValue CondLHS = getValue(Cond);
10931         EVT VT = CondLHS.getValueType();
10932         SDLoc DL = getCurSDLoc();
10933 
10934         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10935                                  DAG.getConstant(CommonBit, DL, VT));
10936         SDValue Cond = DAG.getSetCC(
10937             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10938             ISD::SETEQ);
10939 
10940         // Update successor info.
10941         // Both Small and Big will jump to Small.BB, so we sum up the
10942         // probabilities.
10943         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10944         if (BPI)
10945           addSuccessorWithProb(
10946               SwitchMBB, DefaultMBB,
10947               // The default destination is the first successor in IR.
10948               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10949         else
10950           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10951 
10952         // Insert the true branch.
10953         SDValue BrCond =
10954             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10955                         DAG.getBasicBlock(Small.MBB));
10956         // Insert the false branch.
10957         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10958                              DAG.getBasicBlock(DefaultMBB));
10959 
10960         DAG.setRoot(BrCond);
10961         return;
10962       }
10963     }
10964   }
10965 
10966   if (TM.getOptLevel() != CodeGenOpt::None) {
10967     // Here, we order cases by probability so the most likely case will be
10968     // checked first. However, two clusters can have the same probability in
10969     // which case their relative ordering is non-deterministic. So we use Low
10970     // as a tie-breaker as clusters are guaranteed to never overlap.
10971     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10972                [](const CaseCluster &a, const CaseCluster &b) {
10973       return a.Prob != b.Prob ?
10974              a.Prob > b.Prob :
10975              a.Low->getValue().slt(b.Low->getValue());
10976     });
10977 
10978     // Rearrange the case blocks so that the last one falls through if possible
10979     // without changing the order of probabilities.
10980     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10981       --I;
10982       if (I->Prob > W.LastCluster->Prob)
10983         break;
10984       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10985         std::swap(*I, *W.LastCluster);
10986         break;
10987       }
10988     }
10989   }
10990 
10991   // Compute total probability.
10992   BranchProbability DefaultProb = W.DefaultProb;
10993   BranchProbability UnhandledProbs = DefaultProb;
10994   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10995     UnhandledProbs += I->Prob;
10996 
10997   MachineBasicBlock *CurMBB = W.MBB;
10998   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10999     bool FallthroughUnreachable = false;
11000     MachineBasicBlock *Fallthrough;
11001     if (I == W.LastCluster) {
11002       // For the last cluster, fall through to the default destination.
11003       Fallthrough = DefaultMBB;
11004       FallthroughUnreachable = isa<UnreachableInst>(
11005           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11006     } else {
11007       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11008       CurMF->insert(BBI, Fallthrough);
11009       // Put Cond in a virtual register to make it available from the new blocks.
11010       ExportFromCurrentBlock(Cond);
11011     }
11012     UnhandledProbs -= I->Prob;
11013 
11014     switch (I->Kind) {
11015       case CC_JumpTable: {
11016         // FIXME: Optimize away range check based on pivot comparisons.
11017         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11018         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11019 
11020         // The jump block hasn't been inserted yet; insert it here.
11021         MachineBasicBlock *JumpMBB = JT->MBB;
11022         CurMF->insert(BBI, JumpMBB);
11023 
11024         auto JumpProb = I->Prob;
11025         auto FallthroughProb = UnhandledProbs;
11026 
11027         // If the default statement is a target of the jump table, we evenly
11028         // distribute the default probability to successors of CurMBB. Also
11029         // update the probability on the edge from JumpMBB to Fallthrough.
11030         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11031                                               SE = JumpMBB->succ_end();
11032              SI != SE; ++SI) {
11033           if (*SI == DefaultMBB) {
11034             JumpProb += DefaultProb / 2;
11035             FallthroughProb -= DefaultProb / 2;
11036             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11037             JumpMBB->normalizeSuccProbs();
11038             break;
11039           }
11040         }
11041 
11042         if (FallthroughUnreachable)
11043           JTH->FallthroughUnreachable = true;
11044 
11045         if (!JTH->FallthroughUnreachable)
11046           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11047         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11048         CurMBB->normalizeSuccProbs();
11049 
11050         // The jump table header will be inserted in our current block, do the
11051         // range check, and fall through to our fallthrough block.
11052         JTH->HeaderBB = CurMBB;
11053         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11054 
11055         // If we're in the right place, emit the jump table header right now.
11056         if (CurMBB == SwitchMBB) {
11057           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11058           JTH->Emitted = true;
11059         }
11060         break;
11061       }
11062       case CC_BitTests: {
11063         // FIXME: Optimize away range check based on pivot comparisons.
11064         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11065 
11066         // The bit test blocks haven't been inserted yet; insert them here.
11067         for (BitTestCase &BTC : BTB->Cases)
11068           CurMF->insert(BBI, BTC.ThisBB);
11069 
11070         // Fill in fields of the BitTestBlock.
11071         BTB->Parent = CurMBB;
11072         BTB->Default = Fallthrough;
11073 
11074         BTB->DefaultProb = UnhandledProbs;
11075         // If the cases in bit test don't form a contiguous range, we evenly
11076         // distribute the probability on the edge to Fallthrough to two
11077         // successors of CurMBB.
11078         if (!BTB->ContiguousRange) {
11079           BTB->Prob += DefaultProb / 2;
11080           BTB->DefaultProb -= DefaultProb / 2;
11081         }
11082 
11083         if (FallthroughUnreachable)
11084           BTB->FallthroughUnreachable = true;
11085 
11086         // If we're in the right place, emit the bit test header right now.
11087         if (CurMBB == SwitchMBB) {
11088           visitBitTestHeader(*BTB, SwitchMBB);
11089           BTB->Emitted = true;
11090         }
11091         break;
11092       }
11093       case CC_Range: {
11094         const Value *RHS, *LHS, *MHS;
11095         ISD::CondCode CC;
11096         if (I->Low == I->High) {
11097           // Check Cond == I->Low.
11098           CC = ISD::SETEQ;
11099           LHS = Cond;
11100           RHS=I->Low;
11101           MHS = nullptr;
11102         } else {
11103           // Check I->Low <= Cond <= I->High.
11104           CC = ISD::SETLE;
11105           LHS = I->Low;
11106           MHS = Cond;
11107           RHS = I->High;
11108         }
11109 
11110         // If Fallthrough is unreachable, fold away the comparison.
11111         if (FallthroughUnreachable)
11112           CC = ISD::SETTRUE;
11113 
11114         // The false probability is the sum of all unhandled cases.
11115         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11116                      getCurSDLoc(), I->Prob, UnhandledProbs);
11117 
11118         if (CurMBB == SwitchMBB)
11119           visitSwitchCase(CB, SwitchMBB);
11120         else
11121           SL->SwitchCases.push_back(CB);
11122 
11123         break;
11124       }
11125     }
11126     CurMBB = Fallthrough;
11127   }
11128 }
11129 
11130 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11131                                               CaseClusterIt First,
11132                                               CaseClusterIt Last) {
11133   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11134     if (X.Prob != CC.Prob)
11135       return X.Prob > CC.Prob;
11136 
11137     // Ties are broken by comparing the case value.
11138     return X.Low->getValue().slt(CC.Low->getValue());
11139   });
11140 }
11141 
11142 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11143                                         const SwitchWorkListItem &W,
11144                                         Value *Cond,
11145                                         MachineBasicBlock *SwitchMBB) {
11146   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11147          "Clusters not sorted?");
11148 
11149   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11150 
11151   // Balance the tree based on branch probabilities to create a near-optimal (in
11152   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11153   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11154   CaseClusterIt LastLeft = W.FirstCluster;
11155   CaseClusterIt FirstRight = W.LastCluster;
11156   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11157   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11158 
11159   // Move LastLeft and FirstRight towards each other from opposite directions to
11160   // find a partitioning of the clusters which balances the probability on both
11161   // sides. If LeftProb and RightProb are equal, alternate which side is
11162   // taken to ensure 0-probability nodes are distributed evenly.
11163   unsigned I = 0;
11164   while (LastLeft + 1 < FirstRight) {
11165     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11166       LeftProb += (++LastLeft)->Prob;
11167     else
11168       RightProb += (--FirstRight)->Prob;
11169     I++;
11170   }
11171 
11172   while (true) {
11173     // Our binary search tree differs from a typical BST in that ours can have up
11174     // to three values in each leaf. The pivot selection above doesn't take that
11175     // into account, which means the tree might require more nodes and be less
11176     // efficient. We compensate for this here.
11177 
11178     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11179     unsigned NumRight = W.LastCluster - FirstRight + 1;
11180 
11181     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11182       // If one side has less than 3 clusters, and the other has more than 3,
11183       // consider taking a cluster from the other side.
11184 
11185       if (NumLeft < NumRight) {
11186         // Consider moving the first cluster on the right to the left side.
11187         CaseCluster &CC = *FirstRight;
11188         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11189         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11190         if (LeftSideRank <= RightSideRank) {
11191           // Moving the cluster to the left does not demote it.
11192           ++LastLeft;
11193           ++FirstRight;
11194           continue;
11195         }
11196       } else {
11197         assert(NumRight < NumLeft);
11198         // Consider moving the last element on the left to the right side.
11199         CaseCluster &CC = *LastLeft;
11200         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11201         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11202         if (RightSideRank <= LeftSideRank) {
11203           // Moving the cluster to the right does not demot it.
11204           --LastLeft;
11205           --FirstRight;
11206           continue;
11207         }
11208       }
11209     }
11210     break;
11211   }
11212 
11213   assert(LastLeft + 1 == FirstRight);
11214   assert(LastLeft >= W.FirstCluster);
11215   assert(FirstRight <= W.LastCluster);
11216 
11217   // Use the first element on the right as pivot since we will make less-than
11218   // comparisons against it.
11219   CaseClusterIt PivotCluster = FirstRight;
11220   assert(PivotCluster > W.FirstCluster);
11221   assert(PivotCluster <= W.LastCluster);
11222 
11223   CaseClusterIt FirstLeft = W.FirstCluster;
11224   CaseClusterIt LastRight = W.LastCluster;
11225 
11226   const ConstantInt *Pivot = PivotCluster->Low;
11227 
11228   // New blocks will be inserted immediately after the current one.
11229   MachineFunction::iterator BBI(W.MBB);
11230   ++BBI;
11231 
11232   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11233   // we can branch to its destination directly if it's squeezed exactly in
11234   // between the known lower bound and Pivot - 1.
11235   MachineBasicBlock *LeftMBB;
11236   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11237       FirstLeft->Low == W.GE &&
11238       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11239     LeftMBB = FirstLeft->MBB;
11240   } else {
11241     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11242     FuncInfo.MF->insert(BBI, LeftMBB);
11243     WorkList.push_back(
11244         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11245     // Put Cond in a virtual register to make it available from the new blocks.
11246     ExportFromCurrentBlock(Cond);
11247   }
11248 
11249   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11250   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11251   // directly if RHS.High equals the current upper bound.
11252   MachineBasicBlock *RightMBB;
11253   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11254       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11255     RightMBB = FirstRight->MBB;
11256   } else {
11257     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11258     FuncInfo.MF->insert(BBI, RightMBB);
11259     WorkList.push_back(
11260         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11261     // Put Cond in a virtual register to make it available from the new blocks.
11262     ExportFromCurrentBlock(Cond);
11263   }
11264 
11265   // Create the CaseBlock record that will be used to lower the branch.
11266   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11267                getCurSDLoc(), LeftProb, RightProb);
11268 
11269   if (W.MBB == SwitchMBB)
11270     visitSwitchCase(CB, SwitchMBB);
11271   else
11272     SL->SwitchCases.push_back(CB);
11273 }
11274 
11275 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11276 // from the swith statement.
11277 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11278                                             BranchProbability PeeledCaseProb) {
11279   if (PeeledCaseProb == BranchProbability::getOne())
11280     return BranchProbability::getZero();
11281   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11282 
11283   uint32_t Numerator = CaseProb.getNumerator();
11284   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11285   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11286 }
11287 
11288 // Try to peel the top probability case if it exceeds the threshold.
11289 // Return current MachineBasicBlock for the switch statement if the peeling
11290 // does not occur.
11291 // If the peeling is performed, return the newly created MachineBasicBlock
11292 // for the peeled switch statement. Also update Clusters to remove the peeled
11293 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11294 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11295     const SwitchInst &SI, CaseClusterVector &Clusters,
11296     BranchProbability &PeeledCaseProb) {
11297   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11298   // Don't perform if there is only one cluster or optimizing for size.
11299   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11300       TM.getOptLevel() == CodeGenOpt::None ||
11301       SwitchMBB->getParent()->getFunction().hasMinSize())
11302     return SwitchMBB;
11303 
11304   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11305   unsigned PeeledCaseIndex = 0;
11306   bool SwitchPeeled = false;
11307   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11308     CaseCluster &CC = Clusters[Index];
11309     if (CC.Prob < TopCaseProb)
11310       continue;
11311     TopCaseProb = CC.Prob;
11312     PeeledCaseIndex = Index;
11313     SwitchPeeled = true;
11314   }
11315   if (!SwitchPeeled)
11316     return SwitchMBB;
11317 
11318   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11319                     << TopCaseProb << "\n");
11320 
11321   // Record the MBB for the peeled switch statement.
11322   MachineFunction::iterator BBI(SwitchMBB);
11323   ++BBI;
11324   MachineBasicBlock *PeeledSwitchMBB =
11325       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11326   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11327 
11328   ExportFromCurrentBlock(SI.getCondition());
11329   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11330   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11331                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11332   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11333 
11334   Clusters.erase(PeeledCaseIt);
11335   for (CaseCluster &CC : Clusters) {
11336     LLVM_DEBUG(
11337         dbgs() << "Scale the probablity for one cluster, before scaling: "
11338                << CC.Prob << "\n");
11339     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11340     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11341   }
11342   PeeledCaseProb = TopCaseProb;
11343   return PeeledSwitchMBB;
11344 }
11345 
11346 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11347   // Extract cases from the switch.
11348   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11349   CaseClusterVector Clusters;
11350   Clusters.reserve(SI.getNumCases());
11351   for (auto I : SI.cases()) {
11352     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11353     const ConstantInt *CaseVal = I.getCaseValue();
11354     BranchProbability Prob =
11355         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11356             : BranchProbability(1, SI.getNumCases() + 1);
11357     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11358   }
11359 
11360   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11361 
11362   // Cluster adjacent cases with the same destination. We do this at all
11363   // optimization levels because it's cheap to do and will make codegen faster
11364   // if there are many clusters.
11365   sortAndRangeify(Clusters);
11366 
11367   // The branch probablity of the peeled case.
11368   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11369   MachineBasicBlock *PeeledSwitchMBB =
11370       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11371 
11372   // If there is only the default destination, jump there directly.
11373   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11374   if (Clusters.empty()) {
11375     assert(PeeledSwitchMBB == SwitchMBB);
11376     SwitchMBB->addSuccessor(DefaultMBB);
11377     if (DefaultMBB != NextBlock(SwitchMBB)) {
11378       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11379                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11380     }
11381     return;
11382   }
11383 
11384   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11385   SL->findBitTestClusters(Clusters, &SI);
11386 
11387   LLVM_DEBUG({
11388     dbgs() << "Case clusters: ";
11389     for (const CaseCluster &C : Clusters) {
11390       if (C.Kind == CC_JumpTable)
11391         dbgs() << "JT:";
11392       if (C.Kind == CC_BitTests)
11393         dbgs() << "BT:";
11394 
11395       C.Low->getValue().print(dbgs(), true);
11396       if (C.Low != C.High) {
11397         dbgs() << '-';
11398         C.High->getValue().print(dbgs(), true);
11399       }
11400       dbgs() << ' ';
11401     }
11402     dbgs() << '\n';
11403   });
11404 
11405   assert(!Clusters.empty());
11406   SwitchWorkList WorkList;
11407   CaseClusterIt First = Clusters.begin();
11408   CaseClusterIt Last = Clusters.end() - 1;
11409   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11410   // Scale the branchprobability for DefaultMBB if the peel occurs and
11411   // DefaultMBB is not replaced.
11412   if (PeeledCaseProb != BranchProbability::getZero() &&
11413       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11414     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11415   WorkList.push_back(
11416       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11417 
11418   while (!WorkList.empty()) {
11419     SwitchWorkListItem W = WorkList.pop_back_val();
11420     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11421 
11422     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11423         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11424       // For optimized builds, lower large range as a balanced binary tree.
11425       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11426       continue;
11427     }
11428 
11429     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11430   }
11431 }
11432 
11433 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11435   auto DL = getCurSDLoc();
11436   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11437   setValue(&I, DAG.getStepVector(DL, ResultVT));
11438 }
11439 
11440 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11441   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11442   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11443 
11444   SDLoc DL = getCurSDLoc();
11445   SDValue V = getValue(I.getOperand(0));
11446   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11447 
11448   if (VT.isScalableVector()) {
11449     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11450     return;
11451   }
11452 
11453   // Use VECTOR_SHUFFLE for the fixed-length vector
11454   // to maintain existing behavior.
11455   SmallVector<int, 8> Mask;
11456   unsigned NumElts = VT.getVectorMinNumElements();
11457   for (unsigned i = 0; i != NumElts; ++i)
11458     Mask.push_back(NumElts - 1 - i);
11459 
11460   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11461 }
11462 
11463 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11464   SmallVector<EVT, 4> ValueVTs;
11465   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11466                   ValueVTs);
11467   unsigned NumValues = ValueVTs.size();
11468   if (NumValues == 0) return;
11469 
11470   SmallVector<SDValue, 4> Values(NumValues);
11471   SDValue Op = getValue(I.getOperand(0));
11472 
11473   for (unsigned i = 0; i != NumValues; ++i)
11474     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11475                             SDValue(Op.getNode(), Op.getResNo() + i));
11476 
11477   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11478                            DAG.getVTList(ValueVTs), Values));
11479 }
11480 
11481 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11483   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11484 
11485   SDLoc DL = getCurSDLoc();
11486   SDValue V1 = getValue(I.getOperand(0));
11487   SDValue V2 = getValue(I.getOperand(1));
11488   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11489 
11490   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11491   if (VT.isScalableVector()) {
11492     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11493     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11494                              DAG.getConstant(Imm, DL, IdxVT)));
11495     return;
11496   }
11497 
11498   unsigned NumElts = VT.getVectorNumElements();
11499 
11500   uint64_t Idx = (NumElts + Imm) % NumElts;
11501 
11502   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11503   SmallVector<int, 8> Mask;
11504   for (unsigned i = 0; i < NumElts; ++i)
11505     Mask.push_back(Idx + i);
11506   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11507 }
11508