xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 4a8665e23ed875c7f524e1ecd7e8442dc1b6a423)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BranchProbabilityInfo.h"
28 #include "llvm/Analysis/ConstantFolding.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/Analysis/MemoryLocation.h"
31 #include "llvm/Analysis/TargetLibraryInfo.h"
32 #include "llvm/Analysis/ValueTracking.h"
33 #include "llvm/CodeGen/Analysis.h"
34 #include "llvm/CodeGen/FunctionLoweringInfo.h"
35 #include "llvm/CodeGen/GCMetadata.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
41 #include "llvm/CodeGen/MachineMemOperand.h"
42 #include "llvm/CodeGen/MachineModuleInfo.h"
43 #include "llvm/CodeGen/MachineOperand.h"
44 #include "llvm/CodeGen/MachineRegisterInfo.h"
45 #include "llvm/CodeGen/RuntimeLibcalls.h"
46 #include "llvm/CodeGen/SelectionDAG.h"
47 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
48 #include "llvm/CodeGen/StackMaps.h"
49 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
50 #include "llvm/CodeGen/TargetFrameLowering.h"
51 #include "llvm/CodeGen/TargetInstrInfo.h"
52 #include "llvm/CodeGen/TargetOpcodes.h"
53 #include "llvm/CodeGen/TargetRegisterInfo.h"
54 #include "llvm/CodeGen/TargetSubtargetInfo.h"
55 #include "llvm/CodeGen/WinEHFuncInfo.h"
56 #include "llvm/IR/Argument.h"
57 #include "llvm/IR/Attributes.h"
58 #include "llvm/IR/BasicBlock.h"
59 #include "llvm/IR/CFG.h"
60 #include "llvm/IR/CallingConv.h"
61 #include "llvm/IR/Constant.h"
62 #include "llvm/IR/ConstantRange.h"
63 #include "llvm/IR/Constants.h"
64 #include "llvm/IR/DataLayout.h"
65 #include "llvm/IR/DebugInfoMetadata.h"
66 #include "llvm/IR/DerivedTypes.h"
67 #include "llvm/IR/DiagnosticInfo.h"
68 #include "llvm/IR/Function.h"
69 #include "llvm/IR/GetElementPtrTypeIterator.h"
70 #include "llvm/IR/InlineAsm.h"
71 #include "llvm/IR/InstrTypes.h"
72 #include "llvm/IR/Instructions.h"
73 #include "llvm/IR/IntrinsicInst.h"
74 #include "llvm/IR/Intrinsics.h"
75 #include "llvm/IR/IntrinsicsAArch64.h"
76 #include "llvm/IR/IntrinsicsWebAssembly.h"
77 #include "llvm/IR/LLVMContext.h"
78 #include "llvm/IR/Metadata.h"
79 #include "llvm/IR/Module.h"
80 #include "llvm/IR/Operator.h"
81 #include "llvm/IR/PatternMatch.h"
82 #include "llvm/IR/Statepoint.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/MC/MCContext.h"
87 #include "llvm/Support/AtomicOrdering.h"
88 #include "llvm/Support/Casting.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Compiler.h"
91 #include "llvm/Support/Debug.h"
92 #include "llvm/Support/MathExtras.h"
93 #include "llvm/Support/raw_ostream.h"
94 #include "llvm/Target/TargetIntrinsicInfo.h"
95 #include "llvm/Target/TargetMachine.h"
96 #include "llvm/Target/TargetOptions.h"
97 #include "llvm/Transforms/Utils/Local.h"
98 #include <cstddef>
99 #include <iterator>
100 #include <limits>
101 #include <tuple>
102 
103 using namespace llvm;
104 using namespace PatternMatch;
105 using namespace SwitchCG;
106 
107 #define DEBUG_TYPE "isel"
108 
109 /// LimitFloatPrecision - Generate low-precision inline sequences for
110 /// some float libcalls (6, 8 or 12 bits).
111 static unsigned LimitFloatPrecision;
112 
113 static cl::opt<bool>
114     InsertAssertAlign("insert-assert-align", cl::init(true),
115                       cl::desc("Insert the experimental `assertalign` node."),
116                       cl::ReallyHidden);
117 
118 static cl::opt<unsigned, true>
119     LimitFPPrecision("limit-float-precision",
120                      cl::desc("Generate low-precision inline sequences "
121                               "for some float libcalls"),
122                      cl::location(LimitFloatPrecision), cl::Hidden,
123                      cl::init(0));
124 
125 static cl::opt<unsigned> SwitchPeelThreshold(
126     "switch-peel-threshold", cl::Hidden, cl::init(66),
127     cl::desc("Set the case probability threshold for peeling the case from a "
128              "switch statement. A value greater than 100 will void this "
129              "optimization"));
130 
131 // Limit the width of DAG chains. This is important in general to prevent
132 // DAG-based analysis from blowing up. For example, alias analysis and
133 // load clustering may not complete in reasonable time. It is difficult to
134 // recognize and avoid this situation within each individual analysis, and
135 // future analyses are likely to have the same behavior. Limiting DAG width is
136 // the safe approach and will be especially important with global DAGs.
137 //
138 // MaxParallelChains default is arbitrarily high to avoid affecting
139 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
140 // sequence over this should have been converted to llvm.memcpy by the
141 // frontend. It is easy to induce this behavior with .ll code such as:
142 // %buffer = alloca [4096 x i8]
143 // %data = load [4096 x i8]* %argPtr
144 // store [4096 x i8] %data, [4096 x i8]* %buffer
145 static const unsigned MaxParallelChains = 64;
146 
147 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
148                                       const SDValue *Parts, unsigned NumParts,
149                                       MVT PartVT, EVT ValueVT, const Value *V,
150                                       Optional<CallingConv::ID> CC);
151 
152 /// getCopyFromParts - Create a value that contains the specified legal parts
153 /// combined into the value they represent.  If the parts combine to a type
154 /// larger than ValueVT then AssertOp can be used to specify whether the extra
155 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
156 /// (ISD::AssertSext).
157 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
158                                 const SDValue *Parts, unsigned NumParts,
159                                 MVT PartVT, EVT ValueVT, const Value *V,
160                                 Optional<CallingConv::ID> CC = None,
161                                 Optional<ISD::NodeType> AssertOp = None) {
162   // Let the target assemble the parts if it wants to
163   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
164   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
165                                                    PartVT, ValueVT, CC))
166     return Val;
167 
168   if (ValueVT.isVector())
169     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
170                                   CC);
171 
172   assert(NumParts > 0 && "No parts to assemble!");
173   SDValue Val = Parts[0];
174 
175   if (NumParts > 1) {
176     // Assemble the value from multiple parts.
177     if (ValueVT.isInteger()) {
178       unsigned PartBits = PartVT.getSizeInBits();
179       unsigned ValueBits = ValueVT.getSizeInBits();
180 
181       // Assemble the power of 2 part.
182       unsigned RoundParts =
183           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
184       unsigned RoundBits = PartBits * RoundParts;
185       EVT RoundVT = RoundBits == ValueBits ?
186         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
187       SDValue Lo, Hi;
188 
189       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
190 
191       if (RoundParts > 2) {
192         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
193                               PartVT, HalfVT, V);
194         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
195                               RoundParts / 2, PartVT, HalfVT, V);
196       } else {
197         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
198         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
199       }
200 
201       if (DAG.getDataLayout().isBigEndian())
202         std::swap(Lo, Hi);
203 
204       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
205 
206       if (RoundParts < NumParts) {
207         // Assemble the trailing non-power-of-2 part.
208         unsigned OddParts = NumParts - RoundParts;
209         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
210         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
211                               OddVT, V, CC);
212 
213         // Combine the round and odd parts.
214         Lo = Val;
215         if (DAG.getDataLayout().isBigEndian())
216           std::swap(Lo, Hi);
217         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
218         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
219         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
220                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
221                                          TLI.getShiftAmountTy(
222                                              TotalVT, DAG.getDataLayout())));
223         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
224         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
225       }
226     } else if (PartVT.isFloatingPoint()) {
227       // FP split into multiple FP parts (for ppcf128)
228       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
229              "Unexpected split");
230       SDValue Lo, Hi;
231       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
232       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
233       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
234         std::swap(Lo, Hi);
235       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
236     } else {
237       // FP split into integer parts (soft fp)
238       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
239              !PartVT.isVector() && "Unexpected split");
240       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
241       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
242     }
243   }
244 
245   // There is now one part, held in Val.  Correct it to match ValueVT.
246   // PartEVT is the type of the register class that holds the value.
247   // ValueVT is the type of the inline asm operation.
248   EVT PartEVT = Val.getValueType();
249 
250   if (PartEVT == ValueVT)
251     return Val;
252 
253   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
254       ValueVT.bitsLT(PartEVT)) {
255     // For an FP value in an integer part, we need to truncate to the right
256     // width first.
257     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
258     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
259   }
260 
261   // Handle types that have the same size.
262   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
263     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
264 
265   // Handle types with different sizes.
266   if (PartEVT.isInteger() && ValueVT.isInteger()) {
267     if (ValueVT.bitsLT(PartEVT)) {
268       // For a truncate, see if we have any information to
269       // indicate whether the truncated bits will always be
270       // zero or sign-extension.
271       if (AssertOp.hasValue())
272         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
273                           DAG.getValueType(ValueVT));
274       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
275     }
276     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
277   }
278 
279   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
280     // FP_ROUND's are always exact here.
281     if (ValueVT.bitsLT(Val.getValueType()))
282       return DAG.getNode(
283           ISD::FP_ROUND, DL, ValueVT, Val,
284           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
285 
286     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
287   }
288 
289   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
290   // then truncating.
291   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
292       ValueVT.bitsLT(PartEVT)) {
293     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
294     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
295   }
296 
297   report_fatal_error("Unknown mismatch in getCopyFromParts!");
298 }
299 
300 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
301                                               const Twine &ErrMsg) {
302   const Instruction *I = dyn_cast_or_null<Instruction>(V);
303   if (!V)
304     return Ctx.emitError(ErrMsg);
305 
306   const char *AsmError = ", possible invalid constraint for vector type";
307   if (const CallInst *CI = dyn_cast<CallInst>(I))
308     if (CI->isInlineAsm())
309       return Ctx.emitError(I, ErrMsg + AsmError);
310 
311   return Ctx.emitError(I, ErrMsg);
312 }
313 
314 /// getCopyFromPartsVector - Create a value that contains the specified legal
315 /// parts combined into the value they represent.  If the parts combine to a
316 /// type larger than ValueVT then AssertOp can be used to specify whether the
317 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
318 /// ValueVT (ISD::AssertSext).
319 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
320                                       const SDValue *Parts, unsigned NumParts,
321                                       MVT PartVT, EVT ValueVT, const Value *V,
322                                       Optional<CallingConv::ID> CallConv) {
323   assert(ValueVT.isVector() && "Not a vector value");
324   assert(NumParts > 0 && "No parts to assemble!");
325   const bool IsABIRegCopy = CallConv.hasValue();
326 
327   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
328   SDValue Val = Parts[0];
329 
330   // Handle a multi-element vector.
331   if (NumParts > 1) {
332     EVT IntermediateVT;
333     MVT RegisterVT;
334     unsigned NumIntermediates;
335     unsigned NumRegs;
336 
337     if (IsABIRegCopy) {
338       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
339           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
340           NumIntermediates, RegisterVT);
341     } else {
342       NumRegs =
343           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
344                                      NumIntermediates, RegisterVT);
345     }
346 
347     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
348     NumParts = NumRegs; // Silence a compiler warning.
349     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
350     assert(RegisterVT.getSizeInBits() ==
351            Parts[0].getSimpleValueType().getSizeInBits() &&
352            "Part type sizes don't match!");
353 
354     // Assemble the parts into intermediate operands.
355     SmallVector<SDValue, 8> Ops(NumIntermediates);
356     if (NumIntermediates == NumParts) {
357       // If the register was not expanded, truncate or copy the value,
358       // as appropriate.
359       for (unsigned i = 0; i != NumParts; ++i)
360         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
361                                   PartVT, IntermediateVT, V, CallConv);
362     } else if (NumParts > 0) {
363       // If the intermediate type was expanded, build the intermediate
364       // operands from the parts.
365       assert(NumParts % NumIntermediates == 0 &&
366              "Must expand into a divisible number of parts!");
367       unsigned Factor = NumParts / NumIntermediates;
368       for (unsigned i = 0; i != NumIntermediates; ++i)
369         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
370                                   PartVT, IntermediateVT, V, CallConv);
371     }
372 
373     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
374     // intermediate operands.
375     EVT BuiltVectorTy =
376         IntermediateVT.isVector()
377             ? EVT::getVectorVT(
378                   *DAG.getContext(), IntermediateVT.getScalarType(),
379                   IntermediateVT.getVectorElementCount() * NumParts)
380             : EVT::getVectorVT(*DAG.getContext(),
381                                IntermediateVT.getScalarType(),
382                                NumIntermediates);
383     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
384                                                 : ISD::BUILD_VECTOR,
385                       DL, BuiltVectorTy, Ops);
386   }
387 
388   // There is now one part, held in Val.  Correct it to match ValueVT.
389   EVT PartEVT = Val.getValueType();
390 
391   if (PartEVT == ValueVT)
392     return Val;
393 
394   if (PartEVT.isVector()) {
395     // Vector/Vector bitcast.
396     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
397       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
398 
399     // If the element type of the source/dest vectors are the same, but the
400     // parts vector has more elements than the value vector, then we have a
401     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
402     // elements we want.
403     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
404       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
405               ValueVT.getVectorElementCount().getKnownMinValue()) &&
406              (PartEVT.getVectorElementCount().isScalable() ==
407               ValueVT.getVectorElementCount().isScalable()) &&
408              "Cannot narrow, it would be a lossy transformation");
409       PartEVT =
410           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
411                            ValueVT.getVectorElementCount());
412       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
413                         DAG.getVectorIdxConstant(0, DL));
414       if (PartEVT == ValueVT)
415         return Val;
416     }
417 
418     // Promoted vector extract
419     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
420   }
421 
422   // Trivial bitcast if the types are the same size and the destination
423   // vector type is legal.
424   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
425       TLI.isTypeLegal(ValueVT))
426     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
427 
428   if (ValueVT.getVectorNumElements() != 1) {
429      // Certain ABIs require that vectors are passed as integers. For vectors
430      // are the same size, this is an obvious bitcast.
431      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
432        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
433      } else if (ValueVT.bitsLT(PartEVT)) {
434        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
435        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
436        // Drop the extra bits.
437        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
438        return DAG.getBitcast(ValueVT, Val);
439      }
440 
441      diagnosePossiblyInvalidConstraint(
442          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
443      return DAG.getUNDEF(ValueVT);
444   }
445 
446   // Handle cases such as i8 -> <1 x i1>
447   EVT ValueSVT = ValueVT.getVectorElementType();
448   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
449     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
450       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
451     else
452       Val = ValueVT.isFloatingPoint()
453                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
454                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
455   }
456 
457   return DAG.getBuildVector(ValueVT, DL, Val);
458 }
459 
460 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
461                                  SDValue Val, SDValue *Parts, unsigned NumParts,
462                                  MVT PartVT, const Value *V,
463                                  Optional<CallingConv::ID> CallConv);
464 
465 /// getCopyToParts - Create a series of nodes that contain the specified value
466 /// split into legal parts.  If the parts contain more bits than Val, then, for
467 /// integers, ExtendKind can be used to specify how to generate the extra bits.
468 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
469                            SDValue *Parts, unsigned NumParts, MVT PartVT,
470                            const Value *V,
471                            Optional<CallingConv::ID> CallConv = None,
472                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
473   // Let the target split the parts if it wants to
474   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
475   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
476                                       CallConv))
477     return;
478   EVT ValueVT = Val.getValueType();
479 
480   // Handle the vector case separately.
481   if (ValueVT.isVector())
482     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
483                                 CallConv);
484 
485   unsigned PartBits = PartVT.getSizeInBits();
486   unsigned OrigNumParts = NumParts;
487   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
488          "Copying to an illegal type!");
489 
490   if (NumParts == 0)
491     return;
492 
493   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
494   EVT PartEVT = PartVT;
495   if (PartEVT == ValueVT) {
496     assert(NumParts == 1 && "No-op copy with multiple parts!");
497     Parts[0] = Val;
498     return;
499   }
500 
501   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
502     // If the parts cover more bits than the value has, promote the value.
503     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
504       assert(NumParts == 1 && "Do not know what to promote to!");
505       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
506     } else {
507       if (ValueVT.isFloatingPoint()) {
508         // FP values need to be bitcast, then extended if they are being put
509         // into a larger container.
510         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
511         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
512       }
513       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
514              ValueVT.isInteger() &&
515              "Unknown mismatch!");
516       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
517       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
518       if (PartVT == MVT::x86mmx)
519         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
520     }
521   } else if (PartBits == ValueVT.getSizeInBits()) {
522     // Different types of the same size.
523     assert(NumParts == 1 && PartEVT != ValueVT);
524     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
525   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
526     // If the parts cover less bits than value has, truncate the value.
527     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
528            ValueVT.isInteger() &&
529            "Unknown mismatch!");
530     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
531     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
532     if (PartVT == MVT::x86mmx)
533       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
534   }
535 
536   // The value may have changed - recompute ValueVT.
537   ValueVT = Val.getValueType();
538   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
539          "Failed to tile the value with PartVT!");
540 
541   if (NumParts == 1) {
542     if (PartEVT != ValueVT) {
543       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
544                                         "scalar-to-vector conversion failed");
545       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
546     }
547 
548     Parts[0] = Val;
549     return;
550   }
551 
552   // Expand the value into multiple parts.
553   if (NumParts & (NumParts - 1)) {
554     // The number of parts is not a power of 2.  Split off and copy the tail.
555     assert(PartVT.isInteger() && ValueVT.isInteger() &&
556            "Do not know what to expand to!");
557     unsigned RoundParts = 1 << Log2_32(NumParts);
558     unsigned RoundBits = RoundParts * PartBits;
559     unsigned OddParts = NumParts - RoundParts;
560     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
561       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
562 
563     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
564                    CallConv);
565 
566     if (DAG.getDataLayout().isBigEndian())
567       // The odd parts were reversed by getCopyToParts - unreverse them.
568       std::reverse(Parts + RoundParts, Parts + NumParts);
569 
570     NumParts = RoundParts;
571     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
572     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
573   }
574 
575   // The number of parts is a power of 2.  Repeatedly bisect the value using
576   // EXTRACT_ELEMENT.
577   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
578                          EVT::getIntegerVT(*DAG.getContext(),
579                                            ValueVT.getSizeInBits()),
580                          Val);
581 
582   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
583     for (unsigned i = 0; i < NumParts; i += StepSize) {
584       unsigned ThisBits = StepSize * PartBits / 2;
585       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
586       SDValue &Part0 = Parts[i];
587       SDValue &Part1 = Parts[i+StepSize/2];
588 
589       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
590                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
591       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
592                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
593 
594       if (ThisBits == PartBits && ThisVT != PartVT) {
595         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
596         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
597       }
598     }
599   }
600 
601   if (DAG.getDataLayout().isBigEndian())
602     std::reverse(Parts, Parts + OrigNumParts);
603 }
604 
605 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
606                                      const SDLoc &DL, EVT PartVT) {
607   if (!PartVT.isVector())
608     return SDValue();
609 
610   EVT ValueVT = Val.getValueType();
611   ElementCount PartNumElts = PartVT.getVectorElementCount();
612   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
613 
614   // We only support widening vectors with equivalent element types and
615   // fixed/scalable properties. If a target needs to widen a fixed-length type
616   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
617   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
618       PartNumElts.isScalable() != ValueNumElts.isScalable() ||
619       PartVT.getVectorElementType() != ValueVT.getVectorElementType())
620     return SDValue();
621 
622   // Widening a scalable vector to another scalable vector is done by inserting
623   // the vector into a larger undef one.
624   if (PartNumElts.isScalable())
625     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
626                        Val, DAG.getVectorIdxConstant(0, DL));
627 
628   EVT ElementVT = PartVT.getVectorElementType();
629   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
630   // undef elements.
631   SmallVector<SDValue, 16> Ops;
632   DAG.ExtractVectorElements(Val, Ops);
633   SDValue EltUndef = DAG.getUNDEF(ElementVT);
634   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
635 
636   // FIXME: Use CONCAT for 2x -> 4x.
637   return DAG.getBuildVector(PartVT, DL, Ops);
638 }
639 
640 /// getCopyToPartsVector - Create a series of nodes that contain the specified
641 /// value split into legal parts.
642 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
643                                  SDValue Val, SDValue *Parts, unsigned NumParts,
644                                  MVT PartVT, const Value *V,
645                                  Optional<CallingConv::ID> CallConv) {
646   EVT ValueVT = Val.getValueType();
647   assert(ValueVT.isVector() && "Not a vector");
648   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
649   const bool IsABIRegCopy = CallConv.hasValue();
650 
651   if (NumParts == 1) {
652     EVT PartEVT = PartVT;
653     if (PartEVT == ValueVT) {
654       // Nothing to do.
655     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
656       // Bitconvert vector->vector case.
657       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
658     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
659       Val = Widened;
660     } else if (PartVT.isVector() &&
661                PartEVT.getVectorElementType().bitsGE(
662                    ValueVT.getVectorElementType()) &&
663                PartEVT.getVectorElementCount() ==
664                    ValueVT.getVectorElementCount()) {
665 
666       // Promoted vector extract
667       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
668     } else if (PartEVT.isVector() &&
669                PartEVT.getVectorElementType() !=
670                    ValueVT.getVectorElementType() &&
671                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
672                    TargetLowering::TypeWidenVector) {
673       // Combination of widening and promotion.
674       EVT WidenVT =
675           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
676                            PartVT.getVectorElementCount());
677       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
678       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
679     } else {
680       if (ValueVT.getVectorElementCount().isScalar()) {
681         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
682                           DAG.getVectorIdxConstant(0, DL));
683       } else {
684         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
685         assert(PartVT.getFixedSizeInBits() > ValueSize &&
686                "lossy conversion of vector to scalar type");
687         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
688         Val = DAG.getBitcast(IntermediateType, Val);
689         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
690       }
691     }
692 
693     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
694     Parts[0] = Val;
695     return;
696   }
697 
698   // Handle a multi-element vector.
699   EVT IntermediateVT;
700   MVT RegisterVT;
701   unsigned NumIntermediates;
702   unsigned NumRegs;
703   if (IsABIRegCopy) {
704     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
705         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
706         NumIntermediates, RegisterVT);
707   } else {
708     NumRegs =
709         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
710                                    NumIntermediates, RegisterVT);
711   }
712 
713   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
714   NumParts = NumRegs; // Silence a compiler warning.
715   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
716 
717   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
718          "Mixing scalable and fixed vectors when copying in parts");
719 
720   Optional<ElementCount> DestEltCnt;
721 
722   if (IntermediateVT.isVector())
723     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
724   else
725     DestEltCnt = ElementCount::getFixed(NumIntermediates);
726 
727   EVT BuiltVectorTy = EVT::getVectorVT(
728       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
729 
730   if (ValueVT == BuiltVectorTy) {
731     // Nothing to do.
732   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
733     // Bitconvert vector->vector case.
734     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
735   } else {
736     if (BuiltVectorTy.getVectorElementType().bitsGT(
737             ValueVT.getVectorElementType())) {
738       // Integer promotion.
739       ValueVT = EVT::getVectorVT(*DAG.getContext(),
740                                  BuiltVectorTy.getVectorElementType(),
741                                  ValueVT.getVectorElementCount());
742       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
743     }
744 
745     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
746       Val = Widened;
747     }
748   }
749 
750   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
751 
752   // Split the vector into intermediate operands.
753   SmallVector<SDValue, 8> Ops(NumIntermediates);
754   for (unsigned i = 0; i != NumIntermediates; ++i) {
755     if (IntermediateVT.isVector()) {
756       // This does something sensible for scalable vectors - see the
757       // definition of EXTRACT_SUBVECTOR for further details.
758       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
759       Ops[i] =
760           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
761                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
762     } else {
763       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
764                            DAG.getVectorIdxConstant(i, DL));
765     }
766   }
767 
768   // Split the intermediate operands into legal parts.
769   if (NumParts == NumIntermediates) {
770     // If the register was not expanded, promote or copy the value,
771     // as appropriate.
772     for (unsigned i = 0; i != NumParts; ++i)
773       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
774   } else if (NumParts > 0) {
775     // If the intermediate type was expanded, split each the value into
776     // legal parts.
777     assert(NumIntermediates != 0 && "division by zero");
778     assert(NumParts % NumIntermediates == 0 &&
779            "Must expand into a divisible number of parts!");
780     unsigned Factor = NumParts / NumIntermediates;
781     for (unsigned i = 0; i != NumIntermediates; ++i)
782       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
783                      CallConv);
784   }
785 }
786 
787 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
788                            EVT valuevt, Optional<CallingConv::ID> CC)
789     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
790       RegCount(1, regs.size()), CallConv(CC) {}
791 
792 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
793                            const DataLayout &DL, unsigned Reg, Type *Ty,
794                            Optional<CallingConv::ID> CC) {
795   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
796 
797   CallConv = CC;
798 
799   for (EVT ValueVT : ValueVTs) {
800     unsigned NumRegs =
801         isABIMangled()
802             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
803             : TLI.getNumRegisters(Context, ValueVT);
804     MVT RegisterVT =
805         isABIMangled()
806             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
807             : TLI.getRegisterType(Context, ValueVT);
808     for (unsigned i = 0; i != NumRegs; ++i)
809       Regs.push_back(Reg + i);
810     RegVTs.push_back(RegisterVT);
811     RegCount.push_back(NumRegs);
812     Reg += NumRegs;
813   }
814 }
815 
816 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
817                                       FunctionLoweringInfo &FuncInfo,
818                                       const SDLoc &dl, SDValue &Chain,
819                                       SDValue *Flag, const Value *V) const {
820   // A Value with type {} or [0 x %t] needs no registers.
821   if (ValueVTs.empty())
822     return SDValue();
823 
824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
825 
826   // Assemble the legal parts into the final values.
827   SmallVector<SDValue, 4> Values(ValueVTs.size());
828   SmallVector<SDValue, 8> Parts;
829   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
830     // Copy the legal parts from the registers.
831     EVT ValueVT = ValueVTs[Value];
832     unsigned NumRegs = RegCount[Value];
833     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
834                                           *DAG.getContext(),
835                                           CallConv.getValue(), RegVTs[Value])
836                                     : RegVTs[Value];
837 
838     Parts.resize(NumRegs);
839     for (unsigned i = 0; i != NumRegs; ++i) {
840       SDValue P;
841       if (!Flag) {
842         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
843       } else {
844         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
845         *Flag = P.getValue(2);
846       }
847 
848       Chain = P.getValue(1);
849       Parts[i] = P;
850 
851       // If the source register was virtual and if we know something about it,
852       // add an assert node.
853       if (!Register::isVirtualRegister(Regs[Part + i]) ||
854           !RegisterVT.isInteger())
855         continue;
856 
857       const FunctionLoweringInfo::LiveOutInfo *LOI =
858         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
859       if (!LOI)
860         continue;
861 
862       unsigned RegSize = RegisterVT.getScalarSizeInBits();
863       unsigned NumSignBits = LOI->NumSignBits;
864       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
865 
866       if (NumZeroBits == RegSize) {
867         // The current value is a zero.
868         // Explicitly express that as it would be easier for
869         // optimizations to kick in.
870         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
871         continue;
872       }
873 
874       // FIXME: We capture more information than the dag can represent.  For
875       // now, just use the tightest assertzext/assertsext possible.
876       bool isSExt;
877       EVT FromVT(MVT::Other);
878       if (NumZeroBits) {
879         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
880         isSExt = false;
881       } else if (NumSignBits > 1) {
882         FromVT =
883             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
884         isSExt = true;
885       } else {
886         continue;
887       }
888       // Add an assertion node.
889       assert(FromVT != MVT::Other);
890       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
891                              RegisterVT, P, DAG.getValueType(FromVT));
892     }
893 
894     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
895                                      RegisterVT, ValueVT, V, CallConv);
896     Part += NumRegs;
897     Parts.clear();
898   }
899 
900   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
901 }
902 
903 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
904                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
905                                  const Value *V,
906                                  ISD::NodeType PreferredExtendType) const {
907   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
908   ISD::NodeType ExtendKind = PreferredExtendType;
909 
910   // Get the list of the values's legal parts.
911   unsigned NumRegs = Regs.size();
912   SmallVector<SDValue, 8> Parts(NumRegs);
913   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
914     unsigned NumParts = RegCount[Value];
915 
916     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
917                                           *DAG.getContext(),
918                                           CallConv.getValue(), RegVTs[Value])
919                                     : RegVTs[Value];
920 
921     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
922       ExtendKind = ISD::ZERO_EXTEND;
923 
924     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
925                    NumParts, RegisterVT, V, CallConv, ExtendKind);
926     Part += NumParts;
927   }
928 
929   // Copy the parts into the registers.
930   SmallVector<SDValue, 8> Chains(NumRegs);
931   for (unsigned i = 0; i != NumRegs; ++i) {
932     SDValue Part;
933     if (!Flag) {
934       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
935     } else {
936       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
937       *Flag = Part.getValue(1);
938     }
939 
940     Chains[i] = Part.getValue(0);
941   }
942 
943   if (NumRegs == 1 || Flag)
944     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
945     // flagged to it. That is the CopyToReg nodes and the user are considered
946     // a single scheduling unit. If we create a TokenFactor and return it as
947     // chain, then the TokenFactor is both a predecessor (operand) of the
948     // user as well as a successor (the TF operands are flagged to the user).
949     // c1, f1 = CopyToReg
950     // c2, f2 = CopyToReg
951     // c3     = TokenFactor c1, c2
952     // ...
953     //        = op c3, ..., f2
954     Chain = Chains[NumRegs-1];
955   else
956     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
957 }
958 
959 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
960                                         unsigned MatchingIdx, const SDLoc &dl,
961                                         SelectionDAG &DAG,
962                                         std::vector<SDValue> &Ops) const {
963   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
964 
965   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
966   if (HasMatching)
967     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
968   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
969     // Put the register class of the virtual registers in the flag word.  That
970     // way, later passes can recompute register class constraints for inline
971     // assembly as well as normal instructions.
972     // Don't do this for tied operands that can use the regclass information
973     // from the def.
974     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
975     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
976     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
977   }
978 
979   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
980   Ops.push_back(Res);
981 
982   if (Code == InlineAsm::Kind_Clobber) {
983     // Clobbers should always have a 1:1 mapping with registers, and may
984     // reference registers that have illegal (e.g. vector) types. Hence, we
985     // shouldn't try to apply any sort of splitting logic to them.
986     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
987            "No 1:1 mapping from clobbers to regs?");
988     Register SP = TLI.getStackPointerRegisterToSaveRestore();
989     (void)SP;
990     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
991       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
992       assert(
993           (Regs[I] != SP ||
994            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
995           "If we clobbered the stack pointer, MFI should know about it.");
996     }
997     return;
998   }
999 
1000   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1001     MVT RegisterVT = RegVTs[Value];
1002     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1003                                            RegisterVT);
1004     for (unsigned i = 0; i != NumRegs; ++i) {
1005       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1006       unsigned TheReg = Regs[Reg++];
1007       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1008     }
1009   }
1010 }
1011 
1012 SmallVector<std::pair<unsigned, TypeSize>, 4>
1013 RegsForValue::getRegsAndSizes() const {
1014   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1015   unsigned I = 0;
1016   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1017     unsigned RegCount = std::get<0>(CountAndVT);
1018     MVT RegisterVT = std::get<1>(CountAndVT);
1019     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1020     for (unsigned E = I + RegCount; I != E; ++I)
1021       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1022   }
1023   return OutVec;
1024 }
1025 
1026 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1027                                const TargetLibraryInfo *li) {
1028   AA = aa;
1029   GFI = gfi;
1030   LibInfo = li;
1031   Context = DAG.getContext();
1032   LPadToCallSiteMap.clear();
1033   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1034 }
1035 
1036 void SelectionDAGBuilder::clear() {
1037   NodeMap.clear();
1038   UnusedArgNodeMap.clear();
1039   PendingLoads.clear();
1040   PendingExports.clear();
1041   PendingConstrainedFP.clear();
1042   PendingConstrainedFPStrict.clear();
1043   CurInst = nullptr;
1044   HasTailCall = false;
1045   SDNodeOrder = LowestSDNodeOrder;
1046   StatepointLowering.clear();
1047 }
1048 
1049 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1050   DanglingDebugInfoMap.clear();
1051 }
1052 
1053 // Update DAG root to include dependencies on Pending chains.
1054 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1055   SDValue Root = DAG.getRoot();
1056 
1057   if (Pending.empty())
1058     return Root;
1059 
1060   // Add current root to PendingChains, unless we already indirectly
1061   // depend on it.
1062   if (Root.getOpcode() != ISD::EntryToken) {
1063     unsigned i = 0, e = Pending.size();
1064     for (; i != e; ++i) {
1065       assert(Pending[i].getNode()->getNumOperands() > 1);
1066       if (Pending[i].getNode()->getOperand(0) == Root)
1067         break;  // Don't add the root if we already indirectly depend on it.
1068     }
1069 
1070     if (i == e)
1071       Pending.push_back(Root);
1072   }
1073 
1074   if (Pending.size() == 1)
1075     Root = Pending[0];
1076   else
1077     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1078 
1079   DAG.setRoot(Root);
1080   Pending.clear();
1081   return Root;
1082 }
1083 
1084 SDValue SelectionDAGBuilder::getMemoryRoot() {
1085   return updateRoot(PendingLoads);
1086 }
1087 
1088 SDValue SelectionDAGBuilder::getRoot() {
1089   // Chain up all pending constrained intrinsics together with all
1090   // pending loads, by simply appending them to PendingLoads and
1091   // then calling getMemoryRoot().
1092   PendingLoads.reserve(PendingLoads.size() +
1093                        PendingConstrainedFP.size() +
1094                        PendingConstrainedFPStrict.size());
1095   PendingLoads.append(PendingConstrainedFP.begin(),
1096                       PendingConstrainedFP.end());
1097   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1098                       PendingConstrainedFPStrict.end());
1099   PendingConstrainedFP.clear();
1100   PendingConstrainedFPStrict.clear();
1101   return getMemoryRoot();
1102 }
1103 
1104 SDValue SelectionDAGBuilder::getControlRoot() {
1105   // We need to emit pending fpexcept.strict constrained intrinsics,
1106   // so append them to the PendingExports list.
1107   PendingExports.append(PendingConstrainedFPStrict.begin(),
1108                         PendingConstrainedFPStrict.end());
1109   PendingConstrainedFPStrict.clear();
1110   return updateRoot(PendingExports);
1111 }
1112 
1113 void SelectionDAGBuilder::visit(const Instruction &I) {
1114   // Set up outgoing PHI node register values before emitting the terminator.
1115   if (I.isTerminator()) {
1116     HandlePHINodesInSuccessorBlocks(I.getParent());
1117   }
1118 
1119   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1120   if (!isa<DbgInfoIntrinsic>(I))
1121     ++SDNodeOrder;
1122 
1123   CurInst = &I;
1124 
1125   visit(I.getOpcode(), I);
1126 
1127   if (!I.isTerminator() && !HasTailCall &&
1128       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1129     CopyToExportRegsIfNeeded(&I);
1130 
1131   CurInst = nullptr;
1132 }
1133 
1134 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1135   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1136 }
1137 
1138 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1139   // Note: this doesn't use InstVisitor, because it has to work with
1140   // ConstantExpr's in addition to instructions.
1141   switch (Opcode) {
1142   default: llvm_unreachable("Unknown instruction type encountered!");
1143     // Build the switch statement using the Instruction.def file.
1144 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1145     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1146 #include "llvm/IR/Instruction.def"
1147   }
1148 }
1149 
1150 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1151                                                DebugLoc DL, unsigned Order) {
1152   // We treat variadic dbg_values differently at this stage.
1153   if (DI->hasArgList()) {
1154     // For variadic dbg_values we will now insert an undef.
1155     // FIXME: We can potentially recover these!
1156     SmallVector<SDDbgOperand, 2> Locs;
1157     for (const Value *V : DI->getValues()) {
1158       auto Undef = UndefValue::get(V->getType());
1159       Locs.push_back(SDDbgOperand::fromConst(Undef));
1160     }
1161     SDDbgValue *SDV = DAG.getDbgValueList(
1162         DI->getVariable(), DI->getExpression(), Locs, {},
1163         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1164     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1165   } else {
1166     // TODO: Dangling debug info will eventually either be resolved or produce
1167     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1168     // between the original dbg.value location and its resolved DBG_VALUE,
1169     // which we should ideally fill with an extra Undef DBG_VALUE.
1170     assert(DI->getNumVariableLocationOps() == 1 &&
1171            "DbgValueInst without an ArgList should have a single location "
1172            "operand.");
1173     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1174   }
1175 }
1176 
1177 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1178                                                 const DIExpression *Expr) {
1179   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1180     const DbgValueInst *DI = DDI.getDI();
1181     DIVariable *DanglingVariable = DI->getVariable();
1182     DIExpression *DanglingExpr = DI->getExpression();
1183     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1184       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1185       return true;
1186     }
1187     return false;
1188   };
1189 
1190   for (auto &DDIMI : DanglingDebugInfoMap) {
1191     DanglingDebugInfoVector &DDIV = DDIMI.second;
1192 
1193     // If debug info is to be dropped, run it through final checks to see
1194     // whether it can be salvaged.
1195     for (auto &DDI : DDIV)
1196       if (isMatchingDbgValue(DDI))
1197         salvageUnresolvedDbgValue(DDI);
1198 
1199     erase_if(DDIV, isMatchingDbgValue);
1200   }
1201 }
1202 
1203 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1204 // generate the debug data structures now that we've seen its definition.
1205 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1206                                                    SDValue Val) {
1207   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1208   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1209     return;
1210 
1211   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1212   for (auto &DDI : DDIV) {
1213     const DbgValueInst *DI = DDI.getDI();
1214     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1215     assert(DI && "Ill-formed DanglingDebugInfo");
1216     DebugLoc dl = DDI.getdl();
1217     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1218     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1219     DILocalVariable *Variable = DI->getVariable();
1220     DIExpression *Expr = DI->getExpression();
1221     assert(Variable->isValidLocationForIntrinsic(dl) &&
1222            "Expected inlined-at fields to agree");
1223     SDDbgValue *SDV;
1224     if (Val.getNode()) {
1225       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1226       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1227       // we couldn't resolve it directly when examining the DbgValue intrinsic
1228       // in the first place we should not be more successful here). Unless we
1229       // have some test case that prove this to be correct we should avoid
1230       // calling EmitFuncArgumentDbgValue here.
1231       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1232         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1233                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1234         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1235         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1236         // inserted after the definition of Val when emitting the instructions
1237         // after ISel. An alternative could be to teach
1238         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1239         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1240                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1241                    << ValSDNodeOrder << "\n");
1242         SDV = getDbgValue(Val, Variable, Expr, dl,
1243                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1244         DAG.AddDbgValue(SDV, false);
1245       } else
1246         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1247                           << "in EmitFuncArgumentDbgValue\n");
1248     } else {
1249       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1250       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1251       auto SDV =
1252           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1253       DAG.AddDbgValue(SDV, false);
1254     }
1255   }
1256   DDIV.clear();
1257 }
1258 
1259 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1260   // TODO: For the variadic implementation, instead of only checking the fail
1261   // state of `handleDebugValue`, we need know specifically which values were
1262   // invalid, so that we attempt to salvage only those values when processing
1263   // a DIArgList.
1264   assert(!DDI.getDI()->hasArgList() &&
1265          "Not implemented for variadic dbg_values");
1266   Value *V = DDI.getDI()->getValue(0);
1267   DILocalVariable *Var = DDI.getDI()->getVariable();
1268   DIExpression *Expr = DDI.getDI()->getExpression();
1269   DebugLoc DL = DDI.getdl();
1270   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1271   unsigned SDOrder = DDI.getSDNodeOrder();
1272   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1273   // that DW_OP_stack_value is desired.
1274   assert(isa<DbgValueInst>(DDI.getDI()));
1275   bool StackValue = true;
1276 
1277   // Can this Value can be encoded without any further work?
1278   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
1279     return;
1280 
1281   // Attempt to salvage back through as many instructions as possible. Bail if
1282   // a non-instruction is seen, such as a constant expression or global
1283   // variable. FIXME: Further work could recover those too.
1284   while (isa<Instruction>(V)) {
1285     Instruction &VAsInst = *cast<Instruction>(V);
1286     // Temporary "0", awaiting real implementation.
1287     SmallVector<uint64_t, 16> Ops;
1288     SmallVector<Value *, 4> AdditionalValues;
1289     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1290                              AdditionalValues);
1291     // If we cannot salvage any further, and haven't yet found a suitable debug
1292     // expression, bail out.
1293     if (!V)
1294       break;
1295 
1296     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1297     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1298     // here for variadic dbg_values, remove that condition.
1299     if (!AdditionalValues.empty())
1300       break;
1301 
1302     // New value and expr now represent this debuginfo.
1303     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1304 
1305     // Some kind of simplification occurred: check whether the operand of the
1306     // salvaged debug expression can be encoded in this DAG.
1307     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1308                          /*IsVariadic=*/false)) {
1309       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1310                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1311       return;
1312     }
1313   }
1314 
1315   // This was the final opportunity to salvage this debug information, and it
1316   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1317   // any earlier variable location.
1318   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1319   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1320   DAG.AddDbgValue(SDV, false);
1321 
1322   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1323                     << "\n");
1324   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1325                     << "\n");
1326 }
1327 
1328 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1329                                            DILocalVariable *Var,
1330                                            DIExpression *Expr, DebugLoc dl,
1331                                            DebugLoc InstDL, unsigned Order,
1332                                            bool IsVariadic) {
1333   if (Values.empty())
1334     return true;
1335   SmallVector<SDDbgOperand> LocationOps;
1336   SmallVector<SDNode *> Dependencies;
1337   for (const Value *V : Values) {
1338     // Constant value.
1339     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1340         isa<ConstantPointerNull>(V)) {
1341       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1342       continue;
1343     }
1344 
1345     // If the Value is a frame index, we can create a FrameIndex debug value
1346     // without relying on the DAG at all.
1347     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1348       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1349       if (SI != FuncInfo.StaticAllocaMap.end()) {
1350         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1351         continue;
1352       }
1353     }
1354 
1355     // Do not use getValue() in here; we don't want to generate code at
1356     // this point if it hasn't been done yet.
1357     SDValue N = NodeMap[V];
1358     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1359       N = UnusedArgNodeMap[V];
1360     if (N.getNode()) {
1361       // Only emit func arg dbg value for non-variadic dbg.values for now.
1362       if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1363         return true;
1364       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1365         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1366         // describe stack slot locations.
1367         //
1368         // Consider "int x = 0; int *px = &x;". There are two kinds of
1369         // interesting debug values here after optimization:
1370         //
1371         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1372         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1373         //
1374         // Both describe the direct values of their associated variables.
1375         Dependencies.push_back(N.getNode());
1376         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1377         continue;
1378       }
1379       LocationOps.emplace_back(
1380           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1381       continue;
1382     }
1383 
1384     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1385     // Special rules apply for the first dbg.values of parameter variables in a
1386     // function. Identify them by the fact they reference Argument Values, that
1387     // they're parameters, and they are parameters of the current function. We
1388     // need to let them dangle until they get an SDNode.
1389     bool IsParamOfFunc =
1390         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1391     if (IsParamOfFunc)
1392       return false;
1393 
1394     // The value is not used in this block yet (or it would have an SDNode).
1395     // We still want the value to appear for the user if possible -- if it has
1396     // an associated VReg, we can refer to that instead.
1397     auto VMI = FuncInfo.ValueMap.find(V);
1398     if (VMI != FuncInfo.ValueMap.end()) {
1399       unsigned Reg = VMI->second;
1400       // If this is a PHI node, it may be split up into several MI PHI nodes
1401       // (in FunctionLoweringInfo::set).
1402       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1403                        V->getType(), None);
1404       if (RFV.occupiesMultipleRegs()) {
1405         // FIXME: We could potentially support variadic dbg_values here.
1406         if (IsVariadic)
1407           return false;
1408         unsigned Offset = 0;
1409         unsigned BitsToDescribe = 0;
1410         if (auto VarSize = Var->getSizeInBits())
1411           BitsToDescribe = *VarSize;
1412         if (auto Fragment = Expr->getFragmentInfo())
1413           BitsToDescribe = Fragment->SizeInBits;
1414         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1415           // Bail out if all bits are described already.
1416           if (Offset >= BitsToDescribe)
1417             break;
1418           // TODO: handle scalable vectors.
1419           unsigned RegisterSize = RegAndSize.second;
1420           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1421                                       ? BitsToDescribe - Offset
1422                                       : RegisterSize;
1423           auto FragmentExpr = DIExpression::createFragmentExpression(
1424               Expr, Offset, FragmentSize);
1425           if (!FragmentExpr)
1426             continue;
1427           SDDbgValue *SDV = DAG.getVRegDbgValue(
1428               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1429           DAG.AddDbgValue(SDV, false);
1430           Offset += RegisterSize;
1431         }
1432         return true;
1433       }
1434       // We can use simple vreg locations for variadic dbg_values as well.
1435       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1436       continue;
1437     }
1438     // We failed to create a SDDbgOperand for V.
1439     return false;
1440   }
1441 
1442   // We have created a SDDbgOperand for each Value in Values.
1443   // Should use Order instead of SDNodeOrder?
1444   assert(!LocationOps.empty());
1445   SDDbgValue *SDV =
1446       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1447                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1448   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1449   return true;
1450 }
1451 
1452 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1453   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1454   for (auto &Pair : DanglingDebugInfoMap)
1455     for (auto &DDI : Pair.second)
1456       salvageUnresolvedDbgValue(DDI);
1457   clearDanglingDebugInfo();
1458 }
1459 
1460 /// getCopyFromRegs - If there was virtual register allocated for the value V
1461 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1462 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1463   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1464   SDValue Result;
1465 
1466   if (It != FuncInfo.ValueMap.end()) {
1467     Register InReg = It->second;
1468 
1469     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1470                      DAG.getDataLayout(), InReg, Ty,
1471                      None); // This is not an ABI copy.
1472     SDValue Chain = DAG.getEntryNode();
1473     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1474                                  V);
1475     resolveDanglingDebugInfo(V, Result);
1476   }
1477 
1478   return Result;
1479 }
1480 
1481 /// getValue - Return an SDValue for the given Value.
1482 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1483   // If we already have an SDValue for this value, use it. It's important
1484   // to do this first, so that we don't create a CopyFromReg if we already
1485   // have a regular SDValue.
1486   SDValue &N = NodeMap[V];
1487   if (N.getNode()) return N;
1488 
1489   // If there's a virtual register allocated and initialized for this
1490   // value, use it.
1491   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1492     return copyFromReg;
1493 
1494   // Otherwise create a new SDValue and remember it.
1495   SDValue Val = getValueImpl(V);
1496   NodeMap[V] = Val;
1497   resolveDanglingDebugInfo(V, Val);
1498   return Val;
1499 }
1500 
1501 /// getNonRegisterValue - Return an SDValue for the given Value, but
1502 /// don't look in FuncInfo.ValueMap for a virtual register.
1503 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1504   // If we already have an SDValue for this value, use it.
1505   SDValue &N = NodeMap[V];
1506   if (N.getNode()) {
1507     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1508       // Remove the debug location from the node as the node is about to be used
1509       // in a location which may differ from the original debug location.  This
1510       // is relevant to Constant and ConstantFP nodes because they can appear
1511       // as constant expressions inside PHI nodes.
1512       N->setDebugLoc(DebugLoc());
1513     }
1514     return N;
1515   }
1516 
1517   // Otherwise create a new SDValue and remember it.
1518   SDValue Val = getValueImpl(V);
1519   NodeMap[V] = Val;
1520   resolveDanglingDebugInfo(V, Val);
1521   return Val;
1522 }
1523 
1524 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1525 /// Create an SDValue for the given value.
1526 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1527   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1528 
1529   if (const Constant *C = dyn_cast<Constant>(V)) {
1530     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1531 
1532     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1533       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1534 
1535     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1536       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1537 
1538     if (isa<ConstantPointerNull>(C)) {
1539       unsigned AS = V->getType()->getPointerAddressSpace();
1540       return DAG.getConstant(0, getCurSDLoc(),
1541                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1542     }
1543 
1544     if (match(C, m_VScale(DAG.getDataLayout())))
1545       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1546 
1547     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1548       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1549 
1550     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1551       return DAG.getUNDEF(VT);
1552 
1553     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1554       visit(CE->getOpcode(), *CE);
1555       SDValue N1 = NodeMap[V];
1556       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1557       return N1;
1558     }
1559 
1560     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1561       SmallVector<SDValue, 4> Constants;
1562       for (const Use &U : C->operands()) {
1563         SDNode *Val = getValue(U).getNode();
1564         // If the operand is an empty aggregate, there are no values.
1565         if (!Val) continue;
1566         // Add each leaf value from the operand to the Constants list
1567         // to form a flattened list of all the values.
1568         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1569           Constants.push_back(SDValue(Val, i));
1570       }
1571 
1572       return DAG.getMergeValues(Constants, getCurSDLoc());
1573     }
1574 
1575     if (const ConstantDataSequential *CDS =
1576           dyn_cast<ConstantDataSequential>(C)) {
1577       SmallVector<SDValue, 4> Ops;
1578       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1579         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1580         // Add each leaf value from the operand to the Constants list
1581         // to form a flattened list of all the values.
1582         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1583           Ops.push_back(SDValue(Val, i));
1584       }
1585 
1586       if (isa<ArrayType>(CDS->getType()))
1587         return DAG.getMergeValues(Ops, getCurSDLoc());
1588       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1589     }
1590 
1591     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1592       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1593              "Unknown struct or array constant!");
1594 
1595       SmallVector<EVT, 4> ValueVTs;
1596       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1597       unsigned NumElts = ValueVTs.size();
1598       if (NumElts == 0)
1599         return SDValue(); // empty struct
1600       SmallVector<SDValue, 4> Constants(NumElts);
1601       for (unsigned i = 0; i != NumElts; ++i) {
1602         EVT EltVT = ValueVTs[i];
1603         if (isa<UndefValue>(C))
1604           Constants[i] = DAG.getUNDEF(EltVT);
1605         else if (EltVT.isFloatingPoint())
1606           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1607         else
1608           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1609       }
1610 
1611       return DAG.getMergeValues(Constants, getCurSDLoc());
1612     }
1613 
1614     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1615       return DAG.getBlockAddress(BA, VT);
1616 
1617     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1618       return getValue(Equiv->getGlobalValue());
1619 
1620     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1621       return getValue(NC->getGlobalValue());
1622 
1623     VectorType *VecTy = cast<VectorType>(V->getType());
1624 
1625     // Now that we know the number and type of the elements, get that number of
1626     // elements into the Ops array based on what kind of constant it is.
1627     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1628       SmallVector<SDValue, 16> Ops;
1629       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1630       for (unsigned i = 0; i != NumElements; ++i)
1631         Ops.push_back(getValue(CV->getOperand(i)));
1632 
1633       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1634     }
1635 
1636     if (isa<ConstantAggregateZero>(C)) {
1637       EVT EltVT =
1638           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1639 
1640       SDValue Op;
1641       if (EltVT.isFloatingPoint())
1642         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1643       else
1644         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1645 
1646       if (isa<ScalableVectorType>(VecTy))
1647         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1648 
1649       SmallVector<SDValue, 16> Ops;
1650       Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1651       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1652     }
1653 
1654     llvm_unreachable("Unknown vector constant");
1655   }
1656 
1657   // If this is a static alloca, generate it as the frameindex instead of
1658   // computation.
1659   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1660     DenseMap<const AllocaInst*, int>::iterator SI =
1661       FuncInfo.StaticAllocaMap.find(AI);
1662     if (SI != FuncInfo.StaticAllocaMap.end())
1663       return DAG.getFrameIndex(SI->second,
1664                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1665   }
1666 
1667   // If this is an instruction which fast-isel has deferred, select it now.
1668   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1669     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1670 
1671     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1672                      Inst->getType(), None);
1673     SDValue Chain = DAG.getEntryNode();
1674     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1675   }
1676 
1677   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1678     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1679 
1680   if (const auto *BB = dyn_cast<BasicBlock>(V))
1681     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1682 
1683   llvm_unreachable("Can't get register for value!");
1684 }
1685 
1686 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1687   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1688   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1689   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1690   bool IsSEH = isAsynchronousEHPersonality(Pers);
1691   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1692   if (!IsSEH)
1693     CatchPadMBB->setIsEHScopeEntry();
1694   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1695   if (IsMSVCCXX || IsCoreCLR)
1696     CatchPadMBB->setIsEHFuncletEntry();
1697 }
1698 
1699 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1700   // Update machine-CFG edge.
1701   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1702   FuncInfo.MBB->addSuccessor(TargetMBB);
1703   TargetMBB->setIsEHCatchretTarget(true);
1704   DAG.getMachineFunction().setHasEHCatchret(true);
1705 
1706   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1707   bool IsSEH = isAsynchronousEHPersonality(Pers);
1708   if (IsSEH) {
1709     // If this is not a fall-through branch or optimizations are switched off,
1710     // emit the branch.
1711     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1712         TM.getOptLevel() == CodeGenOpt::None)
1713       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1714                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1715     return;
1716   }
1717 
1718   // Figure out the funclet membership for the catchret's successor.
1719   // This will be used by the FuncletLayout pass to determine how to order the
1720   // BB's.
1721   // A 'catchret' returns to the outer scope's color.
1722   Value *ParentPad = I.getCatchSwitchParentPad();
1723   const BasicBlock *SuccessorColor;
1724   if (isa<ConstantTokenNone>(ParentPad))
1725     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1726   else
1727     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1728   assert(SuccessorColor && "No parent funclet for catchret!");
1729   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1730   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1731 
1732   // Create the terminator node.
1733   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1734                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1735                             DAG.getBasicBlock(SuccessorColorMBB));
1736   DAG.setRoot(Ret);
1737 }
1738 
1739 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1740   // Don't emit any special code for the cleanuppad instruction. It just marks
1741   // the start of an EH scope/funclet.
1742   FuncInfo.MBB->setIsEHScopeEntry();
1743   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1744   if (Pers != EHPersonality::Wasm_CXX) {
1745     FuncInfo.MBB->setIsEHFuncletEntry();
1746     FuncInfo.MBB->setIsCleanupFuncletEntry();
1747   }
1748 }
1749 
1750 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1751 // not match, it is OK to add only the first unwind destination catchpad to the
1752 // successors, because there will be at least one invoke instruction within the
1753 // catch scope that points to the next unwind destination, if one exists, so
1754 // CFGSort cannot mess up with BB sorting order.
1755 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1756 // call within them, and catchpads only consisting of 'catch (...)' have a
1757 // '__cxa_end_catch' call within them, both of which generate invokes in case
1758 // the next unwind destination exists, i.e., the next unwind destination is not
1759 // the caller.)
1760 //
1761 // Having at most one EH pad successor is also simpler and helps later
1762 // transformations.
1763 //
1764 // For example,
1765 // current:
1766 //   invoke void @foo to ... unwind label %catch.dispatch
1767 // catch.dispatch:
1768 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1769 // catch.start:
1770 //   ...
1771 //   ... in this BB or some other child BB dominated by this BB there will be an
1772 //   invoke that points to 'next' BB as an unwind destination
1773 //
1774 // next: ; We don't need to add this to 'current' BB's successor
1775 //   ...
1776 static void findWasmUnwindDestinations(
1777     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1778     BranchProbability Prob,
1779     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1780         &UnwindDests) {
1781   while (EHPadBB) {
1782     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1783     if (isa<CleanupPadInst>(Pad)) {
1784       // Stop on cleanup pads.
1785       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1786       UnwindDests.back().first->setIsEHScopeEntry();
1787       break;
1788     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1789       // Add the catchpad handlers to the possible destinations. We don't
1790       // continue to the unwind destination of the catchswitch for wasm.
1791       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1792         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1793         UnwindDests.back().first->setIsEHScopeEntry();
1794       }
1795       break;
1796     } else {
1797       continue;
1798     }
1799   }
1800 }
1801 
1802 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1803 /// many places it could ultimately go. In the IR, we have a single unwind
1804 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1805 /// This function skips over imaginary basic blocks that hold catchswitch
1806 /// instructions, and finds all the "real" machine
1807 /// basic block destinations. As those destinations may not be successors of
1808 /// EHPadBB, here we also calculate the edge probability to those destinations.
1809 /// The passed-in Prob is the edge probability to EHPadBB.
1810 static void findUnwindDestinations(
1811     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1812     BranchProbability Prob,
1813     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1814         &UnwindDests) {
1815   EHPersonality Personality =
1816     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1817   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1818   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1819   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1820   bool IsSEH = isAsynchronousEHPersonality(Personality);
1821 
1822   if (IsWasmCXX) {
1823     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1824     assert(UnwindDests.size() <= 1 &&
1825            "There should be at most one unwind destination for wasm");
1826     return;
1827   }
1828 
1829   while (EHPadBB) {
1830     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1831     BasicBlock *NewEHPadBB = nullptr;
1832     if (isa<LandingPadInst>(Pad)) {
1833       // Stop on landingpads. They are not funclets.
1834       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1835       break;
1836     } else if (isa<CleanupPadInst>(Pad)) {
1837       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1838       // personalities.
1839       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1840       UnwindDests.back().first->setIsEHScopeEntry();
1841       UnwindDests.back().first->setIsEHFuncletEntry();
1842       break;
1843     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1844       // Add the catchpad handlers to the possible destinations.
1845       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1846         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1847         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1848         if (IsMSVCCXX || IsCoreCLR)
1849           UnwindDests.back().first->setIsEHFuncletEntry();
1850         if (!IsSEH)
1851           UnwindDests.back().first->setIsEHScopeEntry();
1852       }
1853       NewEHPadBB = CatchSwitch->getUnwindDest();
1854     } else {
1855       continue;
1856     }
1857 
1858     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1859     if (BPI && NewEHPadBB)
1860       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1861     EHPadBB = NewEHPadBB;
1862   }
1863 }
1864 
1865 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1866   // Update successor info.
1867   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1868   auto UnwindDest = I.getUnwindDest();
1869   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1870   BranchProbability UnwindDestProb =
1871       (BPI && UnwindDest)
1872           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1873           : BranchProbability::getZero();
1874   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1875   for (auto &UnwindDest : UnwindDests) {
1876     UnwindDest.first->setIsEHPad();
1877     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1878   }
1879   FuncInfo.MBB->normalizeSuccProbs();
1880 
1881   // Create the terminator node.
1882   SDValue Ret =
1883       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1884   DAG.setRoot(Ret);
1885 }
1886 
1887 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1888   report_fatal_error("visitCatchSwitch not yet implemented!");
1889 }
1890 
1891 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1893   auto &DL = DAG.getDataLayout();
1894   SDValue Chain = getControlRoot();
1895   SmallVector<ISD::OutputArg, 8> Outs;
1896   SmallVector<SDValue, 8> OutVals;
1897 
1898   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1899   // lower
1900   //
1901   //   %val = call <ty> @llvm.experimental.deoptimize()
1902   //   ret <ty> %val
1903   //
1904   // differently.
1905   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1906     LowerDeoptimizingReturn();
1907     return;
1908   }
1909 
1910   if (!FuncInfo.CanLowerReturn) {
1911     unsigned DemoteReg = FuncInfo.DemoteRegister;
1912     const Function *F = I.getParent()->getParent();
1913 
1914     // Emit a store of the return value through the virtual register.
1915     // Leave Outs empty so that LowerReturn won't try to load return
1916     // registers the usual way.
1917     SmallVector<EVT, 1> PtrValueVTs;
1918     ComputeValueVTs(TLI, DL,
1919                     F->getReturnType()->getPointerTo(
1920                         DAG.getDataLayout().getAllocaAddrSpace()),
1921                     PtrValueVTs);
1922 
1923     SDValue RetPtr =
1924         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1925     SDValue RetOp = getValue(I.getOperand(0));
1926 
1927     SmallVector<EVT, 4> ValueVTs, MemVTs;
1928     SmallVector<uint64_t, 4> Offsets;
1929     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1930                     &Offsets);
1931     unsigned NumValues = ValueVTs.size();
1932 
1933     SmallVector<SDValue, 4> Chains(NumValues);
1934     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1935     for (unsigned i = 0; i != NumValues; ++i) {
1936       // An aggregate return value cannot wrap around the address space, so
1937       // offsets to its parts don't wrap either.
1938       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1939                                            TypeSize::Fixed(Offsets[i]));
1940 
1941       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1942       if (MemVTs[i] != ValueVTs[i])
1943         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1944       Chains[i] = DAG.getStore(
1945           Chain, getCurSDLoc(), Val,
1946           // FIXME: better loc info would be nice.
1947           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1948           commonAlignment(BaseAlign, Offsets[i]));
1949     }
1950 
1951     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1952                         MVT::Other, Chains);
1953   } else if (I.getNumOperands() != 0) {
1954     SmallVector<EVT, 4> ValueVTs;
1955     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1956     unsigned NumValues = ValueVTs.size();
1957     if (NumValues) {
1958       SDValue RetOp = getValue(I.getOperand(0));
1959 
1960       const Function *F = I.getParent()->getParent();
1961 
1962       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1963           I.getOperand(0)->getType(), F->getCallingConv(),
1964           /*IsVarArg*/ false, DL);
1965 
1966       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1967       if (F->getAttributes().hasRetAttr(Attribute::SExt))
1968         ExtendKind = ISD::SIGN_EXTEND;
1969       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
1970         ExtendKind = ISD::ZERO_EXTEND;
1971 
1972       LLVMContext &Context = F->getContext();
1973       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
1974 
1975       for (unsigned j = 0; j != NumValues; ++j) {
1976         EVT VT = ValueVTs[j];
1977 
1978         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1979           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1980 
1981         CallingConv::ID CC = F->getCallingConv();
1982 
1983         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1984         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1985         SmallVector<SDValue, 4> Parts(NumParts);
1986         getCopyToParts(DAG, getCurSDLoc(),
1987                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1988                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1989 
1990         // 'inreg' on function refers to return value
1991         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1992         if (RetInReg)
1993           Flags.setInReg();
1994 
1995         if (I.getOperand(0)->getType()->isPointerTy()) {
1996           Flags.setPointer();
1997           Flags.setPointerAddrSpace(
1998               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1999         }
2000 
2001         if (NeedsRegBlock) {
2002           Flags.setInConsecutiveRegs();
2003           if (j == NumValues - 1)
2004             Flags.setInConsecutiveRegsLast();
2005         }
2006 
2007         // Propagate extension type if any
2008         if (ExtendKind == ISD::SIGN_EXTEND)
2009           Flags.setSExt();
2010         else if (ExtendKind == ISD::ZERO_EXTEND)
2011           Flags.setZExt();
2012 
2013         for (unsigned i = 0; i < NumParts; ++i) {
2014           Outs.push_back(ISD::OutputArg(Flags,
2015                                         Parts[i].getValueType().getSimpleVT(),
2016                                         VT, /*isfixed=*/true, 0, 0));
2017           OutVals.push_back(Parts[i]);
2018         }
2019       }
2020     }
2021   }
2022 
2023   // Push in swifterror virtual register as the last element of Outs. This makes
2024   // sure swifterror virtual register will be returned in the swifterror
2025   // physical register.
2026   const Function *F = I.getParent()->getParent();
2027   if (TLI.supportSwiftError() &&
2028       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2029     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2030     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2031     Flags.setSwiftError();
2032     Outs.push_back(ISD::OutputArg(
2033         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2034         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2035     // Create SDNode for the swifterror virtual register.
2036     OutVals.push_back(
2037         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2038                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2039                         EVT(TLI.getPointerTy(DL))));
2040   }
2041 
2042   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2043   CallingConv::ID CallConv =
2044     DAG.getMachineFunction().getFunction().getCallingConv();
2045   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2046       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2047 
2048   // Verify that the target's LowerReturn behaved as expected.
2049   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2050          "LowerReturn didn't return a valid chain!");
2051 
2052   // Update the DAG with the new chain value resulting from return lowering.
2053   DAG.setRoot(Chain);
2054 }
2055 
2056 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2057 /// created for it, emit nodes to copy the value into the virtual
2058 /// registers.
2059 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2060   // Skip empty types
2061   if (V->getType()->isEmptyTy())
2062     return;
2063 
2064   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2065   if (VMI != FuncInfo.ValueMap.end()) {
2066     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2067     CopyValueToVirtualRegister(V, VMI->second);
2068   }
2069 }
2070 
2071 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2072 /// the current basic block, add it to ValueMap now so that we'll get a
2073 /// CopyTo/FromReg.
2074 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2075   // No need to export constants.
2076   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2077 
2078   // Already exported?
2079   if (FuncInfo.isExportedInst(V)) return;
2080 
2081   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2082   CopyValueToVirtualRegister(V, Reg);
2083 }
2084 
2085 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2086                                                      const BasicBlock *FromBB) {
2087   // The operands of the setcc have to be in this block.  We don't know
2088   // how to export them from some other block.
2089   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2090     // Can export from current BB.
2091     if (VI->getParent() == FromBB)
2092       return true;
2093 
2094     // Is already exported, noop.
2095     return FuncInfo.isExportedInst(V);
2096   }
2097 
2098   // If this is an argument, we can export it if the BB is the entry block or
2099   // if it is already exported.
2100   if (isa<Argument>(V)) {
2101     if (FromBB->isEntryBlock())
2102       return true;
2103 
2104     // Otherwise, can only export this if it is already exported.
2105     return FuncInfo.isExportedInst(V);
2106   }
2107 
2108   // Otherwise, constants can always be exported.
2109   return true;
2110 }
2111 
2112 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2113 BranchProbability
2114 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2115                                         const MachineBasicBlock *Dst) const {
2116   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2117   const BasicBlock *SrcBB = Src->getBasicBlock();
2118   const BasicBlock *DstBB = Dst->getBasicBlock();
2119   if (!BPI) {
2120     // If BPI is not available, set the default probability as 1 / N, where N is
2121     // the number of successors.
2122     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2123     return BranchProbability(1, SuccSize);
2124   }
2125   return BPI->getEdgeProbability(SrcBB, DstBB);
2126 }
2127 
2128 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2129                                                MachineBasicBlock *Dst,
2130                                                BranchProbability Prob) {
2131   if (!FuncInfo.BPI)
2132     Src->addSuccessorWithoutProb(Dst);
2133   else {
2134     if (Prob.isUnknown())
2135       Prob = getEdgeProbability(Src, Dst);
2136     Src->addSuccessor(Dst, Prob);
2137   }
2138 }
2139 
2140 static bool InBlock(const Value *V, const BasicBlock *BB) {
2141   if (const Instruction *I = dyn_cast<Instruction>(V))
2142     return I->getParent() == BB;
2143   return true;
2144 }
2145 
2146 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2147 /// This function emits a branch and is used at the leaves of an OR or an
2148 /// AND operator tree.
2149 void
2150 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2151                                                   MachineBasicBlock *TBB,
2152                                                   MachineBasicBlock *FBB,
2153                                                   MachineBasicBlock *CurBB,
2154                                                   MachineBasicBlock *SwitchBB,
2155                                                   BranchProbability TProb,
2156                                                   BranchProbability FProb,
2157                                                   bool InvertCond) {
2158   const BasicBlock *BB = CurBB->getBasicBlock();
2159 
2160   // If the leaf of the tree is a comparison, merge the condition into
2161   // the caseblock.
2162   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2163     // The operands of the cmp have to be in this block.  We don't know
2164     // how to export them from some other block.  If this is the first block
2165     // of the sequence, no exporting is needed.
2166     if (CurBB == SwitchBB ||
2167         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2168          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2169       ISD::CondCode Condition;
2170       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2171         ICmpInst::Predicate Pred =
2172             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2173         Condition = getICmpCondCode(Pred);
2174       } else {
2175         const FCmpInst *FC = cast<FCmpInst>(Cond);
2176         FCmpInst::Predicate Pred =
2177             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2178         Condition = getFCmpCondCode(Pred);
2179         if (TM.Options.NoNaNsFPMath)
2180           Condition = getFCmpCodeWithoutNaN(Condition);
2181       }
2182 
2183       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2184                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2185       SL->SwitchCases.push_back(CB);
2186       return;
2187     }
2188   }
2189 
2190   // Create a CaseBlock record representing this branch.
2191   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2192   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2193                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2194   SL->SwitchCases.push_back(CB);
2195 }
2196 
2197 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2198                                                MachineBasicBlock *TBB,
2199                                                MachineBasicBlock *FBB,
2200                                                MachineBasicBlock *CurBB,
2201                                                MachineBasicBlock *SwitchBB,
2202                                                Instruction::BinaryOps Opc,
2203                                                BranchProbability TProb,
2204                                                BranchProbability FProb,
2205                                                bool InvertCond) {
2206   // Skip over not part of the tree and remember to invert op and operands at
2207   // next level.
2208   Value *NotCond;
2209   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2210       InBlock(NotCond, CurBB->getBasicBlock())) {
2211     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2212                          !InvertCond);
2213     return;
2214   }
2215 
2216   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2217   const Value *BOpOp0, *BOpOp1;
2218   // Compute the effective opcode for Cond, taking into account whether it needs
2219   // to be inverted, e.g.
2220   //   and (not (or A, B)), C
2221   // gets lowered as
2222   //   and (and (not A, not B), C)
2223   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2224   if (BOp) {
2225     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2226                ? Instruction::And
2227                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2228                       ? Instruction::Or
2229                       : (Instruction::BinaryOps)0);
2230     if (InvertCond) {
2231       if (BOpc == Instruction::And)
2232         BOpc = Instruction::Or;
2233       else if (BOpc == Instruction::Or)
2234         BOpc = Instruction::And;
2235     }
2236   }
2237 
2238   // If this node is not part of the or/and tree, emit it as a branch.
2239   // Note that all nodes in the tree should have same opcode.
2240   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2241   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2242       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2243       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2244     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2245                                  TProb, FProb, InvertCond);
2246     return;
2247   }
2248 
2249   //  Create TmpBB after CurBB.
2250   MachineFunction::iterator BBI(CurBB);
2251   MachineFunction &MF = DAG.getMachineFunction();
2252   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2253   CurBB->getParent()->insert(++BBI, TmpBB);
2254 
2255   if (Opc == Instruction::Or) {
2256     // Codegen X | Y as:
2257     // BB1:
2258     //   jmp_if_X TBB
2259     //   jmp TmpBB
2260     // TmpBB:
2261     //   jmp_if_Y TBB
2262     //   jmp FBB
2263     //
2264 
2265     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2266     // The requirement is that
2267     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2268     //     = TrueProb for original BB.
2269     // Assuming the original probabilities are A and B, one choice is to set
2270     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2271     // A/(1+B) and 2B/(1+B). This choice assumes that
2272     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2273     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2274     // TmpBB, but the math is more complicated.
2275 
2276     auto NewTrueProb = TProb / 2;
2277     auto NewFalseProb = TProb / 2 + FProb;
2278     // Emit the LHS condition.
2279     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2280                          NewFalseProb, InvertCond);
2281 
2282     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2283     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2284     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2285     // Emit the RHS condition into TmpBB.
2286     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2287                          Probs[1], InvertCond);
2288   } else {
2289     assert(Opc == Instruction::And && "Unknown merge op!");
2290     // Codegen X & Y as:
2291     // BB1:
2292     //   jmp_if_X TmpBB
2293     //   jmp FBB
2294     // TmpBB:
2295     //   jmp_if_Y TBB
2296     //   jmp FBB
2297     //
2298     //  This requires creation of TmpBB after CurBB.
2299 
2300     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2301     // The requirement is that
2302     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2303     //     = FalseProb for original BB.
2304     // Assuming the original probabilities are A and B, one choice is to set
2305     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2306     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2307     // TrueProb for BB1 * FalseProb for TmpBB.
2308 
2309     auto NewTrueProb = TProb + FProb / 2;
2310     auto NewFalseProb = FProb / 2;
2311     // Emit the LHS condition.
2312     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2313                          NewFalseProb, InvertCond);
2314 
2315     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2316     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2317     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2318     // Emit the RHS condition into TmpBB.
2319     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2320                          Probs[1], InvertCond);
2321   }
2322 }
2323 
2324 /// If the set of cases should be emitted as a series of branches, return true.
2325 /// If we should emit this as a bunch of and/or'd together conditions, return
2326 /// false.
2327 bool
2328 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2329   if (Cases.size() != 2) return true;
2330 
2331   // If this is two comparisons of the same values or'd or and'd together, they
2332   // will get folded into a single comparison, so don't emit two blocks.
2333   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2334        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2335       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2336        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2337     return false;
2338   }
2339 
2340   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2341   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2342   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2343       Cases[0].CC == Cases[1].CC &&
2344       isa<Constant>(Cases[0].CmpRHS) &&
2345       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2346     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2347       return false;
2348     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2349       return false;
2350   }
2351 
2352   return true;
2353 }
2354 
2355 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2356   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2357 
2358   // Update machine-CFG edges.
2359   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2360 
2361   if (I.isUnconditional()) {
2362     // Update machine-CFG edges.
2363     BrMBB->addSuccessor(Succ0MBB);
2364 
2365     // If this is not a fall-through branch or optimizations are switched off,
2366     // emit the branch.
2367     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2368       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2369                               MVT::Other, getControlRoot(),
2370                               DAG.getBasicBlock(Succ0MBB)));
2371 
2372     return;
2373   }
2374 
2375   // If this condition is one of the special cases we handle, do special stuff
2376   // now.
2377   const Value *CondVal = I.getCondition();
2378   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2379 
2380   // If this is a series of conditions that are or'd or and'd together, emit
2381   // this as a sequence of branches instead of setcc's with and/or operations.
2382   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2383   // unpredictable branches, and vector extracts because those jumps are likely
2384   // expensive for any target), this should improve performance.
2385   // For example, instead of something like:
2386   //     cmp A, B
2387   //     C = seteq
2388   //     cmp D, E
2389   //     F = setle
2390   //     or C, F
2391   //     jnz foo
2392   // Emit:
2393   //     cmp A, B
2394   //     je foo
2395   //     cmp D, E
2396   //     jle foo
2397   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2398   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2399       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2400     Value *Vec;
2401     const Value *BOp0, *BOp1;
2402     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2403     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2404       Opcode = Instruction::And;
2405     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2406       Opcode = Instruction::Or;
2407 
2408     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2409                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2410       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2411                            getEdgeProbability(BrMBB, Succ0MBB),
2412                            getEdgeProbability(BrMBB, Succ1MBB),
2413                            /*InvertCond=*/false);
2414       // If the compares in later blocks need to use values not currently
2415       // exported from this block, export them now.  This block should always
2416       // be the first entry.
2417       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2418 
2419       // Allow some cases to be rejected.
2420       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2421         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2422           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2423           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2424         }
2425 
2426         // Emit the branch for this block.
2427         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2428         SL->SwitchCases.erase(SL->SwitchCases.begin());
2429         return;
2430       }
2431 
2432       // Okay, we decided not to do this, remove any inserted MBB's and clear
2433       // SwitchCases.
2434       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2435         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2436 
2437       SL->SwitchCases.clear();
2438     }
2439   }
2440 
2441   // Create a CaseBlock record representing this branch.
2442   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2443                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2444 
2445   // Use visitSwitchCase to actually insert the fast branch sequence for this
2446   // cond branch.
2447   visitSwitchCase(CB, BrMBB);
2448 }
2449 
2450 /// visitSwitchCase - Emits the necessary code to represent a single node in
2451 /// the binary search tree resulting from lowering a switch instruction.
2452 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2453                                           MachineBasicBlock *SwitchBB) {
2454   SDValue Cond;
2455   SDValue CondLHS = getValue(CB.CmpLHS);
2456   SDLoc dl = CB.DL;
2457 
2458   if (CB.CC == ISD::SETTRUE) {
2459     // Branch or fall through to TrueBB.
2460     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2461     SwitchBB->normalizeSuccProbs();
2462     if (CB.TrueBB != NextBlock(SwitchBB)) {
2463       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2464                               DAG.getBasicBlock(CB.TrueBB)));
2465     }
2466     return;
2467   }
2468 
2469   auto &TLI = DAG.getTargetLoweringInfo();
2470   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2471 
2472   // Build the setcc now.
2473   if (!CB.CmpMHS) {
2474     // Fold "(X == true)" to X and "(X == false)" to !X to
2475     // handle common cases produced by branch lowering.
2476     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2477         CB.CC == ISD::SETEQ)
2478       Cond = CondLHS;
2479     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2480              CB.CC == ISD::SETEQ) {
2481       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2482       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2483     } else {
2484       SDValue CondRHS = getValue(CB.CmpRHS);
2485 
2486       // If a pointer's DAG type is larger than its memory type then the DAG
2487       // values are zero-extended. This breaks signed comparisons so truncate
2488       // back to the underlying type before doing the compare.
2489       if (CondLHS.getValueType() != MemVT) {
2490         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2491         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2492       }
2493       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2494     }
2495   } else {
2496     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2497 
2498     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2499     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2500 
2501     SDValue CmpOp = getValue(CB.CmpMHS);
2502     EVT VT = CmpOp.getValueType();
2503 
2504     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2505       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2506                           ISD::SETLE);
2507     } else {
2508       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2509                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2510       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2511                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2512     }
2513   }
2514 
2515   // Update successor info
2516   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2517   // TrueBB and FalseBB are always different unless the incoming IR is
2518   // degenerate. This only happens when running llc on weird IR.
2519   if (CB.TrueBB != CB.FalseBB)
2520     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2521   SwitchBB->normalizeSuccProbs();
2522 
2523   // If the lhs block is the next block, invert the condition so that we can
2524   // fall through to the lhs instead of the rhs block.
2525   if (CB.TrueBB == NextBlock(SwitchBB)) {
2526     std::swap(CB.TrueBB, CB.FalseBB);
2527     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2528     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2529   }
2530 
2531   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2532                                MVT::Other, getControlRoot(), Cond,
2533                                DAG.getBasicBlock(CB.TrueBB));
2534 
2535   // Insert the false branch. Do this even if it's a fall through branch,
2536   // this makes it easier to do DAG optimizations which require inverting
2537   // the branch condition.
2538   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2539                        DAG.getBasicBlock(CB.FalseBB));
2540 
2541   DAG.setRoot(BrCond);
2542 }
2543 
2544 /// visitJumpTable - Emit JumpTable node in the current MBB
2545 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2546   // Emit the code for the jump table
2547   assert(JT.Reg != -1U && "Should lower JT Header first!");
2548   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2549   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2550                                      JT.Reg, PTy);
2551   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2552   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2553                                     MVT::Other, Index.getValue(1),
2554                                     Table, Index);
2555   DAG.setRoot(BrJumpTable);
2556 }
2557 
2558 /// visitJumpTableHeader - This function emits necessary code to produce index
2559 /// in the JumpTable from switch case.
2560 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2561                                                JumpTableHeader &JTH,
2562                                                MachineBasicBlock *SwitchBB) {
2563   SDLoc dl = getCurSDLoc();
2564 
2565   // Subtract the lowest switch case value from the value being switched on.
2566   SDValue SwitchOp = getValue(JTH.SValue);
2567   EVT VT = SwitchOp.getValueType();
2568   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2569                             DAG.getConstant(JTH.First, dl, VT));
2570 
2571   // The SDNode we just created, which holds the value being switched on minus
2572   // the smallest case value, needs to be copied to a virtual register so it
2573   // can be used as an index into the jump table in a subsequent basic block.
2574   // This value may be smaller or larger than the target's pointer type, and
2575   // therefore require extension or truncating.
2576   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2577   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2578 
2579   unsigned JumpTableReg =
2580       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2581   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2582                                     JumpTableReg, SwitchOp);
2583   JT.Reg = JumpTableReg;
2584 
2585   if (!JTH.FallthroughUnreachable) {
2586     // Emit the range check for the jump table, and branch to the default block
2587     // for the switch statement if the value being switched on exceeds the
2588     // largest case in the switch.
2589     SDValue CMP = DAG.getSetCC(
2590         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2591                                    Sub.getValueType()),
2592         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2593 
2594     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2595                                  MVT::Other, CopyTo, CMP,
2596                                  DAG.getBasicBlock(JT.Default));
2597 
2598     // Avoid emitting unnecessary branches to the next block.
2599     if (JT.MBB != NextBlock(SwitchBB))
2600       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2601                            DAG.getBasicBlock(JT.MBB));
2602 
2603     DAG.setRoot(BrCond);
2604   } else {
2605     // Avoid emitting unnecessary branches to the next block.
2606     if (JT.MBB != NextBlock(SwitchBB))
2607       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2608                               DAG.getBasicBlock(JT.MBB)));
2609     else
2610       DAG.setRoot(CopyTo);
2611   }
2612 }
2613 
2614 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2615 /// variable if there exists one.
2616 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2617                                  SDValue &Chain) {
2618   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2619   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2620   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2621   MachineFunction &MF = DAG.getMachineFunction();
2622   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2623   MachineSDNode *Node =
2624       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2625   if (Global) {
2626     MachinePointerInfo MPInfo(Global);
2627     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2628                  MachineMemOperand::MODereferenceable;
2629     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2630         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2631     DAG.setNodeMemRefs(Node, {MemRef});
2632   }
2633   if (PtrTy != PtrMemTy)
2634     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2635   return SDValue(Node, 0);
2636 }
2637 
2638 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2639 /// tail spliced into a stack protector check success bb.
2640 ///
2641 /// For a high level explanation of how this fits into the stack protector
2642 /// generation see the comment on the declaration of class
2643 /// StackProtectorDescriptor.
2644 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2645                                                   MachineBasicBlock *ParentBB) {
2646 
2647   // First create the loads to the guard/stack slot for the comparison.
2648   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2649   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2650   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2651 
2652   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2653   int FI = MFI.getStackProtectorIndex();
2654 
2655   SDValue Guard;
2656   SDLoc dl = getCurSDLoc();
2657   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2658   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2659   Align Align =
2660       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2661 
2662   // Generate code to load the content of the guard slot.
2663   SDValue GuardVal = DAG.getLoad(
2664       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2665       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2666       MachineMemOperand::MOVolatile);
2667 
2668   if (TLI.useStackGuardXorFP())
2669     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2670 
2671   // Retrieve guard check function, nullptr if instrumentation is inlined.
2672   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2673     // The target provides a guard check function to validate the guard value.
2674     // Generate a call to that function with the content of the guard slot as
2675     // argument.
2676     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2677     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2678 
2679     TargetLowering::ArgListTy Args;
2680     TargetLowering::ArgListEntry Entry;
2681     Entry.Node = GuardVal;
2682     Entry.Ty = FnTy->getParamType(0);
2683     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2684       Entry.IsInReg = true;
2685     Args.push_back(Entry);
2686 
2687     TargetLowering::CallLoweringInfo CLI(DAG);
2688     CLI.setDebugLoc(getCurSDLoc())
2689         .setChain(DAG.getEntryNode())
2690         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2691                    getValue(GuardCheckFn), std::move(Args));
2692 
2693     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2694     DAG.setRoot(Result.second);
2695     return;
2696   }
2697 
2698   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2699   // Otherwise, emit a volatile load to retrieve the stack guard value.
2700   SDValue Chain = DAG.getEntryNode();
2701   if (TLI.useLoadStackGuardNode()) {
2702     Guard = getLoadStackGuard(DAG, dl, Chain);
2703   } else {
2704     const Value *IRGuard = TLI.getSDagStackGuard(M);
2705     SDValue GuardPtr = getValue(IRGuard);
2706 
2707     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2708                         MachinePointerInfo(IRGuard, 0), Align,
2709                         MachineMemOperand::MOVolatile);
2710   }
2711 
2712   // Perform the comparison via a getsetcc.
2713   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2714                                                         *DAG.getContext(),
2715                                                         Guard.getValueType()),
2716                              Guard, GuardVal, ISD::SETNE);
2717 
2718   // If the guard/stackslot do not equal, branch to failure MBB.
2719   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2720                                MVT::Other, GuardVal.getOperand(0),
2721                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2722   // Otherwise branch to success MBB.
2723   SDValue Br = DAG.getNode(ISD::BR, dl,
2724                            MVT::Other, BrCond,
2725                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2726 
2727   DAG.setRoot(Br);
2728 }
2729 
2730 /// Codegen the failure basic block for a stack protector check.
2731 ///
2732 /// A failure stack protector machine basic block consists simply of a call to
2733 /// __stack_chk_fail().
2734 ///
2735 /// For a high level explanation of how this fits into the stack protector
2736 /// generation see the comment on the declaration of class
2737 /// StackProtectorDescriptor.
2738 void
2739 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2740   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2741   TargetLowering::MakeLibCallOptions CallOptions;
2742   CallOptions.setDiscardResult(true);
2743   SDValue Chain =
2744       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2745                       None, CallOptions, getCurSDLoc()).second;
2746   // On PS4, the "return address" must still be within the calling function,
2747   // even if it's at the very end, so emit an explicit TRAP here.
2748   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2749   if (TM.getTargetTriple().isPS4())
2750     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2751   // WebAssembly needs an unreachable instruction after a non-returning call,
2752   // because the function return type can be different from __stack_chk_fail's
2753   // return type (void).
2754   if (TM.getTargetTriple().isWasm())
2755     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2756 
2757   DAG.setRoot(Chain);
2758 }
2759 
2760 /// visitBitTestHeader - This function emits necessary code to produce value
2761 /// suitable for "bit tests"
2762 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2763                                              MachineBasicBlock *SwitchBB) {
2764   SDLoc dl = getCurSDLoc();
2765 
2766   // Subtract the minimum value.
2767   SDValue SwitchOp = getValue(B.SValue);
2768   EVT VT = SwitchOp.getValueType();
2769   SDValue RangeSub =
2770       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2771 
2772   // Determine the type of the test operands.
2773   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2774   bool UsePtrType = false;
2775   if (!TLI.isTypeLegal(VT)) {
2776     UsePtrType = true;
2777   } else {
2778     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2779       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2780         // Switch table case range are encoded into series of masks.
2781         // Just use pointer type, it's guaranteed to fit.
2782         UsePtrType = true;
2783         break;
2784       }
2785   }
2786   SDValue Sub = RangeSub;
2787   if (UsePtrType) {
2788     VT = TLI.getPointerTy(DAG.getDataLayout());
2789     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2790   }
2791 
2792   B.RegVT = VT.getSimpleVT();
2793   B.Reg = FuncInfo.CreateReg(B.RegVT);
2794   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2795 
2796   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2797 
2798   if (!B.FallthroughUnreachable)
2799     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2800   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2801   SwitchBB->normalizeSuccProbs();
2802 
2803   SDValue Root = CopyTo;
2804   if (!B.FallthroughUnreachable) {
2805     // Conditional branch to the default block.
2806     SDValue RangeCmp = DAG.getSetCC(dl,
2807         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2808                                RangeSub.getValueType()),
2809         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2810         ISD::SETUGT);
2811 
2812     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2813                        DAG.getBasicBlock(B.Default));
2814   }
2815 
2816   // Avoid emitting unnecessary branches to the next block.
2817   if (MBB != NextBlock(SwitchBB))
2818     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2819 
2820   DAG.setRoot(Root);
2821 }
2822 
2823 /// visitBitTestCase - this function produces one "bit test"
2824 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2825                                            MachineBasicBlock* NextMBB,
2826                                            BranchProbability BranchProbToNext,
2827                                            unsigned Reg,
2828                                            BitTestCase &B,
2829                                            MachineBasicBlock *SwitchBB) {
2830   SDLoc dl = getCurSDLoc();
2831   MVT VT = BB.RegVT;
2832   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2833   SDValue Cmp;
2834   unsigned PopCount = countPopulation(B.Mask);
2835   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2836   if (PopCount == 1) {
2837     // Testing for a single bit; just compare the shift count with what it
2838     // would need to be to shift a 1 bit in that position.
2839     Cmp = DAG.getSetCC(
2840         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2841         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2842         ISD::SETEQ);
2843   } else if (PopCount == BB.Range) {
2844     // There is only one zero bit in the range, test for it directly.
2845     Cmp = DAG.getSetCC(
2846         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2847         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2848         ISD::SETNE);
2849   } else {
2850     // Make desired shift
2851     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2852                                     DAG.getConstant(1, dl, VT), ShiftOp);
2853 
2854     // Emit bit tests and jumps
2855     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2856                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2857     Cmp = DAG.getSetCC(
2858         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2859         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2860   }
2861 
2862   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2863   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2864   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2865   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2866   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2867   // one as they are relative probabilities (and thus work more like weights),
2868   // and hence we need to normalize them to let the sum of them become one.
2869   SwitchBB->normalizeSuccProbs();
2870 
2871   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2872                               MVT::Other, getControlRoot(),
2873                               Cmp, DAG.getBasicBlock(B.TargetBB));
2874 
2875   // Avoid emitting unnecessary branches to the next block.
2876   if (NextMBB != NextBlock(SwitchBB))
2877     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2878                         DAG.getBasicBlock(NextMBB));
2879 
2880   DAG.setRoot(BrAnd);
2881 }
2882 
2883 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2884   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2885 
2886   // Retrieve successors. Look through artificial IR level blocks like
2887   // catchswitch for successors.
2888   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2889   const BasicBlock *EHPadBB = I.getSuccessor(1);
2890 
2891   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2892   // have to do anything here to lower funclet bundles.
2893   assert(!I.hasOperandBundlesOtherThan(
2894              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2895               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2896               LLVMContext::OB_cfguardtarget,
2897               LLVMContext::OB_clang_arc_attachedcall}) &&
2898          "Cannot lower invokes with arbitrary operand bundles yet!");
2899 
2900   const Value *Callee(I.getCalledOperand());
2901   const Function *Fn = dyn_cast<Function>(Callee);
2902   if (isa<InlineAsm>(Callee))
2903     visitInlineAsm(I, EHPadBB);
2904   else if (Fn && Fn->isIntrinsic()) {
2905     switch (Fn->getIntrinsicID()) {
2906     default:
2907       llvm_unreachable("Cannot invoke this intrinsic");
2908     case Intrinsic::donothing:
2909       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2910     case Intrinsic::seh_try_begin:
2911     case Intrinsic::seh_scope_begin:
2912     case Intrinsic::seh_try_end:
2913     case Intrinsic::seh_scope_end:
2914       break;
2915     case Intrinsic::experimental_patchpoint_void:
2916     case Intrinsic::experimental_patchpoint_i64:
2917       visitPatchpoint(I, EHPadBB);
2918       break;
2919     case Intrinsic::experimental_gc_statepoint:
2920       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2921       break;
2922     case Intrinsic::wasm_rethrow: {
2923       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2924       // special because it can be invoked, so we manually lower it to a DAG
2925       // node here.
2926       SmallVector<SDValue, 8> Ops;
2927       Ops.push_back(getRoot()); // inchain
2928       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2929       Ops.push_back(
2930           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2931                                 TLI.getPointerTy(DAG.getDataLayout())));
2932       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2933       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2934       break;
2935     }
2936     }
2937   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2938     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2939     // Eventually we will support lowering the @llvm.experimental.deoptimize
2940     // intrinsic, and right now there are no plans to support other intrinsics
2941     // with deopt state.
2942     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2943   } else {
2944     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2945   }
2946 
2947   // If the value of the invoke is used outside of its defining block, make it
2948   // available as a virtual register.
2949   // We already took care of the exported value for the statepoint instruction
2950   // during call to the LowerStatepoint.
2951   if (!isa<GCStatepointInst>(I)) {
2952     CopyToExportRegsIfNeeded(&I);
2953   }
2954 
2955   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2956   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2957   BranchProbability EHPadBBProb =
2958       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2959           : BranchProbability::getZero();
2960   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2961 
2962   // Update successor info.
2963   addSuccessorWithProb(InvokeMBB, Return);
2964   for (auto &UnwindDest : UnwindDests) {
2965     UnwindDest.first->setIsEHPad();
2966     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2967   }
2968   InvokeMBB->normalizeSuccProbs();
2969 
2970   // Drop into normal successor.
2971   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2972                           DAG.getBasicBlock(Return)));
2973 }
2974 
2975 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2976   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2977 
2978   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2979   // have to do anything here to lower funclet bundles.
2980   assert(!I.hasOperandBundlesOtherThan(
2981              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2982          "Cannot lower callbrs with arbitrary operand bundles yet!");
2983 
2984   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2985   visitInlineAsm(I);
2986   CopyToExportRegsIfNeeded(&I);
2987 
2988   // Retrieve successors.
2989   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2990 
2991   // Update successor info.
2992   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2993   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2994     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2995     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2996     Target->setIsInlineAsmBrIndirectTarget();
2997   }
2998   CallBrMBB->normalizeSuccProbs();
2999 
3000   // Drop into default successor.
3001   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3002                           MVT::Other, getControlRoot(),
3003                           DAG.getBasicBlock(Return)));
3004 }
3005 
3006 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3007   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3008 }
3009 
3010 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3011   assert(FuncInfo.MBB->isEHPad() &&
3012          "Call to landingpad not in landing pad!");
3013 
3014   // If there aren't registers to copy the values into (e.g., during SjLj
3015   // exceptions), then don't bother to create these DAG nodes.
3016   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3017   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3018   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3019       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3020     return;
3021 
3022   // If landingpad's return type is token type, we don't create DAG nodes
3023   // for its exception pointer and selector value. The extraction of exception
3024   // pointer or selector value from token type landingpads is not currently
3025   // supported.
3026   if (LP.getType()->isTokenTy())
3027     return;
3028 
3029   SmallVector<EVT, 2> ValueVTs;
3030   SDLoc dl = getCurSDLoc();
3031   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3032   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3033 
3034   // Get the two live-in registers as SDValues. The physregs have already been
3035   // copied into virtual registers.
3036   SDValue Ops[2];
3037   if (FuncInfo.ExceptionPointerVirtReg) {
3038     Ops[0] = DAG.getZExtOrTrunc(
3039         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3040                            FuncInfo.ExceptionPointerVirtReg,
3041                            TLI.getPointerTy(DAG.getDataLayout())),
3042         dl, ValueVTs[0]);
3043   } else {
3044     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3045   }
3046   Ops[1] = DAG.getZExtOrTrunc(
3047       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3048                          FuncInfo.ExceptionSelectorVirtReg,
3049                          TLI.getPointerTy(DAG.getDataLayout())),
3050       dl, ValueVTs[1]);
3051 
3052   // Merge into one.
3053   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3054                             DAG.getVTList(ValueVTs), Ops);
3055   setValue(&LP, Res);
3056 }
3057 
3058 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3059                                            MachineBasicBlock *Last) {
3060   // Update JTCases.
3061   for (JumpTableBlock &JTB : SL->JTCases)
3062     if (JTB.first.HeaderBB == First)
3063       JTB.first.HeaderBB = Last;
3064 
3065   // Update BitTestCases.
3066   for (BitTestBlock &BTB : SL->BitTestCases)
3067     if (BTB.Parent == First)
3068       BTB.Parent = Last;
3069 }
3070 
3071 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3072   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3073 
3074   // Update machine-CFG edges with unique successors.
3075   SmallSet<BasicBlock*, 32> Done;
3076   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3077     BasicBlock *BB = I.getSuccessor(i);
3078     bool Inserted = Done.insert(BB).second;
3079     if (!Inserted)
3080         continue;
3081 
3082     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3083     addSuccessorWithProb(IndirectBrMBB, Succ);
3084   }
3085   IndirectBrMBB->normalizeSuccProbs();
3086 
3087   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3088                           MVT::Other, getControlRoot(),
3089                           getValue(I.getAddress())));
3090 }
3091 
3092 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3093   if (!DAG.getTarget().Options.TrapUnreachable)
3094     return;
3095 
3096   // We may be able to ignore unreachable behind a noreturn call.
3097   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3098     const BasicBlock &BB = *I.getParent();
3099     if (&I != &BB.front()) {
3100       BasicBlock::const_iterator PredI =
3101         std::prev(BasicBlock::const_iterator(&I));
3102       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3103         if (Call->doesNotReturn())
3104           return;
3105       }
3106     }
3107   }
3108 
3109   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3110 }
3111 
3112 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3113   SDNodeFlags Flags;
3114   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3115     Flags.copyFMF(*FPOp);
3116 
3117   SDValue Op = getValue(I.getOperand(0));
3118   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3119                                     Op, Flags);
3120   setValue(&I, UnNodeValue);
3121 }
3122 
3123 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3124   SDNodeFlags Flags;
3125   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3126     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3127     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3128   }
3129   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3130     Flags.setExact(ExactOp->isExact());
3131   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3132     Flags.copyFMF(*FPOp);
3133 
3134   SDValue Op1 = getValue(I.getOperand(0));
3135   SDValue Op2 = getValue(I.getOperand(1));
3136   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3137                                      Op1, Op2, Flags);
3138   setValue(&I, BinNodeValue);
3139 }
3140 
3141 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3142   SDValue Op1 = getValue(I.getOperand(0));
3143   SDValue Op2 = getValue(I.getOperand(1));
3144 
3145   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3146       Op1.getValueType(), DAG.getDataLayout());
3147 
3148   // Coerce the shift amount to the right type if we can. This exposes the
3149   // truncate or zext to optimization early.
3150   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3151     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3152            "Unexpected shift type");
3153     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3154   }
3155 
3156   bool nuw = false;
3157   bool nsw = false;
3158   bool exact = false;
3159 
3160   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3161 
3162     if (const OverflowingBinaryOperator *OFBinOp =
3163             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3164       nuw = OFBinOp->hasNoUnsignedWrap();
3165       nsw = OFBinOp->hasNoSignedWrap();
3166     }
3167     if (const PossiblyExactOperator *ExactOp =
3168             dyn_cast<const PossiblyExactOperator>(&I))
3169       exact = ExactOp->isExact();
3170   }
3171   SDNodeFlags Flags;
3172   Flags.setExact(exact);
3173   Flags.setNoSignedWrap(nsw);
3174   Flags.setNoUnsignedWrap(nuw);
3175   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3176                             Flags);
3177   setValue(&I, Res);
3178 }
3179 
3180 void SelectionDAGBuilder::visitSDiv(const User &I) {
3181   SDValue Op1 = getValue(I.getOperand(0));
3182   SDValue Op2 = getValue(I.getOperand(1));
3183 
3184   SDNodeFlags Flags;
3185   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3186                  cast<PossiblyExactOperator>(&I)->isExact());
3187   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3188                            Op2, Flags));
3189 }
3190 
3191 void SelectionDAGBuilder::visitICmp(const User &I) {
3192   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3193   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3194     predicate = IC->getPredicate();
3195   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3196     predicate = ICmpInst::Predicate(IC->getPredicate());
3197   SDValue Op1 = getValue(I.getOperand(0));
3198   SDValue Op2 = getValue(I.getOperand(1));
3199   ISD::CondCode Opcode = getICmpCondCode(predicate);
3200 
3201   auto &TLI = DAG.getTargetLoweringInfo();
3202   EVT MemVT =
3203       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3204 
3205   // If a pointer's DAG type is larger than its memory type then the DAG values
3206   // are zero-extended. This breaks signed comparisons so truncate back to the
3207   // underlying type before doing the compare.
3208   if (Op1.getValueType() != MemVT) {
3209     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3210     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3211   }
3212 
3213   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3214                                                         I.getType());
3215   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3216 }
3217 
3218 void SelectionDAGBuilder::visitFCmp(const User &I) {
3219   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3220   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3221     predicate = FC->getPredicate();
3222   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3223     predicate = FCmpInst::Predicate(FC->getPredicate());
3224   SDValue Op1 = getValue(I.getOperand(0));
3225   SDValue Op2 = getValue(I.getOperand(1));
3226 
3227   ISD::CondCode Condition = getFCmpCondCode(predicate);
3228   auto *FPMO = cast<FPMathOperator>(&I);
3229   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3230     Condition = getFCmpCodeWithoutNaN(Condition);
3231 
3232   SDNodeFlags Flags;
3233   Flags.copyFMF(*FPMO);
3234   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3235 
3236   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3237                                                         I.getType());
3238   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3239 }
3240 
3241 // Check if the condition of the select has one use or two users that are both
3242 // selects with the same condition.
3243 static bool hasOnlySelectUsers(const Value *Cond) {
3244   return llvm::all_of(Cond->users(), [](const Value *V) {
3245     return isa<SelectInst>(V);
3246   });
3247 }
3248 
3249 void SelectionDAGBuilder::visitSelect(const User &I) {
3250   SmallVector<EVT, 4> ValueVTs;
3251   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3252                   ValueVTs);
3253   unsigned NumValues = ValueVTs.size();
3254   if (NumValues == 0) return;
3255 
3256   SmallVector<SDValue, 4> Values(NumValues);
3257   SDValue Cond     = getValue(I.getOperand(0));
3258   SDValue LHSVal   = getValue(I.getOperand(1));
3259   SDValue RHSVal   = getValue(I.getOperand(2));
3260   SmallVector<SDValue, 1> BaseOps(1, Cond);
3261   ISD::NodeType OpCode =
3262       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3263 
3264   bool IsUnaryAbs = false;
3265   bool Negate = false;
3266 
3267   SDNodeFlags Flags;
3268   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3269     Flags.copyFMF(*FPOp);
3270 
3271   // Min/max matching is only viable if all output VTs are the same.
3272   if (is_splat(ValueVTs)) {
3273     EVT VT = ValueVTs[0];
3274     LLVMContext &Ctx = *DAG.getContext();
3275     auto &TLI = DAG.getTargetLoweringInfo();
3276 
3277     // We care about the legality of the operation after it has been type
3278     // legalized.
3279     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3280       VT = TLI.getTypeToTransformTo(Ctx, VT);
3281 
3282     // If the vselect is legal, assume we want to leave this as a vector setcc +
3283     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3284     // min/max is legal on the scalar type.
3285     bool UseScalarMinMax = VT.isVector() &&
3286       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3287 
3288     Value *LHS, *RHS;
3289     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3290     ISD::NodeType Opc = ISD::DELETED_NODE;
3291     switch (SPR.Flavor) {
3292     case SPF_UMAX:    Opc = ISD::UMAX; break;
3293     case SPF_UMIN:    Opc = ISD::UMIN; break;
3294     case SPF_SMAX:    Opc = ISD::SMAX; break;
3295     case SPF_SMIN:    Opc = ISD::SMIN; break;
3296     case SPF_FMINNUM:
3297       switch (SPR.NaNBehavior) {
3298       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3299       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3300       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3301       case SPNB_RETURNS_ANY: {
3302         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3303           Opc = ISD::FMINNUM;
3304         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3305           Opc = ISD::FMINIMUM;
3306         else if (UseScalarMinMax)
3307           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3308             ISD::FMINNUM : ISD::FMINIMUM;
3309         break;
3310       }
3311       }
3312       break;
3313     case SPF_FMAXNUM:
3314       switch (SPR.NaNBehavior) {
3315       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3316       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3317       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3318       case SPNB_RETURNS_ANY:
3319 
3320         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3321           Opc = ISD::FMAXNUM;
3322         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3323           Opc = ISD::FMAXIMUM;
3324         else if (UseScalarMinMax)
3325           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3326             ISD::FMAXNUM : ISD::FMAXIMUM;
3327         break;
3328       }
3329       break;
3330     case SPF_NABS:
3331       Negate = true;
3332       LLVM_FALLTHROUGH;
3333     case SPF_ABS:
3334       IsUnaryAbs = true;
3335       Opc = ISD::ABS;
3336       break;
3337     default: break;
3338     }
3339 
3340     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3341         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3342          (UseScalarMinMax &&
3343           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3344         // If the underlying comparison instruction is used by any other
3345         // instruction, the consumed instructions won't be destroyed, so it is
3346         // not profitable to convert to a min/max.
3347         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3348       OpCode = Opc;
3349       LHSVal = getValue(LHS);
3350       RHSVal = getValue(RHS);
3351       BaseOps.clear();
3352     }
3353 
3354     if (IsUnaryAbs) {
3355       OpCode = Opc;
3356       LHSVal = getValue(LHS);
3357       BaseOps.clear();
3358     }
3359   }
3360 
3361   if (IsUnaryAbs) {
3362     for (unsigned i = 0; i != NumValues; ++i) {
3363       SDLoc dl = getCurSDLoc();
3364       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3365       Values[i] =
3366           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3367       if (Negate)
3368         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3369                                 Values[i]);
3370     }
3371   } else {
3372     for (unsigned i = 0; i != NumValues; ++i) {
3373       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3374       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3375       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3376       Values[i] = DAG.getNode(
3377           OpCode, getCurSDLoc(),
3378           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3379     }
3380   }
3381 
3382   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3383                            DAG.getVTList(ValueVTs), Values));
3384 }
3385 
3386 void SelectionDAGBuilder::visitTrunc(const User &I) {
3387   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3388   SDValue N = getValue(I.getOperand(0));
3389   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3390                                                         I.getType());
3391   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3392 }
3393 
3394 void SelectionDAGBuilder::visitZExt(const User &I) {
3395   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3396   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3397   SDValue N = getValue(I.getOperand(0));
3398   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3399                                                         I.getType());
3400   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3401 }
3402 
3403 void SelectionDAGBuilder::visitSExt(const User &I) {
3404   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3405   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3406   SDValue N = getValue(I.getOperand(0));
3407   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3408                                                         I.getType());
3409   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3410 }
3411 
3412 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3413   // FPTrunc is never a no-op cast, no need to check
3414   SDValue N = getValue(I.getOperand(0));
3415   SDLoc dl = getCurSDLoc();
3416   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3417   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3418   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3419                            DAG.getTargetConstant(
3420                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3421 }
3422 
3423 void SelectionDAGBuilder::visitFPExt(const User &I) {
3424   // FPExt is never a no-op cast, no need to check
3425   SDValue N = getValue(I.getOperand(0));
3426   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3427                                                         I.getType());
3428   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3429 }
3430 
3431 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3432   // FPToUI is never a no-op cast, no need to check
3433   SDValue N = getValue(I.getOperand(0));
3434   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3435                                                         I.getType());
3436   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3437 }
3438 
3439 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3440   // FPToSI is never a no-op cast, no need to check
3441   SDValue N = getValue(I.getOperand(0));
3442   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3443                                                         I.getType());
3444   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3445 }
3446 
3447 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3448   // UIToFP is never a no-op cast, no need to check
3449   SDValue N = getValue(I.getOperand(0));
3450   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3451                                                         I.getType());
3452   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3453 }
3454 
3455 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3456   // SIToFP is never a no-op cast, no need to check
3457   SDValue N = getValue(I.getOperand(0));
3458   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3459                                                         I.getType());
3460   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3461 }
3462 
3463 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3464   // What to do depends on the size of the integer and the size of the pointer.
3465   // We can either truncate, zero extend, or no-op, accordingly.
3466   SDValue N = getValue(I.getOperand(0));
3467   auto &TLI = DAG.getTargetLoweringInfo();
3468   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3469                                                         I.getType());
3470   EVT PtrMemVT =
3471       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3472   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3473   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3474   setValue(&I, N);
3475 }
3476 
3477 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3478   // What to do depends on the size of the integer and the size of the pointer.
3479   // We can either truncate, zero extend, or no-op, accordingly.
3480   SDValue N = getValue(I.getOperand(0));
3481   auto &TLI = DAG.getTargetLoweringInfo();
3482   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3483   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3484   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3485   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3486   setValue(&I, N);
3487 }
3488 
3489 void SelectionDAGBuilder::visitBitCast(const User &I) {
3490   SDValue N = getValue(I.getOperand(0));
3491   SDLoc dl = getCurSDLoc();
3492   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3493                                                         I.getType());
3494 
3495   // BitCast assures us that source and destination are the same size so this is
3496   // either a BITCAST or a no-op.
3497   if (DestVT != N.getValueType())
3498     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3499                              DestVT, N)); // convert types.
3500   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3501   // might fold any kind of constant expression to an integer constant and that
3502   // is not what we are looking for. Only recognize a bitcast of a genuine
3503   // constant integer as an opaque constant.
3504   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3505     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3506                                  /*isOpaque*/true));
3507   else
3508     setValue(&I, N);            // noop cast.
3509 }
3510 
3511 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3512   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3513   const Value *SV = I.getOperand(0);
3514   SDValue N = getValue(SV);
3515   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3516 
3517   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3518   unsigned DestAS = I.getType()->getPointerAddressSpace();
3519 
3520   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3521     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3522 
3523   setValue(&I, N);
3524 }
3525 
3526 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3527   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3528   SDValue InVec = getValue(I.getOperand(0));
3529   SDValue InVal = getValue(I.getOperand(1));
3530   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3531                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3532   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3533                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3534                            InVec, InVal, InIdx));
3535 }
3536 
3537 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3539   SDValue InVec = getValue(I.getOperand(0));
3540   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3541                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3542   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3543                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3544                            InVec, InIdx));
3545 }
3546 
3547 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3548   SDValue Src1 = getValue(I.getOperand(0));
3549   SDValue Src2 = getValue(I.getOperand(1));
3550   ArrayRef<int> Mask;
3551   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3552     Mask = SVI->getShuffleMask();
3553   else
3554     Mask = cast<ConstantExpr>(I).getShuffleMask();
3555   SDLoc DL = getCurSDLoc();
3556   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3557   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3558   EVT SrcVT = Src1.getValueType();
3559 
3560   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3561       VT.isScalableVector()) {
3562     // Canonical splat form of first element of first input vector.
3563     SDValue FirstElt =
3564         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3565                     DAG.getVectorIdxConstant(0, DL));
3566     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3567     return;
3568   }
3569 
3570   // For now, we only handle splats for scalable vectors.
3571   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3572   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3573   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3574 
3575   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3576   unsigned MaskNumElts = Mask.size();
3577 
3578   if (SrcNumElts == MaskNumElts) {
3579     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3580     return;
3581   }
3582 
3583   // Normalize the shuffle vector since mask and vector length don't match.
3584   if (SrcNumElts < MaskNumElts) {
3585     // Mask is longer than the source vectors. We can use concatenate vector to
3586     // make the mask and vectors lengths match.
3587 
3588     if (MaskNumElts % SrcNumElts == 0) {
3589       // Mask length is a multiple of the source vector length.
3590       // Check if the shuffle is some kind of concatenation of the input
3591       // vectors.
3592       unsigned NumConcat = MaskNumElts / SrcNumElts;
3593       bool IsConcat = true;
3594       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3595       for (unsigned i = 0; i != MaskNumElts; ++i) {
3596         int Idx = Mask[i];
3597         if (Idx < 0)
3598           continue;
3599         // Ensure the indices in each SrcVT sized piece are sequential and that
3600         // the same source is used for the whole piece.
3601         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3602             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3603              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3604           IsConcat = false;
3605           break;
3606         }
3607         // Remember which source this index came from.
3608         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3609       }
3610 
3611       // The shuffle is concatenating multiple vectors together. Just emit
3612       // a CONCAT_VECTORS operation.
3613       if (IsConcat) {
3614         SmallVector<SDValue, 8> ConcatOps;
3615         for (auto Src : ConcatSrcs) {
3616           if (Src < 0)
3617             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3618           else if (Src == 0)
3619             ConcatOps.push_back(Src1);
3620           else
3621             ConcatOps.push_back(Src2);
3622         }
3623         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3624         return;
3625       }
3626     }
3627 
3628     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3629     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3630     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3631                                     PaddedMaskNumElts);
3632 
3633     // Pad both vectors with undefs to make them the same length as the mask.
3634     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3635 
3636     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3637     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3638     MOps1[0] = Src1;
3639     MOps2[0] = Src2;
3640 
3641     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3642     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3643 
3644     // Readjust mask for new input vector length.
3645     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3646     for (unsigned i = 0; i != MaskNumElts; ++i) {
3647       int Idx = Mask[i];
3648       if (Idx >= (int)SrcNumElts)
3649         Idx -= SrcNumElts - PaddedMaskNumElts;
3650       MappedOps[i] = Idx;
3651     }
3652 
3653     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3654 
3655     // If the concatenated vector was padded, extract a subvector with the
3656     // correct number of elements.
3657     if (MaskNumElts != PaddedMaskNumElts)
3658       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3659                            DAG.getVectorIdxConstant(0, DL));
3660 
3661     setValue(&I, Result);
3662     return;
3663   }
3664 
3665   if (SrcNumElts > MaskNumElts) {
3666     // Analyze the access pattern of the vector to see if we can extract
3667     // two subvectors and do the shuffle.
3668     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3669     bool CanExtract = true;
3670     for (int Idx : Mask) {
3671       unsigned Input = 0;
3672       if (Idx < 0)
3673         continue;
3674 
3675       if (Idx >= (int)SrcNumElts) {
3676         Input = 1;
3677         Idx -= SrcNumElts;
3678       }
3679 
3680       // If all the indices come from the same MaskNumElts sized portion of
3681       // the sources we can use extract. Also make sure the extract wouldn't
3682       // extract past the end of the source.
3683       int NewStartIdx = alignDown(Idx, MaskNumElts);
3684       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3685           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3686         CanExtract = false;
3687       // Make sure we always update StartIdx as we use it to track if all
3688       // elements are undef.
3689       StartIdx[Input] = NewStartIdx;
3690     }
3691 
3692     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3693       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3694       return;
3695     }
3696     if (CanExtract) {
3697       // Extract appropriate subvector and generate a vector shuffle
3698       for (unsigned Input = 0; Input < 2; ++Input) {
3699         SDValue &Src = Input == 0 ? Src1 : Src2;
3700         if (StartIdx[Input] < 0)
3701           Src = DAG.getUNDEF(VT);
3702         else {
3703           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3704                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3705         }
3706       }
3707 
3708       // Calculate new mask.
3709       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3710       for (int &Idx : MappedOps) {
3711         if (Idx >= (int)SrcNumElts)
3712           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3713         else if (Idx >= 0)
3714           Idx -= StartIdx[0];
3715       }
3716 
3717       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3718       return;
3719     }
3720   }
3721 
3722   // We can't use either concat vectors or extract subvectors so fall back to
3723   // replacing the shuffle with extract and build vector.
3724   // to insert and build vector.
3725   EVT EltVT = VT.getVectorElementType();
3726   SmallVector<SDValue,8> Ops;
3727   for (int Idx : Mask) {
3728     SDValue Res;
3729 
3730     if (Idx < 0) {
3731       Res = DAG.getUNDEF(EltVT);
3732     } else {
3733       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3734       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3735 
3736       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3737                         DAG.getVectorIdxConstant(Idx, DL));
3738     }
3739 
3740     Ops.push_back(Res);
3741   }
3742 
3743   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3744 }
3745 
3746 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3747   ArrayRef<unsigned> Indices;
3748   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3749     Indices = IV->getIndices();
3750   else
3751     Indices = cast<ConstantExpr>(&I)->getIndices();
3752 
3753   const Value *Op0 = I.getOperand(0);
3754   const Value *Op1 = I.getOperand(1);
3755   Type *AggTy = I.getType();
3756   Type *ValTy = Op1->getType();
3757   bool IntoUndef = isa<UndefValue>(Op0);
3758   bool FromUndef = isa<UndefValue>(Op1);
3759 
3760   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3761 
3762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3763   SmallVector<EVT, 4> AggValueVTs;
3764   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3765   SmallVector<EVT, 4> ValValueVTs;
3766   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3767 
3768   unsigned NumAggValues = AggValueVTs.size();
3769   unsigned NumValValues = ValValueVTs.size();
3770   SmallVector<SDValue, 4> Values(NumAggValues);
3771 
3772   // Ignore an insertvalue that produces an empty object
3773   if (!NumAggValues) {
3774     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3775     return;
3776   }
3777 
3778   SDValue Agg = getValue(Op0);
3779   unsigned i = 0;
3780   // Copy the beginning value(s) from the original aggregate.
3781   for (; i != LinearIndex; ++i)
3782     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3783                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3784   // Copy values from the inserted value(s).
3785   if (NumValValues) {
3786     SDValue Val = getValue(Op1);
3787     for (; i != LinearIndex + NumValValues; ++i)
3788       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3789                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3790   }
3791   // Copy remaining value(s) from the original aggregate.
3792   for (; i != NumAggValues; ++i)
3793     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3794                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3795 
3796   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3797                            DAG.getVTList(AggValueVTs), Values));
3798 }
3799 
3800 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3801   ArrayRef<unsigned> Indices;
3802   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3803     Indices = EV->getIndices();
3804   else
3805     Indices = cast<ConstantExpr>(&I)->getIndices();
3806 
3807   const Value *Op0 = I.getOperand(0);
3808   Type *AggTy = Op0->getType();
3809   Type *ValTy = I.getType();
3810   bool OutOfUndef = isa<UndefValue>(Op0);
3811 
3812   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3813 
3814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3815   SmallVector<EVT, 4> ValValueVTs;
3816   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3817 
3818   unsigned NumValValues = ValValueVTs.size();
3819 
3820   // Ignore a extractvalue that produces an empty object
3821   if (!NumValValues) {
3822     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3823     return;
3824   }
3825 
3826   SmallVector<SDValue, 4> Values(NumValValues);
3827 
3828   SDValue Agg = getValue(Op0);
3829   // Copy out the selected value(s).
3830   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3831     Values[i - LinearIndex] =
3832       OutOfUndef ?
3833         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3834         SDValue(Agg.getNode(), Agg.getResNo() + i);
3835 
3836   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3837                            DAG.getVTList(ValValueVTs), Values));
3838 }
3839 
3840 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3841   Value *Op0 = I.getOperand(0);
3842   // Note that the pointer operand may be a vector of pointers. Take the scalar
3843   // element which holds a pointer.
3844   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3845   SDValue N = getValue(Op0);
3846   SDLoc dl = getCurSDLoc();
3847   auto &TLI = DAG.getTargetLoweringInfo();
3848 
3849   // Normalize Vector GEP - all scalar operands should be converted to the
3850   // splat vector.
3851   bool IsVectorGEP = I.getType()->isVectorTy();
3852   ElementCount VectorElementCount =
3853       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3854                   : ElementCount::getFixed(0);
3855 
3856   if (IsVectorGEP && !N.getValueType().isVector()) {
3857     LLVMContext &Context = *DAG.getContext();
3858     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3859     if (VectorElementCount.isScalable())
3860       N = DAG.getSplatVector(VT, dl, N);
3861     else
3862       N = DAG.getSplatBuildVector(VT, dl, N);
3863   }
3864 
3865   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3866        GTI != E; ++GTI) {
3867     const Value *Idx = GTI.getOperand();
3868     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3869       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3870       if (Field) {
3871         // N = N + Offset
3872         uint64_t Offset =
3873             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3874 
3875         // In an inbounds GEP with an offset that is nonnegative even when
3876         // interpreted as signed, assume there is no unsigned overflow.
3877         SDNodeFlags Flags;
3878         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3879           Flags.setNoUnsignedWrap(true);
3880 
3881         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3882                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3883       }
3884     } else {
3885       // IdxSize is the width of the arithmetic according to IR semantics.
3886       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3887       // (and fix up the result later).
3888       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3889       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3890       TypeSize ElementSize =
3891           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3892       // We intentionally mask away the high bits here; ElementSize may not
3893       // fit in IdxTy.
3894       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3895       bool ElementScalable = ElementSize.isScalable();
3896 
3897       // If this is a scalar constant or a splat vector of constants,
3898       // handle it quickly.
3899       const auto *C = dyn_cast<Constant>(Idx);
3900       if (C && isa<VectorType>(C->getType()))
3901         C = C->getSplatValue();
3902 
3903       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3904       if (CI && CI->isZero())
3905         continue;
3906       if (CI && !ElementScalable) {
3907         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3908         LLVMContext &Context = *DAG.getContext();
3909         SDValue OffsVal;
3910         if (IsVectorGEP)
3911           OffsVal = DAG.getConstant(
3912               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3913         else
3914           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3915 
3916         // In an inbounds GEP with an offset that is nonnegative even when
3917         // interpreted as signed, assume there is no unsigned overflow.
3918         SDNodeFlags Flags;
3919         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3920           Flags.setNoUnsignedWrap(true);
3921 
3922         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3923 
3924         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3925         continue;
3926       }
3927 
3928       // N = N + Idx * ElementMul;
3929       SDValue IdxN = getValue(Idx);
3930 
3931       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3932         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3933                                   VectorElementCount);
3934         if (VectorElementCount.isScalable())
3935           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3936         else
3937           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3938       }
3939 
3940       // If the index is smaller or larger than intptr_t, truncate or extend
3941       // it.
3942       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3943 
3944       if (ElementScalable) {
3945         EVT VScaleTy = N.getValueType().getScalarType();
3946         SDValue VScale = DAG.getNode(
3947             ISD::VSCALE, dl, VScaleTy,
3948             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3949         if (IsVectorGEP)
3950           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3951         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3952       } else {
3953         // If this is a multiply by a power of two, turn it into a shl
3954         // immediately.  This is a very common case.
3955         if (ElementMul != 1) {
3956           if (ElementMul.isPowerOf2()) {
3957             unsigned Amt = ElementMul.logBase2();
3958             IdxN = DAG.getNode(ISD::SHL, dl,
3959                                N.getValueType(), IdxN,
3960                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3961           } else {
3962             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3963                                             IdxN.getValueType());
3964             IdxN = DAG.getNode(ISD::MUL, dl,
3965                                N.getValueType(), IdxN, Scale);
3966           }
3967         }
3968       }
3969 
3970       N = DAG.getNode(ISD::ADD, dl,
3971                       N.getValueType(), N, IdxN);
3972     }
3973   }
3974 
3975   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3976   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3977   if (IsVectorGEP) {
3978     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3979     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3980   }
3981 
3982   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3983     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3984 
3985   setValue(&I, N);
3986 }
3987 
3988 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3989   // If this is a fixed sized alloca in the entry block of the function,
3990   // allocate it statically on the stack.
3991   if (FuncInfo.StaticAllocaMap.count(&I))
3992     return;   // getValue will auto-populate this.
3993 
3994   SDLoc dl = getCurSDLoc();
3995   Type *Ty = I.getAllocatedType();
3996   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3997   auto &DL = DAG.getDataLayout();
3998   TypeSize TySize = DL.getTypeAllocSize(Ty);
3999   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4000 
4001   SDValue AllocSize = getValue(I.getArraySize());
4002 
4003   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4004   if (AllocSize.getValueType() != IntPtr)
4005     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4006 
4007   if (TySize.isScalable())
4008     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4009                             DAG.getVScale(dl, IntPtr,
4010                                           APInt(IntPtr.getScalarSizeInBits(),
4011                                                 TySize.getKnownMinValue())));
4012   else
4013     AllocSize =
4014         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4015                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4016 
4017   // Handle alignment.  If the requested alignment is less than or equal to
4018   // the stack alignment, ignore it.  If the size is greater than or equal to
4019   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4020   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4021   if (*Alignment <= StackAlign)
4022     Alignment = None;
4023 
4024   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4025   // Round the size of the allocation up to the stack alignment size
4026   // by add SA-1 to the size. This doesn't overflow because we're computing
4027   // an address inside an alloca.
4028   SDNodeFlags Flags;
4029   Flags.setNoUnsignedWrap(true);
4030   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4031                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4032 
4033   // Mask out the low bits for alignment purposes.
4034   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4035                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4036 
4037   SDValue Ops[] = {
4038       getRoot(), AllocSize,
4039       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4040   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4041   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4042   setValue(&I, DSA);
4043   DAG.setRoot(DSA.getValue(1));
4044 
4045   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4046 }
4047 
4048 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4049   if (I.isAtomic())
4050     return visitAtomicLoad(I);
4051 
4052   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4053   const Value *SV = I.getOperand(0);
4054   if (TLI.supportSwiftError()) {
4055     // Swifterror values can come from either a function parameter with
4056     // swifterror attribute or an alloca with swifterror attribute.
4057     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4058       if (Arg->hasSwiftErrorAttr())
4059         return visitLoadFromSwiftError(I);
4060     }
4061 
4062     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4063       if (Alloca->isSwiftError())
4064         return visitLoadFromSwiftError(I);
4065     }
4066   }
4067 
4068   SDValue Ptr = getValue(SV);
4069 
4070   Type *Ty = I.getType();
4071   Align Alignment = I.getAlign();
4072 
4073   AAMDNodes AAInfo = I.getAAMetadata();
4074   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4075 
4076   SmallVector<EVT, 4> ValueVTs, MemVTs;
4077   SmallVector<uint64_t, 4> Offsets;
4078   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4079   unsigned NumValues = ValueVTs.size();
4080   if (NumValues == 0)
4081     return;
4082 
4083   bool isVolatile = I.isVolatile();
4084 
4085   SDValue Root;
4086   bool ConstantMemory = false;
4087   if (isVolatile)
4088     // Serialize volatile loads with other side effects.
4089     Root = getRoot();
4090   else if (NumValues > MaxParallelChains)
4091     Root = getMemoryRoot();
4092   else if (AA &&
4093            AA->pointsToConstantMemory(MemoryLocation(
4094                SV,
4095                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4096                AAInfo))) {
4097     // Do not serialize (non-volatile) loads of constant memory with anything.
4098     Root = DAG.getEntryNode();
4099     ConstantMemory = true;
4100   } else {
4101     // Do not serialize non-volatile loads against each other.
4102     Root = DAG.getRoot();
4103   }
4104 
4105   SDLoc dl = getCurSDLoc();
4106 
4107   if (isVolatile)
4108     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4109 
4110   // An aggregate load cannot wrap around the address space, so offsets to its
4111   // parts don't wrap either.
4112   SDNodeFlags Flags;
4113   Flags.setNoUnsignedWrap(true);
4114 
4115   SmallVector<SDValue, 4> Values(NumValues);
4116   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4117   EVT PtrVT = Ptr.getValueType();
4118 
4119   MachineMemOperand::Flags MMOFlags
4120     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4121 
4122   unsigned ChainI = 0;
4123   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4124     // Serializing loads here may result in excessive register pressure, and
4125     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4126     // could recover a bit by hoisting nodes upward in the chain by recognizing
4127     // they are side-effect free or do not alias. The optimizer should really
4128     // avoid this case by converting large object/array copies to llvm.memcpy
4129     // (MaxParallelChains should always remain as failsafe).
4130     if (ChainI == MaxParallelChains) {
4131       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4132       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4133                                   makeArrayRef(Chains.data(), ChainI));
4134       Root = Chain;
4135       ChainI = 0;
4136     }
4137     SDValue A = DAG.getNode(ISD::ADD, dl,
4138                             PtrVT, Ptr,
4139                             DAG.getConstant(Offsets[i], dl, PtrVT),
4140                             Flags);
4141 
4142     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4143                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4144                             MMOFlags, AAInfo, Ranges);
4145     Chains[ChainI] = L.getValue(1);
4146 
4147     if (MemVTs[i] != ValueVTs[i])
4148       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4149 
4150     Values[i] = L;
4151   }
4152 
4153   if (!ConstantMemory) {
4154     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4155                                 makeArrayRef(Chains.data(), ChainI));
4156     if (isVolatile)
4157       DAG.setRoot(Chain);
4158     else
4159       PendingLoads.push_back(Chain);
4160   }
4161 
4162   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4163                            DAG.getVTList(ValueVTs), Values));
4164 }
4165 
4166 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4167   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4168          "call visitStoreToSwiftError when backend supports swifterror");
4169 
4170   SmallVector<EVT, 4> ValueVTs;
4171   SmallVector<uint64_t, 4> Offsets;
4172   const Value *SrcV = I.getOperand(0);
4173   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4174                   SrcV->getType(), ValueVTs, &Offsets);
4175   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4176          "expect a single EVT for swifterror");
4177 
4178   SDValue Src = getValue(SrcV);
4179   // Create a virtual register, then update the virtual register.
4180   Register VReg =
4181       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4182   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4183   // Chain can be getRoot or getControlRoot.
4184   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4185                                       SDValue(Src.getNode(), Src.getResNo()));
4186   DAG.setRoot(CopyNode);
4187 }
4188 
4189 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4190   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4191          "call visitLoadFromSwiftError when backend supports swifterror");
4192 
4193   assert(!I.isVolatile() &&
4194          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4195          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4196          "Support volatile, non temporal, invariant for load_from_swift_error");
4197 
4198   const Value *SV = I.getOperand(0);
4199   Type *Ty = I.getType();
4200   assert(
4201       (!AA ||
4202        !AA->pointsToConstantMemory(MemoryLocation(
4203            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4204            I.getAAMetadata()))) &&
4205       "load_from_swift_error should not be constant memory");
4206 
4207   SmallVector<EVT, 4> ValueVTs;
4208   SmallVector<uint64_t, 4> Offsets;
4209   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4210                   ValueVTs, &Offsets);
4211   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4212          "expect a single EVT for swifterror");
4213 
4214   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4215   SDValue L = DAG.getCopyFromReg(
4216       getRoot(), getCurSDLoc(),
4217       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4218 
4219   setValue(&I, L);
4220 }
4221 
4222 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4223   if (I.isAtomic())
4224     return visitAtomicStore(I);
4225 
4226   const Value *SrcV = I.getOperand(0);
4227   const Value *PtrV = I.getOperand(1);
4228 
4229   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4230   if (TLI.supportSwiftError()) {
4231     // Swifterror values can come from either a function parameter with
4232     // swifterror attribute or an alloca with swifterror attribute.
4233     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4234       if (Arg->hasSwiftErrorAttr())
4235         return visitStoreToSwiftError(I);
4236     }
4237 
4238     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4239       if (Alloca->isSwiftError())
4240         return visitStoreToSwiftError(I);
4241     }
4242   }
4243 
4244   SmallVector<EVT, 4> ValueVTs, MemVTs;
4245   SmallVector<uint64_t, 4> Offsets;
4246   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4247                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4248   unsigned NumValues = ValueVTs.size();
4249   if (NumValues == 0)
4250     return;
4251 
4252   // Get the lowered operands. Note that we do this after
4253   // checking if NumResults is zero, because with zero results
4254   // the operands won't have values in the map.
4255   SDValue Src = getValue(SrcV);
4256   SDValue Ptr = getValue(PtrV);
4257 
4258   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4259   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4260   SDLoc dl = getCurSDLoc();
4261   Align Alignment = I.getAlign();
4262   AAMDNodes AAInfo = I.getAAMetadata();
4263 
4264   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4265 
4266   // An aggregate load cannot wrap around the address space, so offsets to its
4267   // parts don't wrap either.
4268   SDNodeFlags Flags;
4269   Flags.setNoUnsignedWrap(true);
4270 
4271   unsigned ChainI = 0;
4272   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4273     // See visitLoad comments.
4274     if (ChainI == MaxParallelChains) {
4275       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4276                                   makeArrayRef(Chains.data(), ChainI));
4277       Root = Chain;
4278       ChainI = 0;
4279     }
4280     SDValue Add =
4281         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4282     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4283     if (MemVTs[i] != ValueVTs[i])
4284       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4285     SDValue St =
4286         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4287                      Alignment, MMOFlags, AAInfo);
4288     Chains[ChainI] = St;
4289   }
4290 
4291   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4292                                   makeArrayRef(Chains.data(), ChainI));
4293   DAG.setRoot(StoreNode);
4294 }
4295 
4296 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4297                                            bool IsCompressing) {
4298   SDLoc sdl = getCurSDLoc();
4299 
4300   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4301                                MaybeAlign &Alignment) {
4302     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4303     Src0 = I.getArgOperand(0);
4304     Ptr = I.getArgOperand(1);
4305     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4306     Mask = I.getArgOperand(3);
4307   };
4308   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4309                                     MaybeAlign &Alignment) {
4310     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4311     Src0 = I.getArgOperand(0);
4312     Ptr = I.getArgOperand(1);
4313     Mask = I.getArgOperand(2);
4314     Alignment = None;
4315   };
4316 
4317   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4318   MaybeAlign Alignment;
4319   if (IsCompressing)
4320     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4321   else
4322     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4323 
4324   SDValue Ptr = getValue(PtrOperand);
4325   SDValue Src0 = getValue(Src0Operand);
4326   SDValue Mask = getValue(MaskOperand);
4327   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4328 
4329   EVT VT = Src0.getValueType();
4330   if (!Alignment)
4331     Alignment = DAG.getEVTAlign(VT);
4332 
4333   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4334       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4335       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4336   SDValue StoreNode =
4337       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4338                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4339   DAG.setRoot(StoreNode);
4340   setValue(&I, StoreNode);
4341 }
4342 
4343 // Get a uniform base for the Gather/Scatter intrinsic.
4344 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4345 // We try to represent it as a base pointer + vector of indices.
4346 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4347 // The first operand of the GEP may be a single pointer or a vector of pointers
4348 // Example:
4349 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4350 //  or
4351 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4352 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4353 //
4354 // When the first GEP operand is a single pointer - it is the uniform base we
4355 // are looking for. If first operand of the GEP is a splat vector - we
4356 // extract the splat value and use it as a uniform base.
4357 // In all other cases the function returns 'false'.
4358 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4359                            ISD::MemIndexType &IndexType, SDValue &Scale,
4360                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4361   SelectionDAG& DAG = SDB->DAG;
4362   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4363   const DataLayout &DL = DAG.getDataLayout();
4364 
4365   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4366 
4367   // Handle splat constant pointer.
4368   if (auto *C = dyn_cast<Constant>(Ptr)) {
4369     C = C->getSplatValue();
4370     if (!C)
4371       return false;
4372 
4373     Base = SDB->getValue(C);
4374 
4375     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4376     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4377     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4378     IndexType = ISD::SIGNED_SCALED;
4379     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4380     return true;
4381   }
4382 
4383   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4384   if (!GEP || GEP->getParent() != CurBB)
4385     return false;
4386 
4387   if (GEP->getNumOperands() != 2)
4388     return false;
4389 
4390   const Value *BasePtr = GEP->getPointerOperand();
4391   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4392 
4393   // Make sure the base is scalar and the index is a vector.
4394   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4395     return false;
4396 
4397   Base = SDB->getValue(BasePtr);
4398   Index = SDB->getValue(IndexVal);
4399   IndexType = ISD::SIGNED_SCALED;
4400   Scale = DAG.getTargetConstant(
4401               DL.getTypeAllocSize(GEP->getResultElementType()),
4402               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4403   return true;
4404 }
4405 
4406 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4407   SDLoc sdl = getCurSDLoc();
4408 
4409   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4410   const Value *Ptr = I.getArgOperand(1);
4411   SDValue Src0 = getValue(I.getArgOperand(0));
4412   SDValue Mask = getValue(I.getArgOperand(3));
4413   EVT VT = Src0.getValueType();
4414   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4415                         ->getMaybeAlignValue()
4416                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4417   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4418 
4419   SDValue Base;
4420   SDValue Index;
4421   ISD::MemIndexType IndexType;
4422   SDValue Scale;
4423   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4424                                     I.getParent());
4425 
4426   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4427   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4428       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4429       // TODO: Make MachineMemOperands aware of scalable
4430       // vectors.
4431       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4432   if (!UniformBase) {
4433     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4434     Index = getValue(Ptr);
4435     IndexType = ISD::SIGNED_UNSCALED;
4436     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4437   }
4438 
4439   EVT IdxVT = Index.getValueType();
4440   EVT EltTy = IdxVT.getVectorElementType();
4441   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4442     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4443     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4444   }
4445 
4446   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4447   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4448                                          Ops, MMO, IndexType, false);
4449   DAG.setRoot(Scatter);
4450   setValue(&I, Scatter);
4451 }
4452 
4453 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4454   SDLoc sdl = getCurSDLoc();
4455 
4456   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4457                               MaybeAlign &Alignment) {
4458     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4459     Ptr = I.getArgOperand(0);
4460     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4461     Mask = I.getArgOperand(2);
4462     Src0 = I.getArgOperand(3);
4463   };
4464   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4465                                  MaybeAlign &Alignment) {
4466     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4467     Ptr = I.getArgOperand(0);
4468     Alignment = None;
4469     Mask = I.getArgOperand(1);
4470     Src0 = I.getArgOperand(2);
4471   };
4472 
4473   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4474   MaybeAlign Alignment;
4475   if (IsExpanding)
4476     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4477   else
4478     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4479 
4480   SDValue Ptr = getValue(PtrOperand);
4481   SDValue Src0 = getValue(Src0Operand);
4482   SDValue Mask = getValue(MaskOperand);
4483   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4484 
4485   EVT VT = Src0.getValueType();
4486   if (!Alignment)
4487     Alignment = DAG.getEVTAlign(VT);
4488 
4489   AAMDNodes AAInfo = I.getAAMetadata();
4490   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4491 
4492   // Do not serialize masked loads of constant memory with anything.
4493   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4494   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4495 
4496   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4497 
4498   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4499       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4500       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4501 
4502   SDValue Load =
4503       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4504                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4505   if (AddToChain)
4506     PendingLoads.push_back(Load.getValue(1));
4507   setValue(&I, Load);
4508 }
4509 
4510 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4511   SDLoc sdl = getCurSDLoc();
4512 
4513   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4514   const Value *Ptr = I.getArgOperand(0);
4515   SDValue Src0 = getValue(I.getArgOperand(3));
4516   SDValue Mask = getValue(I.getArgOperand(2));
4517 
4518   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4519   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4520   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4521                         ->getMaybeAlignValue()
4522                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4523 
4524   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4525 
4526   SDValue Root = DAG.getRoot();
4527   SDValue Base;
4528   SDValue Index;
4529   ISD::MemIndexType IndexType;
4530   SDValue Scale;
4531   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4532                                     I.getParent());
4533   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4534   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4535       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4536       // TODO: Make MachineMemOperands aware of scalable
4537       // vectors.
4538       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4539 
4540   if (!UniformBase) {
4541     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4542     Index = getValue(Ptr);
4543     IndexType = ISD::SIGNED_UNSCALED;
4544     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4545   }
4546 
4547   EVT IdxVT = Index.getValueType();
4548   EVT EltTy = IdxVT.getVectorElementType();
4549   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4550     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4551     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4552   }
4553 
4554   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4555   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4556                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4557 
4558   PendingLoads.push_back(Gather.getValue(1));
4559   setValue(&I, Gather);
4560 }
4561 
4562 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4563   SDLoc dl = getCurSDLoc();
4564   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4565   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4566   SyncScope::ID SSID = I.getSyncScopeID();
4567 
4568   SDValue InChain = getRoot();
4569 
4570   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4571   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4572 
4573   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4574   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4575 
4576   MachineFunction &MF = DAG.getMachineFunction();
4577   MachineMemOperand *MMO = MF.getMachineMemOperand(
4578       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4579       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4580       FailureOrdering);
4581 
4582   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4583                                    dl, MemVT, VTs, InChain,
4584                                    getValue(I.getPointerOperand()),
4585                                    getValue(I.getCompareOperand()),
4586                                    getValue(I.getNewValOperand()), MMO);
4587 
4588   SDValue OutChain = L.getValue(2);
4589 
4590   setValue(&I, L);
4591   DAG.setRoot(OutChain);
4592 }
4593 
4594 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4595   SDLoc dl = getCurSDLoc();
4596   ISD::NodeType NT;
4597   switch (I.getOperation()) {
4598   default: llvm_unreachable("Unknown atomicrmw operation");
4599   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4600   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4601   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4602   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4603   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4604   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4605   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4606   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4607   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4608   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4609   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4610   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4611   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4612   }
4613   AtomicOrdering Ordering = I.getOrdering();
4614   SyncScope::ID SSID = I.getSyncScopeID();
4615 
4616   SDValue InChain = getRoot();
4617 
4618   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4619   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4620   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4621 
4622   MachineFunction &MF = DAG.getMachineFunction();
4623   MachineMemOperand *MMO = MF.getMachineMemOperand(
4624       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4625       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4626 
4627   SDValue L =
4628     DAG.getAtomic(NT, dl, MemVT, InChain,
4629                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4630                   MMO);
4631 
4632   SDValue OutChain = L.getValue(1);
4633 
4634   setValue(&I, L);
4635   DAG.setRoot(OutChain);
4636 }
4637 
4638 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4639   SDLoc dl = getCurSDLoc();
4640   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4641   SDValue Ops[3];
4642   Ops[0] = getRoot();
4643   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4644                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4645   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4646                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4647   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4648 }
4649 
4650 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4651   SDLoc dl = getCurSDLoc();
4652   AtomicOrdering Order = I.getOrdering();
4653   SyncScope::ID SSID = I.getSyncScopeID();
4654 
4655   SDValue InChain = getRoot();
4656 
4657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4658   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4659   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4660 
4661   if (!TLI.supportsUnalignedAtomics() &&
4662       I.getAlignment() < MemVT.getSizeInBits() / 8)
4663     report_fatal_error("Cannot generate unaligned atomic load");
4664 
4665   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4666 
4667   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4668       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4669       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4670 
4671   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4672 
4673   SDValue Ptr = getValue(I.getPointerOperand());
4674 
4675   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4676     // TODO: Once this is better exercised by tests, it should be merged with
4677     // the normal path for loads to prevent future divergence.
4678     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4679     if (MemVT != VT)
4680       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4681 
4682     setValue(&I, L);
4683     SDValue OutChain = L.getValue(1);
4684     if (!I.isUnordered())
4685       DAG.setRoot(OutChain);
4686     else
4687       PendingLoads.push_back(OutChain);
4688     return;
4689   }
4690 
4691   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4692                             Ptr, MMO);
4693 
4694   SDValue OutChain = L.getValue(1);
4695   if (MemVT != VT)
4696     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4697 
4698   setValue(&I, L);
4699   DAG.setRoot(OutChain);
4700 }
4701 
4702 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4703   SDLoc dl = getCurSDLoc();
4704 
4705   AtomicOrdering Ordering = I.getOrdering();
4706   SyncScope::ID SSID = I.getSyncScopeID();
4707 
4708   SDValue InChain = getRoot();
4709 
4710   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4711   EVT MemVT =
4712       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4713 
4714   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4715     report_fatal_error("Cannot generate unaligned atomic store");
4716 
4717   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4718 
4719   MachineFunction &MF = DAG.getMachineFunction();
4720   MachineMemOperand *MMO = MF.getMachineMemOperand(
4721       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4722       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4723 
4724   SDValue Val = getValue(I.getValueOperand());
4725   if (Val.getValueType() != MemVT)
4726     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4727   SDValue Ptr = getValue(I.getPointerOperand());
4728 
4729   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4730     // TODO: Once this is better exercised by tests, it should be merged with
4731     // the normal path for stores to prevent future divergence.
4732     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4733     DAG.setRoot(S);
4734     return;
4735   }
4736   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4737                                    Ptr, Val, MMO);
4738 
4739 
4740   DAG.setRoot(OutChain);
4741 }
4742 
4743 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4744 /// node.
4745 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4746                                                unsigned Intrinsic) {
4747   // Ignore the callsite's attributes. A specific call site may be marked with
4748   // readnone, but the lowering code will expect the chain based on the
4749   // definition.
4750   const Function *F = I.getCalledFunction();
4751   bool HasChain = !F->doesNotAccessMemory();
4752   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4753 
4754   // Build the operand list.
4755   SmallVector<SDValue, 8> Ops;
4756   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4757     if (OnlyLoad) {
4758       // We don't need to serialize loads against other loads.
4759       Ops.push_back(DAG.getRoot());
4760     } else {
4761       Ops.push_back(getRoot());
4762     }
4763   }
4764 
4765   // Info is set by getTgtMemInstrinsic
4766   TargetLowering::IntrinsicInfo Info;
4767   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4768   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4769                                                DAG.getMachineFunction(),
4770                                                Intrinsic);
4771 
4772   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4773   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4774       Info.opc == ISD::INTRINSIC_W_CHAIN)
4775     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4776                                         TLI.getPointerTy(DAG.getDataLayout())));
4777 
4778   // Add all operands of the call to the operand list.
4779   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4780     const Value *Arg = I.getArgOperand(i);
4781     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4782       Ops.push_back(getValue(Arg));
4783       continue;
4784     }
4785 
4786     // Use TargetConstant instead of a regular constant for immarg.
4787     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4788     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4789       assert(CI->getBitWidth() <= 64 &&
4790              "large intrinsic immediates not handled");
4791       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4792     } else {
4793       Ops.push_back(
4794           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4795     }
4796   }
4797 
4798   SmallVector<EVT, 4> ValueVTs;
4799   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4800 
4801   if (HasChain)
4802     ValueVTs.push_back(MVT::Other);
4803 
4804   SDVTList VTs = DAG.getVTList(ValueVTs);
4805 
4806   // Propagate fast-math-flags from IR to node(s).
4807   SDNodeFlags Flags;
4808   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4809     Flags.copyFMF(*FPMO);
4810   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4811 
4812   // Create the node.
4813   SDValue Result;
4814   if (IsTgtIntrinsic) {
4815     // This is target intrinsic that touches memory
4816     Result =
4817         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4818                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4819                                 Info.align, Info.flags, Info.size,
4820                                 I.getAAMetadata());
4821   } else if (!HasChain) {
4822     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4823   } else if (!I.getType()->isVoidTy()) {
4824     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4825   } else {
4826     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4827   }
4828 
4829   if (HasChain) {
4830     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4831     if (OnlyLoad)
4832       PendingLoads.push_back(Chain);
4833     else
4834       DAG.setRoot(Chain);
4835   }
4836 
4837   if (!I.getType()->isVoidTy()) {
4838     if (!isa<VectorType>(I.getType()))
4839       Result = lowerRangeToAssertZExt(DAG, I, Result);
4840 
4841     MaybeAlign Alignment = I.getRetAlign();
4842     if (!Alignment)
4843       Alignment = F->getAttributes().getRetAlignment();
4844     // Insert `assertalign` node if there's an alignment.
4845     if (InsertAssertAlign && Alignment) {
4846       Result =
4847           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4848     }
4849 
4850     setValue(&I, Result);
4851   }
4852 }
4853 
4854 /// GetSignificand - Get the significand and build it into a floating-point
4855 /// number with exponent of 1:
4856 ///
4857 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4858 ///
4859 /// where Op is the hexadecimal representation of floating point value.
4860 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4861   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4862                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4863   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4864                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4865   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4866 }
4867 
4868 /// GetExponent - Get the exponent:
4869 ///
4870 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4871 ///
4872 /// where Op is the hexadecimal representation of floating point value.
4873 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4874                            const TargetLowering &TLI, const SDLoc &dl) {
4875   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4876                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4877   SDValue t1 = DAG.getNode(
4878       ISD::SRL, dl, MVT::i32, t0,
4879       DAG.getConstant(23, dl,
4880                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
4881   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4882                            DAG.getConstant(127, dl, MVT::i32));
4883   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4884 }
4885 
4886 /// getF32Constant - Get 32-bit floating point constant.
4887 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4888                               const SDLoc &dl) {
4889   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4890                            MVT::f32);
4891 }
4892 
4893 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4894                                        SelectionDAG &DAG) {
4895   // TODO: What fast-math-flags should be set on the floating-point nodes?
4896 
4897   //   IntegerPartOfX = ((int32_t)(t0);
4898   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4899 
4900   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4901   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4902   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4903 
4904   //   IntegerPartOfX <<= 23;
4905   IntegerPartOfX =
4906       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4907                   DAG.getConstant(23, dl,
4908                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
4909                                       MVT::i32, DAG.getDataLayout())));
4910 
4911   SDValue TwoToFractionalPartOfX;
4912   if (LimitFloatPrecision <= 6) {
4913     // For floating-point precision of 6:
4914     //
4915     //   TwoToFractionalPartOfX =
4916     //     0.997535578f +
4917     //       (0.735607626f + 0.252464424f * x) * x;
4918     //
4919     // error 0.0144103317, which is 6 bits
4920     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4921                              getF32Constant(DAG, 0x3e814304, dl));
4922     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4923                              getF32Constant(DAG, 0x3f3c50c8, dl));
4924     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4925     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4926                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4927   } else if (LimitFloatPrecision <= 12) {
4928     // For floating-point precision of 12:
4929     //
4930     //   TwoToFractionalPartOfX =
4931     //     0.999892986f +
4932     //       (0.696457318f +
4933     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4934     //
4935     // error 0.000107046256, which is 13 to 14 bits
4936     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4937                              getF32Constant(DAG, 0x3da235e3, dl));
4938     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4939                              getF32Constant(DAG, 0x3e65b8f3, dl));
4940     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4941     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4942                              getF32Constant(DAG, 0x3f324b07, dl));
4943     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4944     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4945                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4946   } else { // LimitFloatPrecision <= 18
4947     // For floating-point precision of 18:
4948     //
4949     //   TwoToFractionalPartOfX =
4950     //     0.999999982f +
4951     //       (0.693148872f +
4952     //         (0.240227044f +
4953     //           (0.554906021e-1f +
4954     //             (0.961591928e-2f +
4955     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4956     // error 2.47208000*10^(-7), which is better than 18 bits
4957     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4958                              getF32Constant(DAG, 0x3924b03e, dl));
4959     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4960                              getF32Constant(DAG, 0x3ab24b87, dl));
4961     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4962     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4963                              getF32Constant(DAG, 0x3c1d8c17, dl));
4964     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4965     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4966                              getF32Constant(DAG, 0x3d634a1d, dl));
4967     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4968     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4969                              getF32Constant(DAG, 0x3e75fe14, dl));
4970     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4971     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4972                               getF32Constant(DAG, 0x3f317234, dl));
4973     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4974     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4975                                          getF32Constant(DAG, 0x3f800000, dl));
4976   }
4977 
4978   // Add the exponent into the result in integer domain.
4979   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4980   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4981                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4982 }
4983 
4984 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4985 /// limited-precision mode.
4986 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4987                          const TargetLowering &TLI, SDNodeFlags Flags) {
4988   if (Op.getValueType() == MVT::f32 &&
4989       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4990 
4991     // Put the exponent in the right bit position for later addition to the
4992     // final result:
4993     //
4994     // t0 = Op * log2(e)
4995 
4996     // TODO: What fast-math-flags should be set here?
4997     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4998                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4999     return getLimitedPrecisionExp2(t0, dl, DAG);
5000   }
5001 
5002   // No special expansion.
5003   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5004 }
5005 
5006 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5007 /// limited-precision mode.
5008 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5009                          const TargetLowering &TLI, SDNodeFlags Flags) {
5010   // TODO: What fast-math-flags should be set on the floating-point nodes?
5011 
5012   if (Op.getValueType() == MVT::f32 &&
5013       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5014     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5015 
5016     // Scale the exponent by log(2).
5017     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5018     SDValue LogOfExponent =
5019         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5020                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5021 
5022     // Get the significand and build it into a floating-point number with
5023     // exponent of 1.
5024     SDValue X = GetSignificand(DAG, Op1, dl);
5025 
5026     SDValue LogOfMantissa;
5027     if (LimitFloatPrecision <= 6) {
5028       // For floating-point precision of 6:
5029       //
5030       //   LogofMantissa =
5031       //     -1.1609546f +
5032       //       (1.4034025f - 0.23903021f * x) * x;
5033       //
5034       // error 0.0034276066, which is better than 8 bits
5035       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5036                                getF32Constant(DAG, 0xbe74c456, dl));
5037       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5038                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5039       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5040       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5041                                   getF32Constant(DAG, 0x3f949a29, dl));
5042     } else if (LimitFloatPrecision <= 12) {
5043       // For floating-point precision of 12:
5044       //
5045       //   LogOfMantissa =
5046       //     -1.7417939f +
5047       //       (2.8212026f +
5048       //         (-1.4699568f +
5049       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5050       //
5051       // error 0.000061011436, which is 14 bits
5052       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5053                                getF32Constant(DAG, 0xbd67b6d6, dl));
5054       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5055                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5056       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5057       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5058                                getF32Constant(DAG, 0x3fbc278b, dl));
5059       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5060       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5061                                getF32Constant(DAG, 0x40348e95, dl));
5062       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5063       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5064                                   getF32Constant(DAG, 0x3fdef31a, dl));
5065     } else { // LimitFloatPrecision <= 18
5066       // For floating-point precision of 18:
5067       //
5068       //   LogOfMantissa =
5069       //     -2.1072184f +
5070       //       (4.2372794f +
5071       //         (-3.7029485f +
5072       //           (2.2781945f +
5073       //             (-0.87823314f +
5074       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5075       //
5076       // error 0.0000023660568, which is better than 18 bits
5077       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5078                                getF32Constant(DAG, 0xbc91e5ac, dl));
5079       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5080                                getF32Constant(DAG, 0x3e4350aa, dl));
5081       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5082       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5083                                getF32Constant(DAG, 0x3f60d3e3, dl));
5084       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5085       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5086                                getF32Constant(DAG, 0x4011cdf0, dl));
5087       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5088       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5089                                getF32Constant(DAG, 0x406cfd1c, dl));
5090       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5091       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5092                                getF32Constant(DAG, 0x408797cb, dl));
5093       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5094       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5095                                   getF32Constant(DAG, 0x4006dcab, dl));
5096     }
5097 
5098     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5099   }
5100 
5101   // No special expansion.
5102   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5103 }
5104 
5105 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5106 /// limited-precision mode.
5107 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5108                           const TargetLowering &TLI, SDNodeFlags Flags) {
5109   // TODO: What fast-math-flags should be set on the floating-point nodes?
5110 
5111   if (Op.getValueType() == MVT::f32 &&
5112       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5113     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5114 
5115     // Get the exponent.
5116     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5117 
5118     // Get the significand and build it into a floating-point number with
5119     // exponent of 1.
5120     SDValue X = GetSignificand(DAG, Op1, dl);
5121 
5122     // Different possible minimax approximations of significand in
5123     // floating-point for various degrees of accuracy over [1,2].
5124     SDValue Log2ofMantissa;
5125     if (LimitFloatPrecision <= 6) {
5126       // For floating-point precision of 6:
5127       //
5128       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5129       //
5130       // error 0.0049451742, which is more than 7 bits
5131       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5132                                getF32Constant(DAG, 0xbeb08fe0, dl));
5133       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5134                                getF32Constant(DAG, 0x40019463, dl));
5135       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5136       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5137                                    getF32Constant(DAG, 0x3fd6633d, dl));
5138     } else if (LimitFloatPrecision <= 12) {
5139       // For floating-point precision of 12:
5140       //
5141       //   Log2ofMantissa =
5142       //     -2.51285454f +
5143       //       (4.07009056f +
5144       //         (-2.12067489f +
5145       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5146       //
5147       // error 0.0000876136000, which is better than 13 bits
5148       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5149                                getF32Constant(DAG, 0xbda7262e, dl));
5150       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5151                                getF32Constant(DAG, 0x3f25280b, dl));
5152       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5153       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5154                                getF32Constant(DAG, 0x4007b923, dl));
5155       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5156       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5157                                getF32Constant(DAG, 0x40823e2f, dl));
5158       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5159       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5160                                    getF32Constant(DAG, 0x4020d29c, dl));
5161     } else { // LimitFloatPrecision <= 18
5162       // For floating-point precision of 18:
5163       //
5164       //   Log2ofMantissa =
5165       //     -3.0400495f +
5166       //       (6.1129976f +
5167       //         (-5.3420409f +
5168       //           (3.2865683f +
5169       //             (-1.2669343f +
5170       //               (0.27515199f -
5171       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5172       //
5173       // error 0.0000018516, which is better than 18 bits
5174       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5175                                getF32Constant(DAG, 0xbcd2769e, dl));
5176       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5177                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5178       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5179       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5180                                getF32Constant(DAG, 0x3fa22ae7, dl));
5181       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5182       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5183                                getF32Constant(DAG, 0x40525723, dl));
5184       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5185       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5186                                getF32Constant(DAG, 0x40aaf200, dl));
5187       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5188       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5189                                getF32Constant(DAG, 0x40c39dad, dl));
5190       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5191       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5192                                    getF32Constant(DAG, 0x4042902c, dl));
5193     }
5194 
5195     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5196   }
5197 
5198   // No special expansion.
5199   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5200 }
5201 
5202 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5203 /// limited-precision mode.
5204 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5205                            const TargetLowering &TLI, SDNodeFlags Flags) {
5206   // TODO: What fast-math-flags should be set on the floating-point nodes?
5207 
5208   if (Op.getValueType() == MVT::f32 &&
5209       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5210     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5211 
5212     // Scale the exponent by log10(2) [0.30102999f].
5213     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5214     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5215                                         getF32Constant(DAG, 0x3e9a209a, dl));
5216 
5217     // Get the significand and build it into a floating-point number with
5218     // exponent of 1.
5219     SDValue X = GetSignificand(DAG, Op1, dl);
5220 
5221     SDValue Log10ofMantissa;
5222     if (LimitFloatPrecision <= 6) {
5223       // For floating-point precision of 6:
5224       //
5225       //   Log10ofMantissa =
5226       //     -0.50419619f +
5227       //       (0.60948995f - 0.10380950f * x) * x;
5228       //
5229       // error 0.0014886165, which is 6 bits
5230       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5231                                getF32Constant(DAG, 0xbdd49a13, dl));
5232       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5233                                getF32Constant(DAG, 0x3f1c0789, dl));
5234       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5235       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5236                                     getF32Constant(DAG, 0x3f011300, dl));
5237     } else if (LimitFloatPrecision <= 12) {
5238       // For floating-point precision of 12:
5239       //
5240       //   Log10ofMantissa =
5241       //     -0.64831180f +
5242       //       (0.91751397f +
5243       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5244       //
5245       // error 0.00019228036, which is better than 12 bits
5246       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5247                                getF32Constant(DAG, 0x3d431f31, dl));
5248       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5249                                getF32Constant(DAG, 0x3ea21fb2, dl));
5250       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5251       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5252                                getF32Constant(DAG, 0x3f6ae232, dl));
5253       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5254       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5255                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5256     } else { // LimitFloatPrecision <= 18
5257       // For floating-point precision of 18:
5258       //
5259       //   Log10ofMantissa =
5260       //     -0.84299375f +
5261       //       (1.5327582f +
5262       //         (-1.0688956f +
5263       //           (0.49102474f +
5264       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5265       //
5266       // error 0.0000037995730, which is better than 18 bits
5267       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5268                                getF32Constant(DAG, 0x3c5d51ce, dl));
5269       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5270                                getF32Constant(DAG, 0x3e00685a, dl));
5271       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5272       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5273                                getF32Constant(DAG, 0x3efb6798, dl));
5274       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5275       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5276                                getF32Constant(DAG, 0x3f88d192, dl));
5277       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5278       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5279                                getF32Constant(DAG, 0x3fc4316c, dl));
5280       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5281       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5282                                     getF32Constant(DAG, 0x3f57ce70, dl));
5283     }
5284 
5285     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5286   }
5287 
5288   // No special expansion.
5289   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5290 }
5291 
5292 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5293 /// limited-precision mode.
5294 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5295                           const TargetLowering &TLI, SDNodeFlags Flags) {
5296   if (Op.getValueType() == MVT::f32 &&
5297       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5298     return getLimitedPrecisionExp2(Op, dl, DAG);
5299 
5300   // No special expansion.
5301   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5302 }
5303 
5304 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5305 /// limited-precision mode with x == 10.0f.
5306 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5307                          SelectionDAG &DAG, const TargetLowering &TLI,
5308                          SDNodeFlags Flags) {
5309   bool IsExp10 = false;
5310   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5311       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5312     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5313       APFloat Ten(10.0f);
5314       IsExp10 = LHSC->isExactlyValue(Ten);
5315     }
5316   }
5317 
5318   // TODO: What fast-math-flags should be set on the FMUL node?
5319   if (IsExp10) {
5320     // Put the exponent in the right bit position for later addition to the
5321     // final result:
5322     //
5323     //   #define LOG2OF10 3.3219281f
5324     //   t0 = Op * LOG2OF10;
5325     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5326                              getF32Constant(DAG, 0x40549a78, dl));
5327     return getLimitedPrecisionExp2(t0, dl, DAG);
5328   }
5329 
5330   // No special expansion.
5331   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5332 }
5333 
5334 /// ExpandPowI - Expand a llvm.powi intrinsic.
5335 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5336                           SelectionDAG &DAG) {
5337   // If RHS is a constant, we can expand this out to a multiplication tree,
5338   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5339   // optimizing for size, we only want to do this if the expansion would produce
5340   // a small number of multiplies, otherwise we do the full expansion.
5341   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5342     // Get the exponent as a positive value.
5343     unsigned Val = RHSC->getSExtValue();
5344     if ((int)Val < 0) Val = -Val;
5345 
5346     // powi(x, 0) -> 1.0
5347     if (Val == 0)
5348       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5349 
5350     bool OptForSize = DAG.shouldOptForSize();
5351     if (!OptForSize ||
5352         // If optimizing for size, don't insert too many multiplies.
5353         // This inserts up to 5 multiplies.
5354         countPopulation(Val) + Log2_32(Val) < 7) {
5355       // We use the simple binary decomposition method to generate the multiply
5356       // sequence.  There are more optimal ways to do this (for example,
5357       // powi(x,15) generates one more multiply than it should), but this has
5358       // the benefit of being both really simple and much better than a libcall.
5359       SDValue Res;  // Logically starts equal to 1.0
5360       SDValue CurSquare = LHS;
5361       // TODO: Intrinsics should have fast-math-flags that propagate to these
5362       // nodes.
5363       while (Val) {
5364         if (Val & 1) {
5365           if (Res.getNode())
5366             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5367           else
5368             Res = CurSquare;  // 1.0*CurSquare.
5369         }
5370 
5371         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5372                                 CurSquare, CurSquare);
5373         Val >>= 1;
5374       }
5375 
5376       // If the original was negative, invert the result, producing 1/(x*x*x).
5377       if (RHSC->getSExtValue() < 0)
5378         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5379                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5380       return Res;
5381     }
5382   }
5383 
5384   // Otherwise, expand to a libcall.
5385   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5386 }
5387 
5388 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5389                             SDValue LHS, SDValue RHS, SDValue Scale,
5390                             SelectionDAG &DAG, const TargetLowering &TLI) {
5391   EVT VT = LHS.getValueType();
5392   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5393   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5394   LLVMContext &Ctx = *DAG.getContext();
5395 
5396   // If the type is legal but the operation isn't, this node might survive all
5397   // the way to operation legalization. If we end up there and we do not have
5398   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5399   // node.
5400 
5401   // Coax the legalizer into expanding the node during type legalization instead
5402   // by bumping the size by one bit. This will force it to Promote, enabling the
5403   // early expansion and avoiding the need to expand later.
5404 
5405   // We don't have to do this if Scale is 0; that can always be expanded, unless
5406   // it's a saturating signed operation. Those can experience true integer
5407   // division overflow, a case which we must avoid.
5408 
5409   // FIXME: We wouldn't have to do this (or any of the early
5410   // expansion/promotion) if it was possible to expand a libcall of an
5411   // illegal type during operation legalization. But it's not, so things
5412   // get a bit hacky.
5413   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5414   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5415       (TLI.isTypeLegal(VT) ||
5416        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5417     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5418         Opcode, VT, ScaleInt);
5419     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5420       EVT PromVT;
5421       if (VT.isScalarInteger())
5422         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5423       else if (VT.isVector()) {
5424         PromVT = VT.getVectorElementType();
5425         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5426         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5427       } else
5428         llvm_unreachable("Wrong VT for DIVFIX?");
5429       if (Signed) {
5430         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5431         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5432       } else {
5433         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5434         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5435       }
5436       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5437       // For saturating operations, we need to shift up the LHS to get the
5438       // proper saturation width, and then shift down again afterwards.
5439       if (Saturating)
5440         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5441                           DAG.getConstant(1, DL, ShiftTy));
5442       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5443       if (Saturating)
5444         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5445                           DAG.getConstant(1, DL, ShiftTy));
5446       return DAG.getZExtOrTrunc(Res, DL, VT);
5447     }
5448   }
5449 
5450   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5451 }
5452 
5453 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5454 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5455 static void
5456 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5457                      const SDValue &N) {
5458   switch (N.getOpcode()) {
5459   case ISD::CopyFromReg: {
5460     SDValue Op = N.getOperand(1);
5461     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5462                       Op.getValueType().getSizeInBits());
5463     return;
5464   }
5465   case ISD::BITCAST:
5466   case ISD::AssertZext:
5467   case ISD::AssertSext:
5468   case ISD::TRUNCATE:
5469     getUnderlyingArgRegs(Regs, N.getOperand(0));
5470     return;
5471   case ISD::BUILD_PAIR:
5472   case ISD::BUILD_VECTOR:
5473   case ISD::CONCAT_VECTORS:
5474     for (SDValue Op : N->op_values())
5475       getUnderlyingArgRegs(Regs, Op);
5476     return;
5477   default:
5478     return;
5479   }
5480 }
5481 
5482 /// If the DbgValueInst is a dbg_value of a function argument, create the
5483 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5484 /// instruction selection, they will be inserted to the entry BB.
5485 /// We don't currently support this for variadic dbg_values, as they shouldn't
5486 /// appear for function arguments or in the prologue.
5487 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5488     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5489     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5490   const Argument *Arg = dyn_cast<Argument>(V);
5491   if (!Arg)
5492     return false;
5493 
5494   MachineFunction &MF = DAG.getMachineFunction();
5495   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5496 
5497   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5498   // we've been asked to pursue.
5499   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5500                               bool Indirect) {
5501     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5502       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5503       // pointing at the VReg, which will be patched up later.
5504       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5505       auto MIB = BuildMI(MF, DL, Inst);
5506       MIB.addReg(Reg);
5507       MIB.addImm(0);
5508       MIB.addMetadata(Variable);
5509       auto *NewDIExpr = FragExpr;
5510       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5511       // the DIExpression.
5512       if (Indirect)
5513         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5514       MIB.addMetadata(NewDIExpr);
5515       return MIB;
5516     } else {
5517       // Create a completely standard DBG_VALUE.
5518       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5519       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5520     }
5521   };
5522 
5523   if (!IsDbgDeclare) {
5524     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5525     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5526     // the entry block.
5527     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5528     if (!IsInEntryBlock)
5529       return false;
5530 
5531     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5532     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5533     // variable that also is a param.
5534     //
5535     // Although, if we are at the top of the entry block already, we can still
5536     // emit using ArgDbgValue. This might catch some situations when the
5537     // dbg.value refers to an argument that isn't used in the entry block, so
5538     // any CopyToReg node would be optimized out and the only way to express
5539     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5540     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5541     // we should only emit as ArgDbgValue if the Variable is an argument to the
5542     // current function, and the dbg.value intrinsic is found in the entry
5543     // block.
5544     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5545         !DL->getInlinedAt();
5546     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5547     if (!IsInPrologue && !VariableIsFunctionInputArg)
5548       return false;
5549 
5550     // Here we assume that a function argument on IR level only can be used to
5551     // describe one input parameter on source level. If we for example have
5552     // source code like this
5553     //
5554     //    struct A { long x, y; };
5555     //    void foo(struct A a, long b) {
5556     //      ...
5557     //      b = a.x;
5558     //      ...
5559     //    }
5560     //
5561     // and IR like this
5562     //
5563     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5564     //  entry:
5565     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5566     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5567     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5568     //    ...
5569     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5570     //    ...
5571     //
5572     // then the last dbg.value is describing a parameter "b" using a value that
5573     // is an argument. But since we already has used %a1 to describe a parameter
5574     // we should not handle that last dbg.value here (that would result in an
5575     // incorrect hoisting of the DBG_VALUE to the function entry).
5576     // Notice that we allow one dbg.value per IR level argument, to accommodate
5577     // for the situation with fragments above.
5578     if (VariableIsFunctionInputArg) {
5579       unsigned ArgNo = Arg->getArgNo();
5580       if (ArgNo >= FuncInfo.DescribedArgs.size())
5581         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5582       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5583         return false;
5584       FuncInfo.DescribedArgs.set(ArgNo);
5585     }
5586   }
5587 
5588   bool IsIndirect = false;
5589   Optional<MachineOperand> Op;
5590   // Some arguments' frame index is recorded during argument lowering.
5591   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5592   if (FI != std::numeric_limits<int>::max())
5593     Op = MachineOperand::CreateFI(FI);
5594 
5595   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5596   if (!Op && N.getNode()) {
5597     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5598     Register Reg;
5599     if (ArgRegsAndSizes.size() == 1)
5600       Reg = ArgRegsAndSizes.front().first;
5601 
5602     if (Reg && Reg.isVirtual()) {
5603       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5604       Register PR = RegInfo.getLiveInPhysReg(Reg);
5605       if (PR)
5606         Reg = PR;
5607     }
5608     if (Reg) {
5609       Op = MachineOperand::CreateReg(Reg, false);
5610       IsIndirect = IsDbgDeclare;
5611     }
5612   }
5613 
5614   if (!Op && N.getNode()) {
5615     // Check if frame index is available.
5616     SDValue LCandidate = peekThroughBitcasts(N);
5617     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5618       if (FrameIndexSDNode *FINode =
5619           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5620         Op = MachineOperand::CreateFI(FINode->getIndex());
5621   }
5622 
5623   if (!Op) {
5624     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5625     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5626                                          SplitRegs) {
5627       unsigned Offset = 0;
5628       for (const auto &RegAndSize : SplitRegs) {
5629         // If the expression is already a fragment, the current register
5630         // offset+size might extend beyond the fragment. In this case, only
5631         // the register bits that are inside the fragment are relevant.
5632         int RegFragmentSizeInBits = RegAndSize.second;
5633         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5634           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5635           // The register is entirely outside the expression fragment,
5636           // so is irrelevant for debug info.
5637           if (Offset >= ExprFragmentSizeInBits)
5638             break;
5639           // The register is partially outside the expression fragment, only
5640           // the low bits within the fragment are relevant for debug info.
5641           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5642             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5643           }
5644         }
5645 
5646         auto FragmentExpr = DIExpression::createFragmentExpression(
5647             Expr, Offset, RegFragmentSizeInBits);
5648         Offset += RegAndSize.second;
5649         // If a valid fragment expression cannot be created, the variable's
5650         // correct value cannot be determined and so it is set as Undef.
5651         if (!FragmentExpr) {
5652           SDDbgValue *SDV = DAG.getConstantDbgValue(
5653               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5654           DAG.AddDbgValue(SDV, false);
5655           continue;
5656         }
5657         MachineInstr *NewMI =
5658             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare);
5659         FuncInfo.ArgDbgValues.push_back(NewMI);
5660       }
5661     };
5662 
5663     // Check if ValueMap has reg number.
5664     DenseMap<const Value *, Register>::const_iterator
5665       VMI = FuncInfo.ValueMap.find(V);
5666     if (VMI != FuncInfo.ValueMap.end()) {
5667       const auto &TLI = DAG.getTargetLoweringInfo();
5668       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5669                        V->getType(), None);
5670       if (RFV.occupiesMultipleRegs()) {
5671         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5672         return true;
5673       }
5674 
5675       Op = MachineOperand::CreateReg(VMI->second, false);
5676       IsIndirect = IsDbgDeclare;
5677     } else if (ArgRegsAndSizes.size() > 1) {
5678       // This was split due to the calling convention, and no virtual register
5679       // mapping exists for the value.
5680       splitMultiRegDbgValue(ArgRegsAndSizes);
5681       return true;
5682     }
5683   }
5684 
5685   if (!Op)
5686     return false;
5687 
5688   assert(Variable->isValidLocationForIntrinsic(DL) &&
5689          "Expected inlined-at fields to agree");
5690   MachineInstr *NewMI = nullptr;
5691 
5692   if (Op->isReg())
5693     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5694   else
5695     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5696                     Variable, Expr);
5697 
5698   FuncInfo.ArgDbgValues.push_back(NewMI);
5699   return true;
5700 }
5701 
5702 /// Return the appropriate SDDbgValue based on N.
5703 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5704                                              DILocalVariable *Variable,
5705                                              DIExpression *Expr,
5706                                              const DebugLoc &dl,
5707                                              unsigned DbgSDNodeOrder) {
5708   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5709     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5710     // stack slot locations.
5711     //
5712     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5713     // debug values here after optimization:
5714     //
5715     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5716     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5717     //
5718     // Both describe the direct values of their associated variables.
5719     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5720                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5721   }
5722   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5723                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5724 }
5725 
5726 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5727   switch (Intrinsic) {
5728   case Intrinsic::smul_fix:
5729     return ISD::SMULFIX;
5730   case Intrinsic::umul_fix:
5731     return ISD::UMULFIX;
5732   case Intrinsic::smul_fix_sat:
5733     return ISD::SMULFIXSAT;
5734   case Intrinsic::umul_fix_sat:
5735     return ISD::UMULFIXSAT;
5736   case Intrinsic::sdiv_fix:
5737     return ISD::SDIVFIX;
5738   case Intrinsic::udiv_fix:
5739     return ISD::UDIVFIX;
5740   case Intrinsic::sdiv_fix_sat:
5741     return ISD::SDIVFIXSAT;
5742   case Intrinsic::udiv_fix_sat:
5743     return ISD::UDIVFIXSAT;
5744   default:
5745     llvm_unreachable("Unhandled fixed point intrinsic");
5746   }
5747 }
5748 
5749 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5750                                            const char *FunctionName) {
5751   assert(FunctionName && "FunctionName must not be nullptr");
5752   SDValue Callee = DAG.getExternalSymbol(
5753       FunctionName,
5754       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5755   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5756 }
5757 
5758 /// Given a @llvm.call.preallocated.setup, return the corresponding
5759 /// preallocated call.
5760 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5761   assert(cast<CallBase>(PreallocatedSetup)
5762                  ->getCalledFunction()
5763                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5764          "expected call_preallocated_setup Value");
5765   for (auto *U : PreallocatedSetup->users()) {
5766     auto *UseCall = cast<CallBase>(U);
5767     const Function *Fn = UseCall->getCalledFunction();
5768     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5769       return UseCall;
5770     }
5771   }
5772   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5773 }
5774 
5775 /// Lower the call to the specified intrinsic function.
5776 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5777                                              unsigned Intrinsic) {
5778   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5779   SDLoc sdl = getCurSDLoc();
5780   DebugLoc dl = getCurDebugLoc();
5781   SDValue Res;
5782 
5783   SDNodeFlags Flags;
5784   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5785     Flags.copyFMF(*FPOp);
5786 
5787   switch (Intrinsic) {
5788   default:
5789     // By default, turn this into a target intrinsic node.
5790     visitTargetIntrinsic(I, Intrinsic);
5791     return;
5792   case Intrinsic::vscale: {
5793     match(&I, m_VScale(DAG.getDataLayout()));
5794     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5795     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5796     return;
5797   }
5798   case Intrinsic::vastart:  visitVAStart(I); return;
5799   case Intrinsic::vaend:    visitVAEnd(I); return;
5800   case Intrinsic::vacopy:   visitVACopy(I); return;
5801   case Intrinsic::returnaddress:
5802     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5803                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5804                              getValue(I.getArgOperand(0))));
5805     return;
5806   case Intrinsic::addressofreturnaddress:
5807     setValue(&I,
5808              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5809                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5810     return;
5811   case Intrinsic::sponentry:
5812     setValue(&I,
5813              DAG.getNode(ISD::SPONENTRY, sdl,
5814                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5815     return;
5816   case Intrinsic::frameaddress:
5817     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5818                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5819                              getValue(I.getArgOperand(0))));
5820     return;
5821   case Intrinsic::read_volatile_register:
5822   case Intrinsic::read_register: {
5823     Value *Reg = I.getArgOperand(0);
5824     SDValue Chain = getRoot();
5825     SDValue RegName =
5826         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5827     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5828     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5829       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5830     setValue(&I, Res);
5831     DAG.setRoot(Res.getValue(1));
5832     return;
5833   }
5834   case Intrinsic::write_register: {
5835     Value *Reg = I.getArgOperand(0);
5836     Value *RegValue = I.getArgOperand(1);
5837     SDValue Chain = getRoot();
5838     SDValue RegName =
5839         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5840     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5841                             RegName, getValue(RegValue)));
5842     return;
5843   }
5844   case Intrinsic::memcpy: {
5845     const auto &MCI = cast<MemCpyInst>(I);
5846     SDValue Op1 = getValue(I.getArgOperand(0));
5847     SDValue Op2 = getValue(I.getArgOperand(1));
5848     SDValue Op3 = getValue(I.getArgOperand(2));
5849     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5850     Align DstAlign = MCI.getDestAlign().valueOrOne();
5851     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5852     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5853     bool isVol = MCI.isVolatile();
5854     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5855     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5856     // node.
5857     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5858     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5859                                /* AlwaysInline */ false, isTC,
5860                                MachinePointerInfo(I.getArgOperand(0)),
5861                                MachinePointerInfo(I.getArgOperand(1)),
5862                                I.getAAMetadata());
5863     updateDAGForMaybeTailCall(MC);
5864     return;
5865   }
5866   case Intrinsic::memcpy_inline: {
5867     const auto &MCI = cast<MemCpyInlineInst>(I);
5868     SDValue Dst = getValue(I.getArgOperand(0));
5869     SDValue Src = getValue(I.getArgOperand(1));
5870     SDValue Size = getValue(I.getArgOperand(2));
5871     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5872     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5873     Align DstAlign = MCI.getDestAlign().valueOrOne();
5874     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5875     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5876     bool isVol = MCI.isVolatile();
5877     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5878     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5879     // node.
5880     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5881                                /* AlwaysInline */ true, isTC,
5882                                MachinePointerInfo(I.getArgOperand(0)),
5883                                MachinePointerInfo(I.getArgOperand(1)),
5884                                I.getAAMetadata());
5885     updateDAGForMaybeTailCall(MC);
5886     return;
5887   }
5888   case Intrinsic::memset: {
5889     const auto &MSI = cast<MemSetInst>(I);
5890     SDValue Op1 = getValue(I.getArgOperand(0));
5891     SDValue Op2 = getValue(I.getArgOperand(1));
5892     SDValue Op3 = getValue(I.getArgOperand(2));
5893     // @llvm.memset defines 0 and 1 to both mean no alignment.
5894     Align Alignment = MSI.getDestAlign().valueOrOne();
5895     bool isVol = MSI.isVolatile();
5896     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5897     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5898     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5899                                MachinePointerInfo(I.getArgOperand(0)),
5900                                I.getAAMetadata());
5901     updateDAGForMaybeTailCall(MS);
5902     return;
5903   }
5904   case Intrinsic::memmove: {
5905     const auto &MMI = cast<MemMoveInst>(I);
5906     SDValue Op1 = getValue(I.getArgOperand(0));
5907     SDValue Op2 = getValue(I.getArgOperand(1));
5908     SDValue Op3 = getValue(I.getArgOperand(2));
5909     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5910     Align DstAlign = MMI.getDestAlign().valueOrOne();
5911     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5912     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5913     bool isVol = MMI.isVolatile();
5914     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5915     // FIXME: Support passing different dest/src alignments to the memmove DAG
5916     // node.
5917     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5918     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5919                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5920                                 MachinePointerInfo(I.getArgOperand(1)),
5921                                 I.getAAMetadata());
5922     updateDAGForMaybeTailCall(MM);
5923     return;
5924   }
5925   case Intrinsic::memcpy_element_unordered_atomic: {
5926     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5927     SDValue Dst = getValue(MI.getRawDest());
5928     SDValue Src = getValue(MI.getRawSource());
5929     SDValue Length = getValue(MI.getLength());
5930 
5931     unsigned DstAlign = MI.getDestAlignment();
5932     unsigned SrcAlign = MI.getSourceAlignment();
5933     Type *LengthTy = MI.getLength()->getType();
5934     unsigned ElemSz = MI.getElementSizeInBytes();
5935     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5936     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5937                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5938                                      MachinePointerInfo(MI.getRawDest()),
5939                                      MachinePointerInfo(MI.getRawSource()));
5940     updateDAGForMaybeTailCall(MC);
5941     return;
5942   }
5943   case Intrinsic::memmove_element_unordered_atomic: {
5944     auto &MI = cast<AtomicMemMoveInst>(I);
5945     SDValue Dst = getValue(MI.getRawDest());
5946     SDValue Src = getValue(MI.getRawSource());
5947     SDValue Length = getValue(MI.getLength());
5948 
5949     unsigned DstAlign = MI.getDestAlignment();
5950     unsigned SrcAlign = MI.getSourceAlignment();
5951     Type *LengthTy = MI.getLength()->getType();
5952     unsigned ElemSz = MI.getElementSizeInBytes();
5953     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5954     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5955                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5956                                       MachinePointerInfo(MI.getRawDest()),
5957                                       MachinePointerInfo(MI.getRawSource()));
5958     updateDAGForMaybeTailCall(MC);
5959     return;
5960   }
5961   case Intrinsic::memset_element_unordered_atomic: {
5962     auto &MI = cast<AtomicMemSetInst>(I);
5963     SDValue Dst = getValue(MI.getRawDest());
5964     SDValue Val = getValue(MI.getValue());
5965     SDValue Length = getValue(MI.getLength());
5966 
5967     unsigned DstAlign = MI.getDestAlignment();
5968     Type *LengthTy = MI.getLength()->getType();
5969     unsigned ElemSz = MI.getElementSizeInBytes();
5970     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5971     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5972                                      LengthTy, ElemSz, isTC,
5973                                      MachinePointerInfo(MI.getRawDest()));
5974     updateDAGForMaybeTailCall(MC);
5975     return;
5976   }
5977   case Intrinsic::call_preallocated_setup: {
5978     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5979     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5980     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5981                               getRoot(), SrcValue);
5982     setValue(&I, Res);
5983     DAG.setRoot(Res);
5984     return;
5985   }
5986   case Intrinsic::call_preallocated_arg: {
5987     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5988     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5989     SDValue Ops[3];
5990     Ops[0] = getRoot();
5991     Ops[1] = SrcValue;
5992     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5993                                    MVT::i32); // arg index
5994     SDValue Res = DAG.getNode(
5995         ISD::PREALLOCATED_ARG, sdl,
5996         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5997     setValue(&I, Res);
5998     DAG.setRoot(Res.getValue(1));
5999     return;
6000   }
6001   case Intrinsic::dbg_addr:
6002   case Intrinsic::dbg_declare: {
6003     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6004     // they are non-variadic.
6005     const auto &DI = cast<DbgVariableIntrinsic>(I);
6006     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6007     DILocalVariable *Variable = DI.getVariable();
6008     DIExpression *Expression = DI.getExpression();
6009     dropDanglingDebugInfo(Variable, Expression);
6010     assert(Variable && "Missing variable");
6011     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6012                       << "\n");
6013     // Check if address has undef value.
6014     const Value *Address = DI.getVariableLocationOp(0);
6015     if (!Address || isa<UndefValue>(Address) ||
6016         (Address->use_empty() && !isa<Argument>(Address))) {
6017       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6018                         << " (bad/undef/unused-arg address)\n");
6019       return;
6020     }
6021 
6022     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6023 
6024     // Check if this variable can be described by a frame index, typically
6025     // either as a static alloca or a byval parameter.
6026     int FI = std::numeric_limits<int>::max();
6027     if (const auto *AI =
6028             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6029       if (AI->isStaticAlloca()) {
6030         auto I = FuncInfo.StaticAllocaMap.find(AI);
6031         if (I != FuncInfo.StaticAllocaMap.end())
6032           FI = I->second;
6033       }
6034     } else if (const auto *Arg = dyn_cast<Argument>(
6035                    Address->stripInBoundsConstantOffsets())) {
6036       FI = FuncInfo.getArgumentFrameIndex(Arg);
6037     }
6038 
6039     // llvm.dbg.addr is control dependent and always generates indirect
6040     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6041     // the MachineFunction variable table.
6042     if (FI != std::numeric_limits<int>::max()) {
6043       if (Intrinsic == Intrinsic::dbg_addr) {
6044         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6045             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6046             dl, SDNodeOrder);
6047         DAG.AddDbgValue(SDV, isParameter);
6048       } else {
6049         LLVM_DEBUG(dbgs() << "Skipping " << DI
6050                           << " (variable info stashed in MF side table)\n");
6051       }
6052       return;
6053     }
6054 
6055     SDValue &N = NodeMap[Address];
6056     if (!N.getNode() && isa<Argument>(Address))
6057       // Check unused arguments map.
6058       N = UnusedArgNodeMap[Address];
6059     SDDbgValue *SDV;
6060     if (N.getNode()) {
6061       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6062         Address = BCI->getOperand(0);
6063       // Parameters are handled specially.
6064       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6065       if (isParameter && FINode) {
6066         // Byval parameter. We have a frame index at this point.
6067         SDV =
6068             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6069                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6070       } else if (isa<Argument>(Address)) {
6071         // Address is an argument, so try to emit its dbg value using
6072         // virtual register info from the FuncInfo.ValueMap.
6073         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6074         return;
6075       } else {
6076         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6077                               true, dl, SDNodeOrder);
6078       }
6079       DAG.AddDbgValue(SDV, isParameter);
6080     } else {
6081       // If Address is an argument then try to emit its dbg value using
6082       // virtual register info from the FuncInfo.ValueMap.
6083       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6084                                     N)) {
6085         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6086                           << " (could not emit func-arg dbg_value)\n");
6087       }
6088     }
6089     return;
6090   }
6091   case Intrinsic::dbg_label: {
6092     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6093     DILabel *Label = DI.getLabel();
6094     assert(Label && "Missing label");
6095 
6096     SDDbgLabel *SDV;
6097     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6098     DAG.AddDbgLabel(SDV);
6099     return;
6100   }
6101   case Intrinsic::dbg_value: {
6102     const DbgValueInst &DI = cast<DbgValueInst>(I);
6103     assert(DI.getVariable() && "Missing variable");
6104 
6105     DILocalVariable *Variable = DI.getVariable();
6106     DIExpression *Expression = DI.getExpression();
6107     dropDanglingDebugInfo(Variable, Expression);
6108     SmallVector<Value *, 4> Values(DI.getValues());
6109     if (Values.empty())
6110       return;
6111 
6112     if (llvm::is_contained(Values, nullptr))
6113       return;
6114 
6115     bool IsVariadic = DI.hasArgList();
6116     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6117                           SDNodeOrder, IsVariadic))
6118       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6119     return;
6120   }
6121 
6122   case Intrinsic::eh_typeid_for: {
6123     // Find the type id for the given typeinfo.
6124     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6125     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6126     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6127     setValue(&I, Res);
6128     return;
6129   }
6130 
6131   case Intrinsic::eh_return_i32:
6132   case Intrinsic::eh_return_i64:
6133     DAG.getMachineFunction().setCallsEHReturn(true);
6134     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6135                             MVT::Other,
6136                             getControlRoot(),
6137                             getValue(I.getArgOperand(0)),
6138                             getValue(I.getArgOperand(1))));
6139     return;
6140   case Intrinsic::eh_unwind_init:
6141     DAG.getMachineFunction().setCallsUnwindInit(true);
6142     return;
6143   case Intrinsic::eh_dwarf_cfa:
6144     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6145                              TLI.getPointerTy(DAG.getDataLayout()),
6146                              getValue(I.getArgOperand(0))));
6147     return;
6148   case Intrinsic::eh_sjlj_callsite: {
6149     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6150     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6151     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6152     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6153 
6154     MMI.setCurrentCallSite(CI->getZExtValue());
6155     return;
6156   }
6157   case Intrinsic::eh_sjlj_functioncontext: {
6158     // Get and store the index of the function context.
6159     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6160     AllocaInst *FnCtx =
6161       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6162     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6163     MFI.setFunctionContextIndex(FI);
6164     return;
6165   }
6166   case Intrinsic::eh_sjlj_setjmp: {
6167     SDValue Ops[2];
6168     Ops[0] = getRoot();
6169     Ops[1] = getValue(I.getArgOperand(0));
6170     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6171                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6172     setValue(&I, Op.getValue(0));
6173     DAG.setRoot(Op.getValue(1));
6174     return;
6175   }
6176   case Intrinsic::eh_sjlj_longjmp:
6177     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6178                             getRoot(), getValue(I.getArgOperand(0))));
6179     return;
6180   case Intrinsic::eh_sjlj_setup_dispatch:
6181     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6182                             getRoot()));
6183     return;
6184   case Intrinsic::masked_gather:
6185     visitMaskedGather(I);
6186     return;
6187   case Intrinsic::masked_load:
6188     visitMaskedLoad(I);
6189     return;
6190   case Intrinsic::masked_scatter:
6191     visitMaskedScatter(I);
6192     return;
6193   case Intrinsic::masked_store:
6194     visitMaskedStore(I);
6195     return;
6196   case Intrinsic::masked_expandload:
6197     visitMaskedLoad(I, true /* IsExpanding */);
6198     return;
6199   case Intrinsic::masked_compressstore:
6200     visitMaskedStore(I, true /* IsCompressing */);
6201     return;
6202   case Intrinsic::powi:
6203     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6204                             getValue(I.getArgOperand(1)), DAG));
6205     return;
6206   case Intrinsic::log:
6207     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6208     return;
6209   case Intrinsic::log2:
6210     setValue(&I,
6211              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6212     return;
6213   case Intrinsic::log10:
6214     setValue(&I,
6215              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6216     return;
6217   case Intrinsic::exp:
6218     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6219     return;
6220   case Intrinsic::exp2:
6221     setValue(&I,
6222              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6223     return;
6224   case Intrinsic::pow:
6225     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6226                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6227     return;
6228   case Intrinsic::sqrt:
6229   case Intrinsic::fabs:
6230   case Intrinsic::sin:
6231   case Intrinsic::cos:
6232   case Intrinsic::floor:
6233   case Intrinsic::ceil:
6234   case Intrinsic::trunc:
6235   case Intrinsic::rint:
6236   case Intrinsic::nearbyint:
6237   case Intrinsic::round:
6238   case Intrinsic::roundeven:
6239   case Intrinsic::canonicalize: {
6240     unsigned Opcode;
6241     switch (Intrinsic) {
6242     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6243     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6244     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6245     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6246     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6247     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6248     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6249     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6250     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6251     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6252     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6253     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6254     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6255     }
6256 
6257     setValue(&I, DAG.getNode(Opcode, sdl,
6258                              getValue(I.getArgOperand(0)).getValueType(),
6259                              getValue(I.getArgOperand(0)), Flags));
6260     return;
6261   }
6262   case Intrinsic::lround:
6263   case Intrinsic::llround:
6264   case Intrinsic::lrint:
6265   case Intrinsic::llrint: {
6266     unsigned Opcode;
6267     switch (Intrinsic) {
6268     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6269     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6270     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6271     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6272     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6273     }
6274 
6275     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6276     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6277                              getValue(I.getArgOperand(0))));
6278     return;
6279   }
6280   case Intrinsic::minnum:
6281     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6282                              getValue(I.getArgOperand(0)).getValueType(),
6283                              getValue(I.getArgOperand(0)),
6284                              getValue(I.getArgOperand(1)), Flags));
6285     return;
6286   case Intrinsic::maxnum:
6287     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6288                              getValue(I.getArgOperand(0)).getValueType(),
6289                              getValue(I.getArgOperand(0)),
6290                              getValue(I.getArgOperand(1)), Flags));
6291     return;
6292   case Intrinsic::minimum:
6293     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6294                              getValue(I.getArgOperand(0)).getValueType(),
6295                              getValue(I.getArgOperand(0)),
6296                              getValue(I.getArgOperand(1)), Flags));
6297     return;
6298   case Intrinsic::maximum:
6299     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6300                              getValue(I.getArgOperand(0)).getValueType(),
6301                              getValue(I.getArgOperand(0)),
6302                              getValue(I.getArgOperand(1)), Flags));
6303     return;
6304   case Intrinsic::copysign:
6305     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6306                              getValue(I.getArgOperand(0)).getValueType(),
6307                              getValue(I.getArgOperand(0)),
6308                              getValue(I.getArgOperand(1)), Flags));
6309     return;
6310   case Intrinsic::arithmetic_fence: {
6311     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6312                              getValue(I.getArgOperand(0)).getValueType(),
6313                              getValue(I.getArgOperand(0)), Flags));
6314     return;
6315   }
6316   case Intrinsic::fma:
6317     setValue(&I, DAG.getNode(
6318                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6319                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6320                      getValue(I.getArgOperand(2)), Flags));
6321     return;
6322 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6323   case Intrinsic::INTRINSIC:
6324 #include "llvm/IR/ConstrainedOps.def"
6325     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6326     return;
6327 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6328 #include "llvm/IR/VPIntrinsics.def"
6329     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6330     return;
6331   case Intrinsic::fptrunc_round: {
6332     // Get the last argument, the metadata and convert it to an integer in the
6333     // call
6334     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6335     Optional<RoundingMode> RoundMode =
6336         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6337 
6338     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6339 
6340     // Propagate fast-math-flags from IR to node(s).
6341     SDNodeFlags Flags;
6342     Flags.copyFMF(*cast<FPMathOperator>(&I));
6343     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6344 
6345     SDValue Result;
6346     Result = DAG.getNode(
6347         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6348         DAG.getTargetConstant((int)RoundMode.getValue(), sdl,
6349                               TLI.getPointerTy(DAG.getDataLayout())));
6350     setValue(&I, Result);
6351 
6352     return;
6353   }
6354   case Intrinsic::fmuladd: {
6355     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6356     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6357         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6358       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6359                                getValue(I.getArgOperand(0)).getValueType(),
6360                                getValue(I.getArgOperand(0)),
6361                                getValue(I.getArgOperand(1)),
6362                                getValue(I.getArgOperand(2)), Flags));
6363     } else {
6364       // TODO: Intrinsic calls should have fast-math-flags.
6365       SDValue Mul = DAG.getNode(
6366           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6367           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6368       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6369                                 getValue(I.getArgOperand(0)).getValueType(),
6370                                 Mul, getValue(I.getArgOperand(2)), Flags);
6371       setValue(&I, Add);
6372     }
6373     return;
6374   }
6375   case Intrinsic::convert_to_fp16:
6376     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6377                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6378                                          getValue(I.getArgOperand(0)),
6379                                          DAG.getTargetConstant(0, sdl,
6380                                                                MVT::i32))));
6381     return;
6382   case Intrinsic::convert_from_fp16:
6383     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6384                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6385                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6386                                          getValue(I.getArgOperand(0)))));
6387     return;
6388   case Intrinsic::fptosi_sat: {
6389     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6390     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6391                              getValue(I.getArgOperand(0)),
6392                              DAG.getValueType(VT.getScalarType())));
6393     return;
6394   }
6395   case Intrinsic::fptoui_sat: {
6396     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6397     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6398                              getValue(I.getArgOperand(0)),
6399                              DAG.getValueType(VT.getScalarType())));
6400     return;
6401   }
6402   case Intrinsic::set_rounding:
6403     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6404                       {getRoot(), getValue(I.getArgOperand(0))});
6405     setValue(&I, Res);
6406     DAG.setRoot(Res.getValue(0));
6407     return;
6408   case Intrinsic::pcmarker: {
6409     SDValue Tmp = getValue(I.getArgOperand(0));
6410     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6411     return;
6412   }
6413   case Intrinsic::readcyclecounter: {
6414     SDValue Op = getRoot();
6415     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6416                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6417     setValue(&I, Res);
6418     DAG.setRoot(Res.getValue(1));
6419     return;
6420   }
6421   case Intrinsic::bitreverse:
6422     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6423                              getValue(I.getArgOperand(0)).getValueType(),
6424                              getValue(I.getArgOperand(0))));
6425     return;
6426   case Intrinsic::bswap:
6427     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6428                              getValue(I.getArgOperand(0)).getValueType(),
6429                              getValue(I.getArgOperand(0))));
6430     return;
6431   case Intrinsic::cttz: {
6432     SDValue Arg = getValue(I.getArgOperand(0));
6433     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6434     EVT Ty = Arg.getValueType();
6435     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6436                              sdl, Ty, Arg));
6437     return;
6438   }
6439   case Intrinsic::ctlz: {
6440     SDValue Arg = getValue(I.getArgOperand(0));
6441     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6442     EVT Ty = Arg.getValueType();
6443     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6444                              sdl, Ty, Arg));
6445     return;
6446   }
6447   case Intrinsic::ctpop: {
6448     SDValue Arg = getValue(I.getArgOperand(0));
6449     EVT Ty = Arg.getValueType();
6450     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6451     return;
6452   }
6453   case Intrinsic::fshl:
6454   case Intrinsic::fshr: {
6455     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6456     SDValue X = getValue(I.getArgOperand(0));
6457     SDValue Y = getValue(I.getArgOperand(1));
6458     SDValue Z = getValue(I.getArgOperand(2));
6459     EVT VT = X.getValueType();
6460 
6461     if (X == Y) {
6462       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6463       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6464     } else {
6465       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6466       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6467     }
6468     return;
6469   }
6470   case Intrinsic::sadd_sat: {
6471     SDValue Op1 = getValue(I.getArgOperand(0));
6472     SDValue Op2 = getValue(I.getArgOperand(1));
6473     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6474     return;
6475   }
6476   case Intrinsic::uadd_sat: {
6477     SDValue Op1 = getValue(I.getArgOperand(0));
6478     SDValue Op2 = getValue(I.getArgOperand(1));
6479     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6480     return;
6481   }
6482   case Intrinsic::ssub_sat: {
6483     SDValue Op1 = getValue(I.getArgOperand(0));
6484     SDValue Op2 = getValue(I.getArgOperand(1));
6485     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6486     return;
6487   }
6488   case Intrinsic::usub_sat: {
6489     SDValue Op1 = getValue(I.getArgOperand(0));
6490     SDValue Op2 = getValue(I.getArgOperand(1));
6491     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6492     return;
6493   }
6494   case Intrinsic::sshl_sat: {
6495     SDValue Op1 = getValue(I.getArgOperand(0));
6496     SDValue Op2 = getValue(I.getArgOperand(1));
6497     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6498     return;
6499   }
6500   case Intrinsic::ushl_sat: {
6501     SDValue Op1 = getValue(I.getArgOperand(0));
6502     SDValue Op2 = getValue(I.getArgOperand(1));
6503     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6504     return;
6505   }
6506   case Intrinsic::smul_fix:
6507   case Intrinsic::umul_fix:
6508   case Intrinsic::smul_fix_sat:
6509   case Intrinsic::umul_fix_sat: {
6510     SDValue Op1 = getValue(I.getArgOperand(0));
6511     SDValue Op2 = getValue(I.getArgOperand(1));
6512     SDValue Op3 = getValue(I.getArgOperand(2));
6513     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6514                              Op1.getValueType(), Op1, Op2, Op3));
6515     return;
6516   }
6517   case Intrinsic::sdiv_fix:
6518   case Intrinsic::udiv_fix:
6519   case Intrinsic::sdiv_fix_sat:
6520   case Intrinsic::udiv_fix_sat: {
6521     SDValue Op1 = getValue(I.getArgOperand(0));
6522     SDValue Op2 = getValue(I.getArgOperand(1));
6523     SDValue Op3 = getValue(I.getArgOperand(2));
6524     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6525                               Op1, Op2, Op3, DAG, TLI));
6526     return;
6527   }
6528   case Intrinsic::smax: {
6529     SDValue Op1 = getValue(I.getArgOperand(0));
6530     SDValue Op2 = getValue(I.getArgOperand(1));
6531     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6532     return;
6533   }
6534   case Intrinsic::smin: {
6535     SDValue Op1 = getValue(I.getArgOperand(0));
6536     SDValue Op2 = getValue(I.getArgOperand(1));
6537     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6538     return;
6539   }
6540   case Intrinsic::umax: {
6541     SDValue Op1 = getValue(I.getArgOperand(0));
6542     SDValue Op2 = getValue(I.getArgOperand(1));
6543     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6544     return;
6545   }
6546   case Intrinsic::umin: {
6547     SDValue Op1 = getValue(I.getArgOperand(0));
6548     SDValue Op2 = getValue(I.getArgOperand(1));
6549     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6550     return;
6551   }
6552   case Intrinsic::abs: {
6553     // TODO: Preserve "int min is poison" arg in SDAG?
6554     SDValue Op1 = getValue(I.getArgOperand(0));
6555     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6556     return;
6557   }
6558   case Intrinsic::stacksave: {
6559     SDValue Op = getRoot();
6560     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6561     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6562     setValue(&I, Res);
6563     DAG.setRoot(Res.getValue(1));
6564     return;
6565   }
6566   case Intrinsic::stackrestore:
6567     Res = getValue(I.getArgOperand(0));
6568     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6569     return;
6570   case Intrinsic::get_dynamic_area_offset: {
6571     SDValue Op = getRoot();
6572     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6573     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6574     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6575     // target.
6576     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6577       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6578                          " intrinsic!");
6579     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6580                       Op);
6581     DAG.setRoot(Op);
6582     setValue(&I, Res);
6583     return;
6584   }
6585   case Intrinsic::stackguard: {
6586     MachineFunction &MF = DAG.getMachineFunction();
6587     const Module &M = *MF.getFunction().getParent();
6588     SDValue Chain = getRoot();
6589     if (TLI.useLoadStackGuardNode()) {
6590       Res = getLoadStackGuard(DAG, sdl, Chain);
6591     } else {
6592       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6593       const Value *Global = TLI.getSDagStackGuard(M);
6594       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6595       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6596                         MachinePointerInfo(Global, 0), Align,
6597                         MachineMemOperand::MOVolatile);
6598     }
6599     if (TLI.useStackGuardXorFP())
6600       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6601     DAG.setRoot(Chain);
6602     setValue(&I, Res);
6603     return;
6604   }
6605   case Intrinsic::stackprotector: {
6606     // Emit code into the DAG to store the stack guard onto the stack.
6607     MachineFunction &MF = DAG.getMachineFunction();
6608     MachineFrameInfo &MFI = MF.getFrameInfo();
6609     SDValue Src, Chain = getRoot();
6610 
6611     if (TLI.useLoadStackGuardNode())
6612       Src = getLoadStackGuard(DAG, sdl, Chain);
6613     else
6614       Src = getValue(I.getArgOperand(0));   // The guard's value.
6615 
6616     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6617 
6618     int FI = FuncInfo.StaticAllocaMap[Slot];
6619     MFI.setStackProtectorIndex(FI);
6620     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6621 
6622     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6623 
6624     // Store the stack protector onto the stack.
6625     Res = DAG.getStore(
6626         Chain, sdl, Src, FIN,
6627         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6628         MaybeAlign(), MachineMemOperand::MOVolatile);
6629     setValue(&I, Res);
6630     DAG.setRoot(Res);
6631     return;
6632   }
6633   case Intrinsic::objectsize:
6634     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6635 
6636   case Intrinsic::is_constant:
6637     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6638 
6639   case Intrinsic::annotation:
6640   case Intrinsic::ptr_annotation:
6641   case Intrinsic::launder_invariant_group:
6642   case Intrinsic::strip_invariant_group:
6643     // Drop the intrinsic, but forward the value
6644     setValue(&I, getValue(I.getOperand(0)));
6645     return;
6646 
6647   case Intrinsic::assume:
6648   case Intrinsic::experimental_noalias_scope_decl:
6649   case Intrinsic::var_annotation:
6650   case Intrinsic::sideeffect:
6651     // Discard annotate attributes, noalias scope declarations, assumptions, and
6652     // artificial side-effects.
6653     return;
6654 
6655   case Intrinsic::codeview_annotation: {
6656     // Emit a label associated with this metadata.
6657     MachineFunction &MF = DAG.getMachineFunction();
6658     MCSymbol *Label =
6659         MF.getMMI().getContext().createTempSymbol("annotation", true);
6660     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6661     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6662     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6663     DAG.setRoot(Res);
6664     return;
6665   }
6666 
6667   case Intrinsic::init_trampoline: {
6668     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6669 
6670     SDValue Ops[6];
6671     Ops[0] = getRoot();
6672     Ops[1] = getValue(I.getArgOperand(0));
6673     Ops[2] = getValue(I.getArgOperand(1));
6674     Ops[3] = getValue(I.getArgOperand(2));
6675     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6676     Ops[5] = DAG.getSrcValue(F);
6677 
6678     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6679 
6680     DAG.setRoot(Res);
6681     return;
6682   }
6683   case Intrinsic::adjust_trampoline:
6684     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6685                              TLI.getPointerTy(DAG.getDataLayout()),
6686                              getValue(I.getArgOperand(0))));
6687     return;
6688   case Intrinsic::gcroot: {
6689     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6690            "only valid in functions with gc specified, enforced by Verifier");
6691     assert(GFI && "implied by previous");
6692     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6693     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6694 
6695     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6696     GFI->addStackRoot(FI->getIndex(), TypeMap);
6697     return;
6698   }
6699   case Intrinsic::gcread:
6700   case Intrinsic::gcwrite:
6701     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6702   case Intrinsic::flt_rounds:
6703     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6704     setValue(&I, Res);
6705     DAG.setRoot(Res.getValue(1));
6706     return;
6707 
6708   case Intrinsic::expect:
6709     // Just replace __builtin_expect(exp, c) with EXP.
6710     setValue(&I, getValue(I.getArgOperand(0)));
6711     return;
6712 
6713   case Intrinsic::ubsantrap:
6714   case Intrinsic::debugtrap:
6715   case Intrinsic::trap: {
6716     StringRef TrapFuncName =
6717         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6718     if (TrapFuncName.empty()) {
6719       switch (Intrinsic) {
6720       case Intrinsic::trap:
6721         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6722         break;
6723       case Intrinsic::debugtrap:
6724         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6725         break;
6726       case Intrinsic::ubsantrap:
6727         DAG.setRoot(DAG.getNode(
6728             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6729             DAG.getTargetConstant(
6730                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6731                 MVT::i32)));
6732         break;
6733       default: llvm_unreachable("unknown trap intrinsic");
6734       }
6735       return;
6736     }
6737     TargetLowering::ArgListTy Args;
6738     if (Intrinsic == Intrinsic::ubsantrap) {
6739       Args.push_back(TargetLoweringBase::ArgListEntry());
6740       Args[0].Val = I.getArgOperand(0);
6741       Args[0].Node = getValue(Args[0].Val);
6742       Args[0].Ty = Args[0].Val->getType();
6743     }
6744 
6745     TargetLowering::CallLoweringInfo CLI(DAG);
6746     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6747         CallingConv::C, I.getType(),
6748         DAG.getExternalSymbol(TrapFuncName.data(),
6749                               TLI.getPointerTy(DAG.getDataLayout())),
6750         std::move(Args));
6751 
6752     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6753     DAG.setRoot(Result.second);
6754     return;
6755   }
6756 
6757   case Intrinsic::uadd_with_overflow:
6758   case Intrinsic::sadd_with_overflow:
6759   case Intrinsic::usub_with_overflow:
6760   case Intrinsic::ssub_with_overflow:
6761   case Intrinsic::umul_with_overflow:
6762   case Intrinsic::smul_with_overflow: {
6763     ISD::NodeType Op;
6764     switch (Intrinsic) {
6765     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6766     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6767     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6768     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6769     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6770     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6771     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6772     }
6773     SDValue Op1 = getValue(I.getArgOperand(0));
6774     SDValue Op2 = getValue(I.getArgOperand(1));
6775 
6776     EVT ResultVT = Op1.getValueType();
6777     EVT OverflowVT = MVT::i1;
6778     if (ResultVT.isVector())
6779       OverflowVT = EVT::getVectorVT(
6780           *Context, OverflowVT, ResultVT.getVectorElementCount());
6781 
6782     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6783     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6784     return;
6785   }
6786   case Intrinsic::prefetch: {
6787     SDValue Ops[5];
6788     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6789     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6790     Ops[0] = DAG.getRoot();
6791     Ops[1] = getValue(I.getArgOperand(0));
6792     Ops[2] = getValue(I.getArgOperand(1));
6793     Ops[3] = getValue(I.getArgOperand(2));
6794     Ops[4] = getValue(I.getArgOperand(3));
6795     SDValue Result = DAG.getMemIntrinsicNode(
6796         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6797         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6798         /* align */ None, Flags);
6799 
6800     // Chain the prefetch in parallell with any pending loads, to stay out of
6801     // the way of later optimizations.
6802     PendingLoads.push_back(Result);
6803     Result = getRoot();
6804     DAG.setRoot(Result);
6805     return;
6806   }
6807   case Intrinsic::lifetime_start:
6808   case Intrinsic::lifetime_end: {
6809     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6810     // Stack coloring is not enabled in O0, discard region information.
6811     if (TM.getOptLevel() == CodeGenOpt::None)
6812       return;
6813 
6814     const int64_t ObjectSize =
6815         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6816     Value *const ObjectPtr = I.getArgOperand(1);
6817     SmallVector<const Value *, 4> Allocas;
6818     getUnderlyingObjects(ObjectPtr, Allocas);
6819 
6820     for (const Value *Alloca : Allocas) {
6821       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6822 
6823       // Could not find an Alloca.
6824       if (!LifetimeObject)
6825         continue;
6826 
6827       // First check that the Alloca is static, otherwise it won't have a
6828       // valid frame index.
6829       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6830       if (SI == FuncInfo.StaticAllocaMap.end())
6831         return;
6832 
6833       const int FrameIndex = SI->second;
6834       int64_t Offset;
6835       if (GetPointerBaseWithConstantOffset(
6836               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6837         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6838       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6839                                 Offset);
6840       DAG.setRoot(Res);
6841     }
6842     return;
6843   }
6844   case Intrinsic::pseudoprobe: {
6845     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6846     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6847     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6848     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6849     DAG.setRoot(Res);
6850     return;
6851   }
6852   case Intrinsic::invariant_start:
6853     // Discard region information.
6854     setValue(&I,
6855              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
6856     return;
6857   case Intrinsic::invariant_end:
6858     // Discard region information.
6859     return;
6860   case Intrinsic::clear_cache:
6861     /// FunctionName may be null.
6862     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6863       lowerCallToExternalSymbol(I, FunctionName);
6864     return;
6865   case Intrinsic::donothing:
6866   case Intrinsic::seh_try_begin:
6867   case Intrinsic::seh_scope_begin:
6868   case Intrinsic::seh_try_end:
6869   case Intrinsic::seh_scope_end:
6870     // ignore
6871     return;
6872   case Intrinsic::experimental_stackmap:
6873     visitStackmap(I);
6874     return;
6875   case Intrinsic::experimental_patchpoint_void:
6876   case Intrinsic::experimental_patchpoint_i64:
6877     visitPatchpoint(I);
6878     return;
6879   case Intrinsic::experimental_gc_statepoint:
6880     LowerStatepoint(cast<GCStatepointInst>(I));
6881     return;
6882   case Intrinsic::experimental_gc_result:
6883     visitGCResult(cast<GCResultInst>(I));
6884     return;
6885   case Intrinsic::experimental_gc_relocate:
6886     visitGCRelocate(cast<GCRelocateInst>(I));
6887     return;
6888   case Intrinsic::instrprof_cover:
6889     llvm_unreachable("instrprof failed to lower a cover");
6890   case Intrinsic::instrprof_increment:
6891     llvm_unreachable("instrprof failed to lower an increment");
6892   case Intrinsic::instrprof_value_profile:
6893     llvm_unreachable("instrprof failed to lower a value profiling call");
6894   case Intrinsic::localescape: {
6895     MachineFunction &MF = DAG.getMachineFunction();
6896     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6897 
6898     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6899     // is the same on all targets.
6900     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
6901       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6902       if (isa<ConstantPointerNull>(Arg))
6903         continue; // Skip null pointers. They represent a hole in index space.
6904       AllocaInst *Slot = cast<AllocaInst>(Arg);
6905       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6906              "can only escape static allocas");
6907       int FI = FuncInfo.StaticAllocaMap[Slot];
6908       MCSymbol *FrameAllocSym =
6909           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6910               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6911       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6912               TII->get(TargetOpcode::LOCAL_ESCAPE))
6913           .addSym(FrameAllocSym)
6914           .addFrameIndex(FI);
6915     }
6916 
6917     return;
6918   }
6919 
6920   case Intrinsic::localrecover: {
6921     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6922     MachineFunction &MF = DAG.getMachineFunction();
6923 
6924     // Get the symbol that defines the frame offset.
6925     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6926     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6927     unsigned IdxVal =
6928         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6929     MCSymbol *FrameAllocSym =
6930         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6931             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6932 
6933     Value *FP = I.getArgOperand(1);
6934     SDValue FPVal = getValue(FP);
6935     EVT PtrVT = FPVal.getValueType();
6936 
6937     // Create a MCSymbol for the label to avoid any target lowering
6938     // that would make this PC relative.
6939     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6940     SDValue OffsetVal =
6941         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6942 
6943     // Add the offset to the FP.
6944     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6945     setValue(&I, Add);
6946 
6947     return;
6948   }
6949 
6950   case Intrinsic::eh_exceptionpointer:
6951   case Intrinsic::eh_exceptioncode: {
6952     // Get the exception pointer vreg, copy from it, and resize it to fit.
6953     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6954     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6955     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6956     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6957     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
6958     if (Intrinsic == Intrinsic::eh_exceptioncode)
6959       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
6960     setValue(&I, N);
6961     return;
6962   }
6963   case Intrinsic::xray_customevent: {
6964     // Here we want to make sure that the intrinsic behaves as if it has a
6965     // specific calling convention, and only for x86_64.
6966     // FIXME: Support other platforms later.
6967     const auto &Triple = DAG.getTarget().getTargetTriple();
6968     if (Triple.getArch() != Triple::x86_64)
6969       return;
6970 
6971     SmallVector<SDValue, 8> Ops;
6972 
6973     // We want to say that we always want the arguments in registers.
6974     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6975     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6976     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6977     SDValue Chain = getRoot();
6978     Ops.push_back(LogEntryVal);
6979     Ops.push_back(StrSizeVal);
6980     Ops.push_back(Chain);
6981 
6982     // We need to enforce the calling convention for the callsite, so that
6983     // argument ordering is enforced correctly, and that register allocation can
6984     // see that some registers may be assumed clobbered and have to preserve
6985     // them across calls to the intrinsic.
6986     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6987                                            sdl, NodeTys, Ops);
6988     SDValue patchableNode = SDValue(MN, 0);
6989     DAG.setRoot(patchableNode);
6990     setValue(&I, patchableNode);
6991     return;
6992   }
6993   case Intrinsic::xray_typedevent: {
6994     // Here we want to make sure that the intrinsic behaves as if it has a
6995     // specific calling convention, and only for x86_64.
6996     // FIXME: Support other platforms later.
6997     const auto &Triple = DAG.getTarget().getTargetTriple();
6998     if (Triple.getArch() != Triple::x86_64)
6999       return;
7000 
7001     SmallVector<SDValue, 8> Ops;
7002 
7003     // We want to say that we always want the arguments in registers.
7004     // It's unclear to me how manipulating the selection DAG here forces callers
7005     // to provide arguments in registers instead of on the stack.
7006     SDValue LogTypeId = getValue(I.getArgOperand(0));
7007     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7008     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7009     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7010     SDValue Chain = getRoot();
7011     Ops.push_back(LogTypeId);
7012     Ops.push_back(LogEntryVal);
7013     Ops.push_back(StrSizeVal);
7014     Ops.push_back(Chain);
7015 
7016     // We need to enforce the calling convention for the callsite, so that
7017     // argument ordering is enforced correctly, and that register allocation can
7018     // see that some registers may be assumed clobbered and have to preserve
7019     // them across calls to the intrinsic.
7020     MachineSDNode *MN = DAG.getMachineNode(
7021         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7022     SDValue patchableNode = SDValue(MN, 0);
7023     DAG.setRoot(patchableNode);
7024     setValue(&I, patchableNode);
7025     return;
7026   }
7027   case Intrinsic::experimental_deoptimize:
7028     LowerDeoptimizeCall(&I);
7029     return;
7030   case Intrinsic::experimental_stepvector:
7031     visitStepVector(I);
7032     return;
7033   case Intrinsic::vector_reduce_fadd:
7034   case Intrinsic::vector_reduce_fmul:
7035   case Intrinsic::vector_reduce_add:
7036   case Intrinsic::vector_reduce_mul:
7037   case Intrinsic::vector_reduce_and:
7038   case Intrinsic::vector_reduce_or:
7039   case Intrinsic::vector_reduce_xor:
7040   case Intrinsic::vector_reduce_smax:
7041   case Intrinsic::vector_reduce_smin:
7042   case Intrinsic::vector_reduce_umax:
7043   case Intrinsic::vector_reduce_umin:
7044   case Intrinsic::vector_reduce_fmax:
7045   case Intrinsic::vector_reduce_fmin:
7046     visitVectorReduce(I, Intrinsic);
7047     return;
7048 
7049   case Intrinsic::icall_branch_funnel: {
7050     SmallVector<SDValue, 16> Ops;
7051     Ops.push_back(getValue(I.getArgOperand(0)));
7052 
7053     int64_t Offset;
7054     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7055         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7056     if (!Base)
7057       report_fatal_error(
7058           "llvm.icall.branch.funnel operand must be a GlobalValue");
7059     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7060 
7061     struct BranchFunnelTarget {
7062       int64_t Offset;
7063       SDValue Target;
7064     };
7065     SmallVector<BranchFunnelTarget, 8> Targets;
7066 
7067     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7068       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7069           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7070       if (ElemBase != Base)
7071         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7072                            "to the same GlobalValue");
7073 
7074       SDValue Val = getValue(I.getArgOperand(Op + 1));
7075       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7076       if (!GA)
7077         report_fatal_error(
7078             "llvm.icall.branch.funnel operand must be a GlobalValue");
7079       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7080                                      GA->getGlobal(), sdl, Val.getValueType(),
7081                                      GA->getOffset())});
7082     }
7083     llvm::sort(Targets,
7084                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7085                  return T1.Offset < T2.Offset;
7086                });
7087 
7088     for (auto &T : Targets) {
7089       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7090       Ops.push_back(T.Target);
7091     }
7092 
7093     Ops.push_back(DAG.getRoot()); // Chain
7094     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7095                                  MVT::Other, Ops),
7096               0);
7097     DAG.setRoot(N);
7098     setValue(&I, N);
7099     HasTailCall = true;
7100     return;
7101   }
7102 
7103   case Intrinsic::wasm_landingpad_index:
7104     // Information this intrinsic contained has been transferred to
7105     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7106     // delete it now.
7107     return;
7108 
7109   case Intrinsic::aarch64_settag:
7110   case Intrinsic::aarch64_settag_zero: {
7111     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7112     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7113     SDValue Val = TSI.EmitTargetCodeForSetTag(
7114         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7115         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7116         ZeroMemory);
7117     DAG.setRoot(Val);
7118     setValue(&I, Val);
7119     return;
7120   }
7121   case Intrinsic::ptrmask: {
7122     SDValue Ptr = getValue(I.getOperand(0));
7123     SDValue Const = getValue(I.getOperand(1));
7124 
7125     EVT PtrVT = Ptr.getValueType();
7126     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7127                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7128     return;
7129   }
7130   case Intrinsic::get_active_lane_mask: {
7131     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7132     SDValue Index = getValue(I.getOperand(0));
7133     EVT ElementVT = Index.getValueType();
7134 
7135     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7136       visitTargetIntrinsic(I, Intrinsic);
7137       return;
7138     }
7139 
7140     SDValue TripCount = getValue(I.getOperand(1));
7141     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7142 
7143     SDValue VectorIndex, VectorTripCount;
7144     if (VecTy.isScalableVector()) {
7145       VectorIndex = DAG.getSplatVector(VecTy, sdl, Index);
7146       VectorTripCount = DAG.getSplatVector(VecTy, sdl, TripCount);
7147     } else {
7148       VectorIndex = DAG.getSplatBuildVector(VecTy, sdl, Index);
7149       VectorTripCount = DAG.getSplatBuildVector(VecTy, sdl, TripCount);
7150     }
7151     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7152     SDValue VectorInduction = DAG.getNode(
7153         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7154     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7155                                  VectorTripCount, ISD::CondCode::SETULT);
7156     setValue(&I, SetCC);
7157     return;
7158   }
7159   case Intrinsic::experimental_vector_insert: {
7160     SDValue Vec = getValue(I.getOperand(0));
7161     SDValue SubVec = getValue(I.getOperand(1));
7162     SDValue Index = getValue(I.getOperand(2));
7163 
7164     // The intrinsic's index type is i64, but the SDNode requires an index type
7165     // suitable for the target. Convert the index as required.
7166     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7167     if (Index.getValueType() != VectorIdxTy)
7168       Index = DAG.getVectorIdxConstant(
7169           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7170 
7171     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7172     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7173                              Index));
7174     return;
7175   }
7176   case Intrinsic::experimental_vector_extract: {
7177     SDValue Vec = getValue(I.getOperand(0));
7178     SDValue Index = getValue(I.getOperand(1));
7179     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7180 
7181     // The intrinsic's index type is i64, but the SDNode requires an index type
7182     // suitable for the target. Convert the index as required.
7183     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7184     if (Index.getValueType() != VectorIdxTy)
7185       Index = DAG.getVectorIdxConstant(
7186           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7187 
7188     setValue(&I,
7189              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7190     return;
7191   }
7192   case Intrinsic::experimental_vector_reverse:
7193     visitVectorReverse(I);
7194     return;
7195   case Intrinsic::experimental_vector_splice:
7196     visitVectorSplice(I);
7197     return;
7198   }
7199 }
7200 
7201 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7202     const ConstrainedFPIntrinsic &FPI) {
7203   SDLoc sdl = getCurSDLoc();
7204 
7205   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7206   SmallVector<EVT, 4> ValueVTs;
7207   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7208   ValueVTs.push_back(MVT::Other); // Out chain
7209 
7210   // We do not need to serialize constrained FP intrinsics against
7211   // each other or against (nonvolatile) loads, so they can be
7212   // chained like loads.
7213   SDValue Chain = DAG.getRoot();
7214   SmallVector<SDValue, 4> Opers;
7215   Opers.push_back(Chain);
7216   if (FPI.isUnaryOp()) {
7217     Opers.push_back(getValue(FPI.getArgOperand(0)));
7218   } else if (FPI.isTernaryOp()) {
7219     Opers.push_back(getValue(FPI.getArgOperand(0)));
7220     Opers.push_back(getValue(FPI.getArgOperand(1)));
7221     Opers.push_back(getValue(FPI.getArgOperand(2)));
7222   } else {
7223     Opers.push_back(getValue(FPI.getArgOperand(0)));
7224     Opers.push_back(getValue(FPI.getArgOperand(1)));
7225   }
7226 
7227   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7228     assert(Result.getNode()->getNumValues() == 2);
7229 
7230     // Push node to the appropriate list so that future instructions can be
7231     // chained up correctly.
7232     SDValue OutChain = Result.getValue(1);
7233     switch (EB) {
7234     case fp::ExceptionBehavior::ebIgnore:
7235       // The only reason why ebIgnore nodes still need to be chained is that
7236       // they might depend on the current rounding mode, and therefore must
7237       // not be moved across instruction that may change that mode.
7238       LLVM_FALLTHROUGH;
7239     case fp::ExceptionBehavior::ebMayTrap:
7240       // These must not be moved across calls or instructions that may change
7241       // floating-point exception masks.
7242       PendingConstrainedFP.push_back(OutChain);
7243       break;
7244     case fp::ExceptionBehavior::ebStrict:
7245       // These must not be moved across calls or instructions that may change
7246       // floating-point exception masks or read floating-point exception flags.
7247       // In addition, they cannot be optimized out even if unused.
7248       PendingConstrainedFPStrict.push_back(OutChain);
7249       break;
7250     }
7251   };
7252 
7253   SDVTList VTs = DAG.getVTList(ValueVTs);
7254   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7255 
7256   SDNodeFlags Flags;
7257   if (EB == fp::ExceptionBehavior::ebIgnore)
7258     Flags.setNoFPExcept(true);
7259 
7260   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7261     Flags.copyFMF(*FPOp);
7262 
7263   unsigned Opcode;
7264   switch (FPI.getIntrinsicID()) {
7265   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7266 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7267   case Intrinsic::INTRINSIC:                                                   \
7268     Opcode = ISD::STRICT_##DAGN;                                               \
7269     break;
7270 #include "llvm/IR/ConstrainedOps.def"
7271   case Intrinsic::experimental_constrained_fmuladd: {
7272     Opcode = ISD::STRICT_FMA;
7273     // Break fmuladd into fmul and fadd.
7274     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7275         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7276                                         ValueVTs[0])) {
7277       Opers.pop_back();
7278       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7279       pushOutChain(Mul, EB);
7280       Opcode = ISD::STRICT_FADD;
7281       Opers.clear();
7282       Opers.push_back(Mul.getValue(1));
7283       Opers.push_back(Mul.getValue(0));
7284       Opers.push_back(getValue(FPI.getArgOperand(2)));
7285     }
7286     break;
7287   }
7288   }
7289 
7290   // A few strict DAG nodes carry additional operands that are not
7291   // set up by the default code above.
7292   switch (Opcode) {
7293   default: break;
7294   case ISD::STRICT_FP_ROUND:
7295     Opers.push_back(
7296         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7297     break;
7298   case ISD::STRICT_FSETCC:
7299   case ISD::STRICT_FSETCCS: {
7300     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7301     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7302     if (TM.Options.NoNaNsFPMath)
7303       Condition = getFCmpCodeWithoutNaN(Condition);
7304     Opers.push_back(DAG.getCondCode(Condition));
7305     break;
7306   }
7307   }
7308 
7309   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7310   pushOutChain(Result, EB);
7311 
7312   SDValue FPResult = Result.getValue(0);
7313   setValue(&FPI, FPResult);
7314 }
7315 
7316 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7317   Optional<unsigned> ResOPC;
7318   switch (VPIntrin.getIntrinsicID()) {
7319 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7320 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) ResOPC = ISD::VPSD;
7321 #define END_REGISTER_VP_INTRINSIC(VPID) break;
7322 #include "llvm/IR/VPIntrinsics.def"
7323   }
7324 
7325   if (!ResOPC.hasValue())
7326     llvm_unreachable(
7327         "Inconsistency: no SDNode available for this VPIntrinsic!");
7328 
7329   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7330       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7331     if (VPIntrin.getFastMathFlags().allowReassoc())
7332       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7333                                                 : ISD::VP_REDUCE_FMUL;
7334   }
7335 
7336   return ResOPC.getValue();
7337 }
7338 
7339 void SelectionDAGBuilder::visitVPLoadGather(const VPIntrinsic &VPIntrin, EVT VT,
7340                                             SmallVector<SDValue, 7> &OpValues,
7341                                             bool IsGather) {
7342   SDLoc DL = getCurSDLoc();
7343   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7344   Value *PtrOperand = VPIntrin.getArgOperand(0);
7345   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7346   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7347   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7348   SDValue LD;
7349   bool AddToChain = true;
7350   if (!IsGather) {
7351     // Do not serialize variable-length loads of constant memory with
7352     // anything.
7353     if (!Alignment)
7354       Alignment = DAG.getEVTAlign(VT);
7355     MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7356     AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7357     SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7358     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7359         MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7360         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7361     LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7362                        MMO, false /*IsExpanding */);
7363   } else {
7364     if (!Alignment)
7365       Alignment = DAG.getEVTAlign(VT.getScalarType());
7366     unsigned AS =
7367         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7368     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7369         MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7370         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7371     SDValue Base, Index, Scale;
7372     ISD::MemIndexType IndexType;
7373     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7374                                       this, VPIntrin.getParent());
7375     if (!UniformBase) {
7376       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7377       Index = getValue(PtrOperand);
7378       IndexType = ISD::SIGNED_UNSCALED;
7379       Scale =
7380           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7381     }
7382     EVT IdxVT = Index.getValueType();
7383     EVT EltTy = IdxVT.getVectorElementType();
7384     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7385       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7386       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7387     }
7388     LD = DAG.getGatherVP(
7389         DAG.getVTList(VT, MVT::Other), VT, DL,
7390         {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7391         IndexType);
7392   }
7393   if (AddToChain)
7394     PendingLoads.push_back(LD.getValue(1));
7395   setValue(&VPIntrin, LD);
7396 }
7397 
7398 void SelectionDAGBuilder::visitVPStoreScatter(const VPIntrinsic &VPIntrin,
7399                                               SmallVector<SDValue, 7> &OpValues,
7400                                               bool IsScatter) {
7401   SDLoc DL = getCurSDLoc();
7402   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7403   Value *PtrOperand = VPIntrin.getArgOperand(1);
7404   EVT VT = OpValues[0].getValueType();
7405   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7406   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7407   SDValue ST;
7408   if (!IsScatter) {
7409     if (!Alignment)
7410       Alignment = DAG.getEVTAlign(VT);
7411     SDValue Ptr = OpValues[1];
7412     SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7413     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7414         MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7415         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7416     ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7417                         OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7418                         /* IsTruncating */ false, /*IsCompressing*/ false);
7419   } else {
7420     if (!Alignment)
7421       Alignment = DAG.getEVTAlign(VT.getScalarType());
7422     unsigned AS =
7423         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7424     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7425         MachinePointerInfo(AS), MachineMemOperand::MOStore,
7426         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7427     SDValue Base, Index, Scale;
7428     ISD::MemIndexType IndexType;
7429     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7430                                       this, VPIntrin.getParent());
7431     if (!UniformBase) {
7432       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7433       Index = getValue(PtrOperand);
7434       IndexType = ISD::SIGNED_UNSCALED;
7435       Scale =
7436           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7437     }
7438     EVT IdxVT = Index.getValueType();
7439     EVT EltTy = IdxVT.getVectorElementType();
7440     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7441       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7442       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7443     }
7444     ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7445                           {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7446                            OpValues[2], OpValues[3]},
7447                           MMO, IndexType);
7448   }
7449   DAG.setRoot(ST);
7450   setValue(&VPIntrin, ST);
7451 }
7452 
7453 void SelectionDAGBuilder::visitVPStridedLoad(
7454     const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) {
7455   SDLoc DL = getCurSDLoc();
7456   Value *PtrOperand = VPIntrin.getArgOperand(0);
7457   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7458   if (!Alignment)
7459     Alignment = DAG.getEVTAlign(VT.getScalarType());
7460   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7461   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7462   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7463   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7464   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7465   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7466       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7467       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7468 
7469   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7470                                     OpValues[2], OpValues[3], MMO,
7471                                     false /*IsExpanding*/);
7472 
7473   if (AddToChain)
7474     PendingLoads.push_back(LD.getValue(1));
7475   setValue(&VPIntrin, LD);
7476 }
7477 
7478 void SelectionDAGBuilder::visitVPStridedStore(
7479     const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) {
7480   SDLoc DL = getCurSDLoc();
7481   Value *PtrOperand = VPIntrin.getArgOperand(1);
7482   EVT VT = OpValues[0].getValueType();
7483   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7484   if (!Alignment)
7485     Alignment = DAG.getEVTAlign(VT.getScalarType());
7486   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7487   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7488       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7489       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7490 
7491   SDValue ST = DAG.getStridedStoreVP(
7492       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7493       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7494       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7495       /*IsCompressing*/ false);
7496 
7497   DAG.setRoot(ST);
7498   setValue(&VPIntrin, ST);
7499 }
7500 
7501 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7502     const VPIntrinsic &VPIntrin) {
7503   SDLoc DL = getCurSDLoc();
7504   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7505 
7506   SmallVector<EVT, 4> ValueVTs;
7507   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7508   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7509   SDVTList VTs = DAG.getVTList(ValueVTs);
7510 
7511   auto EVLParamPos =
7512       VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID());
7513 
7514   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7515   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7516          "Unexpected target EVL type");
7517 
7518   // Request operands.
7519   SmallVector<SDValue, 7> OpValues;
7520   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7521     auto Op = getValue(VPIntrin.getArgOperand(I));
7522     if (I == EVLParamPos)
7523       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7524     OpValues.push_back(Op);
7525   }
7526 
7527   switch (Opcode) {
7528   default: {
7529     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7530     setValue(&VPIntrin, Result);
7531     break;
7532   }
7533   case ISD::VP_LOAD:
7534   case ISD::VP_GATHER:
7535     visitVPLoadGather(VPIntrin, ValueVTs[0], OpValues,
7536                       Opcode == ISD::VP_GATHER);
7537     break;
7538   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7539     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7540     break;
7541   case ISD::VP_STORE:
7542   case ISD::VP_SCATTER:
7543     visitVPStoreScatter(VPIntrin, OpValues, Opcode == ISD::VP_SCATTER);
7544     break;
7545   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7546     visitVPStridedStore(VPIntrin, OpValues);
7547     break;
7548   }
7549 }
7550 
7551 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7552                                           const BasicBlock *EHPadBB,
7553                                           MCSymbol *&BeginLabel) {
7554   MachineFunction &MF = DAG.getMachineFunction();
7555   MachineModuleInfo &MMI = MF.getMMI();
7556 
7557   // Insert a label before the invoke call to mark the try range.  This can be
7558   // used to detect deletion of the invoke via the MachineModuleInfo.
7559   BeginLabel = MMI.getContext().createTempSymbol();
7560 
7561   // For SjLj, keep track of which landing pads go with which invokes
7562   // so as to maintain the ordering of pads in the LSDA.
7563   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7564   if (CallSiteIndex) {
7565     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7566     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7567 
7568     // Now that the call site is handled, stop tracking it.
7569     MMI.setCurrentCallSite(0);
7570   }
7571 
7572   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7573 }
7574 
7575 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7576                                         const BasicBlock *EHPadBB,
7577                                         MCSymbol *BeginLabel) {
7578   assert(BeginLabel && "BeginLabel should've been set");
7579 
7580   MachineFunction &MF = DAG.getMachineFunction();
7581   MachineModuleInfo &MMI = MF.getMMI();
7582 
7583   // Insert a label at the end of the invoke call to mark the try range.  This
7584   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7585   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7586   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7587 
7588   // Inform MachineModuleInfo of range.
7589   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7590   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7591   // actually use outlined funclets and their LSDA info style.
7592   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7593     assert(II && "II should've been set");
7594     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7595     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7596   } else if (!isScopedEHPersonality(Pers)) {
7597     assert(EHPadBB);
7598     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7599   }
7600 
7601   return Chain;
7602 }
7603 
7604 std::pair<SDValue, SDValue>
7605 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7606                                     const BasicBlock *EHPadBB) {
7607   MCSymbol *BeginLabel = nullptr;
7608 
7609   if (EHPadBB) {
7610     // Both PendingLoads and PendingExports must be flushed here;
7611     // this call might not return.
7612     (void)getRoot();
7613     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7614     CLI.setChain(getRoot());
7615   }
7616 
7617   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7618   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7619 
7620   assert((CLI.IsTailCall || Result.second.getNode()) &&
7621          "Non-null chain expected with non-tail call!");
7622   assert((Result.second.getNode() || !Result.first.getNode()) &&
7623          "Null value expected with tail call!");
7624 
7625   if (!Result.second.getNode()) {
7626     // As a special case, a null chain means that a tail call has been emitted
7627     // and the DAG root is already updated.
7628     HasTailCall = true;
7629 
7630     // Since there's no actual continuation from this block, nothing can be
7631     // relying on us setting vregs for them.
7632     PendingExports.clear();
7633   } else {
7634     DAG.setRoot(Result.second);
7635   }
7636 
7637   if (EHPadBB) {
7638     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7639                            BeginLabel));
7640   }
7641 
7642   return Result;
7643 }
7644 
7645 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7646                                       bool isTailCall,
7647                                       bool isMustTailCall,
7648                                       const BasicBlock *EHPadBB) {
7649   auto &DL = DAG.getDataLayout();
7650   FunctionType *FTy = CB.getFunctionType();
7651   Type *RetTy = CB.getType();
7652 
7653   TargetLowering::ArgListTy Args;
7654   Args.reserve(CB.arg_size());
7655 
7656   const Value *SwiftErrorVal = nullptr;
7657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7658 
7659   if (isTailCall) {
7660     // Avoid emitting tail calls in functions with the disable-tail-calls
7661     // attribute.
7662     auto *Caller = CB.getParent()->getParent();
7663     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7664         "true" && !isMustTailCall)
7665       isTailCall = false;
7666 
7667     // We can't tail call inside a function with a swifterror argument. Lowering
7668     // does not support this yet. It would have to move into the swifterror
7669     // register before the call.
7670     if (TLI.supportSwiftError() &&
7671         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7672       isTailCall = false;
7673   }
7674 
7675   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7676     TargetLowering::ArgListEntry Entry;
7677     const Value *V = *I;
7678 
7679     // Skip empty types
7680     if (V->getType()->isEmptyTy())
7681       continue;
7682 
7683     SDValue ArgNode = getValue(V);
7684     Entry.Node = ArgNode; Entry.Ty = V->getType();
7685 
7686     Entry.setAttributes(&CB, I - CB.arg_begin());
7687 
7688     // Use swifterror virtual register as input to the call.
7689     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7690       SwiftErrorVal = V;
7691       // We find the virtual register for the actual swifterror argument.
7692       // Instead of using the Value, we use the virtual register instead.
7693       Entry.Node =
7694           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7695                           EVT(TLI.getPointerTy(DL)));
7696     }
7697 
7698     Args.push_back(Entry);
7699 
7700     // If we have an explicit sret argument that is an Instruction, (i.e., it
7701     // might point to function-local memory), we can't meaningfully tail-call.
7702     if (Entry.IsSRet && isa<Instruction>(V))
7703       isTailCall = false;
7704   }
7705 
7706   // If call site has a cfguardtarget operand bundle, create and add an
7707   // additional ArgListEntry.
7708   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7709     TargetLowering::ArgListEntry Entry;
7710     Value *V = Bundle->Inputs[0];
7711     SDValue ArgNode = getValue(V);
7712     Entry.Node = ArgNode;
7713     Entry.Ty = V->getType();
7714     Entry.IsCFGuardTarget = true;
7715     Args.push_back(Entry);
7716   }
7717 
7718   // Check if target-independent constraints permit a tail call here.
7719   // Target-dependent constraints are checked within TLI->LowerCallTo.
7720   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7721     isTailCall = false;
7722 
7723   // Disable tail calls if there is an swifterror argument. Targets have not
7724   // been updated to support tail calls.
7725   if (TLI.supportSwiftError() && SwiftErrorVal)
7726     isTailCall = false;
7727 
7728   TargetLowering::CallLoweringInfo CLI(DAG);
7729   CLI.setDebugLoc(getCurSDLoc())
7730       .setChain(getRoot())
7731       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7732       .setTailCall(isTailCall)
7733       .setConvergent(CB.isConvergent())
7734       .setIsPreallocated(
7735           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7736   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7737 
7738   if (Result.first.getNode()) {
7739     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7740     setValue(&CB, Result.first);
7741   }
7742 
7743   // The last element of CLI.InVals has the SDValue for swifterror return.
7744   // Here we copy it to a virtual register and update SwiftErrorMap for
7745   // book-keeping.
7746   if (SwiftErrorVal && TLI.supportSwiftError()) {
7747     // Get the last element of InVals.
7748     SDValue Src = CLI.InVals.back();
7749     Register VReg =
7750         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7751     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7752     DAG.setRoot(CopyNode);
7753   }
7754 }
7755 
7756 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7757                              SelectionDAGBuilder &Builder) {
7758   // Check to see if this load can be trivially constant folded, e.g. if the
7759   // input is from a string literal.
7760   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7761     // Cast pointer to the type we really want to load.
7762     Type *LoadTy =
7763         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7764     if (LoadVT.isVector())
7765       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7766 
7767     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7768                                          PointerType::getUnqual(LoadTy));
7769 
7770     if (const Constant *LoadCst =
7771             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
7772                                          LoadTy, Builder.DAG.getDataLayout()))
7773       return Builder.getValue(LoadCst);
7774   }
7775 
7776   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7777   // still constant memory, the input chain can be the entry node.
7778   SDValue Root;
7779   bool ConstantMemory = false;
7780 
7781   // Do not serialize (non-volatile) loads of constant memory with anything.
7782   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7783     Root = Builder.DAG.getEntryNode();
7784     ConstantMemory = true;
7785   } else {
7786     // Do not serialize non-volatile loads against each other.
7787     Root = Builder.DAG.getRoot();
7788   }
7789 
7790   SDValue Ptr = Builder.getValue(PtrVal);
7791   SDValue LoadVal =
7792       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7793                           MachinePointerInfo(PtrVal), Align(1));
7794 
7795   if (!ConstantMemory)
7796     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7797   return LoadVal;
7798 }
7799 
7800 /// Record the value for an instruction that produces an integer result,
7801 /// converting the type where necessary.
7802 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7803                                                   SDValue Value,
7804                                                   bool IsSigned) {
7805   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7806                                                     I.getType(), true);
7807   if (IsSigned)
7808     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7809   else
7810     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7811   setValue(&I, Value);
7812 }
7813 
7814 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7815 /// true and lower it. Otherwise return false, and it will be lowered like a
7816 /// normal call.
7817 /// The caller already checked that \p I calls the appropriate LibFunc with a
7818 /// correct prototype.
7819 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7820   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7821   const Value *Size = I.getArgOperand(2);
7822   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7823   if (CSize && CSize->getZExtValue() == 0) {
7824     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7825                                                           I.getType(), true);
7826     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7827     return true;
7828   }
7829 
7830   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7831   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7832       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7833       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7834   if (Res.first.getNode()) {
7835     processIntegerCallValue(I, Res.first, true);
7836     PendingLoads.push_back(Res.second);
7837     return true;
7838   }
7839 
7840   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7841   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7842   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7843     return false;
7844 
7845   // If the target has a fast compare for the given size, it will return a
7846   // preferred load type for that size. Require that the load VT is legal and
7847   // that the target supports unaligned loads of that type. Otherwise, return
7848   // INVALID.
7849   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7850     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7851     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7852     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7853       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7854       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7855       // TODO: Check alignment of src and dest ptrs.
7856       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7857       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7858       if (!TLI.isTypeLegal(LVT) ||
7859           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7860           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7861         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7862     }
7863 
7864     return LVT;
7865   };
7866 
7867   // This turns into unaligned loads. We only do this if the target natively
7868   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7869   // we'll only produce a small number of byte loads.
7870   MVT LoadVT;
7871   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7872   switch (NumBitsToCompare) {
7873   default:
7874     return false;
7875   case 16:
7876     LoadVT = MVT::i16;
7877     break;
7878   case 32:
7879     LoadVT = MVT::i32;
7880     break;
7881   case 64:
7882   case 128:
7883   case 256:
7884     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7885     break;
7886   }
7887 
7888   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7889     return false;
7890 
7891   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7892   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7893 
7894   // Bitcast to a wide integer type if the loads are vectors.
7895   if (LoadVT.isVector()) {
7896     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7897     LoadL = DAG.getBitcast(CmpVT, LoadL);
7898     LoadR = DAG.getBitcast(CmpVT, LoadR);
7899   }
7900 
7901   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7902   processIntegerCallValue(I, Cmp, false);
7903   return true;
7904 }
7905 
7906 /// See if we can lower a memchr call into an optimized form. If so, return
7907 /// true and lower it. Otherwise return false, and it will be lowered like a
7908 /// normal call.
7909 /// The caller already checked that \p I calls the appropriate LibFunc with a
7910 /// correct prototype.
7911 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7912   const Value *Src = I.getArgOperand(0);
7913   const Value *Char = I.getArgOperand(1);
7914   const Value *Length = I.getArgOperand(2);
7915 
7916   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7917   std::pair<SDValue, SDValue> Res =
7918     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7919                                 getValue(Src), getValue(Char), getValue(Length),
7920                                 MachinePointerInfo(Src));
7921   if (Res.first.getNode()) {
7922     setValue(&I, Res.first);
7923     PendingLoads.push_back(Res.second);
7924     return true;
7925   }
7926 
7927   return false;
7928 }
7929 
7930 /// See if we can lower a mempcpy call into an optimized form. If so, return
7931 /// true and lower it. Otherwise return false, and it will be lowered like a
7932 /// normal call.
7933 /// The caller already checked that \p I calls the appropriate LibFunc with a
7934 /// correct prototype.
7935 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7936   SDValue Dst = getValue(I.getArgOperand(0));
7937   SDValue Src = getValue(I.getArgOperand(1));
7938   SDValue Size = getValue(I.getArgOperand(2));
7939 
7940   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7941   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7942   // DAG::getMemcpy needs Alignment to be defined.
7943   Align Alignment = std::min(DstAlign, SrcAlign);
7944 
7945   bool isVol = false;
7946   SDLoc sdl = getCurSDLoc();
7947 
7948   // In the mempcpy context we need to pass in a false value for isTailCall
7949   // because the return pointer needs to be adjusted by the size of
7950   // the copied memory.
7951   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7952   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7953                              /*isTailCall=*/false,
7954                              MachinePointerInfo(I.getArgOperand(0)),
7955                              MachinePointerInfo(I.getArgOperand(1)),
7956                              I.getAAMetadata());
7957   assert(MC.getNode() != nullptr &&
7958          "** memcpy should not be lowered as TailCall in mempcpy context **");
7959   DAG.setRoot(MC);
7960 
7961   // Check if Size needs to be truncated or extended.
7962   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7963 
7964   // Adjust return pointer to point just past the last dst byte.
7965   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7966                                     Dst, Size);
7967   setValue(&I, DstPlusSize);
7968   return true;
7969 }
7970 
7971 /// See if we can lower a strcpy call into an optimized form.  If so, return
7972 /// true and lower it, otherwise return false and it will be lowered like a
7973 /// normal call.
7974 /// The caller already checked that \p I calls the appropriate LibFunc with a
7975 /// correct prototype.
7976 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7977   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7978 
7979   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7980   std::pair<SDValue, SDValue> Res =
7981     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7982                                 getValue(Arg0), getValue(Arg1),
7983                                 MachinePointerInfo(Arg0),
7984                                 MachinePointerInfo(Arg1), isStpcpy);
7985   if (Res.first.getNode()) {
7986     setValue(&I, Res.first);
7987     DAG.setRoot(Res.second);
7988     return true;
7989   }
7990 
7991   return false;
7992 }
7993 
7994 /// See if we can lower a strcmp call into an optimized form.  If so, return
7995 /// true and lower it, otherwise return false and it will be lowered like a
7996 /// normal call.
7997 /// The caller already checked that \p I calls the appropriate LibFunc with a
7998 /// correct prototype.
7999 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8000   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8001 
8002   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8003   std::pair<SDValue, SDValue> Res =
8004     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8005                                 getValue(Arg0), getValue(Arg1),
8006                                 MachinePointerInfo(Arg0),
8007                                 MachinePointerInfo(Arg1));
8008   if (Res.first.getNode()) {
8009     processIntegerCallValue(I, Res.first, true);
8010     PendingLoads.push_back(Res.second);
8011     return true;
8012   }
8013 
8014   return false;
8015 }
8016 
8017 /// See if we can lower a strlen call into an optimized form.  If so, return
8018 /// true and lower it, otherwise return false and it will be lowered like a
8019 /// normal call.
8020 /// The caller already checked that \p I calls the appropriate LibFunc with a
8021 /// correct prototype.
8022 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8023   const Value *Arg0 = I.getArgOperand(0);
8024 
8025   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8026   std::pair<SDValue, SDValue> Res =
8027     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8028                                 getValue(Arg0), MachinePointerInfo(Arg0));
8029   if (Res.first.getNode()) {
8030     processIntegerCallValue(I, Res.first, false);
8031     PendingLoads.push_back(Res.second);
8032     return true;
8033   }
8034 
8035   return false;
8036 }
8037 
8038 /// See if we can lower a strnlen call into an optimized form.  If so, return
8039 /// true and lower it, otherwise return false and it will be lowered like a
8040 /// normal call.
8041 /// The caller already checked that \p I calls the appropriate LibFunc with a
8042 /// correct prototype.
8043 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8044   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8045 
8046   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8047   std::pair<SDValue, SDValue> Res =
8048     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8049                                  getValue(Arg0), getValue(Arg1),
8050                                  MachinePointerInfo(Arg0));
8051   if (Res.first.getNode()) {
8052     processIntegerCallValue(I, Res.first, false);
8053     PendingLoads.push_back(Res.second);
8054     return true;
8055   }
8056 
8057   return false;
8058 }
8059 
8060 /// See if we can lower a unary floating-point operation into an SDNode with
8061 /// the specified Opcode.  If so, return true and lower it, otherwise return
8062 /// false and it will be lowered like a normal call.
8063 /// The caller already checked that \p I calls the appropriate LibFunc with a
8064 /// correct prototype.
8065 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8066                                               unsigned Opcode) {
8067   // We already checked this call's prototype; verify it doesn't modify errno.
8068   if (!I.onlyReadsMemory())
8069     return false;
8070 
8071   SDNodeFlags Flags;
8072   Flags.copyFMF(cast<FPMathOperator>(I));
8073 
8074   SDValue Tmp = getValue(I.getArgOperand(0));
8075   setValue(&I,
8076            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8077   return true;
8078 }
8079 
8080 /// See if we can lower a binary floating-point operation into an SDNode with
8081 /// the specified Opcode. If so, return true and lower it. Otherwise return
8082 /// false, and it will be lowered like a normal call.
8083 /// The caller already checked that \p I calls the appropriate LibFunc with a
8084 /// correct prototype.
8085 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8086                                                unsigned Opcode) {
8087   // We already checked this call's prototype; verify it doesn't modify errno.
8088   if (!I.onlyReadsMemory())
8089     return false;
8090 
8091   SDNodeFlags Flags;
8092   Flags.copyFMF(cast<FPMathOperator>(I));
8093 
8094   SDValue Tmp0 = getValue(I.getArgOperand(0));
8095   SDValue Tmp1 = getValue(I.getArgOperand(1));
8096   EVT VT = Tmp0.getValueType();
8097   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8098   return true;
8099 }
8100 
8101 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8102   // Handle inline assembly differently.
8103   if (I.isInlineAsm()) {
8104     visitInlineAsm(I);
8105     return;
8106   }
8107 
8108   if (Function *F = I.getCalledFunction()) {
8109     diagnoseDontCall(I);
8110 
8111     if (F->isDeclaration()) {
8112       // Is this an LLVM intrinsic or a target-specific intrinsic?
8113       unsigned IID = F->getIntrinsicID();
8114       if (!IID)
8115         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8116           IID = II->getIntrinsicID(F);
8117 
8118       if (IID) {
8119         visitIntrinsicCall(I, IID);
8120         return;
8121       }
8122     }
8123 
8124     // Check for well-known libc/libm calls.  If the function is internal, it
8125     // can't be a library call.  Don't do the check if marked as nobuiltin for
8126     // some reason or the call site requires strict floating point semantics.
8127     LibFunc Func;
8128     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8129         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8130         LibInfo->hasOptimizedCodeGen(Func)) {
8131       switch (Func) {
8132       default: break;
8133       case LibFunc_bcmp:
8134         if (visitMemCmpBCmpCall(I))
8135           return;
8136         break;
8137       case LibFunc_copysign:
8138       case LibFunc_copysignf:
8139       case LibFunc_copysignl:
8140         // We already checked this call's prototype; verify it doesn't modify
8141         // errno.
8142         if (I.onlyReadsMemory()) {
8143           SDValue LHS = getValue(I.getArgOperand(0));
8144           SDValue RHS = getValue(I.getArgOperand(1));
8145           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8146                                    LHS.getValueType(), LHS, RHS));
8147           return;
8148         }
8149         break;
8150       case LibFunc_fabs:
8151       case LibFunc_fabsf:
8152       case LibFunc_fabsl:
8153         if (visitUnaryFloatCall(I, ISD::FABS))
8154           return;
8155         break;
8156       case LibFunc_fmin:
8157       case LibFunc_fminf:
8158       case LibFunc_fminl:
8159         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8160           return;
8161         break;
8162       case LibFunc_fmax:
8163       case LibFunc_fmaxf:
8164       case LibFunc_fmaxl:
8165         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8166           return;
8167         break;
8168       case LibFunc_sin:
8169       case LibFunc_sinf:
8170       case LibFunc_sinl:
8171         if (visitUnaryFloatCall(I, ISD::FSIN))
8172           return;
8173         break;
8174       case LibFunc_cos:
8175       case LibFunc_cosf:
8176       case LibFunc_cosl:
8177         if (visitUnaryFloatCall(I, ISD::FCOS))
8178           return;
8179         break;
8180       case LibFunc_sqrt:
8181       case LibFunc_sqrtf:
8182       case LibFunc_sqrtl:
8183       case LibFunc_sqrt_finite:
8184       case LibFunc_sqrtf_finite:
8185       case LibFunc_sqrtl_finite:
8186         if (visitUnaryFloatCall(I, ISD::FSQRT))
8187           return;
8188         break;
8189       case LibFunc_floor:
8190       case LibFunc_floorf:
8191       case LibFunc_floorl:
8192         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8193           return;
8194         break;
8195       case LibFunc_nearbyint:
8196       case LibFunc_nearbyintf:
8197       case LibFunc_nearbyintl:
8198         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8199           return;
8200         break;
8201       case LibFunc_ceil:
8202       case LibFunc_ceilf:
8203       case LibFunc_ceill:
8204         if (visitUnaryFloatCall(I, ISD::FCEIL))
8205           return;
8206         break;
8207       case LibFunc_rint:
8208       case LibFunc_rintf:
8209       case LibFunc_rintl:
8210         if (visitUnaryFloatCall(I, ISD::FRINT))
8211           return;
8212         break;
8213       case LibFunc_round:
8214       case LibFunc_roundf:
8215       case LibFunc_roundl:
8216         if (visitUnaryFloatCall(I, ISD::FROUND))
8217           return;
8218         break;
8219       case LibFunc_trunc:
8220       case LibFunc_truncf:
8221       case LibFunc_truncl:
8222         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8223           return;
8224         break;
8225       case LibFunc_log2:
8226       case LibFunc_log2f:
8227       case LibFunc_log2l:
8228         if (visitUnaryFloatCall(I, ISD::FLOG2))
8229           return;
8230         break;
8231       case LibFunc_exp2:
8232       case LibFunc_exp2f:
8233       case LibFunc_exp2l:
8234         if (visitUnaryFloatCall(I, ISD::FEXP2))
8235           return;
8236         break;
8237       case LibFunc_memcmp:
8238         if (visitMemCmpBCmpCall(I))
8239           return;
8240         break;
8241       case LibFunc_mempcpy:
8242         if (visitMemPCpyCall(I))
8243           return;
8244         break;
8245       case LibFunc_memchr:
8246         if (visitMemChrCall(I))
8247           return;
8248         break;
8249       case LibFunc_strcpy:
8250         if (visitStrCpyCall(I, false))
8251           return;
8252         break;
8253       case LibFunc_stpcpy:
8254         if (visitStrCpyCall(I, true))
8255           return;
8256         break;
8257       case LibFunc_strcmp:
8258         if (visitStrCmpCall(I))
8259           return;
8260         break;
8261       case LibFunc_strlen:
8262         if (visitStrLenCall(I))
8263           return;
8264         break;
8265       case LibFunc_strnlen:
8266         if (visitStrNLenCall(I))
8267           return;
8268         break;
8269       }
8270     }
8271   }
8272 
8273   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8274   // have to do anything here to lower funclet bundles.
8275   // CFGuardTarget bundles are lowered in LowerCallTo.
8276   assert(!I.hasOperandBundlesOtherThan(
8277              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8278               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8279               LLVMContext::OB_clang_arc_attachedcall}) &&
8280          "Cannot lower calls with arbitrary operand bundles!");
8281 
8282   SDValue Callee = getValue(I.getCalledOperand());
8283 
8284   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8285     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8286   else
8287     // Check if we can potentially perform a tail call. More detailed checking
8288     // is be done within LowerCallTo, after more information about the call is
8289     // known.
8290     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8291 }
8292 
8293 namespace {
8294 
8295 /// AsmOperandInfo - This contains information for each constraint that we are
8296 /// lowering.
8297 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8298 public:
8299   /// CallOperand - If this is the result output operand or a clobber
8300   /// this is null, otherwise it is the incoming operand to the CallInst.
8301   /// This gets modified as the asm is processed.
8302   SDValue CallOperand;
8303 
8304   /// AssignedRegs - If this is a register or register class operand, this
8305   /// contains the set of register corresponding to the operand.
8306   RegsForValue AssignedRegs;
8307 
8308   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8309     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8310   }
8311 
8312   /// Whether or not this operand accesses memory
8313   bool hasMemory(const TargetLowering &TLI) const {
8314     // Indirect operand accesses access memory.
8315     if (isIndirect)
8316       return true;
8317 
8318     for (const auto &Code : Codes)
8319       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8320         return true;
8321 
8322     return false;
8323   }
8324 
8325   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
8326   /// corresponds to.  If there is no Value* for this operand, it returns
8327   /// MVT::Other.
8328   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
8329                            const DataLayout &DL,
8330                            llvm::Type *ParamElemType) const {
8331     if (!CallOperandVal) return MVT::Other;
8332 
8333     if (isa<BasicBlock>(CallOperandVal))
8334       return TLI.getProgramPointerTy(DL);
8335 
8336     llvm::Type *OpTy = CallOperandVal->getType();
8337 
8338     // FIXME: code duplicated from TargetLowering::ParseConstraints().
8339     // If this is an indirect operand, the operand is a pointer to the
8340     // accessed type.
8341     if (isIndirect) {
8342       OpTy = ParamElemType;
8343       assert(OpTy && "Indirect operand must have elementtype attribute");
8344     }
8345 
8346     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
8347     if (StructType *STy = dyn_cast<StructType>(OpTy))
8348       if (STy->getNumElements() == 1)
8349         OpTy = STy->getElementType(0);
8350 
8351     // If OpTy is not a single value, it may be a struct/union that we
8352     // can tile with integers.
8353     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
8354       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
8355       switch (BitSize) {
8356       default: break;
8357       case 1:
8358       case 8:
8359       case 16:
8360       case 32:
8361       case 64:
8362       case 128:
8363         OpTy = IntegerType::get(Context, BitSize);
8364         break;
8365       }
8366     }
8367 
8368     return TLI.getAsmOperandValueType(DL, OpTy, true);
8369   }
8370 };
8371 
8372 
8373 } // end anonymous namespace
8374 
8375 /// Make sure that the output operand \p OpInfo and its corresponding input
8376 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8377 /// out).
8378 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8379                                SDISelAsmOperandInfo &MatchingOpInfo,
8380                                SelectionDAG &DAG) {
8381   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8382     return;
8383 
8384   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8385   const auto &TLI = DAG.getTargetLoweringInfo();
8386 
8387   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8388       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8389                                        OpInfo.ConstraintVT);
8390   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8391       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8392                                        MatchingOpInfo.ConstraintVT);
8393   if ((OpInfo.ConstraintVT.isInteger() !=
8394        MatchingOpInfo.ConstraintVT.isInteger()) ||
8395       (MatchRC.second != InputRC.second)) {
8396     // FIXME: error out in a more elegant fashion
8397     report_fatal_error("Unsupported asm: input constraint"
8398                        " with a matching output constraint of"
8399                        " incompatible type!");
8400   }
8401   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8402 }
8403 
8404 /// Get a direct memory input to behave well as an indirect operand.
8405 /// This may introduce stores, hence the need for a \p Chain.
8406 /// \return The (possibly updated) chain.
8407 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8408                                         SDISelAsmOperandInfo &OpInfo,
8409                                         SelectionDAG &DAG) {
8410   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8411 
8412   // If we don't have an indirect input, put it in the constpool if we can,
8413   // otherwise spill it to a stack slot.
8414   // TODO: This isn't quite right. We need to handle these according to
8415   // the addressing mode that the constraint wants. Also, this may take
8416   // an additional register for the computation and we don't want that
8417   // either.
8418 
8419   // If the operand is a float, integer, or vector constant, spill to a
8420   // constant pool entry to get its address.
8421   const Value *OpVal = OpInfo.CallOperandVal;
8422   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8423       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8424     OpInfo.CallOperand = DAG.getConstantPool(
8425         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8426     return Chain;
8427   }
8428 
8429   // Otherwise, create a stack slot and emit a store to it before the asm.
8430   Type *Ty = OpVal->getType();
8431   auto &DL = DAG.getDataLayout();
8432   uint64_t TySize = DL.getTypeAllocSize(Ty);
8433   MachineFunction &MF = DAG.getMachineFunction();
8434   int SSFI = MF.getFrameInfo().CreateStackObject(
8435       TySize, DL.getPrefTypeAlign(Ty), false);
8436   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8437   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8438                             MachinePointerInfo::getFixedStack(MF, SSFI),
8439                             TLI.getMemValueType(DL, Ty));
8440   OpInfo.CallOperand = StackSlot;
8441 
8442   return Chain;
8443 }
8444 
8445 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8446 /// specified operand.  We prefer to assign virtual registers, to allow the
8447 /// register allocator to handle the assignment process.  However, if the asm
8448 /// uses features that we can't model on machineinstrs, we have SDISel do the
8449 /// allocation.  This produces generally horrible, but correct, code.
8450 ///
8451 ///   OpInfo describes the operand
8452 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8453 static llvm::Optional<unsigned>
8454 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8455                      SDISelAsmOperandInfo &OpInfo,
8456                      SDISelAsmOperandInfo &RefOpInfo) {
8457   LLVMContext &Context = *DAG.getContext();
8458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8459 
8460   MachineFunction &MF = DAG.getMachineFunction();
8461   SmallVector<unsigned, 4> Regs;
8462   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8463 
8464   // No work to do for memory operations.
8465   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8466     return None;
8467 
8468   // If this is a constraint for a single physreg, or a constraint for a
8469   // register class, find it.
8470   unsigned AssignedReg;
8471   const TargetRegisterClass *RC;
8472   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8473       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8474   // RC is unset only on failure. Return immediately.
8475   if (!RC)
8476     return None;
8477 
8478   // Get the actual register value type.  This is important, because the user
8479   // may have asked for (e.g.) the AX register in i32 type.  We need to
8480   // remember that AX is actually i16 to get the right extension.
8481   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8482 
8483   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8484     // If this is an FP operand in an integer register (or visa versa), or more
8485     // generally if the operand value disagrees with the register class we plan
8486     // to stick it in, fix the operand type.
8487     //
8488     // If this is an input value, the bitcast to the new type is done now.
8489     // Bitcast for output value is done at the end of visitInlineAsm().
8490     if ((OpInfo.Type == InlineAsm::isOutput ||
8491          OpInfo.Type == InlineAsm::isInput) &&
8492         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8493       // Try to convert to the first EVT that the reg class contains.  If the
8494       // types are identical size, use a bitcast to convert (e.g. two differing
8495       // vector types).  Note: output bitcast is done at the end of
8496       // visitInlineAsm().
8497       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8498         // Exclude indirect inputs while they are unsupported because the code
8499         // to perform the load is missing and thus OpInfo.CallOperand still
8500         // refers to the input address rather than the pointed-to value.
8501         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8502           OpInfo.CallOperand =
8503               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8504         OpInfo.ConstraintVT = RegVT;
8505         // If the operand is an FP value and we want it in integer registers,
8506         // use the corresponding integer type. This turns an f64 value into
8507         // i64, which can be passed with two i32 values on a 32-bit machine.
8508       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8509         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8510         if (OpInfo.Type == InlineAsm::isInput)
8511           OpInfo.CallOperand =
8512               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8513         OpInfo.ConstraintVT = VT;
8514       }
8515     }
8516   }
8517 
8518   // No need to allocate a matching input constraint since the constraint it's
8519   // matching to has already been allocated.
8520   if (OpInfo.isMatchingInputConstraint())
8521     return None;
8522 
8523   EVT ValueVT = OpInfo.ConstraintVT;
8524   if (OpInfo.ConstraintVT == MVT::Other)
8525     ValueVT = RegVT;
8526 
8527   // Initialize NumRegs.
8528   unsigned NumRegs = 1;
8529   if (OpInfo.ConstraintVT != MVT::Other)
8530     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8531 
8532   // If this is a constraint for a specific physical register, like {r17},
8533   // assign it now.
8534 
8535   // If this associated to a specific register, initialize iterator to correct
8536   // place. If virtual, make sure we have enough registers
8537 
8538   // Initialize iterator if necessary
8539   TargetRegisterClass::iterator I = RC->begin();
8540   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8541 
8542   // Do not check for single registers.
8543   if (AssignedReg) {
8544     I = std::find(I, RC->end(), AssignedReg);
8545     if (I == RC->end()) {
8546       // RC does not contain the selected register, which indicates a
8547       // mismatch between the register and the required type/bitwidth.
8548       return {AssignedReg};
8549     }
8550   }
8551 
8552   for (; NumRegs; --NumRegs, ++I) {
8553     assert(I != RC->end() && "Ran out of registers to allocate!");
8554     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8555     Regs.push_back(R);
8556   }
8557 
8558   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8559   return None;
8560 }
8561 
8562 static unsigned
8563 findMatchingInlineAsmOperand(unsigned OperandNo,
8564                              const std::vector<SDValue> &AsmNodeOperands) {
8565   // Scan until we find the definition we already emitted of this operand.
8566   unsigned CurOp = InlineAsm::Op_FirstOperand;
8567   for (; OperandNo; --OperandNo) {
8568     // Advance to the next operand.
8569     unsigned OpFlag =
8570         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8571     assert((InlineAsm::isRegDefKind(OpFlag) ||
8572             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8573             InlineAsm::isMemKind(OpFlag)) &&
8574            "Skipped past definitions?");
8575     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8576   }
8577   return CurOp;
8578 }
8579 
8580 namespace {
8581 
8582 class ExtraFlags {
8583   unsigned Flags = 0;
8584 
8585 public:
8586   explicit ExtraFlags(const CallBase &Call) {
8587     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8588     if (IA->hasSideEffects())
8589       Flags |= InlineAsm::Extra_HasSideEffects;
8590     if (IA->isAlignStack())
8591       Flags |= InlineAsm::Extra_IsAlignStack;
8592     if (Call.isConvergent())
8593       Flags |= InlineAsm::Extra_IsConvergent;
8594     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8595   }
8596 
8597   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8598     // Ideally, we would only check against memory constraints.  However, the
8599     // meaning of an Other constraint can be target-specific and we can't easily
8600     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8601     // for Other constraints as well.
8602     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8603         OpInfo.ConstraintType == TargetLowering::C_Other) {
8604       if (OpInfo.Type == InlineAsm::isInput)
8605         Flags |= InlineAsm::Extra_MayLoad;
8606       else if (OpInfo.Type == InlineAsm::isOutput)
8607         Flags |= InlineAsm::Extra_MayStore;
8608       else if (OpInfo.Type == InlineAsm::isClobber)
8609         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8610     }
8611   }
8612 
8613   unsigned get() const { return Flags; }
8614 };
8615 
8616 } // end anonymous namespace
8617 
8618 /// visitInlineAsm - Handle a call to an InlineAsm object.
8619 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8620                                          const BasicBlock *EHPadBB) {
8621   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8622 
8623   /// ConstraintOperands - Information about all of the constraints.
8624   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8625 
8626   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8627   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8628       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8629 
8630   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8631   // AsmDialect, MayLoad, MayStore).
8632   bool HasSideEffect = IA->hasSideEffects();
8633   ExtraFlags ExtraInfo(Call);
8634 
8635   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8636   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8637   for (auto &T : TargetConstraints) {
8638     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8639     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8640 
8641     // Compute the value type for each operand.
8642     if (OpInfo.hasArg()) {
8643       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
8644       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8645       Type *ParamElemTy = Call.getParamElementType(ArgNo);
8646       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8647                                            DAG.getDataLayout(), ParamElemTy);
8648       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8649       ArgNo++;
8650     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8651       // The return value of the call is this value.  As such, there is no
8652       // corresponding argument.
8653       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8654       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8655         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8656             DAG.getDataLayout(), STy->getElementType(ResNo));
8657       } else {
8658         assert(ResNo == 0 && "Asm only has one result!");
8659         OpInfo.ConstraintVT = TLI.getAsmOperandValueType(
8660             DAG.getDataLayout(), Call.getType()).getSimpleVT();
8661       }
8662       ++ResNo;
8663     } else {
8664       OpInfo.ConstraintVT = MVT::Other;
8665     }
8666 
8667     if (!HasSideEffect)
8668       HasSideEffect = OpInfo.hasMemory(TLI);
8669 
8670     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8671     // FIXME: Could we compute this on OpInfo rather than T?
8672 
8673     // Compute the constraint code and ConstraintType to use.
8674     TLI.ComputeConstraintToUse(T, SDValue());
8675 
8676     if (T.ConstraintType == TargetLowering::C_Immediate &&
8677         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8678       // We've delayed emitting a diagnostic like the "n" constraint because
8679       // inlining could cause an integer showing up.
8680       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8681                                           "' expects an integer constant "
8682                                           "expression");
8683 
8684     ExtraInfo.update(T);
8685   }
8686 
8687   // We won't need to flush pending loads if this asm doesn't touch
8688   // memory and is nonvolatile.
8689   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8690 
8691   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8692   if (EmitEHLabels) {
8693     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8694   }
8695   bool IsCallBr = isa<CallBrInst>(Call);
8696 
8697   if (IsCallBr || EmitEHLabels) {
8698     // If this is a callbr or invoke we need to flush pending exports since
8699     // inlineasm_br and invoke are terminators.
8700     // We need to do this before nodes are glued to the inlineasm_br node.
8701     Chain = getControlRoot();
8702   }
8703 
8704   MCSymbol *BeginLabel = nullptr;
8705   if (EmitEHLabels) {
8706     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8707   }
8708 
8709   // Second pass over the constraints: compute which constraint option to use.
8710   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8711     // If this is an output operand with a matching input operand, look up the
8712     // matching input. If their types mismatch, e.g. one is an integer, the
8713     // other is floating point, or their sizes are different, flag it as an
8714     // error.
8715     if (OpInfo.hasMatchingInput()) {
8716       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8717       patchMatchingInput(OpInfo, Input, DAG);
8718     }
8719 
8720     // Compute the constraint code and ConstraintType to use.
8721     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8722 
8723     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8724         OpInfo.Type == InlineAsm::isClobber)
8725       continue;
8726 
8727     // If this is a memory input, and if the operand is not indirect, do what we
8728     // need to provide an address for the memory input.
8729     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8730         !OpInfo.isIndirect) {
8731       assert((OpInfo.isMultipleAlternative ||
8732               (OpInfo.Type == InlineAsm::isInput)) &&
8733              "Can only indirectify direct input operands!");
8734 
8735       // Memory operands really want the address of the value.
8736       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8737 
8738       // There is no longer a Value* corresponding to this operand.
8739       OpInfo.CallOperandVal = nullptr;
8740 
8741       // It is now an indirect operand.
8742       OpInfo.isIndirect = true;
8743     }
8744 
8745   }
8746 
8747   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8748   std::vector<SDValue> AsmNodeOperands;
8749   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8750   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8751       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8752 
8753   // If we have a !srcloc metadata node associated with it, we want to attach
8754   // this to the ultimately generated inline asm machineinstr.  To do this, we
8755   // pass in the third operand as this (potentially null) inline asm MDNode.
8756   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8757   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8758 
8759   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8760   // bits as operand 3.
8761   AsmNodeOperands.push_back(DAG.getTargetConstant(
8762       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8763 
8764   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8765   // this, assign virtual and physical registers for inputs and otput.
8766   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8767     // Assign Registers.
8768     SDISelAsmOperandInfo &RefOpInfo =
8769         OpInfo.isMatchingInputConstraint()
8770             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8771             : OpInfo;
8772     const auto RegError =
8773         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8774     if (RegError.hasValue()) {
8775       const MachineFunction &MF = DAG.getMachineFunction();
8776       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8777       const char *RegName = TRI.getName(RegError.getValue());
8778       emitInlineAsmError(Call, "register '" + Twine(RegName) +
8779                                    "' allocated for constraint '" +
8780                                    Twine(OpInfo.ConstraintCode) +
8781                                    "' does not match required type");
8782       return;
8783     }
8784 
8785     auto DetectWriteToReservedRegister = [&]() {
8786       const MachineFunction &MF = DAG.getMachineFunction();
8787       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8788       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8789         if (Register::isPhysicalRegister(Reg) &&
8790             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8791           const char *RegName = TRI.getName(Reg);
8792           emitInlineAsmError(Call, "write to reserved register '" +
8793                                        Twine(RegName) + "'");
8794           return true;
8795         }
8796       }
8797       return false;
8798     };
8799 
8800     switch (OpInfo.Type) {
8801     case InlineAsm::isOutput:
8802       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8803         unsigned ConstraintID =
8804             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8805         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8806                "Failed to convert memory constraint code to constraint id.");
8807 
8808         // Add information to the INLINEASM node to know about this output.
8809         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8810         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8811         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8812                                                         MVT::i32));
8813         AsmNodeOperands.push_back(OpInfo.CallOperand);
8814       } else {
8815         // Otherwise, this outputs to a register (directly for C_Register /
8816         // C_RegisterClass, and a target-defined fashion for
8817         // C_Immediate/C_Other). Find a register that we can use.
8818         if (OpInfo.AssignedRegs.Regs.empty()) {
8819           emitInlineAsmError(
8820               Call, "couldn't allocate output register for constraint '" +
8821                         Twine(OpInfo.ConstraintCode) + "'");
8822           return;
8823         }
8824 
8825         if (DetectWriteToReservedRegister())
8826           return;
8827 
8828         // Add information to the INLINEASM node to know that this register is
8829         // set.
8830         OpInfo.AssignedRegs.AddInlineAsmOperands(
8831             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8832                                   : InlineAsm::Kind_RegDef,
8833             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8834       }
8835       break;
8836 
8837     case InlineAsm::isInput: {
8838       SDValue InOperandVal = OpInfo.CallOperand;
8839 
8840       if (OpInfo.isMatchingInputConstraint()) {
8841         // If this is required to match an output register we have already set,
8842         // just use its register.
8843         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8844                                                   AsmNodeOperands);
8845         unsigned OpFlag =
8846           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8847         if (InlineAsm::isRegDefKind(OpFlag) ||
8848             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8849           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8850           if (OpInfo.isIndirect) {
8851             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8852             emitInlineAsmError(Call, "inline asm not supported yet: "
8853                                      "don't know how to handle tied "
8854                                      "indirect register inputs");
8855             return;
8856           }
8857 
8858           SmallVector<unsigned, 4> Regs;
8859           MachineFunction &MF = DAG.getMachineFunction();
8860           MachineRegisterInfo &MRI = MF.getRegInfo();
8861           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8862           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
8863           Register TiedReg = R->getReg();
8864           MVT RegVT = R->getSimpleValueType(0);
8865           const TargetRegisterClass *RC =
8866               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
8867               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
8868                                       : TRI.getMinimalPhysRegClass(TiedReg);
8869           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8870           for (unsigned i = 0; i != NumRegs; ++i)
8871             Regs.push_back(MRI.createVirtualRegister(RC));
8872 
8873           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8874 
8875           SDLoc dl = getCurSDLoc();
8876           // Use the produced MatchedRegs object to
8877           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8878           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8879                                            true, OpInfo.getMatchedOperand(), dl,
8880                                            DAG, AsmNodeOperands);
8881           break;
8882         }
8883 
8884         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8885         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8886                "Unexpected number of operands");
8887         // Add information to the INLINEASM node to know about this input.
8888         // See InlineAsm.h isUseOperandTiedToDef.
8889         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8890         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8891                                                     OpInfo.getMatchedOperand());
8892         AsmNodeOperands.push_back(DAG.getTargetConstant(
8893             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8894         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8895         break;
8896       }
8897 
8898       // Treat indirect 'X' constraint as memory.
8899       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8900           OpInfo.isIndirect)
8901         OpInfo.ConstraintType = TargetLowering::C_Memory;
8902 
8903       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8904           OpInfo.ConstraintType == TargetLowering::C_Other) {
8905         std::vector<SDValue> Ops;
8906         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8907                                           Ops, DAG);
8908         if (Ops.empty()) {
8909           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8910             if (isa<ConstantSDNode>(InOperandVal)) {
8911               emitInlineAsmError(Call, "value out of range for constraint '" +
8912                                            Twine(OpInfo.ConstraintCode) + "'");
8913               return;
8914             }
8915 
8916           emitInlineAsmError(Call,
8917                              "invalid operand for inline asm constraint '" +
8918                                  Twine(OpInfo.ConstraintCode) + "'");
8919           return;
8920         }
8921 
8922         // Add information to the INLINEASM node to know about this input.
8923         unsigned ResOpType =
8924           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8925         AsmNodeOperands.push_back(DAG.getTargetConstant(
8926             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8927         llvm::append_range(AsmNodeOperands, Ops);
8928         break;
8929       }
8930 
8931       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8932         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8933         assert(InOperandVal.getValueType() ==
8934                    TLI.getPointerTy(DAG.getDataLayout()) &&
8935                "Memory operands expect pointer values");
8936 
8937         unsigned ConstraintID =
8938             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8939         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8940                "Failed to convert memory constraint code to constraint id.");
8941 
8942         // Add information to the INLINEASM node to know about this input.
8943         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8944         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8945         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8946                                                         getCurSDLoc(),
8947                                                         MVT::i32));
8948         AsmNodeOperands.push_back(InOperandVal);
8949         break;
8950       }
8951 
8952       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8953               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8954              "Unknown constraint type!");
8955 
8956       // TODO: Support this.
8957       if (OpInfo.isIndirect) {
8958         emitInlineAsmError(
8959             Call, "Don't know how to handle indirect register inputs yet "
8960                   "for constraint '" +
8961                       Twine(OpInfo.ConstraintCode) + "'");
8962         return;
8963       }
8964 
8965       // Copy the input into the appropriate registers.
8966       if (OpInfo.AssignedRegs.Regs.empty()) {
8967         emitInlineAsmError(Call,
8968                            "couldn't allocate input reg for constraint '" +
8969                                Twine(OpInfo.ConstraintCode) + "'");
8970         return;
8971       }
8972 
8973       if (DetectWriteToReservedRegister())
8974         return;
8975 
8976       SDLoc dl = getCurSDLoc();
8977 
8978       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8979                                         &Call);
8980 
8981       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8982                                                dl, DAG, AsmNodeOperands);
8983       break;
8984     }
8985     case InlineAsm::isClobber:
8986       // Add the clobbered value to the operand list, so that the register
8987       // allocator is aware that the physreg got clobbered.
8988       if (!OpInfo.AssignedRegs.Regs.empty())
8989         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8990                                                  false, 0, getCurSDLoc(), DAG,
8991                                                  AsmNodeOperands);
8992       break;
8993     }
8994   }
8995 
8996   // Finish up input operands.  Set the input chain and add the flag last.
8997   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8998   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8999 
9000   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9001   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9002                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9003   Flag = Chain.getValue(1);
9004 
9005   // Do additional work to generate outputs.
9006 
9007   SmallVector<EVT, 1> ResultVTs;
9008   SmallVector<SDValue, 1> ResultValues;
9009   SmallVector<SDValue, 8> OutChains;
9010 
9011   llvm::Type *CallResultType = Call.getType();
9012   ArrayRef<Type *> ResultTypes;
9013   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9014     ResultTypes = StructResult->elements();
9015   else if (!CallResultType->isVoidTy())
9016     ResultTypes = makeArrayRef(CallResultType);
9017 
9018   auto CurResultType = ResultTypes.begin();
9019   auto handleRegAssign = [&](SDValue V) {
9020     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9021     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9022     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9023     ++CurResultType;
9024     // If the type of the inline asm call site return value is different but has
9025     // same size as the type of the asm output bitcast it.  One example of this
9026     // is for vectors with different width / number of elements.  This can
9027     // happen for register classes that can contain multiple different value
9028     // types.  The preg or vreg allocated may not have the same VT as was
9029     // expected.
9030     //
9031     // This can also happen for a return value that disagrees with the register
9032     // class it is put in, eg. a double in a general-purpose register on a
9033     // 32-bit machine.
9034     if (ResultVT != V.getValueType() &&
9035         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9036       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9037     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9038              V.getValueType().isInteger()) {
9039       // If a result value was tied to an input value, the computed result
9040       // may have a wider width than the expected result.  Extract the
9041       // relevant portion.
9042       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9043     }
9044     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9045     ResultVTs.push_back(ResultVT);
9046     ResultValues.push_back(V);
9047   };
9048 
9049   // Deal with output operands.
9050   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9051     if (OpInfo.Type == InlineAsm::isOutput) {
9052       SDValue Val;
9053       // Skip trivial output operands.
9054       if (OpInfo.AssignedRegs.Regs.empty())
9055         continue;
9056 
9057       switch (OpInfo.ConstraintType) {
9058       case TargetLowering::C_Register:
9059       case TargetLowering::C_RegisterClass:
9060         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9061                                                   Chain, &Flag, &Call);
9062         break;
9063       case TargetLowering::C_Immediate:
9064       case TargetLowering::C_Other:
9065         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9066                                               OpInfo, DAG);
9067         break;
9068       case TargetLowering::C_Memory:
9069         break; // Already handled.
9070       case TargetLowering::C_Unknown:
9071         assert(false && "Unexpected unknown constraint");
9072       }
9073 
9074       // Indirect output manifest as stores. Record output chains.
9075       if (OpInfo.isIndirect) {
9076         const Value *Ptr = OpInfo.CallOperandVal;
9077         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9078         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9079                                      MachinePointerInfo(Ptr));
9080         OutChains.push_back(Store);
9081       } else {
9082         // generate CopyFromRegs to associated registers.
9083         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9084         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9085           for (const SDValue &V : Val->op_values())
9086             handleRegAssign(V);
9087         } else
9088           handleRegAssign(Val);
9089       }
9090     }
9091   }
9092 
9093   // Set results.
9094   if (!ResultValues.empty()) {
9095     assert(CurResultType == ResultTypes.end() &&
9096            "Mismatch in number of ResultTypes");
9097     assert(ResultValues.size() == ResultTypes.size() &&
9098            "Mismatch in number of output operands in asm result");
9099 
9100     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9101                             DAG.getVTList(ResultVTs), ResultValues);
9102     setValue(&Call, V);
9103   }
9104 
9105   // Collect store chains.
9106   if (!OutChains.empty())
9107     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9108 
9109   if (EmitEHLabels) {
9110     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9111   }
9112 
9113   // Only Update Root if inline assembly has a memory effect.
9114   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9115       EmitEHLabels)
9116     DAG.setRoot(Chain);
9117 }
9118 
9119 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9120                                              const Twine &Message) {
9121   LLVMContext &Ctx = *DAG.getContext();
9122   Ctx.emitError(&Call, Message);
9123 
9124   // Make sure we leave the DAG in a valid state
9125   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9126   SmallVector<EVT, 1> ValueVTs;
9127   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9128 
9129   if (ValueVTs.empty())
9130     return;
9131 
9132   SmallVector<SDValue, 1> Ops;
9133   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9134     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9135 
9136   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9137 }
9138 
9139 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9140   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9141                           MVT::Other, getRoot(),
9142                           getValue(I.getArgOperand(0)),
9143                           DAG.getSrcValue(I.getArgOperand(0))));
9144 }
9145 
9146 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9147   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9148   const DataLayout &DL = DAG.getDataLayout();
9149   SDValue V = DAG.getVAArg(
9150       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9151       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9152       DL.getABITypeAlign(I.getType()).value());
9153   DAG.setRoot(V.getValue(1));
9154 
9155   if (I.getType()->isPointerTy())
9156     V = DAG.getPtrExtOrTrunc(
9157         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9158   setValue(&I, V);
9159 }
9160 
9161 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9162   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9163                           MVT::Other, getRoot(),
9164                           getValue(I.getArgOperand(0)),
9165                           DAG.getSrcValue(I.getArgOperand(0))));
9166 }
9167 
9168 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9169   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9170                           MVT::Other, getRoot(),
9171                           getValue(I.getArgOperand(0)),
9172                           getValue(I.getArgOperand(1)),
9173                           DAG.getSrcValue(I.getArgOperand(0)),
9174                           DAG.getSrcValue(I.getArgOperand(1))));
9175 }
9176 
9177 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9178                                                     const Instruction &I,
9179                                                     SDValue Op) {
9180   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9181   if (!Range)
9182     return Op;
9183 
9184   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9185   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9186     return Op;
9187 
9188   APInt Lo = CR.getUnsignedMin();
9189   if (!Lo.isMinValue())
9190     return Op;
9191 
9192   APInt Hi = CR.getUnsignedMax();
9193   unsigned Bits = std::max(Hi.getActiveBits(),
9194                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9195 
9196   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9197 
9198   SDLoc SL = getCurSDLoc();
9199 
9200   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9201                              DAG.getValueType(SmallVT));
9202   unsigned NumVals = Op.getNode()->getNumValues();
9203   if (NumVals == 1)
9204     return ZExt;
9205 
9206   SmallVector<SDValue, 4> Ops;
9207 
9208   Ops.push_back(ZExt);
9209   for (unsigned I = 1; I != NumVals; ++I)
9210     Ops.push_back(Op.getValue(I));
9211 
9212   return DAG.getMergeValues(Ops, SL);
9213 }
9214 
9215 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9216 /// the call being lowered.
9217 ///
9218 /// This is a helper for lowering intrinsics that follow a target calling
9219 /// convention or require stack pointer adjustment. Only a subset of the
9220 /// intrinsic's operands need to participate in the calling convention.
9221 void SelectionDAGBuilder::populateCallLoweringInfo(
9222     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9223     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9224     bool IsPatchPoint) {
9225   TargetLowering::ArgListTy Args;
9226   Args.reserve(NumArgs);
9227 
9228   // Populate the argument list.
9229   // Attributes for args start at offset 1, after the return attribute.
9230   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9231        ArgI != ArgE; ++ArgI) {
9232     const Value *V = Call->getOperand(ArgI);
9233 
9234     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9235 
9236     TargetLowering::ArgListEntry Entry;
9237     Entry.Node = getValue(V);
9238     Entry.Ty = V->getType();
9239     Entry.setAttributes(Call, ArgI);
9240     Args.push_back(Entry);
9241   }
9242 
9243   CLI.setDebugLoc(getCurSDLoc())
9244       .setChain(getRoot())
9245       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9246       .setDiscardResult(Call->use_empty())
9247       .setIsPatchPoint(IsPatchPoint)
9248       .setIsPreallocated(
9249           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9250 }
9251 
9252 /// Add a stack map intrinsic call's live variable operands to a stackmap
9253 /// or patchpoint target node's operand list.
9254 ///
9255 /// Constants are converted to TargetConstants purely as an optimization to
9256 /// avoid constant materialization and register allocation.
9257 ///
9258 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9259 /// generate addess computation nodes, and so FinalizeISel can convert the
9260 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9261 /// address materialization and register allocation, but may also be required
9262 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9263 /// alloca in the entry block, then the runtime may assume that the alloca's
9264 /// StackMap location can be read immediately after compilation and that the
9265 /// location is valid at any point during execution (this is similar to the
9266 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9267 /// only available in a register, then the runtime would need to trap when
9268 /// execution reaches the StackMap in order to read the alloca's location.
9269 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9270                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9271                                 SelectionDAGBuilder &Builder) {
9272   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
9273     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
9274     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
9275       Ops.push_back(
9276         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
9277       Ops.push_back(
9278         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
9279     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
9280       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
9281       Ops.push_back(Builder.DAG.getTargetFrameIndex(
9282           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
9283     } else
9284       Ops.push_back(OpVal);
9285   }
9286 }
9287 
9288 /// Lower llvm.experimental.stackmap directly to its target opcode.
9289 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9290   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
9291   //                                  [live variables...])
9292 
9293   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9294 
9295   SDValue Chain, InFlag, Callee, NullPtr;
9296   SmallVector<SDValue, 32> Ops;
9297 
9298   SDLoc DL = getCurSDLoc();
9299   Callee = getValue(CI.getCalledOperand());
9300   NullPtr = DAG.getIntPtrConstant(0, DL, true);
9301 
9302   // The stackmap intrinsic only records the live variables (the arguments
9303   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9304   // intrinsic, this won't be lowered to a function call. This means we don't
9305   // have to worry about calling conventions and target specific lowering code.
9306   // Instead we perform the call lowering right here.
9307   //
9308   // chain, flag = CALLSEQ_START(chain, 0, 0)
9309   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9310   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9311   //
9312   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9313   InFlag = Chain.getValue(1);
9314 
9315   // Add the <id> and <numBytes> constants.
9316   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
9317   Ops.push_back(DAG.getTargetConstant(
9318                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
9319   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
9320   Ops.push_back(DAG.getTargetConstant(
9321                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
9322                   MVT::i32));
9323 
9324   // Push live variables for the stack map.
9325   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9326 
9327   // We are not pushing any register mask info here on the operands list,
9328   // because the stackmap doesn't clobber anything.
9329 
9330   // Push the chain and the glue flag.
9331   Ops.push_back(Chain);
9332   Ops.push_back(InFlag);
9333 
9334   // Create the STACKMAP node.
9335   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9336   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
9337   Chain = SDValue(SM, 0);
9338   InFlag = Chain.getValue(1);
9339 
9340   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9341 
9342   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9343 
9344   // Set the root to the target-lowered call chain.
9345   DAG.setRoot(Chain);
9346 
9347   // Inform the Frame Information that we have a stackmap in this function.
9348   FuncInfo.MF->getFrameInfo().setHasStackMap();
9349 }
9350 
9351 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9352 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9353                                           const BasicBlock *EHPadBB) {
9354   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9355   //                                                 i32 <numBytes>,
9356   //                                                 i8* <target>,
9357   //                                                 i32 <numArgs>,
9358   //                                                 [Args...],
9359   //                                                 [live variables...])
9360 
9361   CallingConv::ID CC = CB.getCallingConv();
9362   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9363   bool HasDef = !CB.getType()->isVoidTy();
9364   SDLoc dl = getCurSDLoc();
9365   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9366 
9367   // Handle immediate and symbolic callees.
9368   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9369     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9370                                    /*isTarget=*/true);
9371   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9372     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9373                                          SDLoc(SymbolicCallee),
9374                                          SymbolicCallee->getValueType(0));
9375 
9376   // Get the real number of arguments participating in the call <numArgs>
9377   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9378   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9379 
9380   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9381   // Intrinsics include all meta-operands up to but not including CC.
9382   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9383   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9384          "Not enough arguments provided to the patchpoint intrinsic");
9385 
9386   // For AnyRegCC the arguments are lowered later on manually.
9387   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9388   Type *ReturnTy =
9389       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9390 
9391   TargetLowering::CallLoweringInfo CLI(DAG);
9392   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9393                            ReturnTy, true);
9394   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9395 
9396   SDNode *CallEnd = Result.second.getNode();
9397   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9398     CallEnd = CallEnd->getOperand(0).getNode();
9399 
9400   /// Get a call instruction from the call sequence chain.
9401   /// Tail calls are not allowed.
9402   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9403          "Expected a callseq node.");
9404   SDNode *Call = CallEnd->getOperand(0).getNode();
9405   bool HasGlue = Call->getGluedNode();
9406 
9407   // Replace the target specific call node with the patchable intrinsic.
9408   SmallVector<SDValue, 8> Ops;
9409 
9410   // Add the <id> and <numBytes> constants.
9411   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9412   Ops.push_back(DAG.getTargetConstant(
9413                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9414   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9415   Ops.push_back(DAG.getTargetConstant(
9416                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9417                   MVT::i32));
9418 
9419   // Add the callee.
9420   Ops.push_back(Callee);
9421 
9422   // Adjust <numArgs> to account for any arguments that have been passed on the
9423   // stack instead.
9424   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9425   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9426   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9427   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9428 
9429   // Add the calling convention
9430   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9431 
9432   // Add the arguments we omitted previously. The register allocator should
9433   // place these in any free register.
9434   if (IsAnyRegCC)
9435     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9436       Ops.push_back(getValue(CB.getArgOperand(i)));
9437 
9438   // Push the arguments from the call instruction up to the register mask.
9439   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9440   Ops.append(Call->op_begin() + 2, e);
9441 
9442   // Push live variables for the stack map.
9443   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9444 
9445   // Push the register mask info.
9446   if (HasGlue)
9447     Ops.push_back(*(Call->op_end()-2));
9448   else
9449     Ops.push_back(*(Call->op_end()-1));
9450 
9451   // Push the chain (this is originally the first operand of the call, but
9452   // becomes now the last or second to last operand).
9453   Ops.push_back(*(Call->op_begin()));
9454 
9455   // Push the glue flag (last operand).
9456   if (HasGlue)
9457     Ops.push_back(*(Call->op_end()-1));
9458 
9459   SDVTList NodeTys;
9460   if (IsAnyRegCC && HasDef) {
9461     // Create the return types based on the intrinsic definition
9462     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9463     SmallVector<EVT, 3> ValueVTs;
9464     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9465     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9466 
9467     // There is always a chain and a glue type at the end
9468     ValueVTs.push_back(MVT::Other);
9469     ValueVTs.push_back(MVT::Glue);
9470     NodeTys = DAG.getVTList(ValueVTs);
9471   } else
9472     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9473 
9474   // Replace the target specific call node with a PATCHPOINT node.
9475   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9476                                          dl, NodeTys, Ops);
9477 
9478   // Update the NodeMap.
9479   if (HasDef) {
9480     if (IsAnyRegCC)
9481       setValue(&CB, SDValue(MN, 0));
9482     else
9483       setValue(&CB, Result.first);
9484   }
9485 
9486   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9487   // call sequence. Furthermore the location of the chain and glue can change
9488   // when the AnyReg calling convention is used and the intrinsic returns a
9489   // value.
9490   if (IsAnyRegCC && HasDef) {
9491     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9492     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9493     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9494   } else
9495     DAG.ReplaceAllUsesWith(Call, MN);
9496   DAG.DeleteNode(Call);
9497 
9498   // Inform the Frame Information that we have a patchpoint in this function.
9499   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9500 }
9501 
9502 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9503                                             unsigned Intrinsic) {
9504   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9505   SDValue Op1 = getValue(I.getArgOperand(0));
9506   SDValue Op2;
9507   if (I.arg_size() > 1)
9508     Op2 = getValue(I.getArgOperand(1));
9509   SDLoc dl = getCurSDLoc();
9510   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9511   SDValue Res;
9512   SDNodeFlags SDFlags;
9513   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9514     SDFlags.copyFMF(*FPMO);
9515 
9516   switch (Intrinsic) {
9517   case Intrinsic::vector_reduce_fadd:
9518     if (SDFlags.hasAllowReassociation())
9519       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9520                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9521                         SDFlags);
9522     else
9523       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9524     break;
9525   case Intrinsic::vector_reduce_fmul:
9526     if (SDFlags.hasAllowReassociation())
9527       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9528                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9529                         SDFlags);
9530     else
9531       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9532     break;
9533   case Intrinsic::vector_reduce_add:
9534     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9535     break;
9536   case Intrinsic::vector_reduce_mul:
9537     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9538     break;
9539   case Intrinsic::vector_reduce_and:
9540     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9541     break;
9542   case Intrinsic::vector_reduce_or:
9543     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9544     break;
9545   case Intrinsic::vector_reduce_xor:
9546     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9547     break;
9548   case Intrinsic::vector_reduce_smax:
9549     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9550     break;
9551   case Intrinsic::vector_reduce_smin:
9552     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9553     break;
9554   case Intrinsic::vector_reduce_umax:
9555     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9556     break;
9557   case Intrinsic::vector_reduce_umin:
9558     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9559     break;
9560   case Intrinsic::vector_reduce_fmax:
9561     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9562     break;
9563   case Intrinsic::vector_reduce_fmin:
9564     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9565     break;
9566   default:
9567     llvm_unreachable("Unhandled vector reduce intrinsic");
9568   }
9569   setValue(&I, Res);
9570 }
9571 
9572 /// Returns an AttributeList representing the attributes applied to the return
9573 /// value of the given call.
9574 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9575   SmallVector<Attribute::AttrKind, 2> Attrs;
9576   if (CLI.RetSExt)
9577     Attrs.push_back(Attribute::SExt);
9578   if (CLI.RetZExt)
9579     Attrs.push_back(Attribute::ZExt);
9580   if (CLI.IsInReg)
9581     Attrs.push_back(Attribute::InReg);
9582 
9583   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9584                             Attrs);
9585 }
9586 
9587 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9588 /// implementation, which just calls LowerCall.
9589 /// FIXME: When all targets are
9590 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9591 std::pair<SDValue, SDValue>
9592 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9593   // Handle the incoming return values from the call.
9594   CLI.Ins.clear();
9595   Type *OrigRetTy = CLI.RetTy;
9596   SmallVector<EVT, 4> RetTys;
9597   SmallVector<uint64_t, 4> Offsets;
9598   auto &DL = CLI.DAG.getDataLayout();
9599   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9600 
9601   if (CLI.IsPostTypeLegalization) {
9602     // If we are lowering a libcall after legalization, split the return type.
9603     SmallVector<EVT, 4> OldRetTys;
9604     SmallVector<uint64_t, 4> OldOffsets;
9605     RetTys.swap(OldRetTys);
9606     Offsets.swap(OldOffsets);
9607 
9608     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9609       EVT RetVT = OldRetTys[i];
9610       uint64_t Offset = OldOffsets[i];
9611       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9612       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9613       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9614       RetTys.append(NumRegs, RegisterVT);
9615       for (unsigned j = 0; j != NumRegs; ++j)
9616         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9617     }
9618   }
9619 
9620   SmallVector<ISD::OutputArg, 4> Outs;
9621   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9622 
9623   bool CanLowerReturn =
9624       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9625                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9626 
9627   SDValue DemoteStackSlot;
9628   int DemoteStackIdx = -100;
9629   if (!CanLowerReturn) {
9630     // FIXME: equivalent assert?
9631     // assert(!CS.hasInAllocaArgument() &&
9632     //        "sret demotion is incompatible with inalloca");
9633     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9634     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9635     MachineFunction &MF = CLI.DAG.getMachineFunction();
9636     DemoteStackIdx =
9637         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9638     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9639                                               DL.getAllocaAddrSpace());
9640 
9641     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9642     ArgListEntry Entry;
9643     Entry.Node = DemoteStackSlot;
9644     Entry.Ty = StackSlotPtrType;
9645     Entry.IsSExt = false;
9646     Entry.IsZExt = false;
9647     Entry.IsInReg = false;
9648     Entry.IsSRet = true;
9649     Entry.IsNest = false;
9650     Entry.IsByVal = false;
9651     Entry.IsByRef = false;
9652     Entry.IsReturned = false;
9653     Entry.IsSwiftSelf = false;
9654     Entry.IsSwiftAsync = false;
9655     Entry.IsSwiftError = false;
9656     Entry.IsCFGuardTarget = false;
9657     Entry.Alignment = Alignment;
9658     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9659     CLI.NumFixedArgs += 1;
9660     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9661 
9662     // sret demotion isn't compatible with tail-calls, since the sret argument
9663     // points into the callers stack frame.
9664     CLI.IsTailCall = false;
9665   } else {
9666     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9667         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9668     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9669       ISD::ArgFlagsTy Flags;
9670       if (NeedsRegBlock) {
9671         Flags.setInConsecutiveRegs();
9672         if (I == RetTys.size() - 1)
9673           Flags.setInConsecutiveRegsLast();
9674       }
9675       EVT VT = RetTys[I];
9676       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9677                                                      CLI.CallConv, VT);
9678       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9679                                                        CLI.CallConv, VT);
9680       for (unsigned i = 0; i != NumRegs; ++i) {
9681         ISD::InputArg MyFlags;
9682         MyFlags.Flags = Flags;
9683         MyFlags.VT = RegisterVT;
9684         MyFlags.ArgVT = VT;
9685         MyFlags.Used = CLI.IsReturnValueUsed;
9686         if (CLI.RetTy->isPointerTy()) {
9687           MyFlags.Flags.setPointer();
9688           MyFlags.Flags.setPointerAddrSpace(
9689               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9690         }
9691         if (CLI.RetSExt)
9692           MyFlags.Flags.setSExt();
9693         if (CLI.RetZExt)
9694           MyFlags.Flags.setZExt();
9695         if (CLI.IsInReg)
9696           MyFlags.Flags.setInReg();
9697         CLI.Ins.push_back(MyFlags);
9698       }
9699     }
9700   }
9701 
9702   // We push in swifterror return as the last element of CLI.Ins.
9703   ArgListTy &Args = CLI.getArgs();
9704   if (supportSwiftError()) {
9705     for (const ArgListEntry &Arg : Args) {
9706       if (Arg.IsSwiftError) {
9707         ISD::InputArg MyFlags;
9708         MyFlags.VT = getPointerTy(DL);
9709         MyFlags.ArgVT = EVT(getPointerTy(DL));
9710         MyFlags.Flags.setSwiftError();
9711         CLI.Ins.push_back(MyFlags);
9712       }
9713     }
9714   }
9715 
9716   // Handle all of the outgoing arguments.
9717   CLI.Outs.clear();
9718   CLI.OutVals.clear();
9719   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9720     SmallVector<EVT, 4> ValueVTs;
9721     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9722     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9723     Type *FinalType = Args[i].Ty;
9724     if (Args[i].IsByVal)
9725       FinalType = Args[i].IndirectType;
9726     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9727         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9728     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9729          ++Value) {
9730       EVT VT = ValueVTs[Value];
9731       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9732       SDValue Op = SDValue(Args[i].Node.getNode(),
9733                            Args[i].Node.getResNo() + Value);
9734       ISD::ArgFlagsTy Flags;
9735 
9736       // Certain targets (such as MIPS), may have a different ABI alignment
9737       // for a type depending on the context. Give the target a chance to
9738       // specify the alignment it wants.
9739       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9740       Flags.setOrigAlign(OriginalAlignment);
9741 
9742       if (Args[i].Ty->isPointerTy()) {
9743         Flags.setPointer();
9744         Flags.setPointerAddrSpace(
9745             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9746       }
9747       if (Args[i].IsZExt)
9748         Flags.setZExt();
9749       if (Args[i].IsSExt)
9750         Flags.setSExt();
9751       if (Args[i].IsInReg) {
9752         // If we are using vectorcall calling convention, a structure that is
9753         // passed InReg - is surely an HVA
9754         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9755             isa<StructType>(FinalType)) {
9756           // The first value of a structure is marked
9757           if (0 == Value)
9758             Flags.setHvaStart();
9759           Flags.setHva();
9760         }
9761         // Set InReg Flag
9762         Flags.setInReg();
9763       }
9764       if (Args[i].IsSRet)
9765         Flags.setSRet();
9766       if (Args[i].IsSwiftSelf)
9767         Flags.setSwiftSelf();
9768       if (Args[i].IsSwiftAsync)
9769         Flags.setSwiftAsync();
9770       if (Args[i].IsSwiftError)
9771         Flags.setSwiftError();
9772       if (Args[i].IsCFGuardTarget)
9773         Flags.setCFGuardTarget();
9774       if (Args[i].IsByVal)
9775         Flags.setByVal();
9776       if (Args[i].IsByRef)
9777         Flags.setByRef();
9778       if (Args[i].IsPreallocated) {
9779         Flags.setPreallocated();
9780         // Set the byval flag for CCAssignFn callbacks that don't know about
9781         // preallocated.  This way we can know how many bytes we should've
9782         // allocated and how many bytes a callee cleanup function will pop.  If
9783         // we port preallocated to more targets, we'll have to add custom
9784         // preallocated handling in the various CC lowering callbacks.
9785         Flags.setByVal();
9786       }
9787       if (Args[i].IsInAlloca) {
9788         Flags.setInAlloca();
9789         // Set the byval flag for CCAssignFn callbacks that don't know about
9790         // inalloca.  This way we can know how many bytes we should've allocated
9791         // and how many bytes a callee cleanup function will pop.  If we port
9792         // inalloca to more targets, we'll have to add custom inalloca handling
9793         // in the various CC lowering callbacks.
9794         Flags.setByVal();
9795       }
9796       Align MemAlign;
9797       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9798         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9799         Flags.setByValSize(FrameSize);
9800 
9801         // info is not there but there are cases it cannot get right.
9802         if (auto MA = Args[i].Alignment)
9803           MemAlign = *MA;
9804         else
9805           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
9806       } else if (auto MA = Args[i].Alignment) {
9807         MemAlign = *MA;
9808       } else {
9809         MemAlign = OriginalAlignment;
9810       }
9811       Flags.setMemAlign(MemAlign);
9812       if (Args[i].IsNest)
9813         Flags.setNest();
9814       if (NeedsRegBlock)
9815         Flags.setInConsecutiveRegs();
9816 
9817       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9818                                                  CLI.CallConv, VT);
9819       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9820                                                         CLI.CallConv, VT);
9821       SmallVector<SDValue, 4> Parts(NumParts);
9822       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9823 
9824       if (Args[i].IsSExt)
9825         ExtendKind = ISD::SIGN_EXTEND;
9826       else if (Args[i].IsZExt)
9827         ExtendKind = ISD::ZERO_EXTEND;
9828 
9829       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9830       // for now.
9831       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9832           CanLowerReturn) {
9833         assert((CLI.RetTy == Args[i].Ty ||
9834                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9835                  CLI.RetTy->getPointerAddressSpace() ==
9836                      Args[i].Ty->getPointerAddressSpace())) &&
9837                RetTys.size() == NumValues && "unexpected use of 'returned'");
9838         // Before passing 'returned' to the target lowering code, ensure that
9839         // either the register MVT and the actual EVT are the same size or that
9840         // the return value and argument are extended in the same way; in these
9841         // cases it's safe to pass the argument register value unchanged as the
9842         // return register value (although it's at the target's option whether
9843         // to do so)
9844         // TODO: allow code generation to take advantage of partially preserved
9845         // registers rather than clobbering the entire register when the
9846         // parameter extension method is not compatible with the return
9847         // extension method
9848         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9849             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9850              CLI.RetZExt == Args[i].IsZExt))
9851           Flags.setReturned();
9852       }
9853 
9854       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9855                      CLI.CallConv, ExtendKind);
9856 
9857       for (unsigned j = 0; j != NumParts; ++j) {
9858         // if it isn't first piece, alignment must be 1
9859         // For scalable vectors the scalable part is currently handled
9860         // by individual targets, so we just use the known minimum size here.
9861         ISD::OutputArg MyFlags(
9862             Flags, Parts[j].getValueType().getSimpleVT(), VT,
9863             i < CLI.NumFixedArgs, i,
9864             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
9865         if (NumParts > 1 && j == 0)
9866           MyFlags.Flags.setSplit();
9867         else if (j != 0) {
9868           MyFlags.Flags.setOrigAlign(Align(1));
9869           if (j == NumParts - 1)
9870             MyFlags.Flags.setSplitEnd();
9871         }
9872 
9873         CLI.Outs.push_back(MyFlags);
9874         CLI.OutVals.push_back(Parts[j]);
9875       }
9876 
9877       if (NeedsRegBlock && Value == NumValues - 1)
9878         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9879     }
9880   }
9881 
9882   SmallVector<SDValue, 4> InVals;
9883   CLI.Chain = LowerCall(CLI, InVals);
9884 
9885   // Update CLI.InVals to use outside of this function.
9886   CLI.InVals = InVals;
9887 
9888   // Verify that the target's LowerCall behaved as expected.
9889   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9890          "LowerCall didn't return a valid chain!");
9891   assert((!CLI.IsTailCall || InVals.empty()) &&
9892          "LowerCall emitted a return value for a tail call!");
9893   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9894          "LowerCall didn't emit the correct number of values!");
9895 
9896   // For a tail call, the return value is merely live-out and there aren't
9897   // any nodes in the DAG representing it. Return a special value to
9898   // indicate that a tail call has been emitted and no more Instructions
9899   // should be processed in the current block.
9900   if (CLI.IsTailCall) {
9901     CLI.DAG.setRoot(CLI.Chain);
9902     return std::make_pair(SDValue(), SDValue());
9903   }
9904 
9905 #ifndef NDEBUG
9906   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9907     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9908     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9909            "LowerCall emitted a value with the wrong type!");
9910   }
9911 #endif
9912 
9913   SmallVector<SDValue, 4> ReturnValues;
9914   if (!CanLowerReturn) {
9915     // The instruction result is the result of loading from the
9916     // hidden sret parameter.
9917     SmallVector<EVT, 1> PVTs;
9918     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9919 
9920     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9921     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9922     EVT PtrVT = PVTs[0];
9923 
9924     unsigned NumValues = RetTys.size();
9925     ReturnValues.resize(NumValues);
9926     SmallVector<SDValue, 4> Chains(NumValues);
9927 
9928     // An aggregate return value cannot wrap around the address space, so
9929     // offsets to its parts don't wrap either.
9930     SDNodeFlags Flags;
9931     Flags.setNoUnsignedWrap(true);
9932 
9933     MachineFunction &MF = CLI.DAG.getMachineFunction();
9934     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9935     for (unsigned i = 0; i < NumValues; ++i) {
9936       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9937                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9938                                                         PtrVT), Flags);
9939       SDValue L = CLI.DAG.getLoad(
9940           RetTys[i], CLI.DL, CLI.Chain, Add,
9941           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9942                                             DemoteStackIdx, Offsets[i]),
9943           HiddenSRetAlign);
9944       ReturnValues[i] = L;
9945       Chains[i] = L.getValue(1);
9946     }
9947 
9948     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9949   } else {
9950     // Collect the legal value parts into potentially illegal values
9951     // that correspond to the original function's return values.
9952     Optional<ISD::NodeType> AssertOp;
9953     if (CLI.RetSExt)
9954       AssertOp = ISD::AssertSext;
9955     else if (CLI.RetZExt)
9956       AssertOp = ISD::AssertZext;
9957     unsigned CurReg = 0;
9958     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9959       EVT VT = RetTys[I];
9960       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9961                                                      CLI.CallConv, VT);
9962       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9963                                                        CLI.CallConv, VT);
9964 
9965       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9966                                               NumRegs, RegisterVT, VT, nullptr,
9967                                               CLI.CallConv, AssertOp));
9968       CurReg += NumRegs;
9969     }
9970 
9971     // For a function returning void, there is no return value. We can't create
9972     // such a node, so we just return a null return value in that case. In
9973     // that case, nothing will actually look at the value.
9974     if (ReturnValues.empty())
9975       return std::make_pair(SDValue(), CLI.Chain);
9976   }
9977 
9978   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9979                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9980   return std::make_pair(Res, CLI.Chain);
9981 }
9982 
9983 /// Places new result values for the node in Results (their number
9984 /// and types must exactly match those of the original return values of
9985 /// the node), or leaves Results empty, which indicates that the node is not
9986 /// to be custom lowered after all.
9987 void TargetLowering::LowerOperationWrapper(SDNode *N,
9988                                            SmallVectorImpl<SDValue> &Results,
9989                                            SelectionDAG &DAG) const {
9990   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9991 
9992   if (!Res.getNode())
9993     return;
9994 
9995   // If the original node has one result, take the return value from
9996   // LowerOperation as is. It might not be result number 0.
9997   if (N->getNumValues() == 1) {
9998     Results.push_back(Res);
9999     return;
10000   }
10001 
10002   // If the original node has multiple results, then the return node should
10003   // have the same number of results.
10004   assert((N->getNumValues() == Res->getNumValues()) &&
10005       "Lowering returned the wrong number of results!");
10006 
10007   // Places new result values base on N result number.
10008   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10009     Results.push_back(Res.getValue(I));
10010 }
10011 
10012 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10013   llvm_unreachable("LowerOperation not implemented for this target!");
10014 }
10015 
10016 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10017                                                      unsigned Reg,
10018                                                      ISD::NodeType ExtendType) {
10019   SDValue Op = getNonRegisterValue(V);
10020   assert((Op.getOpcode() != ISD::CopyFromReg ||
10021           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10022          "Copy from a reg to the same reg!");
10023   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10024 
10025   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10026   // If this is an InlineAsm we have to match the registers required, not the
10027   // notional registers required by the type.
10028 
10029   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10030                    None); // This is not an ABI copy.
10031   SDValue Chain = DAG.getEntryNode();
10032 
10033   if (ExtendType == ISD::ANY_EXTEND) {
10034     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10035     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10036       ExtendType = PreferredExtendIt->second;
10037   }
10038   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10039   PendingExports.push_back(Chain);
10040 }
10041 
10042 #include "llvm/CodeGen/SelectionDAGISel.h"
10043 
10044 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10045 /// entry block, return true.  This includes arguments used by switches, since
10046 /// the switch may expand into multiple basic blocks.
10047 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10048   // With FastISel active, we may be splitting blocks, so force creation
10049   // of virtual registers for all non-dead arguments.
10050   if (FastISel)
10051     return A->use_empty();
10052 
10053   const BasicBlock &Entry = A->getParent()->front();
10054   for (const User *U : A->users())
10055     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10056       return false;  // Use not in entry block.
10057 
10058   return true;
10059 }
10060 
10061 using ArgCopyElisionMapTy =
10062     DenseMap<const Argument *,
10063              std::pair<const AllocaInst *, const StoreInst *>>;
10064 
10065 /// Scan the entry block of the function in FuncInfo for arguments that look
10066 /// like copies into a local alloca. Record any copied arguments in
10067 /// ArgCopyElisionCandidates.
10068 static void
10069 findArgumentCopyElisionCandidates(const DataLayout &DL,
10070                                   FunctionLoweringInfo *FuncInfo,
10071                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10072   // Record the state of every static alloca used in the entry block. Argument
10073   // allocas are all used in the entry block, so we need approximately as many
10074   // entries as we have arguments.
10075   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10076   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10077   unsigned NumArgs = FuncInfo->Fn->arg_size();
10078   StaticAllocas.reserve(NumArgs * 2);
10079 
10080   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10081     if (!V)
10082       return nullptr;
10083     V = V->stripPointerCasts();
10084     const auto *AI = dyn_cast<AllocaInst>(V);
10085     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10086       return nullptr;
10087     auto Iter = StaticAllocas.insert({AI, Unknown});
10088     return &Iter.first->second;
10089   };
10090 
10091   // Look for stores of arguments to static allocas. Look through bitcasts and
10092   // GEPs to handle type coercions, as long as the alloca is fully initialized
10093   // by the store. Any non-store use of an alloca escapes it and any subsequent
10094   // unanalyzed store might write it.
10095   // FIXME: Handle structs initialized with multiple stores.
10096   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10097     // Look for stores, and handle non-store uses conservatively.
10098     const auto *SI = dyn_cast<StoreInst>(&I);
10099     if (!SI) {
10100       // We will look through cast uses, so ignore them completely.
10101       if (I.isCast())
10102         continue;
10103       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10104       // to allocas.
10105       if (I.isDebugOrPseudoInst())
10106         continue;
10107       // This is an unknown instruction. Assume it escapes or writes to all
10108       // static alloca operands.
10109       for (const Use &U : I.operands()) {
10110         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10111           *Info = StaticAllocaInfo::Clobbered;
10112       }
10113       continue;
10114     }
10115 
10116     // If the stored value is a static alloca, mark it as escaped.
10117     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10118       *Info = StaticAllocaInfo::Clobbered;
10119 
10120     // Check if the destination is a static alloca.
10121     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10122     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10123     if (!Info)
10124       continue;
10125     const AllocaInst *AI = cast<AllocaInst>(Dst);
10126 
10127     // Skip allocas that have been initialized or clobbered.
10128     if (*Info != StaticAllocaInfo::Unknown)
10129       continue;
10130 
10131     // Check if the stored value is an argument, and that this store fully
10132     // initializes the alloca.
10133     // If the argument type has padding bits we can't directly forward a pointer
10134     // as the upper bits may contain garbage.
10135     // Don't elide copies from the same argument twice.
10136     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10137     const auto *Arg = dyn_cast<Argument>(Val);
10138     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10139         Arg->getType()->isEmptyTy() ||
10140         DL.getTypeStoreSize(Arg->getType()) !=
10141             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10142         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10143         ArgCopyElisionCandidates.count(Arg)) {
10144       *Info = StaticAllocaInfo::Clobbered;
10145       continue;
10146     }
10147 
10148     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10149                       << '\n');
10150 
10151     // Mark this alloca and store for argument copy elision.
10152     *Info = StaticAllocaInfo::Elidable;
10153     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10154 
10155     // Stop scanning if we've seen all arguments. This will happen early in -O0
10156     // builds, which is useful, because -O0 builds have large entry blocks and
10157     // many allocas.
10158     if (ArgCopyElisionCandidates.size() == NumArgs)
10159       break;
10160   }
10161 }
10162 
10163 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10164 /// ArgVal is a load from a suitable fixed stack object.
10165 static void tryToElideArgumentCopy(
10166     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10167     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10168     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10169     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10170     SDValue ArgVal, bool &ArgHasUses) {
10171   // Check if this is a load from a fixed stack object.
10172   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10173   if (!LNode)
10174     return;
10175   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10176   if (!FINode)
10177     return;
10178 
10179   // Check that the fixed stack object is the right size and alignment.
10180   // Look at the alignment that the user wrote on the alloca instead of looking
10181   // at the stack object.
10182   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10183   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10184   const AllocaInst *AI = ArgCopyIter->second.first;
10185   int FixedIndex = FINode->getIndex();
10186   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10187   int OldIndex = AllocaIndex;
10188   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10189   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10190     LLVM_DEBUG(
10191         dbgs() << "  argument copy elision failed due to bad fixed stack "
10192                   "object size\n");
10193     return;
10194   }
10195   Align RequiredAlignment = AI->getAlign();
10196   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10197     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10198                          "greater than stack argument alignment ("
10199                       << DebugStr(RequiredAlignment) << " vs "
10200                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10201     return;
10202   }
10203 
10204   // Perform the elision. Delete the old stack object and replace its only use
10205   // in the variable info map. Mark the stack object as mutable.
10206   LLVM_DEBUG({
10207     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10208            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10209            << '\n';
10210   });
10211   MFI.RemoveStackObject(OldIndex);
10212   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10213   AllocaIndex = FixedIndex;
10214   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10215   Chains.push_back(ArgVal.getValue(1));
10216 
10217   // Avoid emitting code for the store implementing the copy.
10218   const StoreInst *SI = ArgCopyIter->second.second;
10219   ElidedArgCopyInstrs.insert(SI);
10220 
10221   // Check for uses of the argument again so that we can avoid exporting ArgVal
10222   // if it is't used by anything other than the store.
10223   for (const Value *U : Arg.users()) {
10224     if (U != SI) {
10225       ArgHasUses = true;
10226       break;
10227     }
10228   }
10229 }
10230 
10231 void SelectionDAGISel::LowerArguments(const Function &F) {
10232   SelectionDAG &DAG = SDB->DAG;
10233   SDLoc dl = SDB->getCurSDLoc();
10234   const DataLayout &DL = DAG.getDataLayout();
10235   SmallVector<ISD::InputArg, 16> Ins;
10236 
10237   // In Naked functions we aren't going to save any registers.
10238   if (F.hasFnAttribute(Attribute::Naked))
10239     return;
10240 
10241   if (!FuncInfo->CanLowerReturn) {
10242     // Put in an sret pointer parameter before all the other parameters.
10243     SmallVector<EVT, 1> ValueVTs;
10244     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10245                     F.getReturnType()->getPointerTo(
10246                         DAG.getDataLayout().getAllocaAddrSpace()),
10247                     ValueVTs);
10248 
10249     // NOTE: Assuming that a pointer will never break down to more than one VT
10250     // or one register.
10251     ISD::ArgFlagsTy Flags;
10252     Flags.setSRet();
10253     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10254     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10255                          ISD::InputArg::NoArgIndex, 0);
10256     Ins.push_back(RetArg);
10257   }
10258 
10259   // Look for stores of arguments to static allocas. Mark such arguments with a
10260   // flag to ask the target to give us the memory location of that argument if
10261   // available.
10262   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10263   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10264                                     ArgCopyElisionCandidates);
10265 
10266   // Set up the incoming argument description vector.
10267   for (const Argument &Arg : F.args()) {
10268     unsigned ArgNo = Arg.getArgNo();
10269     SmallVector<EVT, 4> ValueVTs;
10270     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10271     bool isArgValueUsed = !Arg.use_empty();
10272     unsigned PartBase = 0;
10273     Type *FinalType = Arg.getType();
10274     if (Arg.hasAttribute(Attribute::ByVal))
10275       FinalType = Arg.getParamByValType();
10276     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10277         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10278     for (unsigned Value = 0, NumValues = ValueVTs.size();
10279          Value != NumValues; ++Value) {
10280       EVT VT = ValueVTs[Value];
10281       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10282       ISD::ArgFlagsTy Flags;
10283 
10284 
10285       if (Arg.getType()->isPointerTy()) {
10286         Flags.setPointer();
10287         Flags.setPointerAddrSpace(
10288             cast<PointerType>(Arg.getType())->getAddressSpace());
10289       }
10290       if (Arg.hasAttribute(Attribute::ZExt))
10291         Flags.setZExt();
10292       if (Arg.hasAttribute(Attribute::SExt))
10293         Flags.setSExt();
10294       if (Arg.hasAttribute(Attribute::InReg)) {
10295         // If we are using vectorcall calling convention, a structure that is
10296         // passed InReg - is surely an HVA
10297         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10298             isa<StructType>(Arg.getType())) {
10299           // The first value of a structure is marked
10300           if (0 == Value)
10301             Flags.setHvaStart();
10302           Flags.setHva();
10303         }
10304         // Set InReg Flag
10305         Flags.setInReg();
10306       }
10307       if (Arg.hasAttribute(Attribute::StructRet))
10308         Flags.setSRet();
10309       if (Arg.hasAttribute(Attribute::SwiftSelf))
10310         Flags.setSwiftSelf();
10311       if (Arg.hasAttribute(Attribute::SwiftAsync))
10312         Flags.setSwiftAsync();
10313       if (Arg.hasAttribute(Attribute::SwiftError))
10314         Flags.setSwiftError();
10315       if (Arg.hasAttribute(Attribute::ByVal))
10316         Flags.setByVal();
10317       if (Arg.hasAttribute(Attribute::ByRef))
10318         Flags.setByRef();
10319       if (Arg.hasAttribute(Attribute::InAlloca)) {
10320         Flags.setInAlloca();
10321         // Set the byval flag for CCAssignFn callbacks that don't know about
10322         // inalloca.  This way we can know how many bytes we should've allocated
10323         // and how many bytes a callee cleanup function will pop.  If we port
10324         // inalloca to more targets, we'll have to add custom inalloca handling
10325         // in the various CC lowering callbacks.
10326         Flags.setByVal();
10327       }
10328       if (Arg.hasAttribute(Attribute::Preallocated)) {
10329         Flags.setPreallocated();
10330         // Set the byval flag for CCAssignFn callbacks that don't know about
10331         // preallocated.  This way we can know how many bytes we should've
10332         // allocated and how many bytes a callee cleanup function will pop.  If
10333         // we port preallocated to more targets, we'll have to add custom
10334         // preallocated handling in the various CC lowering callbacks.
10335         Flags.setByVal();
10336       }
10337 
10338       // Certain targets (such as MIPS), may have a different ABI alignment
10339       // for a type depending on the context. Give the target a chance to
10340       // specify the alignment it wants.
10341       const Align OriginalAlignment(
10342           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10343       Flags.setOrigAlign(OriginalAlignment);
10344 
10345       Align MemAlign;
10346       Type *ArgMemTy = nullptr;
10347       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10348           Flags.isByRef()) {
10349         if (!ArgMemTy)
10350           ArgMemTy = Arg.getPointeeInMemoryValueType();
10351 
10352         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10353 
10354         // For in-memory arguments, size and alignment should be passed from FE.
10355         // BE will guess if this info is not there but there are cases it cannot
10356         // get right.
10357         if (auto ParamAlign = Arg.getParamStackAlign())
10358           MemAlign = *ParamAlign;
10359         else if ((ParamAlign = Arg.getParamAlign()))
10360           MemAlign = *ParamAlign;
10361         else
10362           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10363         if (Flags.isByRef())
10364           Flags.setByRefSize(MemSize);
10365         else
10366           Flags.setByValSize(MemSize);
10367       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10368         MemAlign = *ParamAlign;
10369       } else {
10370         MemAlign = OriginalAlignment;
10371       }
10372       Flags.setMemAlign(MemAlign);
10373 
10374       if (Arg.hasAttribute(Attribute::Nest))
10375         Flags.setNest();
10376       if (NeedsRegBlock)
10377         Flags.setInConsecutiveRegs();
10378       if (ArgCopyElisionCandidates.count(&Arg))
10379         Flags.setCopyElisionCandidate();
10380       if (Arg.hasAttribute(Attribute::Returned))
10381         Flags.setReturned();
10382 
10383       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10384           *CurDAG->getContext(), F.getCallingConv(), VT);
10385       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10386           *CurDAG->getContext(), F.getCallingConv(), VT);
10387       for (unsigned i = 0; i != NumRegs; ++i) {
10388         // For scalable vectors, use the minimum size; individual targets
10389         // are responsible for handling scalable vector arguments and
10390         // return values.
10391         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10392                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10393         if (NumRegs > 1 && i == 0)
10394           MyFlags.Flags.setSplit();
10395         // if it isn't first piece, alignment must be 1
10396         else if (i > 0) {
10397           MyFlags.Flags.setOrigAlign(Align(1));
10398           if (i == NumRegs - 1)
10399             MyFlags.Flags.setSplitEnd();
10400         }
10401         Ins.push_back(MyFlags);
10402       }
10403       if (NeedsRegBlock && Value == NumValues - 1)
10404         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10405       PartBase += VT.getStoreSize().getKnownMinSize();
10406     }
10407   }
10408 
10409   // Call the target to set up the argument values.
10410   SmallVector<SDValue, 8> InVals;
10411   SDValue NewRoot = TLI->LowerFormalArguments(
10412       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10413 
10414   // Verify that the target's LowerFormalArguments behaved as expected.
10415   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10416          "LowerFormalArguments didn't return a valid chain!");
10417   assert(InVals.size() == Ins.size() &&
10418          "LowerFormalArguments didn't emit the correct number of values!");
10419   LLVM_DEBUG({
10420     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10421       assert(InVals[i].getNode() &&
10422              "LowerFormalArguments emitted a null value!");
10423       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10424              "LowerFormalArguments emitted a value with the wrong type!");
10425     }
10426   });
10427 
10428   // Update the DAG with the new chain value resulting from argument lowering.
10429   DAG.setRoot(NewRoot);
10430 
10431   // Set up the argument values.
10432   unsigned i = 0;
10433   if (!FuncInfo->CanLowerReturn) {
10434     // Create a virtual register for the sret pointer, and put in a copy
10435     // from the sret argument into it.
10436     SmallVector<EVT, 1> ValueVTs;
10437     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10438                     F.getReturnType()->getPointerTo(
10439                         DAG.getDataLayout().getAllocaAddrSpace()),
10440                     ValueVTs);
10441     MVT VT = ValueVTs[0].getSimpleVT();
10442     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10443     Optional<ISD::NodeType> AssertOp = None;
10444     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10445                                         nullptr, F.getCallingConv(), AssertOp);
10446 
10447     MachineFunction& MF = SDB->DAG.getMachineFunction();
10448     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10449     Register SRetReg =
10450         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10451     FuncInfo->DemoteRegister = SRetReg;
10452     NewRoot =
10453         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10454     DAG.setRoot(NewRoot);
10455 
10456     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10457     ++i;
10458   }
10459 
10460   SmallVector<SDValue, 4> Chains;
10461   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10462   for (const Argument &Arg : F.args()) {
10463     SmallVector<SDValue, 4> ArgValues;
10464     SmallVector<EVT, 4> ValueVTs;
10465     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10466     unsigned NumValues = ValueVTs.size();
10467     if (NumValues == 0)
10468       continue;
10469 
10470     bool ArgHasUses = !Arg.use_empty();
10471 
10472     // Elide the copying store if the target loaded this argument from a
10473     // suitable fixed stack object.
10474     if (Ins[i].Flags.isCopyElisionCandidate()) {
10475       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10476                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10477                              InVals[i], ArgHasUses);
10478     }
10479 
10480     // If this argument is unused then remember its value. It is used to generate
10481     // debugging information.
10482     bool isSwiftErrorArg =
10483         TLI->supportSwiftError() &&
10484         Arg.hasAttribute(Attribute::SwiftError);
10485     if (!ArgHasUses && !isSwiftErrorArg) {
10486       SDB->setUnusedArgValue(&Arg, InVals[i]);
10487 
10488       // Also remember any frame index for use in FastISel.
10489       if (FrameIndexSDNode *FI =
10490           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10491         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10492     }
10493 
10494     for (unsigned Val = 0; Val != NumValues; ++Val) {
10495       EVT VT = ValueVTs[Val];
10496       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10497                                                       F.getCallingConv(), VT);
10498       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10499           *CurDAG->getContext(), F.getCallingConv(), VT);
10500 
10501       // Even an apparent 'unused' swifterror argument needs to be returned. So
10502       // we do generate a copy for it that can be used on return from the
10503       // function.
10504       if (ArgHasUses || isSwiftErrorArg) {
10505         Optional<ISD::NodeType> AssertOp;
10506         if (Arg.hasAttribute(Attribute::SExt))
10507           AssertOp = ISD::AssertSext;
10508         else if (Arg.hasAttribute(Attribute::ZExt))
10509           AssertOp = ISD::AssertZext;
10510 
10511         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10512                                              PartVT, VT, nullptr,
10513                                              F.getCallingConv(), AssertOp));
10514       }
10515 
10516       i += NumParts;
10517     }
10518 
10519     // We don't need to do anything else for unused arguments.
10520     if (ArgValues.empty())
10521       continue;
10522 
10523     // Note down frame index.
10524     if (FrameIndexSDNode *FI =
10525         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10526       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10527 
10528     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10529                                      SDB->getCurSDLoc());
10530 
10531     SDB->setValue(&Arg, Res);
10532     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10533       // We want to associate the argument with the frame index, among
10534       // involved operands, that correspond to the lowest address. The
10535       // getCopyFromParts function, called earlier, is swapping the order of
10536       // the operands to BUILD_PAIR depending on endianness. The result of
10537       // that swapping is that the least significant bits of the argument will
10538       // be in the first operand of the BUILD_PAIR node, and the most
10539       // significant bits will be in the second operand.
10540       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10541       if (LoadSDNode *LNode =
10542           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10543         if (FrameIndexSDNode *FI =
10544             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10545           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10546     }
10547 
10548     // Analyses past this point are naive and don't expect an assertion.
10549     if (Res.getOpcode() == ISD::AssertZext)
10550       Res = Res.getOperand(0);
10551 
10552     // Update the SwiftErrorVRegDefMap.
10553     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10554       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10555       if (Register::isVirtualRegister(Reg))
10556         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10557                                    Reg);
10558     }
10559 
10560     // If this argument is live outside of the entry block, insert a copy from
10561     // wherever we got it to the vreg that other BB's will reference it as.
10562     if (Res.getOpcode() == ISD::CopyFromReg) {
10563       // If we can, though, try to skip creating an unnecessary vreg.
10564       // FIXME: This isn't very clean... it would be nice to make this more
10565       // general.
10566       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10567       if (Register::isVirtualRegister(Reg)) {
10568         FuncInfo->ValueMap[&Arg] = Reg;
10569         continue;
10570       }
10571     }
10572     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10573       FuncInfo->InitializeRegForValue(&Arg);
10574       SDB->CopyToExportRegsIfNeeded(&Arg);
10575     }
10576   }
10577 
10578   if (!Chains.empty()) {
10579     Chains.push_back(NewRoot);
10580     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10581   }
10582 
10583   DAG.setRoot(NewRoot);
10584 
10585   assert(i == InVals.size() && "Argument register count mismatch!");
10586 
10587   // If any argument copy elisions occurred and we have debug info, update the
10588   // stale frame indices used in the dbg.declare variable info table.
10589   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10590   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10591     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10592       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10593       if (I != ArgCopyElisionFrameIndexMap.end())
10594         VI.Slot = I->second;
10595     }
10596   }
10597 
10598   // Finally, if the target has anything special to do, allow it to do so.
10599   emitFunctionEntryCode();
10600 }
10601 
10602 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10603 /// ensure constants are generated when needed.  Remember the virtual registers
10604 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10605 /// directly add them, because expansion might result in multiple MBB's for one
10606 /// BB.  As such, the start of the BB might correspond to a different MBB than
10607 /// the end.
10608 void
10609 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10610   const Instruction *TI = LLVMBB->getTerminator();
10611 
10612   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10613 
10614   // Check PHI nodes in successors that expect a value to be available from this
10615   // block.
10616   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10617     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10618     if (!isa<PHINode>(SuccBB->begin())) continue;
10619     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10620 
10621     // If this terminator has multiple identical successors (common for
10622     // switches), only handle each succ once.
10623     if (!SuccsHandled.insert(SuccMBB).second)
10624       continue;
10625 
10626     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10627 
10628     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10629     // nodes and Machine PHI nodes, but the incoming operands have not been
10630     // emitted yet.
10631     for (const PHINode &PN : SuccBB->phis()) {
10632       // Ignore dead phi's.
10633       if (PN.use_empty())
10634         continue;
10635 
10636       // Skip empty types
10637       if (PN.getType()->isEmptyTy())
10638         continue;
10639 
10640       unsigned Reg;
10641       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10642 
10643       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10644         unsigned &RegOut = ConstantsOut[C];
10645         if (RegOut == 0) {
10646           RegOut = FuncInfo.CreateRegs(C);
10647           // We need to zero extend ConstantInt phi operands to match
10648           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
10649           ISD::NodeType ExtendType =
10650               isa<ConstantInt>(PHIOp) ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND;
10651           CopyValueToVirtualRegister(C, RegOut, ExtendType);
10652         }
10653         Reg = RegOut;
10654       } else {
10655         DenseMap<const Value *, Register>::iterator I =
10656           FuncInfo.ValueMap.find(PHIOp);
10657         if (I != FuncInfo.ValueMap.end())
10658           Reg = I->second;
10659         else {
10660           assert(isa<AllocaInst>(PHIOp) &&
10661                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10662                  "Didn't codegen value into a register!??");
10663           Reg = FuncInfo.CreateRegs(PHIOp);
10664           CopyValueToVirtualRegister(PHIOp, Reg);
10665         }
10666       }
10667 
10668       // Remember that this register needs to added to the machine PHI node as
10669       // the input for this MBB.
10670       SmallVector<EVT, 4> ValueVTs;
10671       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10672       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10673       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10674         EVT VT = ValueVTs[vti];
10675         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10676         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10677           FuncInfo.PHINodesToUpdate.push_back(
10678               std::make_pair(&*MBBI++, Reg + i));
10679         Reg += NumRegisters;
10680       }
10681     }
10682   }
10683 
10684   ConstantsOut.clear();
10685 }
10686 
10687 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10688   MachineFunction::iterator I(MBB);
10689   if (++I == FuncInfo.MF->end())
10690     return nullptr;
10691   return &*I;
10692 }
10693 
10694 /// During lowering new call nodes can be created (such as memset, etc.).
10695 /// Those will become new roots of the current DAG, but complications arise
10696 /// when they are tail calls. In such cases, the call lowering will update
10697 /// the root, but the builder still needs to know that a tail call has been
10698 /// lowered in order to avoid generating an additional return.
10699 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10700   // If the node is null, we do have a tail call.
10701   if (MaybeTC.getNode() != nullptr)
10702     DAG.setRoot(MaybeTC);
10703   else
10704     HasTailCall = true;
10705 }
10706 
10707 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10708                                         MachineBasicBlock *SwitchMBB,
10709                                         MachineBasicBlock *DefaultMBB) {
10710   MachineFunction *CurMF = FuncInfo.MF;
10711   MachineBasicBlock *NextMBB = nullptr;
10712   MachineFunction::iterator BBI(W.MBB);
10713   if (++BBI != FuncInfo.MF->end())
10714     NextMBB = &*BBI;
10715 
10716   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10717 
10718   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10719 
10720   if (Size == 2 && W.MBB == SwitchMBB) {
10721     // If any two of the cases has the same destination, and if one value
10722     // is the same as the other, but has one bit unset that the other has set,
10723     // use bit manipulation to do two compares at once.  For example:
10724     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10725     // TODO: This could be extended to merge any 2 cases in switches with 3
10726     // cases.
10727     // TODO: Handle cases where W.CaseBB != SwitchBB.
10728     CaseCluster &Small = *W.FirstCluster;
10729     CaseCluster &Big = *W.LastCluster;
10730 
10731     if (Small.Low == Small.High && Big.Low == Big.High &&
10732         Small.MBB == Big.MBB) {
10733       const APInt &SmallValue = Small.Low->getValue();
10734       const APInt &BigValue = Big.Low->getValue();
10735 
10736       // Check that there is only one bit different.
10737       APInt CommonBit = BigValue ^ SmallValue;
10738       if (CommonBit.isPowerOf2()) {
10739         SDValue CondLHS = getValue(Cond);
10740         EVT VT = CondLHS.getValueType();
10741         SDLoc DL = getCurSDLoc();
10742 
10743         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10744                                  DAG.getConstant(CommonBit, DL, VT));
10745         SDValue Cond = DAG.getSetCC(
10746             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10747             ISD::SETEQ);
10748 
10749         // Update successor info.
10750         // Both Small and Big will jump to Small.BB, so we sum up the
10751         // probabilities.
10752         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10753         if (BPI)
10754           addSuccessorWithProb(
10755               SwitchMBB, DefaultMBB,
10756               // The default destination is the first successor in IR.
10757               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10758         else
10759           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10760 
10761         // Insert the true branch.
10762         SDValue BrCond =
10763             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10764                         DAG.getBasicBlock(Small.MBB));
10765         // Insert the false branch.
10766         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10767                              DAG.getBasicBlock(DefaultMBB));
10768 
10769         DAG.setRoot(BrCond);
10770         return;
10771       }
10772     }
10773   }
10774 
10775   if (TM.getOptLevel() != CodeGenOpt::None) {
10776     // Here, we order cases by probability so the most likely case will be
10777     // checked first. However, two clusters can have the same probability in
10778     // which case their relative ordering is non-deterministic. So we use Low
10779     // as a tie-breaker as clusters are guaranteed to never overlap.
10780     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10781                [](const CaseCluster &a, const CaseCluster &b) {
10782       return a.Prob != b.Prob ?
10783              a.Prob > b.Prob :
10784              a.Low->getValue().slt(b.Low->getValue());
10785     });
10786 
10787     // Rearrange the case blocks so that the last one falls through if possible
10788     // without changing the order of probabilities.
10789     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10790       --I;
10791       if (I->Prob > W.LastCluster->Prob)
10792         break;
10793       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10794         std::swap(*I, *W.LastCluster);
10795         break;
10796       }
10797     }
10798   }
10799 
10800   // Compute total probability.
10801   BranchProbability DefaultProb = W.DefaultProb;
10802   BranchProbability UnhandledProbs = DefaultProb;
10803   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10804     UnhandledProbs += I->Prob;
10805 
10806   MachineBasicBlock *CurMBB = W.MBB;
10807   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10808     bool FallthroughUnreachable = false;
10809     MachineBasicBlock *Fallthrough;
10810     if (I == W.LastCluster) {
10811       // For the last cluster, fall through to the default destination.
10812       Fallthrough = DefaultMBB;
10813       FallthroughUnreachable = isa<UnreachableInst>(
10814           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10815     } else {
10816       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10817       CurMF->insert(BBI, Fallthrough);
10818       // Put Cond in a virtual register to make it available from the new blocks.
10819       ExportFromCurrentBlock(Cond);
10820     }
10821     UnhandledProbs -= I->Prob;
10822 
10823     switch (I->Kind) {
10824       case CC_JumpTable: {
10825         // FIXME: Optimize away range check based on pivot comparisons.
10826         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10827         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10828 
10829         // The jump block hasn't been inserted yet; insert it here.
10830         MachineBasicBlock *JumpMBB = JT->MBB;
10831         CurMF->insert(BBI, JumpMBB);
10832 
10833         auto JumpProb = I->Prob;
10834         auto FallthroughProb = UnhandledProbs;
10835 
10836         // If the default statement is a target of the jump table, we evenly
10837         // distribute the default probability to successors of CurMBB. Also
10838         // update the probability on the edge from JumpMBB to Fallthrough.
10839         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10840                                               SE = JumpMBB->succ_end();
10841              SI != SE; ++SI) {
10842           if (*SI == DefaultMBB) {
10843             JumpProb += DefaultProb / 2;
10844             FallthroughProb -= DefaultProb / 2;
10845             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10846             JumpMBB->normalizeSuccProbs();
10847             break;
10848           }
10849         }
10850 
10851         if (FallthroughUnreachable)
10852           JTH->FallthroughUnreachable = true;
10853 
10854         if (!JTH->FallthroughUnreachable)
10855           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10856         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10857         CurMBB->normalizeSuccProbs();
10858 
10859         // The jump table header will be inserted in our current block, do the
10860         // range check, and fall through to our fallthrough block.
10861         JTH->HeaderBB = CurMBB;
10862         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10863 
10864         // If we're in the right place, emit the jump table header right now.
10865         if (CurMBB == SwitchMBB) {
10866           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10867           JTH->Emitted = true;
10868         }
10869         break;
10870       }
10871       case CC_BitTests: {
10872         // FIXME: Optimize away range check based on pivot comparisons.
10873         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10874 
10875         // The bit test blocks haven't been inserted yet; insert them here.
10876         for (BitTestCase &BTC : BTB->Cases)
10877           CurMF->insert(BBI, BTC.ThisBB);
10878 
10879         // Fill in fields of the BitTestBlock.
10880         BTB->Parent = CurMBB;
10881         BTB->Default = Fallthrough;
10882 
10883         BTB->DefaultProb = UnhandledProbs;
10884         // If the cases in bit test don't form a contiguous range, we evenly
10885         // distribute the probability on the edge to Fallthrough to two
10886         // successors of CurMBB.
10887         if (!BTB->ContiguousRange) {
10888           BTB->Prob += DefaultProb / 2;
10889           BTB->DefaultProb -= DefaultProb / 2;
10890         }
10891 
10892         if (FallthroughUnreachable)
10893           BTB->FallthroughUnreachable = true;
10894 
10895         // If we're in the right place, emit the bit test header right now.
10896         if (CurMBB == SwitchMBB) {
10897           visitBitTestHeader(*BTB, SwitchMBB);
10898           BTB->Emitted = true;
10899         }
10900         break;
10901       }
10902       case CC_Range: {
10903         const Value *RHS, *LHS, *MHS;
10904         ISD::CondCode CC;
10905         if (I->Low == I->High) {
10906           // Check Cond == I->Low.
10907           CC = ISD::SETEQ;
10908           LHS = Cond;
10909           RHS=I->Low;
10910           MHS = nullptr;
10911         } else {
10912           // Check I->Low <= Cond <= I->High.
10913           CC = ISD::SETLE;
10914           LHS = I->Low;
10915           MHS = Cond;
10916           RHS = I->High;
10917         }
10918 
10919         // If Fallthrough is unreachable, fold away the comparison.
10920         if (FallthroughUnreachable)
10921           CC = ISD::SETTRUE;
10922 
10923         // The false probability is the sum of all unhandled cases.
10924         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10925                      getCurSDLoc(), I->Prob, UnhandledProbs);
10926 
10927         if (CurMBB == SwitchMBB)
10928           visitSwitchCase(CB, SwitchMBB);
10929         else
10930           SL->SwitchCases.push_back(CB);
10931 
10932         break;
10933       }
10934     }
10935     CurMBB = Fallthrough;
10936   }
10937 }
10938 
10939 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10940                                               CaseClusterIt First,
10941                                               CaseClusterIt Last) {
10942   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10943     if (X.Prob != CC.Prob)
10944       return X.Prob > CC.Prob;
10945 
10946     // Ties are broken by comparing the case value.
10947     return X.Low->getValue().slt(CC.Low->getValue());
10948   });
10949 }
10950 
10951 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10952                                         const SwitchWorkListItem &W,
10953                                         Value *Cond,
10954                                         MachineBasicBlock *SwitchMBB) {
10955   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10956          "Clusters not sorted?");
10957 
10958   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10959 
10960   // Balance the tree based on branch probabilities to create a near-optimal (in
10961   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10962   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10963   CaseClusterIt LastLeft = W.FirstCluster;
10964   CaseClusterIt FirstRight = W.LastCluster;
10965   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10966   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10967 
10968   // Move LastLeft and FirstRight towards each other from opposite directions to
10969   // find a partitioning of the clusters which balances the probability on both
10970   // sides. If LeftProb and RightProb are equal, alternate which side is
10971   // taken to ensure 0-probability nodes are distributed evenly.
10972   unsigned I = 0;
10973   while (LastLeft + 1 < FirstRight) {
10974     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10975       LeftProb += (++LastLeft)->Prob;
10976     else
10977       RightProb += (--FirstRight)->Prob;
10978     I++;
10979   }
10980 
10981   while (true) {
10982     // Our binary search tree differs from a typical BST in that ours can have up
10983     // to three values in each leaf. The pivot selection above doesn't take that
10984     // into account, which means the tree might require more nodes and be less
10985     // efficient. We compensate for this here.
10986 
10987     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10988     unsigned NumRight = W.LastCluster - FirstRight + 1;
10989 
10990     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10991       // If one side has less than 3 clusters, and the other has more than 3,
10992       // consider taking a cluster from the other side.
10993 
10994       if (NumLeft < NumRight) {
10995         // Consider moving the first cluster on the right to the left side.
10996         CaseCluster &CC = *FirstRight;
10997         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10998         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10999         if (LeftSideRank <= RightSideRank) {
11000           // Moving the cluster to the left does not demote it.
11001           ++LastLeft;
11002           ++FirstRight;
11003           continue;
11004         }
11005       } else {
11006         assert(NumRight < NumLeft);
11007         // Consider moving the last element on the left to the right side.
11008         CaseCluster &CC = *LastLeft;
11009         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11010         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11011         if (RightSideRank <= LeftSideRank) {
11012           // Moving the cluster to the right does not demot it.
11013           --LastLeft;
11014           --FirstRight;
11015           continue;
11016         }
11017       }
11018     }
11019     break;
11020   }
11021 
11022   assert(LastLeft + 1 == FirstRight);
11023   assert(LastLeft >= W.FirstCluster);
11024   assert(FirstRight <= W.LastCluster);
11025 
11026   // Use the first element on the right as pivot since we will make less-than
11027   // comparisons against it.
11028   CaseClusterIt PivotCluster = FirstRight;
11029   assert(PivotCluster > W.FirstCluster);
11030   assert(PivotCluster <= W.LastCluster);
11031 
11032   CaseClusterIt FirstLeft = W.FirstCluster;
11033   CaseClusterIt LastRight = W.LastCluster;
11034 
11035   const ConstantInt *Pivot = PivotCluster->Low;
11036 
11037   // New blocks will be inserted immediately after the current one.
11038   MachineFunction::iterator BBI(W.MBB);
11039   ++BBI;
11040 
11041   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11042   // we can branch to its destination directly if it's squeezed exactly in
11043   // between the known lower bound and Pivot - 1.
11044   MachineBasicBlock *LeftMBB;
11045   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11046       FirstLeft->Low == W.GE &&
11047       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11048     LeftMBB = FirstLeft->MBB;
11049   } else {
11050     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11051     FuncInfo.MF->insert(BBI, LeftMBB);
11052     WorkList.push_back(
11053         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11054     // Put Cond in a virtual register to make it available from the new blocks.
11055     ExportFromCurrentBlock(Cond);
11056   }
11057 
11058   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11059   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11060   // directly if RHS.High equals the current upper bound.
11061   MachineBasicBlock *RightMBB;
11062   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11063       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11064     RightMBB = FirstRight->MBB;
11065   } else {
11066     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11067     FuncInfo.MF->insert(BBI, RightMBB);
11068     WorkList.push_back(
11069         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11070     // Put Cond in a virtual register to make it available from the new blocks.
11071     ExportFromCurrentBlock(Cond);
11072   }
11073 
11074   // Create the CaseBlock record that will be used to lower the branch.
11075   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11076                getCurSDLoc(), LeftProb, RightProb);
11077 
11078   if (W.MBB == SwitchMBB)
11079     visitSwitchCase(CB, SwitchMBB);
11080   else
11081     SL->SwitchCases.push_back(CB);
11082 }
11083 
11084 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11085 // from the swith statement.
11086 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11087                                             BranchProbability PeeledCaseProb) {
11088   if (PeeledCaseProb == BranchProbability::getOne())
11089     return BranchProbability::getZero();
11090   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11091 
11092   uint32_t Numerator = CaseProb.getNumerator();
11093   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11094   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11095 }
11096 
11097 // Try to peel the top probability case if it exceeds the threshold.
11098 // Return current MachineBasicBlock for the switch statement if the peeling
11099 // does not occur.
11100 // If the peeling is performed, return the newly created MachineBasicBlock
11101 // for the peeled switch statement. Also update Clusters to remove the peeled
11102 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11103 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11104     const SwitchInst &SI, CaseClusterVector &Clusters,
11105     BranchProbability &PeeledCaseProb) {
11106   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11107   // Don't perform if there is only one cluster or optimizing for size.
11108   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11109       TM.getOptLevel() == CodeGenOpt::None ||
11110       SwitchMBB->getParent()->getFunction().hasMinSize())
11111     return SwitchMBB;
11112 
11113   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11114   unsigned PeeledCaseIndex = 0;
11115   bool SwitchPeeled = false;
11116   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11117     CaseCluster &CC = Clusters[Index];
11118     if (CC.Prob < TopCaseProb)
11119       continue;
11120     TopCaseProb = CC.Prob;
11121     PeeledCaseIndex = Index;
11122     SwitchPeeled = true;
11123   }
11124   if (!SwitchPeeled)
11125     return SwitchMBB;
11126 
11127   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11128                     << TopCaseProb << "\n");
11129 
11130   // Record the MBB for the peeled switch statement.
11131   MachineFunction::iterator BBI(SwitchMBB);
11132   ++BBI;
11133   MachineBasicBlock *PeeledSwitchMBB =
11134       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11135   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11136 
11137   ExportFromCurrentBlock(SI.getCondition());
11138   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11139   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11140                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11141   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11142 
11143   Clusters.erase(PeeledCaseIt);
11144   for (CaseCluster &CC : Clusters) {
11145     LLVM_DEBUG(
11146         dbgs() << "Scale the probablity for one cluster, before scaling: "
11147                << CC.Prob << "\n");
11148     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11149     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11150   }
11151   PeeledCaseProb = TopCaseProb;
11152   return PeeledSwitchMBB;
11153 }
11154 
11155 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11156   // Extract cases from the switch.
11157   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11158   CaseClusterVector Clusters;
11159   Clusters.reserve(SI.getNumCases());
11160   for (auto I : SI.cases()) {
11161     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11162     const ConstantInt *CaseVal = I.getCaseValue();
11163     BranchProbability Prob =
11164         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11165             : BranchProbability(1, SI.getNumCases() + 1);
11166     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11167   }
11168 
11169   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11170 
11171   // Cluster adjacent cases with the same destination. We do this at all
11172   // optimization levels because it's cheap to do and will make codegen faster
11173   // if there are many clusters.
11174   sortAndRangeify(Clusters);
11175 
11176   // The branch probablity of the peeled case.
11177   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11178   MachineBasicBlock *PeeledSwitchMBB =
11179       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11180 
11181   // If there is only the default destination, jump there directly.
11182   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11183   if (Clusters.empty()) {
11184     assert(PeeledSwitchMBB == SwitchMBB);
11185     SwitchMBB->addSuccessor(DefaultMBB);
11186     if (DefaultMBB != NextBlock(SwitchMBB)) {
11187       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11188                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11189     }
11190     return;
11191   }
11192 
11193   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11194   SL->findBitTestClusters(Clusters, &SI);
11195 
11196   LLVM_DEBUG({
11197     dbgs() << "Case clusters: ";
11198     for (const CaseCluster &C : Clusters) {
11199       if (C.Kind == CC_JumpTable)
11200         dbgs() << "JT:";
11201       if (C.Kind == CC_BitTests)
11202         dbgs() << "BT:";
11203 
11204       C.Low->getValue().print(dbgs(), true);
11205       if (C.Low != C.High) {
11206         dbgs() << '-';
11207         C.High->getValue().print(dbgs(), true);
11208       }
11209       dbgs() << ' ';
11210     }
11211     dbgs() << '\n';
11212   });
11213 
11214   assert(!Clusters.empty());
11215   SwitchWorkList WorkList;
11216   CaseClusterIt First = Clusters.begin();
11217   CaseClusterIt Last = Clusters.end() - 1;
11218   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11219   // Scale the branchprobability for DefaultMBB if the peel occurs and
11220   // DefaultMBB is not replaced.
11221   if (PeeledCaseProb != BranchProbability::getZero() &&
11222       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11223     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11224   WorkList.push_back(
11225       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11226 
11227   while (!WorkList.empty()) {
11228     SwitchWorkListItem W = WorkList.pop_back_val();
11229     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11230 
11231     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11232         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11233       // For optimized builds, lower large range as a balanced binary tree.
11234       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11235       continue;
11236     }
11237 
11238     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11239   }
11240 }
11241 
11242 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11243   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11244   auto DL = getCurSDLoc();
11245   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11246   setValue(&I, DAG.getStepVector(DL, ResultVT));
11247 }
11248 
11249 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11250   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11251   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11252 
11253   SDLoc DL = getCurSDLoc();
11254   SDValue V = getValue(I.getOperand(0));
11255   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11256 
11257   if (VT.isScalableVector()) {
11258     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11259     return;
11260   }
11261 
11262   // Use VECTOR_SHUFFLE for the fixed-length vector
11263   // to maintain existing behavior.
11264   SmallVector<int, 8> Mask;
11265   unsigned NumElts = VT.getVectorMinNumElements();
11266   for (unsigned i = 0; i != NumElts; ++i)
11267     Mask.push_back(NumElts - 1 - i);
11268 
11269   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11270 }
11271 
11272 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11273   SmallVector<EVT, 4> ValueVTs;
11274   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11275                   ValueVTs);
11276   unsigned NumValues = ValueVTs.size();
11277   if (NumValues == 0) return;
11278 
11279   SmallVector<SDValue, 4> Values(NumValues);
11280   SDValue Op = getValue(I.getOperand(0));
11281 
11282   for (unsigned i = 0; i != NumValues; ++i)
11283     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11284                             SDValue(Op.getNode(), Op.getResNo() + i));
11285 
11286   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11287                            DAG.getVTList(ValueVTs), Values));
11288 }
11289 
11290 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11291   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11292   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11293 
11294   SDLoc DL = getCurSDLoc();
11295   SDValue V1 = getValue(I.getOperand(0));
11296   SDValue V2 = getValue(I.getOperand(1));
11297   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11298 
11299   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11300   if (VT.isScalableVector()) {
11301     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11302     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11303                              DAG.getConstant(Imm, DL, IdxVT)));
11304     return;
11305   }
11306 
11307   unsigned NumElts = VT.getVectorNumElements();
11308 
11309   uint64_t Idx = (NumElts + Imm) % NumElts;
11310 
11311   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11312   SmallVector<int, 8> Mask;
11313   for (unsigned i = 0; i < NumElts; ++i)
11314     Mask.push_back(Idx + i);
11315   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11316 }
11317