xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 85eae45520dd3ace28c7da34f77aaeec566ad97b)
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 =
220             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
221                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
222                                         TLI.getPointerTy(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, TLI.getPointerTy(DAG.getDataLayout())));
4880   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4881                            DAG.getConstant(127, dl, MVT::i32));
4882   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4883 }
4884 
4885 /// getF32Constant - Get 32-bit floating point constant.
4886 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4887                               const SDLoc &dl) {
4888   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4889                            MVT::f32);
4890 }
4891 
4892 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4893                                        SelectionDAG &DAG) {
4894   // TODO: What fast-math-flags should be set on the floating-point nodes?
4895 
4896   //   IntegerPartOfX = ((int32_t)(t0);
4897   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4898 
4899   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4900   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4901   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4902 
4903   //   IntegerPartOfX <<= 23;
4904   IntegerPartOfX = DAG.getNode(
4905       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4906       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4907                                   DAG.getDataLayout())));
4908 
4909   SDValue TwoToFractionalPartOfX;
4910   if (LimitFloatPrecision <= 6) {
4911     // For floating-point precision of 6:
4912     //
4913     //   TwoToFractionalPartOfX =
4914     //     0.997535578f +
4915     //       (0.735607626f + 0.252464424f * x) * x;
4916     //
4917     // error 0.0144103317, which is 6 bits
4918     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4919                              getF32Constant(DAG, 0x3e814304, dl));
4920     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4921                              getF32Constant(DAG, 0x3f3c50c8, dl));
4922     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4923     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4924                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4925   } else if (LimitFloatPrecision <= 12) {
4926     // For floating-point precision of 12:
4927     //
4928     //   TwoToFractionalPartOfX =
4929     //     0.999892986f +
4930     //       (0.696457318f +
4931     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4932     //
4933     // error 0.000107046256, which is 13 to 14 bits
4934     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4935                              getF32Constant(DAG, 0x3da235e3, dl));
4936     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4937                              getF32Constant(DAG, 0x3e65b8f3, dl));
4938     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4939     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4940                              getF32Constant(DAG, 0x3f324b07, dl));
4941     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4942     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4943                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4944   } else { // LimitFloatPrecision <= 18
4945     // For floating-point precision of 18:
4946     //
4947     //   TwoToFractionalPartOfX =
4948     //     0.999999982f +
4949     //       (0.693148872f +
4950     //         (0.240227044f +
4951     //           (0.554906021e-1f +
4952     //             (0.961591928e-2f +
4953     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4954     // error 2.47208000*10^(-7), which is better than 18 bits
4955     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4956                              getF32Constant(DAG, 0x3924b03e, dl));
4957     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4958                              getF32Constant(DAG, 0x3ab24b87, dl));
4959     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4960     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4961                              getF32Constant(DAG, 0x3c1d8c17, dl));
4962     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4963     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4964                              getF32Constant(DAG, 0x3d634a1d, dl));
4965     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4966     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4967                              getF32Constant(DAG, 0x3e75fe14, dl));
4968     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4969     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4970                               getF32Constant(DAG, 0x3f317234, dl));
4971     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4972     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4973                                          getF32Constant(DAG, 0x3f800000, dl));
4974   }
4975 
4976   // Add the exponent into the result in integer domain.
4977   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4978   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4979                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4980 }
4981 
4982 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4983 /// limited-precision mode.
4984 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4985                          const TargetLowering &TLI, SDNodeFlags Flags) {
4986   if (Op.getValueType() == MVT::f32 &&
4987       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4988 
4989     // Put the exponent in the right bit position for later addition to the
4990     // final result:
4991     //
4992     // t0 = Op * log2(e)
4993 
4994     // TODO: What fast-math-flags should be set here?
4995     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4996                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4997     return getLimitedPrecisionExp2(t0, dl, DAG);
4998   }
4999 
5000   // No special expansion.
5001   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5002 }
5003 
5004 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5005 /// limited-precision mode.
5006 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5007                          const TargetLowering &TLI, SDNodeFlags Flags) {
5008   // TODO: What fast-math-flags should be set on the floating-point nodes?
5009 
5010   if (Op.getValueType() == MVT::f32 &&
5011       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5012     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5013 
5014     // Scale the exponent by log(2).
5015     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5016     SDValue LogOfExponent =
5017         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5018                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5019 
5020     // Get the significand and build it into a floating-point number with
5021     // exponent of 1.
5022     SDValue X = GetSignificand(DAG, Op1, dl);
5023 
5024     SDValue LogOfMantissa;
5025     if (LimitFloatPrecision <= 6) {
5026       // For floating-point precision of 6:
5027       //
5028       //   LogofMantissa =
5029       //     -1.1609546f +
5030       //       (1.4034025f - 0.23903021f * x) * x;
5031       //
5032       // error 0.0034276066, which is better than 8 bits
5033       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5034                                getF32Constant(DAG, 0xbe74c456, dl));
5035       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5036                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5037       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5038       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5039                                   getF32Constant(DAG, 0x3f949a29, dl));
5040     } else if (LimitFloatPrecision <= 12) {
5041       // For floating-point precision of 12:
5042       //
5043       //   LogOfMantissa =
5044       //     -1.7417939f +
5045       //       (2.8212026f +
5046       //         (-1.4699568f +
5047       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5048       //
5049       // error 0.000061011436, which is 14 bits
5050       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5051                                getF32Constant(DAG, 0xbd67b6d6, dl));
5052       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5053                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5054       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5055       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5056                                getF32Constant(DAG, 0x3fbc278b, dl));
5057       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5058       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5059                                getF32Constant(DAG, 0x40348e95, dl));
5060       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5061       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5062                                   getF32Constant(DAG, 0x3fdef31a, dl));
5063     } else { // LimitFloatPrecision <= 18
5064       // For floating-point precision of 18:
5065       //
5066       //   LogOfMantissa =
5067       //     -2.1072184f +
5068       //       (4.2372794f +
5069       //         (-3.7029485f +
5070       //           (2.2781945f +
5071       //             (-0.87823314f +
5072       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5073       //
5074       // error 0.0000023660568, which is better than 18 bits
5075       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5076                                getF32Constant(DAG, 0xbc91e5ac, dl));
5077       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5078                                getF32Constant(DAG, 0x3e4350aa, dl));
5079       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5080       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5081                                getF32Constant(DAG, 0x3f60d3e3, dl));
5082       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5083       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5084                                getF32Constant(DAG, 0x4011cdf0, dl));
5085       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5086       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5087                                getF32Constant(DAG, 0x406cfd1c, dl));
5088       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5089       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5090                                getF32Constant(DAG, 0x408797cb, dl));
5091       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5092       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5093                                   getF32Constant(DAG, 0x4006dcab, dl));
5094     }
5095 
5096     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5097   }
5098 
5099   // No special expansion.
5100   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5101 }
5102 
5103 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5104 /// limited-precision mode.
5105 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5106                           const TargetLowering &TLI, SDNodeFlags Flags) {
5107   // TODO: What fast-math-flags should be set on the floating-point nodes?
5108 
5109   if (Op.getValueType() == MVT::f32 &&
5110       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5111     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5112 
5113     // Get the exponent.
5114     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5115 
5116     // Get the significand and build it into a floating-point number with
5117     // exponent of 1.
5118     SDValue X = GetSignificand(DAG, Op1, dl);
5119 
5120     // Different possible minimax approximations of significand in
5121     // floating-point for various degrees of accuracy over [1,2].
5122     SDValue Log2ofMantissa;
5123     if (LimitFloatPrecision <= 6) {
5124       // For floating-point precision of 6:
5125       //
5126       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5127       //
5128       // error 0.0049451742, which is more than 7 bits
5129       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5130                                getF32Constant(DAG, 0xbeb08fe0, dl));
5131       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5132                                getF32Constant(DAG, 0x40019463, dl));
5133       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5134       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5135                                    getF32Constant(DAG, 0x3fd6633d, dl));
5136     } else if (LimitFloatPrecision <= 12) {
5137       // For floating-point precision of 12:
5138       //
5139       //   Log2ofMantissa =
5140       //     -2.51285454f +
5141       //       (4.07009056f +
5142       //         (-2.12067489f +
5143       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5144       //
5145       // error 0.0000876136000, which is better than 13 bits
5146       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5147                                getF32Constant(DAG, 0xbda7262e, dl));
5148       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5149                                getF32Constant(DAG, 0x3f25280b, dl));
5150       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5151       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5152                                getF32Constant(DAG, 0x4007b923, dl));
5153       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5154       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5155                                getF32Constant(DAG, 0x40823e2f, dl));
5156       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5157       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5158                                    getF32Constant(DAG, 0x4020d29c, dl));
5159     } else { // LimitFloatPrecision <= 18
5160       // For floating-point precision of 18:
5161       //
5162       //   Log2ofMantissa =
5163       //     -3.0400495f +
5164       //       (6.1129976f +
5165       //         (-5.3420409f +
5166       //           (3.2865683f +
5167       //             (-1.2669343f +
5168       //               (0.27515199f -
5169       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5170       //
5171       // error 0.0000018516, which is better than 18 bits
5172       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5173                                getF32Constant(DAG, 0xbcd2769e, dl));
5174       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5175                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5176       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5177       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5178                                getF32Constant(DAG, 0x3fa22ae7, dl));
5179       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5180       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5181                                getF32Constant(DAG, 0x40525723, dl));
5182       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5183       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5184                                getF32Constant(DAG, 0x40aaf200, dl));
5185       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5186       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5187                                getF32Constant(DAG, 0x40c39dad, dl));
5188       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5189       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5190                                    getF32Constant(DAG, 0x4042902c, dl));
5191     }
5192 
5193     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5194   }
5195 
5196   // No special expansion.
5197   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5198 }
5199 
5200 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5201 /// limited-precision mode.
5202 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5203                            const TargetLowering &TLI, SDNodeFlags Flags) {
5204   // TODO: What fast-math-flags should be set on the floating-point nodes?
5205 
5206   if (Op.getValueType() == MVT::f32 &&
5207       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5208     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5209 
5210     // Scale the exponent by log10(2) [0.30102999f].
5211     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5212     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5213                                         getF32Constant(DAG, 0x3e9a209a, dl));
5214 
5215     // Get the significand and build it into a floating-point number with
5216     // exponent of 1.
5217     SDValue X = GetSignificand(DAG, Op1, dl);
5218 
5219     SDValue Log10ofMantissa;
5220     if (LimitFloatPrecision <= 6) {
5221       // For floating-point precision of 6:
5222       //
5223       //   Log10ofMantissa =
5224       //     -0.50419619f +
5225       //       (0.60948995f - 0.10380950f * x) * x;
5226       //
5227       // error 0.0014886165, which is 6 bits
5228       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5229                                getF32Constant(DAG, 0xbdd49a13, dl));
5230       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5231                                getF32Constant(DAG, 0x3f1c0789, dl));
5232       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5233       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5234                                     getF32Constant(DAG, 0x3f011300, dl));
5235     } else if (LimitFloatPrecision <= 12) {
5236       // For floating-point precision of 12:
5237       //
5238       //   Log10ofMantissa =
5239       //     -0.64831180f +
5240       //       (0.91751397f +
5241       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5242       //
5243       // error 0.00019228036, which is better than 12 bits
5244       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5245                                getF32Constant(DAG, 0x3d431f31, dl));
5246       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5247                                getF32Constant(DAG, 0x3ea21fb2, dl));
5248       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5249       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5250                                getF32Constant(DAG, 0x3f6ae232, dl));
5251       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5252       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5253                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5254     } else { // LimitFloatPrecision <= 18
5255       // For floating-point precision of 18:
5256       //
5257       //   Log10ofMantissa =
5258       //     -0.84299375f +
5259       //       (1.5327582f +
5260       //         (-1.0688956f +
5261       //           (0.49102474f +
5262       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5263       //
5264       // error 0.0000037995730, which is better than 18 bits
5265       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5266                                getF32Constant(DAG, 0x3c5d51ce, dl));
5267       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5268                                getF32Constant(DAG, 0x3e00685a, dl));
5269       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5270       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5271                                getF32Constant(DAG, 0x3efb6798, dl));
5272       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5273       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5274                                getF32Constant(DAG, 0x3f88d192, dl));
5275       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5276       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5277                                getF32Constant(DAG, 0x3fc4316c, dl));
5278       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5279       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5280                                     getF32Constant(DAG, 0x3f57ce70, dl));
5281     }
5282 
5283     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5284   }
5285 
5286   // No special expansion.
5287   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5288 }
5289 
5290 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5291 /// limited-precision mode.
5292 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5293                           const TargetLowering &TLI, SDNodeFlags Flags) {
5294   if (Op.getValueType() == MVT::f32 &&
5295       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5296     return getLimitedPrecisionExp2(Op, dl, DAG);
5297 
5298   // No special expansion.
5299   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5300 }
5301 
5302 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5303 /// limited-precision mode with x == 10.0f.
5304 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5305                          SelectionDAG &DAG, const TargetLowering &TLI,
5306                          SDNodeFlags Flags) {
5307   bool IsExp10 = false;
5308   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5309       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5310     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5311       APFloat Ten(10.0f);
5312       IsExp10 = LHSC->isExactlyValue(Ten);
5313     }
5314   }
5315 
5316   // TODO: What fast-math-flags should be set on the FMUL node?
5317   if (IsExp10) {
5318     // Put the exponent in the right bit position for later addition to the
5319     // final result:
5320     //
5321     //   #define LOG2OF10 3.3219281f
5322     //   t0 = Op * LOG2OF10;
5323     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5324                              getF32Constant(DAG, 0x40549a78, dl));
5325     return getLimitedPrecisionExp2(t0, dl, DAG);
5326   }
5327 
5328   // No special expansion.
5329   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5330 }
5331 
5332 /// ExpandPowI - Expand a llvm.powi intrinsic.
5333 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5334                           SelectionDAG &DAG) {
5335   // If RHS is a constant, we can expand this out to a multiplication tree,
5336   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5337   // optimizing for size, we only want to do this if the expansion would produce
5338   // a small number of multiplies, otherwise we do the full expansion.
5339   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5340     // Get the exponent as a positive value.
5341     unsigned Val = RHSC->getSExtValue();
5342     if ((int)Val < 0) Val = -Val;
5343 
5344     // powi(x, 0) -> 1.0
5345     if (Val == 0)
5346       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5347 
5348     bool OptForSize = DAG.shouldOptForSize();
5349     if (!OptForSize ||
5350         // If optimizing for size, don't insert too many multiplies.
5351         // This inserts up to 5 multiplies.
5352         countPopulation(Val) + Log2_32(Val) < 7) {
5353       // We use the simple binary decomposition method to generate the multiply
5354       // sequence.  There are more optimal ways to do this (for example,
5355       // powi(x,15) generates one more multiply than it should), but this has
5356       // the benefit of being both really simple and much better than a libcall.
5357       SDValue Res;  // Logically starts equal to 1.0
5358       SDValue CurSquare = LHS;
5359       // TODO: Intrinsics should have fast-math-flags that propagate to these
5360       // nodes.
5361       while (Val) {
5362         if (Val & 1) {
5363           if (Res.getNode())
5364             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5365           else
5366             Res = CurSquare;  // 1.0*CurSquare.
5367         }
5368 
5369         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5370                                 CurSquare, CurSquare);
5371         Val >>= 1;
5372       }
5373 
5374       // If the original was negative, invert the result, producing 1/(x*x*x).
5375       if (RHSC->getSExtValue() < 0)
5376         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5377                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5378       return Res;
5379     }
5380   }
5381 
5382   // Otherwise, expand to a libcall.
5383   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5384 }
5385 
5386 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5387                             SDValue LHS, SDValue RHS, SDValue Scale,
5388                             SelectionDAG &DAG, const TargetLowering &TLI) {
5389   EVT VT = LHS.getValueType();
5390   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5391   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5392   LLVMContext &Ctx = *DAG.getContext();
5393 
5394   // If the type is legal but the operation isn't, this node might survive all
5395   // the way to operation legalization. If we end up there and we do not have
5396   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5397   // node.
5398 
5399   // Coax the legalizer into expanding the node during type legalization instead
5400   // by bumping the size by one bit. This will force it to Promote, enabling the
5401   // early expansion and avoiding the need to expand later.
5402 
5403   // We don't have to do this if Scale is 0; that can always be expanded, unless
5404   // it's a saturating signed operation. Those can experience true integer
5405   // division overflow, a case which we must avoid.
5406 
5407   // FIXME: We wouldn't have to do this (or any of the early
5408   // expansion/promotion) if it was possible to expand a libcall of an
5409   // illegal type during operation legalization. But it's not, so things
5410   // get a bit hacky.
5411   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5412   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5413       (TLI.isTypeLegal(VT) ||
5414        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5415     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5416         Opcode, VT, ScaleInt);
5417     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5418       EVT PromVT;
5419       if (VT.isScalarInteger())
5420         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5421       else if (VT.isVector()) {
5422         PromVT = VT.getVectorElementType();
5423         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5424         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5425       } else
5426         llvm_unreachable("Wrong VT for DIVFIX?");
5427       if (Signed) {
5428         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5429         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5430       } else {
5431         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5432         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5433       }
5434       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5435       // For saturating operations, we need to shift up the LHS to get the
5436       // proper saturation width, and then shift down again afterwards.
5437       if (Saturating)
5438         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5439                           DAG.getConstant(1, DL, ShiftTy));
5440       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5441       if (Saturating)
5442         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5443                           DAG.getConstant(1, DL, ShiftTy));
5444       return DAG.getZExtOrTrunc(Res, DL, VT);
5445     }
5446   }
5447 
5448   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5449 }
5450 
5451 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5452 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5453 static void
5454 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5455                      const SDValue &N) {
5456   switch (N.getOpcode()) {
5457   case ISD::CopyFromReg: {
5458     SDValue Op = N.getOperand(1);
5459     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5460                       Op.getValueType().getSizeInBits());
5461     return;
5462   }
5463   case ISD::BITCAST:
5464   case ISD::AssertZext:
5465   case ISD::AssertSext:
5466   case ISD::TRUNCATE:
5467     getUnderlyingArgRegs(Regs, N.getOperand(0));
5468     return;
5469   case ISD::BUILD_PAIR:
5470   case ISD::BUILD_VECTOR:
5471   case ISD::CONCAT_VECTORS:
5472     for (SDValue Op : N->op_values())
5473       getUnderlyingArgRegs(Regs, Op);
5474     return;
5475   default:
5476     return;
5477   }
5478 }
5479 
5480 /// If the DbgValueInst is a dbg_value of a function argument, create the
5481 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5482 /// instruction selection, they will be inserted to the entry BB.
5483 /// We don't currently support this for variadic dbg_values, as they shouldn't
5484 /// appear for function arguments or in the prologue.
5485 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5486     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5487     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5488   const Argument *Arg = dyn_cast<Argument>(V);
5489   if (!Arg)
5490     return false;
5491 
5492   MachineFunction &MF = DAG.getMachineFunction();
5493   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5494 
5495   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5496   // we've been asked to pursue.
5497   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5498                               bool Indirect) {
5499     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5500       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5501       // pointing at the VReg, which will be patched up later.
5502       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5503       auto MIB = BuildMI(MF, DL, Inst);
5504       MIB.addReg(Reg);
5505       MIB.addImm(0);
5506       MIB.addMetadata(Variable);
5507       auto *NewDIExpr = FragExpr;
5508       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5509       // the DIExpression.
5510       if (Indirect)
5511         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5512       MIB.addMetadata(NewDIExpr);
5513       return MIB;
5514     } else {
5515       // Create a completely standard DBG_VALUE.
5516       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5517       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5518     }
5519   };
5520 
5521   if (!IsDbgDeclare) {
5522     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5523     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5524     // the entry block.
5525     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5526     if (!IsInEntryBlock)
5527       return false;
5528 
5529     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5530     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5531     // variable that also is a param.
5532     //
5533     // Although, if we are at the top of the entry block already, we can still
5534     // emit using ArgDbgValue. This might catch some situations when the
5535     // dbg.value refers to an argument that isn't used in the entry block, so
5536     // any CopyToReg node would be optimized out and the only way to express
5537     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5538     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5539     // we should only emit as ArgDbgValue if the Variable is an argument to the
5540     // current function, and the dbg.value intrinsic is found in the entry
5541     // block.
5542     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5543         !DL->getInlinedAt();
5544     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5545     if (!IsInPrologue && !VariableIsFunctionInputArg)
5546       return false;
5547 
5548     // Here we assume that a function argument on IR level only can be used to
5549     // describe one input parameter on source level. If we for example have
5550     // source code like this
5551     //
5552     //    struct A { long x, y; };
5553     //    void foo(struct A a, long b) {
5554     //      ...
5555     //      b = a.x;
5556     //      ...
5557     //    }
5558     //
5559     // and IR like this
5560     //
5561     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5562     //  entry:
5563     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5564     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5565     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5566     //    ...
5567     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5568     //    ...
5569     //
5570     // then the last dbg.value is describing a parameter "b" using a value that
5571     // is an argument. But since we already has used %a1 to describe a parameter
5572     // we should not handle that last dbg.value here (that would result in an
5573     // incorrect hoisting of the DBG_VALUE to the function entry).
5574     // Notice that we allow one dbg.value per IR level argument, to accommodate
5575     // for the situation with fragments above.
5576     if (VariableIsFunctionInputArg) {
5577       unsigned ArgNo = Arg->getArgNo();
5578       if (ArgNo >= FuncInfo.DescribedArgs.size())
5579         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5580       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5581         return false;
5582       FuncInfo.DescribedArgs.set(ArgNo);
5583     }
5584   }
5585 
5586   bool IsIndirect = false;
5587   Optional<MachineOperand> Op;
5588   // Some arguments' frame index is recorded during argument lowering.
5589   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5590   if (FI != std::numeric_limits<int>::max())
5591     Op = MachineOperand::CreateFI(FI);
5592 
5593   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5594   if (!Op && N.getNode()) {
5595     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5596     Register Reg;
5597     if (ArgRegsAndSizes.size() == 1)
5598       Reg = ArgRegsAndSizes.front().first;
5599 
5600     if (Reg && Reg.isVirtual()) {
5601       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5602       Register PR = RegInfo.getLiveInPhysReg(Reg);
5603       if (PR)
5604         Reg = PR;
5605     }
5606     if (Reg) {
5607       Op = MachineOperand::CreateReg(Reg, false);
5608       IsIndirect = IsDbgDeclare;
5609     }
5610   }
5611 
5612   if (!Op && N.getNode()) {
5613     // Check if frame index is available.
5614     SDValue LCandidate = peekThroughBitcasts(N);
5615     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5616       if (FrameIndexSDNode *FINode =
5617           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5618         Op = MachineOperand::CreateFI(FINode->getIndex());
5619   }
5620 
5621   if (!Op) {
5622     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5623     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5624                                          SplitRegs) {
5625       unsigned Offset = 0;
5626       for (const auto &RegAndSize : SplitRegs) {
5627         // If the expression is already a fragment, the current register
5628         // offset+size might extend beyond the fragment. In this case, only
5629         // the register bits that are inside the fragment are relevant.
5630         int RegFragmentSizeInBits = RegAndSize.second;
5631         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5632           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5633           // The register is entirely outside the expression fragment,
5634           // so is irrelevant for debug info.
5635           if (Offset >= ExprFragmentSizeInBits)
5636             break;
5637           // The register is partially outside the expression fragment, only
5638           // the low bits within the fragment are relevant for debug info.
5639           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5640             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5641           }
5642         }
5643 
5644         auto FragmentExpr = DIExpression::createFragmentExpression(
5645             Expr, Offset, RegFragmentSizeInBits);
5646         Offset += RegAndSize.second;
5647         // If a valid fragment expression cannot be created, the variable's
5648         // correct value cannot be determined and so it is set as Undef.
5649         if (!FragmentExpr) {
5650           SDDbgValue *SDV = DAG.getConstantDbgValue(
5651               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5652           DAG.AddDbgValue(SDV, false);
5653           continue;
5654         }
5655         MachineInstr *NewMI =
5656             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare);
5657         FuncInfo.ArgDbgValues.push_back(NewMI);
5658       }
5659     };
5660 
5661     // Check if ValueMap has reg number.
5662     DenseMap<const Value *, Register>::const_iterator
5663       VMI = FuncInfo.ValueMap.find(V);
5664     if (VMI != FuncInfo.ValueMap.end()) {
5665       const auto &TLI = DAG.getTargetLoweringInfo();
5666       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5667                        V->getType(), None);
5668       if (RFV.occupiesMultipleRegs()) {
5669         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5670         return true;
5671       }
5672 
5673       Op = MachineOperand::CreateReg(VMI->second, false);
5674       IsIndirect = IsDbgDeclare;
5675     } else if (ArgRegsAndSizes.size() > 1) {
5676       // This was split due to the calling convention, and no virtual register
5677       // mapping exists for the value.
5678       splitMultiRegDbgValue(ArgRegsAndSizes);
5679       return true;
5680     }
5681   }
5682 
5683   if (!Op)
5684     return false;
5685 
5686   assert(Variable->isValidLocationForIntrinsic(DL) &&
5687          "Expected inlined-at fields to agree");
5688   MachineInstr *NewMI = nullptr;
5689 
5690   if (Op->isReg())
5691     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5692   else
5693     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5694                     Variable, Expr);
5695 
5696   FuncInfo.ArgDbgValues.push_back(NewMI);
5697   return true;
5698 }
5699 
5700 /// Return the appropriate SDDbgValue based on N.
5701 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5702                                              DILocalVariable *Variable,
5703                                              DIExpression *Expr,
5704                                              const DebugLoc &dl,
5705                                              unsigned DbgSDNodeOrder) {
5706   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5707     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5708     // stack slot locations.
5709     //
5710     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5711     // debug values here after optimization:
5712     //
5713     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5714     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5715     //
5716     // Both describe the direct values of their associated variables.
5717     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5718                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5719   }
5720   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5721                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5722 }
5723 
5724 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5725   switch (Intrinsic) {
5726   case Intrinsic::smul_fix:
5727     return ISD::SMULFIX;
5728   case Intrinsic::umul_fix:
5729     return ISD::UMULFIX;
5730   case Intrinsic::smul_fix_sat:
5731     return ISD::SMULFIXSAT;
5732   case Intrinsic::umul_fix_sat:
5733     return ISD::UMULFIXSAT;
5734   case Intrinsic::sdiv_fix:
5735     return ISD::SDIVFIX;
5736   case Intrinsic::udiv_fix:
5737     return ISD::UDIVFIX;
5738   case Intrinsic::sdiv_fix_sat:
5739     return ISD::SDIVFIXSAT;
5740   case Intrinsic::udiv_fix_sat:
5741     return ISD::UDIVFIXSAT;
5742   default:
5743     llvm_unreachable("Unhandled fixed point intrinsic");
5744   }
5745 }
5746 
5747 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5748                                            const char *FunctionName) {
5749   assert(FunctionName && "FunctionName must not be nullptr");
5750   SDValue Callee = DAG.getExternalSymbol(
5751       FunctionName,
5752       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5753   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5754 }
5755 
5756 /// Given a @llvm.call.preallocated.setup, return the corresponding
5757 /// preallocated call.
5758 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5759   assert(cast<CallBase>(PreallocatedSetup)
5760                  ->getCalledFunction()
5761                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5762          "expected call_preallocated_setup Value");
5763   for (auto *U : PreallocatedSetup->users()) {
5764     auto *UseCall = cast<CallBase>(U);
5765     const Function *Fn = UseCall->getCalledFunction();
5766     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5767       return UseCall;
5768     }
5769   }
5770   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5771 }
5772 
5773 /// Lower the call to the specified intrinsic function.
5774 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5775                                              unsigned Intrinsic) {
5776   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5777   SDLoc sdl = getCurSDLoc();
5778   DebugLoc dl = getCurDebugLoc();
5779   SDValue Res;
5780 
5781   SDNodeFlags Flags;
5782   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5783     Flags.copyFMF(*FPOp);
5784 
5785   switch (Intrinsic) {
5786   default:
5787     // By default, turn this into a target intrinsic node.
5788     visitTargetIntrinsic(I, Intrinsic);
5789     return;
5790   case Intrinsic::vscale: {
5791     match(&I, m_VScale(DAG.getDataLayout()));
5792     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5793     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5794     return;
5795   }
5796   case Intrinsic::vastart:  visitVAStart(I); return;
5797   case Intrinsic::vaend:    visitVAEnd(I); return;
5798   case Intrinsic::vacopy:   visitVACopy(I); return;
5799   case Intrinsic::returnaddress:
5800     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5801                              TLI.getPointerTy(DAG.getDataLayout()),
5802                              getValue(I.getArgOperand(0))));
5803     return;
5804   case Intrinsic::addressofreturnaddress:
5805     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5806                              TLI.getPointerTy(DAG.getDataLayout())));
5807     return;
5808   case Intrinsic::sponentry:
5809     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5810                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5811     return;
5812   case Intrinsic::frameaddress:
5813     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5814                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5815                              getValue(I.getArgOperand(0))));
5816     return;
5817   case Intrinsic::read_volatile_register:
5818   case Intrinsic::read_register: {
5819     Value *Reg = I.getArgOperand(0);
5820     SDValue Chain = getRoot();
5821     SDValue RegName =
5822         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5823     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5824     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5825       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5826     setValue(&I, Res);
5827     DAG.setRoot(Res.getValue(1));
5828     return;
5829   }
5830   case Intrinsic::write_register: {
5831     Value *Reg = I.getArgOperand(0);
5832     Value *RegValue = I.getArgOperand(1);
5833     SDValue Chain = getRoot();
5834     SDValue RegName =
5835         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5836     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5837                             RegName, getValue(RegValue)));
5838     return;
5839   }
5840   case Intrinsic::memcpy: {
5841     const auto &MCI = cast<MemCpyInst>(I);
5842     SDValue Op1 = getValue(I.getArgOperand(0));
5843     SDValue Op2 = getValue(I.getArgOperand(1));
5844     SDValue Op3 = getValue(I.getArgOperand(2));
5845     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5846     Align DstAlign = MCI.getDestAlign().valueOrOne();
5847     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5848     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5849     bool isVol = MCI.isVolatile();
5850     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5851     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5852     // node.
5853     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5854     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5855                                /* AlwaysInline */ false, isTC,
5856                                MachinePointerInfo(I.getArgOperand(0)),
5857                                MachinePointerInfo(I.getArgOperand(1)),
5858                                I.getAAMetadata());
5859     updateDAGForMaybeTailCall(MC);
5860     return;
5861   }
5862   case Intrinsic::memcpy_inline: {
5863     const auto &MCI = cast<MemCpyInlineInst>(I);
5864     SDValue Dst = getValue(I.getArgOperand(0));
5865     SDValue Src = getValue(I.getArgOperand(1));
5866     SDValue Size = getValue(I.getArgOperand(2));
5867     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5868     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5869     Align DstAlign = MCI.getDestAlign().valueOrOne();
5870     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5871     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5872     bool isVol = MCI.isVolatile();
5873     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5874     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5875     // node.
5876     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5877                                /* AlwaysInline */ true, isTC,
5878                                MachinePointerInfo(I.getArgOperand(0)),
5879                                MachinePointerInfo(I.getArgOperand(1)),
5880                                I.getAAMetadata());
5881     updateDAGForMaybeTailCall(MC);
5882     return;
5883   }
5884   case Intrinsic::memset: {
5885     const auto &MSI = cast<MemSetInst>(I);
5886     SDValue Op1 = getValue(I.getArgOperand(0));
5887     SDValue Op2 = getValue(I.getArgOperand(1));
5888     SDValue Op3 = getValue(I.getArgOperand(2));
5889     // @llvm.memset defines 0 and 1 to both mean no alignment.
5890     Align Alignment = MSI.getDestAlign().valueOrOne();
5891     bool isVol = MSI.isVolatile();
5892     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5893     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5894     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5895                                MachinePointerInfo(I.getArgOperand(0)),
5896                                I.getAAMetadata());
5897     updateDAGForMaybeTailCall(MS);
5898     return;
5899   }
5900   case Intrinsic::memmove: {
5901     const auto &MMI = cast<MemMoveInst>(I);
5902     SDValue Op1 = getValue(I.getArgOperand(0));
5903     SDValue Op2 = getValue(I.getArgOperand(1));
5904     SDValue Op3 = getValue(I.getArgOperand(2));
5905     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5906     Align DstAlign = MMI.getDestAlign().valueOrOne();
5907     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5908     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5909     bool isVol = MMI.isVolatile();
5910     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5911     // FIXME: Support passing different dest/src alignments to the memmove DAG
5912     // node.
5913     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5914     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5915                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5916                                 MachinePointerInfo(I.getArgOperand(1)),
5917                                 I.getAAMetadata());
5918     updateDAGForMaybeTailCall(MM);
5919     return;
5920   }
5921   case Intrinsic::memcpy_element_unordered_atomic: {
5922     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5923     SDValue Dst = getValue(MI.getRawDest());
5924     SDValue Src = getValue(MI.getRawSource());
5925     SDValue Length = getValue(MI.getLength());
5926 
5927     unsigned DstAlign = MI.getDestAlignment();
5928     unsigned SrcAlign = MI.getSourceAlignment();
5929     Type *LengthTy = MI.getLength()->getType();
5930     unsigned ElemSz = MI.getElementSizeInBytes();
5931     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5932     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5933                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5934                                      MachinePointerInfo(MI.getRawDest()),
5935                                      MachinePointerInfo(MI.getRawSource()));
5936     updateDAGForMaybeTailCall(MC);
5937     return;
5938   }
5939   case Intrinsic::memmove_element_unordered_atomic: {
5940     auto &MI = cast<AtomicMemMoveInst>(I);
5941     SDValue Dst = getValue(MI.getRawDest());
5942     SDValue Src = getValue(MI.getRawSource());
5943     SDValue Length = getValue(MI.getLength());
5944 
5945     unsigned DstAlign = MI.getDestAlignment();
5946     unsigned SrcAlign = MI.getSourceAlignment();
5947     Type *LengthTy = MI.getLength()->getType();
5948     unsigned ElemSz = MI.getElementSizeInBytes();
5949     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5950     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5951                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5952                                       MachinePointerInfo(MI.getRawDest()),
5953                                       MachinePointerInfo(MI.getRawSource()));
5954     updateDAGForMaybeTailCall(MC);
5955     return;
5956   }
5957   case Intrinsic::memset_element_unordered_atomic: {
5958     auto &MI = cast<AtomicMemSetInst>(I);
5959     SDValue Dst = getValue(MI.getRawDest());
5960     SDValue Val = getValue(MI.getValue());
5961     SDValue Length = getValue(MI.getLength());
5962 
5963     unsigned DstAlign = MI.getDestAlignment();
5964     Type *LengthTy = MI.getLength()->getType();
5965     unsigned ElemSz = MI.getElementSizeInBytes();
5966     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5967     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5968                                      LengthTy, ElemSz, isTC,
5969                                      MachinePointerInfo(MI.getRawDest()));
5970     updateDAGForMaybeTailCall(MC);
5971     return;
5972   }
5973   case Intrinsic::call_preallocated_setup: {
5974     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5975     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5976     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5977                               getRoot(), SrcValue);
5978     setValue(&I, Res);
5979     DAG.setRoot(Res);
5980     return;
5981   }
5982   case Intrinsic::call_preallocated_arg: {
5983     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5984     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5985     SDValue Ops[3];
5986     Ops[0] = getRoot();
5987     Ops[1] = SrcValue;
5988     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5989                                    MVT::i32); // arg index
5990     SDValue Res = DAG.getNode(
5991         ISD::PREALLOCATED_ARG, sdl,
5992         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5993     setValue(&I, Res);
5994     DAG.setRoot(Res.getValue(1));
5995     return;
5996   }
5997   case Intrinsic::dbg_addr:
5998   case Intrinsic::dbg_declare: {
5999     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6000     // they are non-variadic.
6001     const auto &DI = cast<DbgVariableIntrinsic>(I);
6002     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6003     DILocalVariable *Variable = DI.getVariable();
6004     DIExpression *Expression = DI.getExpression();
6005     dropDanglingDebugInfo(Variable, Expression);
6006     assert(Variable && "Missing variable");
6007     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6008                       << "\n");
6009     // Check if address has undef value.
6010     const Value *Address = DI.getVariableLocationOp(0);
6011     if (!Address || isa<UndefValue>(Address) ||
6012         (Address->use_empty() && !isa<Argument>(Address))) {
6013       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6014                         << " (bad/undef/unused-arg address)\n");
6015       return;
6016     }
6017 
6018     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6019 
6020     // Check if this variable can be described by a frame index, typically
6021     // either as a static alloca or a byval parameter.
6022     int FI = std::numeric_limits<int>::max();
6023     if (const auto *AI =
6024             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6025       if (AI->isStaticAlloca()) {
6026         auto I = FuncInfo.StaticAllocaMap.find(AI);
6027         if (I != FuncInfo.StaticAllocaMap.end())
6028           FI = I->second;
6029       }
6030     } else if (const auto *Arg = dyn_cast<Argument>(
6031                    Address->stripInBoundsConstantOffsets())) {
6032       FI = FuncInfo.getArgumentFrameIndex(Arg);
6033     }
6034 
6035     // llvm.dbg.addr is control dependent and always generates indirect
6036     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6037     // the MachineFunction variable table.
6038     if (FI != std::numeric_limits<int>::max()) {
6039       if (Intrinsic == Intrinsic::dbg_addr) {
6040         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6041             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6042             dl, SDNodeOrder);
6043         DAG.AddDbgValue(SDV, isParameter);
6044       } else {
6045         LLVM_DEBUG(dbgs() << "Skipping " << DI
6046                           << " (variable info stashed in MF side table)\n");
6047       }
6048       return;
6049     }
6050 
6051     SDValue &N = NodeMap[Address];
6052     if (!N.getNode() && isa<Argument>(Address))
6053       // Check unused arguments map.
6054       N = UnusedArgNodeMap[Address];
6055     SDDbgValue *SDV;
6056     if (N.getNode()) {
6057       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6058         Address = BCI->getOperand(0);
6059       // Parameters are handled specially.
6060       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6061       if (isParameter && FINode) {
6062         // Byval parameter. We have a frame index at this point.
6063         SDV =
6064             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6065                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6066       } else if (isa<Argument>(Address)) {
6067         // Address is an argument, so try to emit its dbg value using
6068         // virtual register info from the FuncInfo.ValueMap.
6069         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6070         return;
6071       } else {
6072         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6073                               true, dl, SDNodeOrder);
6074       }
6075       DAG.AddDbgValue(SDV, isParameter);
6076     } else {
6077       // If Address is an argument then try to emit its dbg value using
6078       // virtual register info from the FuncInfo.ValueMap.
6079       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6080                                     N)) {
6081         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6082                           << " (could not emit func-arg dbg_value)\n");
6083       }
6084     }
6085     return;
6086   }
6087   case Intrinsic::dbg_label: {
6088     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6089     DILabel *Label = DI.getLabel();
6090     assert(Label && "Missing label");
6091 
6092     SDDbgLabel *SDV;
6093     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6094     DAG.AddDbgLabel(SDV);
6095     return;
6096   }
6097   case Intrinsic::dbg_value: {
6098     const DbgValueInst &DI = cast<DbgValueInst>(I);
6099     assert(DI.getVariable() && "Missing variable");
6100 
6101     DILocalVariable *Variable = DI.getVariable();
6102     DIExpression *Expression = DI.getExpression();
6103     dropDanglingDebugInfo(Variable, Expression);
6104     SmallVector<Value *, 4> Values(DI.getValues());
6105     if (Values.empty())
6106       return;
6107 
6108     if (llvm::is_contained(Values, nullptr))
6109       return;
6110 
6111     bool IsVariadic = DI.hasArgList();
6112     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6113                           SDNodeOrder, IsVariadic))
6114       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6115     return;
6116   }
6117 
6118   case Intrinsic::eh_typeid_for: {
6119     // Find the type id for the given typeinfo.
6120     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6121     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6122     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6123     setValue(&I, Res);
6124     return;
6125   }
6126 
6127   case Intrinsic::eh_return_i32:
6128   case Intrinsic::eh_return_i64:
6129     DAG.getMachineFunction().setCallsEHReturn(true);
6130     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6131                             MVT::Other,
6132                             getControlRoot(),
6133                             getValue(I.getArgOperand(0)),
6134                             getValue(I.getArgOperand(1))));
6135     return;
6136   case Intrinsic::eh_unwind_init:
6137     DAG.getMachineFunction().setCallsUnwindInit(true);
6138     return;
6139   case Intrinsic::eh_dwarf_cfa:
6140     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6141                              TLI.getPointerTy(DAG.getDataLayout()),
6142                              getValue(I.getArgOperand(0))));
6143     return;
6144   case Intrinsic::eh_sjlj_callsite: {
6145     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6146     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6147     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6148     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6149 
6150     MMI.setCurrentCallSite(CI->getZExtValue());
6151     return;
6152   }
6153   case Intrinsic::eh_sjlj_functioncontext: {
6154     // Get and store the index of the function context.
6155     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6156     AllocaInst *FnCtx =
6157       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6158     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6159     MFI.setFunctionContextIndex(FI);
6160     return;
6161   }
6162   case Intrinsic::eh_sjlj_setjmp: {
6163     SDValue Ops[2];
6164     Ops[0] = getRoot();
6165     Ops[1] = getValue(I.getArgOperand(0));
6166     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6167                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6168     setValue(&I, Op.getValue(0));
6169     DAG.setRoot(Op.getValue(1));
6170     return;
6171   }
6172   case Intrinsic::eh_sjlj_longjmp:
6173     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6174                             getRoot(), getValue(I.getArgOperand(0))));
6175     return;
6176   case Intrinsic::eh_sjlj_setup_dispatch:
6177     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6178                             getRoot()));
6179     return;
6180   case Intrinsic::masked_gather:
6181     visitMaskedGather(I);
6182     return;
6183   case Intrinsic::masked_load:
6184     visitMaskedLoad(I);
6185     return;
6186   case Intrinsic::masked_scatter:
6187     visitMaskedScatter(I);
6188     return;
6189   case Intrinsic::masked_store:
6190     visitMaskedStore(I);
6191     return;
6192   case Intrinsic::masked_expandload:
6193     visitMaskedLoad(I, true /* IsExpanding */);
6194     return;
6195   case Intrinsic::masked_compressstore:
6196     visitMaskedStore(I, true /* IsCompressing */);
6197     return;
6198   case Intrinsic::powi:
6199     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6200                             getValue(I.getArgOperand(1)), DAG));
6201     return;
6202   case Intrinsic::log:
6203     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6204     return;
6205   case Intrinsic::log2:
6206     setValue(&I,
6207              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6208     return;
6209   case Intrinsic::log10:
6210     setValue(&I,
6211              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6212     return;
6213   case Intrinsic::exp:
6214     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6215     return;
6216   case Intrinsic::exp2:
6217     setValue(&I,
6218              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6219     return;
6220   case Intrinsic::pow:
6221     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6222                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6223     return;
6224   case Intrinsic::sqrt:
6225   case Intrinsic::fabs:
6226   case Intrinsic::sin:
6227   case Intrinsic::cos:
6228   case Intrinsic::floor:
6229   case Intrinsic::ceil:
6230   case Intrinsic::trunc:
6231   case Intrinsic::rint:
6232   case Intrinsic::nearbyint:
6233   case Intrinsic::round:
6234   case Intrinsic::roundeven:
6235   case Intrinsic::canonicalize: {
6236     unsigned Opcode;
6237     switch (Intrinsic) {
6238     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6239     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6240     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6241     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6242     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6243     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6244     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6245     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6246     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6247     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6248     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6249     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6250     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6251     }
6252 
6253     setValue(&I, DAG.getNode(Opcode, sdl,
6254                              getValue(I.getArgOperand(0)).getValueType(),
6255                              getValue(I.getArgOperand(0)), Flags));
6256     return;
6257   }
6258   case Intrinsic::lround:
6259   case Intrinsic::llround:
6260   case Intrinsic::lrint:
6261   case Intrinsic::llrint: {
6262     unsigned Opcode;
6263     switch (Intrinsic) {
6264     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6265     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6266     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6267     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6268     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6269     }
6270 
6271     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6272     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6273                              getValue(I.getArgOperand(0))));
6274     return;
6275   }
6276   case Intrinsic::minnum:
6277     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6278                              getValue(I.getArgOperand(0)).getValueType(),
6279                              getValue(I.getArgOperand(0)),
6280                              getValue(I.getArgOperand(1)), Flags));
6281     return;
6282   case Intrinsic::maxnum:
6283     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6284                              getValue(I.getArgOperand(0)).getValueType(),
6285                              getValue(I.getArgOperand(0)),
6286                              getValue(I.getArgOperand(1)), Flags));
6287     return;
6288   case Intrinsic::minimum:
6289     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6290                              getValue(I.getArgOperand(0)).getValueType(),
6291                              getValue(I.getArgOperand(0)),
6292                              getValue(I.getArgOperand(1)), Flags));
6293     return;
6294   case Intrinsic::maximum:
6295     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6296                              getValue(I.getArgOperand(0)).getValueType(),
6297                              getValue(I.getArgOperand(0)),
6298                              getValue(I.getArgOperand(1)), Flags));
6299     return;
6300   case Intrinsic::copysign:
6301     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6302                              getValue(I.getArgOperand(0)).getValueType(),
6303                              getValue(I.getArgOperand(0)),
6304                              getValue(I.getArgOperand(1)), Flags));
6305     return;
6306   case Intrinsic::arithmetic_fence: {
6307     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6308                              getValue(I.getArgOperand(0)).getValueType(),
6309                              getValue(I.getArgOperand(0)), Flags));
6310     return;
6311   }
6312   case Intrinsic::fma:
6313     setValue(&I, DAG.getNode(
6314                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6315                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6316                      getValue(I.getArgOperand(2)), Flags));
6317     return;
6318 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6319   case Intrinsic::INTRINSIC:
6320 #include "llvm/IR/ConstrainedOps.def"
6321     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6322     return;
6323 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6324 #include "llvm/IR/VPIntrinsics.def"
6325     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6326     return;
6327   case Intrinsic::fptrunc_round: {
6328     // Get the last argument, the metadata and convert it to an integer in the
6329     // call
6330     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6331     Optional<RoundingMode> RoundMode =
6332         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6333 
6334     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6335 
6336     // Propagate fast-math-flags from IR to node(s).
6337     SDNodeFlags Flags;
6338     Flags.copyFMF(*cast<FPMathOperator>(&I));
6339     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6340 
6341     SDValue Result;
6342     Result = DAG.getNode(
6343         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6344         DAG.getTargetConstant((int)RoundMode.getValue(), sdl,
6345                               TLI.getPointerTy(DAG.getDataLayout())));
6346     setValue(&I, Result);
6347 
6348     return;
6349   }
6350   case Intrinsic::fmuladd: {
6351     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6352     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6353         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6354       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6355                                getValue(I.getArgOperand(0)).getValueType(),
6356                                getValue(I.getArgOperand(0)),
6357                                getValue(I.getArgOperand(1)),
6358                                getValue(I.getArgOperand(2)), Flags));
6359     } else {
6360       // TODO: Intrinsic calls should have fast-math-flags.
6361       SDValue Mul = DAG.getNode(
6362           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6363           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6364       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6365                                 getValue(I.getArgOperand(0)).getValueType(),
6366                                 Mul, getValue(I.getArgOperand(2)), Flags);
6367       setValue(&I, Add);
6368     }
6369     return;
6370   }
6371   case Intrinsic::convert_to_fp16:
6372     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6373                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6374                                          getValue(I.getArgOperand(0)),
6375                                          DAG.getTargetConstant(0, sdl,
6376                                                                MVT::i32))));
6377     return;
6378   case Intrinsic::convert_from_fp16:
6379     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6380                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6381                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6382                                          getValue(I.getArgOperand(0)))));
6383     return;
6384   case Intrinsic::fptosi_sat: {
6385     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6386     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6387                              getValue(I.getArgOperand(0)),
6388                              DAG.getValueType(VT.getScalarType())));
6389     return;
6390   }
6391   case Intrinsic::fptoui_sat: {
6392     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6393     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6394                              getValue(I.getArgOperand(0)),
6395                              DAG.getValueType(VT.getScalarType())));
6396     return;
6397   }
6398   case Intrinsic::set_rounding:
6399     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6400                       {getRoot(), getValue(I.getArgOperand(0))});
6401     setValue(&I, Res);
6402     DAG.setRoot(Res.getValue(0));
6403     return;
6404   case Intrinsic::pcmarker: {
6405     SDValue Tmp = getValue(I.getArgOperand(0));
6406     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6407     return;
6408   }
6409   case Intrinsic::readcyclecounter: {
6410     SDValue Op = getRoot();
6411     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6412                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6413     setValue(&I, Res);
6414     DAG.setRoot(Res.getValue(1));
6415     return;
6416   }
6417   case Intrinsic::bitreverse:
6418     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6419                              getValue(I.getArgOperand(0)).getValueType(),
6420                              getValue(I.getArgOperand(0))));
6421     return;
6422   case Intrinsic::bswap:
6423     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6424                              getValue(I.getArgOperand(0)).getValueType(),
6425                              getValue(I.getArgOperand(0))));
6426     return;
6427   case Intrinsic::cttz: {
6428     SDValue Arg = getValue(I.getArgOperand(0));
6429     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6430     EVT Ty = Arg.getValueType();
6431     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6432                              sdl, Ty, Arg));
6433     return;
6434   }
6435   case Intrinsic::ctlz: {
6436     SDValue Arg = getValue(I.getArgOperand(0));
6437     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6438     EVT Ty = Arg.getValueType();
6439     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6440                              sdl, Ty, Arg));
6441     return;
6442   }
6443   case Intrinsic::ctpop: {
6444     SDValue Arg = getValue(I.getArgOperand(0));
6445     EVT Ty = Arg.getValueType();
6446     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6447     return;
6448   }
6449   case Intrinsic::fshl:
6450   case Intrinsic::fshr: {
6451     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6452     SDValue X = getValue(I.getArgOperand(0));
6453     SDValue Y = getValue(I.getArgOperand(1));
6454     SDValue Z = getValue(I.getArgOperand(2));
6455     EVT VT = X.getValueType();
6456 
6457     if (X == Y) {
6458       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6459       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6460     } else {
6461       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6462       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6463     }
6464     return;
6465   }
6466   case Intrinsic::sadd_sat: {
6467     SDValue Op1 = getValue(I.getArgOperand(0));
6468     SDValue Op2 = getValue(I.getArgOperand(1));
6469     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6470     return;
6471   }
6472   case Intrinsic::uadd_sat: {
6473     SDValue Op1 = getValue(I.getArgOperand(0));
6474     SDValue Op2 = getValue(I.getArgOperand(1));
6475     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6476     return;
6477   }
6478   case Intrinsic::ssub_sat: {
6479     SDValue Op1 = getValue(I.getArgOperand(0));
6480     SDValue Op2 = getValue(I.getArgOperand(1));
6481     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6482     return;
6483   }
6484   case Intrinsic::usub_sat: {
6485     SDValue Op1 = getValue(I.getArgOperand(0));
6486     SDValue Op2 = getValue(I.getArgOperand(1));
6487     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6488     return;
6489   }
6490   case Intrinsic::sshl_sat: {
6491     SDValue Op1 = getValue(I.getArgOperand(0));
6492     SDValue Op2 = getValue(I.getArgOperand(1));
6493     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6494     return;
6495   }
6496   case Intrinsic::ushl_sat: {
6497     SDValue Op1 = getValue(I.getArgOperand(0));
6498     SDValue Op2 = getValue(I.getArgOperand(1));
6499     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6500     return;
6501   }
6502   case Intrinsic::smul_fix:
6503   case Intrinsic::umul_fix:
6504   case Intrinsic::smul_fix_sat:
6505   case Intrinsic::umul_fix_sat: {
6506     SDValue Op1 = getValue(I.getArgOperand(0));
6507     SDValue Op2 = getValue(I.getArgOperand(1));
6508     SDValue Op3 = getValue(I.getArgOperand(2));
6509     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6510                              Op1.getValueType(), Op1, Op2, Op3));
6511     return;
6512   }
6513   case Intrinsic::sdiv_fix:
6514   case Intrinsic::udiv_fix:
6515   case Intrinsic::sdiv_fix_sat:
6516   case Intrinsic::udiv_fix_sat: {
6517     SDValue Op1 = getValue(I.getArgOperand(0));
6518     SDValue Op2 = getValue(I.getArgOperand(1));
6519     SDValue Op3 = getValue(I.getArgOperand(2));
6520     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6521                               Op1, Op2, Op3, DAG, TLI));
6522     return;
6523   }
6524   case Intrinsic::smax: {
6525     SDValue Op1 = getValue(I.getArgOperand(0));
6526     SDValue Op2 = getValue(I.getArgOperand(1));
6527     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6528     return;
6529   }
6530   case Intrinsic::smin: {
6531     SDValue Op1 = getValue(I.getArgOperand(0));
6532     SDValue Op2 = getValue(I.getArgOperand(1));
6533     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6534     return;
6535   }
6536   case Intrinsic::umax: {
6537     SDValue Op1 = getValue(I.getArgOperand(0));
6538     SDValue Op2 = getValue(I.getArgOperand(1));
6539     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6540     return;
6541   }
6542   case Intrinsic::umin: {
6543     SDValue Op1 = getValue(I.getArgOperand(0));
6544     SDValue Op2 = getValue(I.getArgOperand(1));
6545     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6546     return;
6547   }
6548   case Intrinsic::abs: {
6549     // TODO: Preserve "int min is poison" arg in SDAG?
6550     SDValue Op1 = getValue(I.getArgOperand(0));
6551     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6552     return;
6553   }
6554   case Intrinsic::stacksave: {
6555     SDValue Op = getRoot();
6556     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6557     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6558     setValue(&I, Res);
6559     DAG.setRoot(Res.getValue(1));
6560     return;
6561   }
6562   case Intrinsic::stackrestore:
6563     Res = getValue(I.getArgOperand(0));
6564     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6565     return;
6566   case Intrinsic::get_dynamic_area_offset: {
6567     SDValue Op = getRoot();
6568     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6569     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6570     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6571     // target.
6572     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6573       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6574                          " intrinsic!");
6575     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6576                       Op);
6577     DAG.setRoot(Op);
6578     setValue(&I, Res);
6579     return;
6580   }
6581   case Intrinsic::stackguard: {
6582     MachineFunction &MF = DAG.getMachineFunction();
6583     const Module &M = *MF.getFunction().getParent();
6584     SDValue Chain = getRoot();
6585     if (TLI.useLoadStackGuardNode()) {
6586       Res = getLoadStackGuard(DAG, sdl, Chain);
6587     } else {
6588       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6589       const Value *Global = TLI.getSDagStackGuard(M);
6590       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6591       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6592                         MachinePointerInfo(Global, 0), Align,
6593                         MachineMemOperand::MOVolatile);
6594     }
6595     if (TLI.useStackGuardXorFP())
6596       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6597     DAG.setRoot(Chain);
6598     setValue(&I, Res);
6599     return;
6600   }
6601   case Intrinsic::stackprotector: {
6602     // Emit code into the DAG to store the stack guard onto the stack.
6603     MachineFunction &MF = DAG.getMachineFunction();
6604     MachineFrameInfo &MFI = MF.getFrameInfo();
6605     SDValue Src, Chain = getRoot();
6606 
6607     if (TLI.useLoadStackGuardNode())
6608       Src = getLoadStackGuard(DAG, sdl, Chain);
6609     else
6610       Src = getValue(I.getArgOperand(0));   // The guard's value.
6611 
6612     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6613 
6614     int FI = FuncInfo.StaticAllocaMap[Slot];
6615     MFI.setStackProtectorIndex(FI);
6616     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6617 
6618     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6619 
6620     // Store the stack protector onto the stack.
6621     Res = DAG.getStore(
6622         Chain, sdl, Src, FIN,
6623         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6624         MaybeAlign(), MachineMemOperand::MOVolatile);
6625     setValue(&I, Res);
6626     DAG.setRoot(Res);
6627     return;
6628   }
6629   case Intrinsic::objectsize:
6630     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6631 
6632   case Intrinsic::is_constant:
6633     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6634 
6635   case Intrinsic::annotation:
6636   case Intrinsic::ptr_annotation:
6637   case Intrinsic::launder_invariant_group:
6638   case Intrinsic::strip_invariant_group:
6639     // Drop the intrinsic, but forward the value
6640     setValue(&I, getValue(I.getOperand(0)));
6641     return;
6642 
6643   case Intrinsic::assume:
6644   case Intrinsic::experimental_noalias_scope_decl:
6645   case Intrinsic::var_annotation:
6646   case Intrinsic::sideeffect:
6647     // Discard annotate attributes, noalias scope declarations, assumptions, and
6648     // artificial side-effects.
6649     return;
6650 
6651   case Intrinsic::codeview_annotation: {
6652     // Emit a label associated with this metadata.
6653     MachineFunction &MF = DAG.getMachineFunction();
6654     MCSymbol *Label =
6655         MF.getMMI().getContext().createTempSymbol("annotation", true);
6656     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6657     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6658     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6659     DAG.setRoot(Res);
6660     return;
6661   }
6662 
6663   case Intrinsic::init_trampoline: {
6664     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6665 
6666     SDValue Ops[6];
6667     Ops[0] = getRoot();
6668     Ops[1] = getValue(I.getArgOperand(0));
6669     Ops[2] = getValue(I.getArgOperand(1));
6670     Ops[3] = getValue(I.getArgOperand(2));
6671     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6672     Ops[5] = DAG.getSrcValue(F);
6673 
6674     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6675 
6676     DAG.setRoot(Res);
6677     return;
6678   }
6679   case Intrinsic::adjust_trampoline:
6680     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6681                              TLI.getPointerTy(DAG.getDataLayout()),
6682                              getValue(I.getArgOperand(0))));
6683     return;
6684   case Intrinsic::gcroot: {
6685     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6686            "only valid in functions with gc specified, enforced by Verifier");
6687     assert(GFI && "implied by previous");
6688     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6689     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6690 
6691     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6692     GFI->addStackRoot(FI->getIndex(), TypeMap);
6693     return;
6694   }
6695   case Intrinsic::gcread:
6696   case Intrinsic::gcwrite:
6697     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6698   case Intrinsic::flt_rounds:
6699     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6700     setValue(&I, Res);
6701     DAG.setRoot(Res.getValue(1));
6702     return;
6703 
6704   case Intrinsic::expect:
6705     // Just replace __builtin_expect(exp, c) with EXP.
6706     setValue(&I, getValue(I.getArgOperand(0)));
6707     return;
6708 
6709   case Intrinsic::ubsantrap:
6710   case Intrinsic::debugtrap:
6711   case Intrinsic::trap: {
6712     StringRef TrapFuncName =
6713         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6714     if (TrapFuncName.empty()) {
6715       switch (Intrinsic) {
6716       case Intrinsic::trap:
6717         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6718         break;
6719       case Intrinsic::debugtrap:
6720         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6721         break;
6722       case Intrinsic::ubsantrap:
6723         DAG.setRoot(DAG.getNode(
6724             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6725             DAG.getTargetConstant(
6726                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6727                 MVT::i32)));
6728         break;
6729       default: llvm_unreachable("unknown trap intrinsic");
6730       }
6731       return;
6732     }
6733     TargetLowering::ArgListTy Args;
6734     if (Intrinsic == Intrinsic::ubsantrap) {
6735       Args.push_back(TargetLoweringBase::ArgListEntry());
6736       Args[0].Val = I.getArgOperand(0);
6737       Args[0].Node = getValue(Args[0].Val);
6738       Args[0].Ty = Args[0].Val->getType();
6739     }
6740 
6741     TargetLowering::CallLoweringInfo CLI(DAG);
6742     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6743         CallingConv::C, I.getType(),
6744         DAG.getExternalSymbol(TrapFuncName.data(),
6745                               TLI.getPointerTy(DAG.getDataLayout())),
6746         std::move(Args));
6747 
6748     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6749     DAG.setRoot(Result.second);
6750     return;
6751   }
6752 
6753   case Intrinsic::uadd_with_overflow:
6754   case Intrinsic::sadd_with_overflow:
6755   case Intrinsic::usub_with_overflow:
6756   case Intrinsic::ssub_with_overflow:
6757   case Intrinsic::umul_with_overflow:
6758   case Intrinsic::smul_with_overflow: {
6759     ISD::NodeType Op;
6760     switch (Intrinsic) {
6761     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6762     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6763     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6764     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6765     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6766     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6767     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6768     }
6769     SDValue Op1 = getValue(I.getArgOperand(0));
6770     SDValue Op2 = getValue(I.getArgOperand(1));
6771 
6772     EVT ResultVT = Op1.getValueType();
6773     EVT OverflowVT = MVT::i1;
6774     if (ResultVT.isVector())
6775       OverflowVT = EVT::getVectorVT(
6776           *Context, OverflowVT, ResultVT.getVectorElementCount());
6777 
6778     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6779     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6780     return;
6781   }
6782   case Intrinsic::prefetch: {
6783     SDValue Ops[5];
6784     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6785     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6786     Ops[0] = DAG.getRoot();
6787     Ops[1] = getValue(I.getArgOperand(0));
6788     Ops[2] = getValue(I.getArgOperand(1));
6789     Ops[3] = getValue(I.getArgOperand(2));
6790     Ops[4] = getValue(I.getArgOperand(3));
6791     SDValue Result = DAG.getMemIntrinsicNode(
6792         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6793         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6794         /* align */ None, Flags);
6795 
6796     // Chain the prefetch in parallell with any pending loads, to stay out of
6797     // the way of later optimizations.
6798     PendingLoads.push_back(Result);
6799     Result = getRoot();
6800     DAG.setRoot(Result);
6801     return;
6802   }
6803   case Intrinsic::lifetime_start:
6804   case Intrinsic::lifetime_end: {
6805     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6806     // Stack coloring is not enabled in O0, discard region information.
6807     if (TM.getOptLevel() == CodeGenOpt::None)
6808       return;
6809 
6810     const int64_t ObjectSize =
6811         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6812     Value *const ObjectPtr = I.getArgOperand(1);
6813     SmallVector<const Value *, 4> Allocas;
6814     getUnderlyingObjects(ObjectPtr, Allocas);
6815 
6816     for (const Value *Alloca : Allocas) {
6817       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6818 
6819       // Could not find an Alloca.
6820       if (!LifetimeObject)
6821         continue;
6822 
6823       // First check that the Alloca is static, otherwise it won't have a
6824       // valid frame index.
6825       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6826       if (SI == FuncInfo.StaticAllocaMap.end())
6827         return;
6828 
6829       const int FrameIndex = SI->second;
6830       int64_t Offset;
6831       if (GetPointerBaseWithConstantOffset(
6832               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6833         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6834       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6835                                 Offset);
6836       DAG.setRoot(Res);
6837     }
6838     return;
6839   }
6840   case Intrinsic::pseudoprobe: {
6841     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6842     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6843     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6844     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6845     DAG.setRoot(Res);
6846     return;
6847   }
6848   case Intrinsic::invariant_start:
6849     // Discard region information.
6850     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6851     return;
6852   case Intrinsic::invariant_end:
6853     // Discard region information.
6854     return;
6855   case Intrinsic::clear_cache:
6856     /// FunctionName may be null.
6857     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6858       lowerCallToExternalSymbol(I, FunctionName);
6859     return;
6860   case Intrinsic::donothing:
6861   case Intrinsic::seh_try_begin:
6862   case Intrinsic::seh_scope_begin:
6863   case Intrinsic::seh_try_end:
6864   case Intrinsic::seh_scope_end:
6865     // ignore
6866     return;
6867   case Intrinsic::experimental_stackmap:
6868     visitStackmap(I);
6869     return;
6870   case Intrinsic::experimental_patchpoint_void:
6871   case Intrinsic::experimental_patchpoint_i64:
6872     visitPatchpoint(I);
6873     return;
6874   case Intrinsic::experimental_gc_statepoint:
6875     LowerStatepoint(cast<GCStatepointInst>(I));
6876     return;
6877   case Intrinsic::experimental_gc_result:
6878     visitGCResult(cast<GCResultInst>(I));
6879     return;
6880   case Intrinsic::experimental_gc_relocate:
6881     visitGCRelocate(cast<GCRelocateInst>(I));
6882     return;
6883   case Intrinsic::instrprof_cover:
6884     llvm_unreachable("instrprof failed to lower a cover");
6885   case Intrinsic::instrprof_increment:
6886     llvm_unreachable("instrprof failed to lower an increment");
6887   case Intrinsic::instrprof_value_profile:
6888     llvm_unreachable("instrprof failed to lower a value profiling call");
6889   case Intrinsic::localescape: {
6890     MachineFunction &MF = DAG.getMachineFunction();
6891     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6892 
6893     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6894     // is the same on all targets.
6895     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
6896       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6897       if (isa<ConstantPointerNull>(Arg))
6898         continue; // Skip null pointers. They represent a hole in index space.
6899       AllocaInst *Slot = cast<AllocaInst>(Arg);
6900       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6901              "can only escape static allocas");
6902       int FI = FuncInfo.StaticAllocaMap[Slot];
6903       MCSymbol *FrameAllocSym =
6904           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6905               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6906       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6907               TII->get(TargetOpcode::LOCAL_ESCAPE))
6908           .addSym(FrameAllocSym)
6909           .addFrameIndex(FI);
6910     }
6911 
6912     return;
6913   }
6914 
6915   case Intrinsic::localrecover: {
6916     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6917     MachineFunction &MF = DAG.getMachineFunction();
6918 
6919     // Get the symbol that defines the frame offset.
6920     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6921     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6922     unsigned IdxVal =
6923         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6924     MCSymbol *FrameAllocSym =
6925         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6926             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6927 
6928     Value *FP = I.getArgOperand(1);
6929     SDValue FPVal = getValue(FP);
6930     EVT PtrVT = FPVal.getValueType();
6931 
6932     // Create a MCSymbol for the label to avoid any target lowering
6933     // that would make this PC relative.
6934     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6935     SDValue OffsetVal =
6936         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6937 
6938     // Add the offset to the FP.
6939     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6940     setValue(&I, Add);
6941 
6942     return;
6943   }
6944 
6945   case Intrinsic::eh_exceptionpointer:
6946   case Intrinsic::eh_exceptioncode: {
6947     // Get the exception pointer vreg, copy from it, and resize it to fit.
6948     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6949     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6950     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6951     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6952     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
6953     if (Intrinsic == Intrinsic::eh_exceptioncode)
6954       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
6955     setValue(&I, N);
6956     return;
6957   }
6958   case Intrinsic::xray_customevent: {
6959     // Here we want to make sure that the intrinsic behaves as if it has a
6960     // specific calling convention, and only for x86_64.
6961     // FIXME: Support other platforms later.
6962     const auto &Triple = DAG.getTarget().getTargetTriple();
6963     if (Triple.getArch() != Triple::x86_64)
6964       return;
6965 
6966     SmallVector<SDValue, 8> Ops;
6967 
6968     // We want to say that we always want the arguments in registers.
6969     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6970     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6971     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6972     SDValue Chain = getRoot();
6973     Ops.push_back(LogEntryVal);
6974     Ops.push_back(StrSizeVal);
6975     Ops.push_back(Chain);
6976 
6977     // We need to enforce the calling convention for the callsite, so that
6978     // argument ordering is enforced correctly, and that register allocation can
6979     // see that some registers may be assumed clobbered and have to preserve
6980     // them across calls to the intrinsic.
6981     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6982                                            sdl, NodeTys, Ops);
6983     SDValue patchableNode = SDValue(MN, 0);
6984     DAG.setRoot(patchableNode);
6985     setValue(&I, patchableNode);
6986     return;
6987   }
6988   case Intrinsic::xray_typedevent: {
6989     // Here we want to make sure that the intrinsic behaves as if it has a
6990     // specific calling convention, and only for x86_64.
6991     // FIXME: Support other platforms later.
6992     const auto &Triple = DAG.getTarget().getTargetTriple();
6993     if (Triple.getArch() != Triple::x86_64)
6994       return;
6995 
6996     SmallVector<SDValue, 8> Ops;
6997 
6998     // We want to say that we always want the arguments in registers.
6999     // It's unclear to me how manipulating the selection DAG here forces callers
7000     // to provide arguments in registers instead of on the stack.
7001     SDValue LogTypeId = getValue(I.getArgOperand(0));
7002     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7003     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7004     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7005     SDValue Chain = getRoot();
7006     Ops.push_back(LogTypeId);
7007     Ops.push_back(LogEntryVal);
7008     Ops.push_back(StrSizeVal);
7009     Ops.push_back(Chain);
7010 
7011     // We need to enforce the calling convention for the callsite, so that
7012     // argument ordering is enforced correctly, and that register allocation can
7013     // see that some registers may be assumed clobbered and have to preserve
7014     // them across calls to the intrinsic.
7015     MachineSDNode *MN = DAG.getMachineNode(
7016         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7017     SDValue patchableNode = SDValue(MN, 0);
7018     DAG.setRoot(patchableNode);
7019     setValue(&I, patchableNode);
7020     return;
7021   }
7022   case Intrinsic::experimental_deoptimize:
7023     LowerDeoptimizeCall(&I);
7024     return;
7025   case Intrinsic::experimental_stepvector:
7026     visitStepVector(I);
7027     return;
7028   case Intrinsic::vector_reduce_fadd:
7029   case Intrinsic::vector_reduce_fmul:
7030   case Intrinsic::vector_reduce_add:
7031   case Intrinsic::vector_reduce_mul:
7032   case Intrinsic::vector_reduce_and:
7033   case Intrinsic::vector_reduce_or:
7034   case Intrinsic::vector_reduce_xor:
7035   case Intrinsic::vector_reduce_smax:
7036   case Intrinsic::vector_reduce_smin:
7037   case Intrinsic::vector_reduce_umax:
7038   case Intrinsic::vector_reduce_umin:
7039   case Intrinsic::vector_reduce_fmax:
7040   case Intrinsic::vector_reduce_fmin:
7041     visitVectorReduce(I, Intrinsic);
7042     return;
7043 
7044   case Intrinsic::icall_branch_funnel: {
7045     SmallVector<SDValue, 16> Ops;
7046     Ops.push_back(getValue(I.getArgOperand(0)));
7047 
7048     int64_t Offset;
7049     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7050         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7051     if (!Base)
7052       report_fatal_error(
7053           "llvm.icall.branch.funnel operand must be a GlobalValue");
7054     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7055 
7056     struct BranchFunnelTarget {
7057       int64_t Offset;
7058       SDValue Target;
7059     };
7060     SmallVector<BranchFunnelTarget, 8> Targets;
7061 
7062     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7063       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7064           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7065       if (ElemBase != Base)
7066         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7067                            "to the same GlobalValue");
7068 
7069       SDValue Val = getValue(I.getArgOperand(Op + 1));
7070       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7071       if (!GA)
7072         report_fatal_error(
7073             "llvm.icall.branch.funnel operand must be a GlobalValue");
7074       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7075                                      GA->getGlobal(), sdl, Val.getValueType(),
7076                                      GA->getOffset())});
7077     }
7078     llvm::sort(Targets,
7079                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7080                  return T1.Offset < T2.Offset;
7081                });
7082 
7083     for (auto &T : Targets) {
7084       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7085       Ops.push_back(T.Target);
7086     }
7087 
7088     Ops.push_back(DAG.getRoot()); // Chain
7089     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7090                                  MVT::Other, Ops),
7091               0);
7092     DAG.setRoot(N);
7093     setValue(&I, N);
7094     HasTailCall = true;
7095     return;
7096   }
7097 
7098   case Intrinsic::wasm_landingpad_index:
7099     // Information this intrinsic contained has been transferred to
7100     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7101     // delete it now.
7102     return;
7103 
7104   case Intrinsic::aarch64_settag:
7105   case Intrinsic::aarch64_settag_zero: {
7106     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7107     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7108     SDValue Val = TSI.EmitTargetCodeForSetTag(
7109         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7110         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7111         ZeroMemory);
7112     DAG.setRoot(Val);
7113     setValue(&I, Val);
7114     return;
7115   }
7116   case Intrinsic::ptrmask: {
7117     SDValue Ptr = getValue(I.getOperand(0));
7118     SDValue Const = getValue(I.getOperand(1));
7119 
7120     EVT PtrVT = Ptr.getValueType();
7121     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7122                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7123     return;
7124   }
7125   case Intrinsic::get_active_lane_mask: {
7126     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7127     SDValue Index = getValue(I.getOperand(0));
7128     EVT ElementVT = Index.getValueType();
7129 
7130     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7131       visitTargetIntrinsic(I, Intrinsic);
7132       return;
7133     }
7134 
7135     SDValue TripCount = getValue(I.getOperand(1));
7136     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7137 
7138     SDValue VectorIndex, VectorTripCount;
7139     if (VecTy.isScalableVector()) {
7140       VectorIndex = DAG.getSplatVector(VecTy, sdl, Index);
7141       VectorTripCount = DAG.getSplatVector(VecTy, sdl, TripCount);
7142     } else {
7143       VectorIndex = DAG.getSplatBuildVector(VecTy, sdl, Index);
7144       VectorTripCount = DAG.getSplatBuildVector(VecTy, sdl, TripCount);
7145     }
7146     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7147     SDValue VectorInduction = DAG.getNode(
7148         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7149     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7150                                  VectorTripCount, ISD::CondCode::SETULT);
7151     setValue(&I, SetCC);
7152     return;
7153   }
7154   case Intrinsic::experimental_vector_insert: {
7155     SDValue Vec = getValue(I.getOperand(0));
7156     SDValue SubVec = getValue(I.getOperand(1));
7157     SDValue Index = getValue(I.getOperand(2));
7158 
7159     // The intrinsic's index type is i64, but the SDNode requires an index type
7160     // suitable for the target. Convert the index as required.
7161     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7162     if (Index.getValueType() != VectorIdxTy)
7163       Index = DAG.getVectorIdxConstant(
7164           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7165 
7166     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7167     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7168                              Index));
7169     return;
7170   }
7171   case Intrinsic::experimental_vector_extract: {
7172     SDValue Vec = getValue(I.getOperand(0));
7173     SDValue Index = getValue(I.getOperand(1));
7174     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7175 
7176     // The intrinsic's index type is i64, but the SDNode requires an index type
7177     // suitable for the target. Convert the index as required.
7178     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7179     if (Index.getValueType() != VectorIdxTy)
7180       Index = DAG.getVectorIdxConstant(
7181           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7182 
7183     setValue(&I,
7184              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7185     return;
7186   }
7187   case Intrinsic::experimental_vector_reverse:
7188     visitVectorReverse(I);
7189     return;
7190   case Intrinsic::experimental_vector_splice:
7191     visitVectorSplice(I);
7192     return;
7193   }
7194 }
7195 
7196 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7197     const ConstrainedFPIntrinsic &FPI) {
7198   SDLoc sdl = getCurSDLoc();
7199 
7200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7201   SmallVector<EVT, 4> ValueVTs;
7202   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7203   ValueVTs.push_back(MVT::Other); // Out chain
7204 
7205   // We do not need to serialize constrained FP intrinsics against
7206   // each other or against (nonvolatile) loads, so they can be
7207   // chained like loads.
7208   SDValue Chain = DAG.getRoot();
7209   SmallVector<SDValue, 4> Opers;
7210   Opers.push_back(Chain);
7211   if (FPI.isUnaryOp()) {
7212     Opers.push_back(getValue(FPI.getArgOperand(0)));
7213   } else if (FPI.isTernaryOp()) {
7214     Opers.push_back(getValue(FPI.getArgOperand(0)));
7215     Opers.push_back(getValue(FPI.getArgOperand(1)));
7216     Opers.push_back(getValue(FPI.getArgOperand(2)));
7217   } else {
7218     Opers.push_back(getValue(FPI.getArgOperand(0)));
7219     Opers.push_back(getValue(FPI.getArgOperand(1)));
7220   }
7221 
7222   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7223     assert(Result.getNode()->getNumValues() == 2);
7224 
7225     // Push node to the appropriate list so that future instructions can be
7226     // chained up correctly.
7227     SDValue OutChain = Result.getValue(1);
7228     switch (EB) {
7229     case fp::ExceptionBehavior::ebIgnore:
7230       // The only reason why ebIgnore nodes still need to be chained is that
7231       // they might depend on the current rounding mode, and therefore must
7232       // not be moved across instruction that may change that mode.
7233       LLVM_FALLTHROUGH;
7234     case fp::ExceptionBehavior::ebMayTrap:
7235       // These must not be moved across calls or instructions that may change
7236       // floating-point exception masks.
7237       PendingConstrainedFP.push_back(OutChain);
7238       break;
7239     case fp::ExceptionBehavior::ebStrict:
7240       // These must not be moved across calls or instructions that may change
7241       // floating-point exception masks or read floating-point exception flags.
7242       // In addition, they cannot be optimized out even if unused.
7243       PendingConstrainedFPStrict.push_back(OutChain);
7244       break;
7245     }
7246   };
7247 
7248   SDVTList VTs = DAG.getVTList(ValueVTs);
7249   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7250 
7251   SDNodeFlags Flags;
7252   if (EB == fp::ExceptionBehavior::ebIgnore)
7253     Flags.setNoFPExcept(true);
7254 
7255   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7256     Flags.copyFMF(*FPOp);
7257 
7258   unsigned Opcode;
7259   switch (FPI.getIntrinsicID()) {
7260   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7261 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7262   case Intrinsic::INTRINSIC:                                                   \
7263     Opcode = ISD::STRICT_##DAGN;                                               \
7264     break;
7265 #include "llvm/IR/ConstrainedOps.def"
7266   case Intrinsic::experimental_constrained_fmuladd: {
7267     Opcode = ISD::STRICT_FMA;
7268     // Break fmuladd into fmul and fadd.
7269     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7270         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7271                                         ValueVTs[0])) {
7272       Opers.pop_back();
7273       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7274       pushOutChain(Mul, EB);
7275       Opcode = ISD::STRICT_FADD;
7276       Opers.clear();
7277       Opers.push_back(Mul.getValue(1));
7278       Opers.push_back(Mul.getValue(0));
7279       Opers.push_back(getValue(FPI.getArgOperand(2)));
7280     }
7281     break;
7282   }
7283   }
7284 
7285   // A few strict DAG nodes carry additional operands that are not
7286   // set up by the default code above.
7287   switch (Opcode) {
7288   default: break;
7289   case ISD::STRICT_FP_ROUND:
7290     Opers.push_back(
7291         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7292     break;
7293   case ISD::STRICT_FSETCC:
7294   case ISD::STRICT_FSETCCS: {
7295     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7296     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7297     if (TM.Options.NoNaNsFPMath)
7298       Condition = getFCmpCodeWithoutNaN(Condition);
7299     Opers.push_back(DAG.getCondCode(Condition));
7300     break;
7301   }
7302   }
7303 
7304   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7305   pushOutChain(Result, EB);
7306 
7307   SDValue FPResult = Result.getValue(0);
7308   setValue(&FPI, FPResult);
7309 }
7310 
7311 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7312   Optional<unsigned> ResOPC;
7313   switch (VPIntrin.getIntrinsicID()) {
7314 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7315 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) ResOPC = ISD::VPSD;
7316 #define END_REGISTER_VP_INTRINSIC(VPID) break;
7317 #include "llvm/IR/VPIntrinsics.def"
7318   }
7319 
7320   if (!ResOPC.hasValue())
7321     llvm_unreachable(
7322         "Inconsistency: no SDNode available for this VPIntrinsic!");
7323 
7324   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7325       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7326     if (VPIntrin.getFastMathFlags().allowReassoc())
7327       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7328                                                 : ISD::VP_REDUCE_FMUL;
7329   }
7330 
7331   return ResOPC.getValue();
7332 }
7333 
7334 void SelectionDAGBuilder::visitVPLoadGather(const VPIntrinsic &VPIntrin, EVT VT,
7335                                             SmallVector<SDValue, 7> &OpValues,
7336                                             bool IsGather) {
7337   SDLoc DL = getCurSDLoc();
7338   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7339   Value *PtrOperand = VPIntrin.getArgOperand(0);
7340   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7341   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7342   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7343   SDValue LD;
7344   bool AddToChain = true;
7345   if (!IsGather) {
7346     // Do not serialize variable-length loads of constant memory with
7347     // anything.
7348     if (!Alignment)
7349       Alignment = DAG.getEVTAlign(VT);
7350     MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7351     AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7352     SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7353     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7354         MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7355         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7356     LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7357                        MMO, false /*IsExpanding */);
7358   } else {
7359     if (!Alignment)
7360       Alignment = DAG.getEVTAlign(VT.getScalarType());
7361     unsigned AS =
7362         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7363     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7364         MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7365         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7366     SDValue Base, Index, Scale;
7367     ISD::MemIndexType IndexType;
7368     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7369                                       this, VPIntrin.getParent());
7370     if (!UniformBase) {
7371       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7372       Index = getValue(PtrOperand);
7373       IndexType = ISD::SIGNED_UNSCALED;
7374       Scale =
7375           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7376     }
7377     EVT IdxVT = Index.getValueType();
7378     EVT EltTy = IdxVT.getVectorElementType();
7379     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7380       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7381       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7382     }
7383     LD = DAG.getGatherVP(
7384         DAG.getVTList(VT, MVT::Other), VT, DL,
7385         {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7386         IndexType);
7387   }
7388   if (AddToChain)
7389     PendingLoads.push_back(LD.getValue(1));
7390   setValue(&VPIntrin, LD);
7391 }
7392 
7393 void SelectionDAGBuilder::visitVPStoreScatter(const VPIntrinsic &VPIntrin,
7394                                               SmallVector<SDValue, 7> &OpValues,
7395                                               bool IsScatter) {
7396   SDLoc DL = getCurSDLoc();
7397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7398   Value *PtrOperand = VPIntrin.getArgOperand(1);
7399   EVT VT = OpValues[0].getValueType();
7400   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7401   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7402   SDValue ST;
7403   if (!IsScatter) {
7404     if (!Alignment)
7405       Alignment = DAG.getEVTAlign(VT);
7406     SDValue Ptr = OpValues[1];
7407     SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7408     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7409         MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7410         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7411     ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7412                         OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7413                         /* IsTruncating */ false, /*IsCompressing*/ false);
7414   } else {
7415     if (!Alignment)
7416       Alignment = DAG.getEVTAlign(VT.getScalarType());
7417     unsigned AS =
7418         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7419     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7420         MachinePointerInfo(AS), MachineMemOperand::MOStore,
7421         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7422     SDValue Base, Index, Scale;
7423     ISD::MemIndexType IndexType;
7424     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7425                                       this, VPIntrin.getParent());
7426     if (!UniformBase) {
7427       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7428       Index = getValue(PtrOperand);
7429       IndexType = ISD::SIGNED_UNSCALED;
7430       Scale =
7431           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7432     }
7433     EVT IdxVT = Index.getValueType();
7434     EVT EltTy = IdxVT.getVectorElementType();
7435     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7436       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7437       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7438     }
7439     ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7440                           {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7441                            OpValues[2], OpValues[3]},
7442                           MMO, IndexType);
7443   }
7444   DAG.setRoot(ST);
7445   setValue(&VPIntrin, ST);
7446 }
7447 
7448 void SelectionDAGBuilder::visitVPStridedLoad(
7449     const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) {
7450   SDLoc DL = getCurSDLoc();
7451   Value *PtrOperand = VPIntrin.getArgOperand(0);
7452   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7453   if (!Alignment)
7454     Alignment = DAG.getEVTAlign(VT.getScalarType());
7455   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7456   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7457   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7458   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7459   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7460   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7461       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7462       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7463 
7464   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7465                                     OpValues[2], OpValues[3], MMO,
7466                                     false /*IsExpanding*/);
7467 
7468   if (AddToChain)
7469     PendingLoads.push_back(LD.getValue(1));
7470   setValue(&VPIntrin, LD);
7471 }
7472 
7473 void SelectionDAGBuilder::visitVPStridedStore(
7474     const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) {
7475   SDLoc DL = getCurSDLoc();
7476   Value *PtrOperand = VPIntrin.getArgOperand(1);
7477   EVT VT = OpValues[0].getValueType();
7478   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7479   if (!Alignment)
7480     Alignment = DAG.getEVTAlign(VT.getScalarType());
7481   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7482   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7483       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7484       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7485 
7486   SDValue ST = DAG.getStridedStoreVP(
7487       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7488       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7489       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7490       /*IsCompressing*/ false);
7491 
7492   DAG.setRoot(ST);
7493   setValue(&VPIntrin, ST);
7494 }
7495 
7496 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7497     const VPIntrinsic &VPIntrin) {
7498   SDLoc DL = getCurSDLoc();
7499   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7500 
7501   SmallVector<EVT, 4> ValueVTs;
7502   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7503   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7504   SDVTList VTs = DAG.getVTList(ValueVTs);
7505 
7506   auto EVLParamPos =
7507       VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID());
7508 
7509   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7510   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7511          "Unexpected target EVL type");
7512 
7513   // Request operands.
7514   SmallVector<SDValue, 7> OpValues;
7515   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7516     auto Op = getValue(VPIntrin.getArgOperand(I));
7517     if (I == EVLParamPos)
7518       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7519     OpValues.push_back(Op);
7520   }
7521 
7522   switch (Opcode) {
7523   default: {
7524     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7525     setValue(&VPIntrin, Result);
7526     break;
7527   }
7528   case ISD::VP_LOAD:
7529   case ISD::VP_GATHER:
7530     visitVPLoadGather(VPIntrin, ValueVTs[0], OpValues,
7531                       Opcode == ISD::VP_GATHER);
7532     break;
7533   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7534     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7535     break;
7536   case ISD::VP_STORE:
7537   case ISD::VP_SCATTER:
7538     visitVPStoreScatter(VPIntrin, OpValues, Opcode == ISD::VP_SCATTER);
7539     break;
7540   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7541     visitVPStridedStore(VPIntrin, OpValues);
7542     break;
7543   }
7544 }
7545 
7546 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7547                                           const BasicBlock *EHPadBB,
7548                                           MCSymbol *&BeginLabel) {
7549   MachineFunction &MF = DAG.getMachineFunction();
7550   MachineModuleInfo &MMI = MF.getMMI();
7551 
7552   // Insert a label before the invoke call to mark the try range.  This can be
7553   // used to detect deletion of the invoke via the MachineModuleInfo.
7554   BeginLabel = MMI.getContext().createTempSymbol();
7555 
7556   // For SjLj, keep track of which landing pads go with which invokes
7557   // so as to maintain the ordering of pads in the LSDA.
7558   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7559   if (CallSiteIndex) {
7560     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7561     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7562 
7563     // Now that the call site is handled, stop tracking it.
7564     MMI.setCurrentCallSite(0);
7565   }
7566 
7567   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7568 }
7569 
7570 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7571                                         const BasicBlock *EHPadBB,
7572                                         MCSymbol *BeginLabel) {
7573   assert(BeginLabel && "BeginLabel should've been set");
7574 
7575   MachineFunction &MF = DAG.getMachineFunction();
7576   MachineModuleInfo &MMI = MF.getMMI();
7577 
7578   // Insert a label at the end of the invoke call to mark the try range.  This
7579   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7580   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7581   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7582 
7583   // Inform MachineModuleInfo of range.
7584   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7585   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7586   // actually use outlined funclets and their LSDA info style.
7587   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7588     assert(II && "II should've been set");
7589     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7590     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7591   } else if (!isScopedEHPersonality(Pers)) {
7592     assert(EHPadBB);
7593     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7594   }
7595 
7596   return Chain;
7597 }
7598 
7599 std::pair<SDValue, SDValue>
7600 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7601                                     const BasicBlock *EHPadBB) {
7602   MCSymbol *BeginLabel = nullptr;
7603 
7604   if (EHPadBB) {
7605     // Both PendingLoads and PendingExports must be flushed here;
7606     // this call might not return.
7607     (void)getRoot();
7608     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7609     CLI.setChain(getRoot());
7610   }
7611 
7612   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7613   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7614 
7615   assert((CLI.IsTailCall || Result.second.getNode()) &&
7616          "Non-null chain expected with non-tail call!");
7617   assert((Result.second.getNode() || !Result.first.getNode()) &&
7618          "Null value expected with tail call!");
7619 
7620   if (!Result.second.getNode()) {
7621     // As a special case, a null chain means that a tail call has been emitted
7622     // and the DAG root is already updated.
7623     HasTailCall = true;
7624 
7625     // Since there's no actual continuation from this block, nothing can be
7626     // relying on us setting vregs for them.
7627     PendingExports.clear();
7628   } else {
7629     DAG.setRoot(Result.second);
7630   }
7631 
7632   if (EHPadBB) {
7633     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7634                            BeginLabel));
7635   }
7636 
7637   return Result;
7638 }
7639 
7640 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7641                                       bool isTailCall,
7642                                       bool isMustTailCall,
7643                                       const BasicBlock *EHPadBB) {
7644   auto &DL = DAG.getDataLayout();
7645   FunctionType *FTy = CB.getFunctionType();
7646   Type *RetTy = CB.getType();
7647 
7648   TargetLowering::ArgListTy Args;
7649   Args.reserve(CB.arg_size());
7650 
7651   const Value *SwiftErrorVal = nullptr;
7652   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7653 
7654   if (isTailCall) {
7655     // Avoid emitting tail calls in functions with the disable-tail-calls
7656     // attribute.
7657     auto *Caller = CB.getParent()->getParent();
7658     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7659         "true" && !isMustTailCall)
7660       isTailCall = false;
7661 
7662     // We can't tail call inside a function with a swifterror argument. Lowering
7663     // does not support this yet. It would have to move into the swifterror
7664     // register before the call.
7665     if (TLI.supportSwiftError() &&
7666         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7667       isTailCall = false;
7668   }
7669 
7670   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7671     TargetLowering::ArgListEntry Entry;
7672     const Value *V = *I;
7673 
7674     // Skip empty types
7675     if (V->getType()->isEmptyTy())
7676       continue;
7677 
7678     SDValue ArgNode = getValue(V);
7679     Entry.Node = ArgNode; Entry.Ty = V->getType();
7680 
7681     Entry.setAttributes(&CB, I - CB.arg_begin());
7682 
7683     // Use swifterror virtual register as input to the call.
7684     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7685       SwiftErrorVal = V;
7686       // We find the virtual register for the actual swifterror argument.
7687       // Instead of using the Value, we use the virtual register instead.
7688       Entry.Node =
7689           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7690                           EVT(TLI.getPointerTy(DL)));
7691     }
7692 
7693     Args.push_back(Entry);
7694 
7695     // If we have an explicit sret argument that is an Instruction, (i.e., it
7696     // might point to function-local memory), we can't meaningfully tail-call.
7697     if (Entry.IsSRet && isa<Instruction>(V))
7698       isTailCall = false;
7699   }
7700 
7701   // If call site has a cfguardtarget operand bundle, create and add an
7702   // additional ArgListEntry.
7703   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7704     TargetLowering::ArgListEntry Entry;
7705     Value *V = Bundle->Inputs[0];
7706     SDValue ArgNode = getValue(V);
7707     Entry.Node = ArgNode;
7708     Entry.Ty = V->getType();
7709     Entry.IsCFGuardTarget = true;
7710     Args.push_back(Entry);
7711   }
7712 
7713   // Check if target-independent constraints permit a tail call here.
7714   // Target-dependent constraints are checked within TLI->LowerCallTo.
7715   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7716     isTailCall = false;
7717 
7718   // Disable tail calls if there is an swifterror argument. Targets have not
7719   // been updated to support tail calls.
7720   if (TLI.supportSwiftError() && SwiftErrorVal)
7721     isTailCall = false;
7722 
7723   TargetLowering::CallLoweringInfo CLI(DAG);
7724   CLI.setDebugLoc(getCurSDLoc())
7725       .setChain(getRoot())
7726       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7727       .setTailCall(isTailCall)
7728       .setConvergent(CB.isConvergent())
7729       .setIsPreallocated(
7730           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7731   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7732 
7733   if (Result.first.getNode()) {
7734     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7735     setValue(&CB, Result.first);
7736   }
7737 
7738   // The last element of CLI.InVals has the SDValue for swifterror return.
7739   // Here we copy it to a virtual register and update SwiftErrorMap for
7740   // book-keeping.
7741   if (SwiftErrorVal && TLI.supportSwiftError()) {
7742     // Get the last element of InVals.
7743     SDValue Src = CLI.InVals.back();
7744     Register VReg =
7745         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7746     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7747     DAG.setRoot(CopyNode);
7748   }
7749 }
7750 
7751 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7752                              SelectionDAGBuilder &Builder) {
7753   // Check to see if this load can be trivially constant folded, e.g. if the
7754   // input is from a string literal.
7755   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7756     // Cast pointer to the type we really want to load.
7757     Type *LoadTy =
7758         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7759     if (LoadVT.isVector())
7760       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7761 
7762     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7763                                          PointerType::getUnqual(LoadTy));
7764 
7765     if (const Constant *LoadCst =
7766             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
7767                                          LoadTy, Builder.DAG.getDataLayout()))
7768       return Builder.getValue(LoadCst);
7769   }
7770 
7771   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7772   // still constant memory, the input chain can be the entry node.
7773   SDValue Root;
7774   bool ConstantMemory = false;
7775 
7776   // Do not serialize (non-volatile) loads of constant memory with anything.
7777   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7778     Root = Builder.DAG.getEntryNode();
7779     ConstantMemory = true;
7780   } else {
7781     // Do not serialize non-volatile loads against each other.
7782     Root = Builder.DAG.getRoot();
7783   }
7784 
7785   SDValue Ptr = Builder.getValue(PtrVal);
7786   SDValue LoadVal =
7787       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7788                           MachinePointerInfo(PtrVal), Align(1));
7789 
7790   if (!ConstantMemory)
7791     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7792   return LoadVal;
7793 }
7794 
7795 /// Record the value for an instruction that produces an integer result,
7796 /// converting the type where necessary.
7797 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7798                                                   SDValue Value,
7799                                                   bool IsSigned) {
7800   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7801                                                     I.getType(), true);
7802   if (IsSigned)
7803     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7804   else
7805     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7806   setValue(&I, Value);
7807 }
7808 
7809 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7810 /// true and lower it. Otherwise return false, and it will be lowered like a
7811 /// normal call.
7812 /// The caller already checked that \p I calls the appropriate LibFunc with a
7813 /// correct prototype.
7814 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7815   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7816   const Value *Size = I.getArgOperand(2);
7817   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7818   if (CSize && CSize->getZExtValue() == 0) {
7819     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7820                                                           I.getType(), true);
7821     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7822     return true;
7823   }
7824 
7825   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7826   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7827       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7828       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7829   if (Res.first.getNode()) {
7830     processIntegerCallValue(I, Res.first, true);
7831     PendingLoads.push_back(Res.second);
7832     return true;
7833   }
7834 
7835   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7836   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7837   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7838     return false;
7839 
7840   // If the target has a fast compare for the given size, it will return a
7841   // preferred load type for that size. Require that the load VT is legal and
7842   // that the target supports unaligned loads of that type. Otherwise, return
7843   // INVALID.
7844   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7845     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7846     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7847     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7848       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7849       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7850       // TODO: Check alignment of src and dest ptrs.
7851       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7852       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7853       if (!TLI.isTypeLegal(LVT) ||
7854           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7855           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7856         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7857     }
7858 
7859     return LVT;
7860   };
7861 
7862   // This turns into unaligned loads. We only do this if the target natively
7863   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7864   // we'll only produce a small number of byte loads.
7865   MVT LoadVT;
7866   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7867   switch (NumBitsToCompare) {
7868   default:
7869     return false;
7870   case 16:
7871     LoadVT = MVT::i16;
7872     break;
7873   case 32:
7874     LoadVT = MVT::i32;
7875     break;
7876   case 64:
7877   case 128:
7878   case 256:
7879     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7880     break;
7881   }
7882 
7883   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7884     return false;
7885 
7886   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7887   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7888 
7889   // Bitcast to a wide integer type if the loads are vectors.
7890   if (LoadVT.isVector()) {
7891     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7892     LoadL = DAG.getBitcast(CmpVT, LoadL);
7893     LoadR = DAG.getBitcast(CmpVT, LoadR);
7894   }
7895 
7896   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7897   processIntegerCallValue(I, Cmp, false);
7898   return true;
7899 }
7900 
7901 /// See if we can lower a memchr call into an optimized form. If so, return
7902 /// true and lower it. Otherwise return false, and it will be lowered like a
7903 /// normal call.
7904 /// The caller already checked that \p I calls the appropriate LibFunc with a
7905 /// correct prototype.
7906 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7907   const Value *Src = I.getArgOperand(0);
7908   const Value *Char = I.getArgOperand(1);
7909   const Value *Length = I.getArgOperand(2);
7910 
7911   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7912   std::pair<SDValue, SDValue> Res =
7913     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7914                                 getValue(Src), getValue(Char), getValue(Length),
7915                                 MachinePointerInfo(Src));
7916   if (Res.first.getNode()) {
7917     setValue(&I, Res.first);
7918     PendingLoads.push_back(Res.second);
7919     return true;
7920   }
7921 
7922   return false;
7923 }
7924 
7925 /// See if we can lower a mempcpy call into an optimized form. If so, return
7926 /// true and lower it. Otherwise return false, and it will be lowered like a
7927 /// normal call.
7928 /// The caller already checked that \p I calls the appropriate LibFunc with a
7929 /// correct prototype.
7930 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7931   SDValue Dst = getValue(I.getArgOperand(0));
7932   SDValue Src = getValue(I.getArgOperand(1));
7933   SDValue Size = getValue(I.getArgOperand(2));
7934 
7935   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7936   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7937   // DAG::getMemcpy needs Alignment to be defined.
7938   Align Alignment = std::min(DstAlign, SrcAlign);
7939 
7940   bool isVol = false;
7941   SDLoc sdl = getCurSDLoc();
7942 
7943   // In the mempcpy context we need to pass in a false value for isTailCall
7944   // because the return pointer needs to be adjusted by the size of
7945   // the copied memory.
7946   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7947   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7948                              /*isTailCall=*/false,
7949                              MachinePointerInfo(I.getArgOperand(0)),
7950                              MachinePointerInfo(I.getArgOperand(1)),
7951                              I.getAAMetadata());
7952   assert(MC.getNode() != nullptr &&
7953          "** memcpy should not be lowered as TailCall in mempcpy context **");
7954   DAG.setRoot(MC);
7955 
7956   // Check if Size needs to be truncated or extended.
7957   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7958 
7959   // Adjust return pointer to point just past the last dst byte.
7960   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7961                                     Dst, Size);
7962   setValue(&I, DstPlusSize);
7963   return true;
7964 }
7965 
7966 /// See if we can lower a strcpy call into an optimized form.  If so, return
7967 /// true and lower it, otherwise return false and it will be lowered like a
7968 /// normal call.
7969 /// The caller already checked that \p I calls the appropriate LibFunc with a
7970 /// correct prototype.
7971 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7972   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7973 
7974   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7975   std::pair<SDValue, SDValue> Res =
7976     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7977                                 getValue(Arg0), getValue(Arg1),
7978                                 MachinePointerInfo(Arg0),
7979                                 MachinePointerInfo(Arg1), isStpcpy);
7980   if (Res.first.getNode()) {
7981     setValue(&I, Res.first);
7982     DAG.setRoot(Res.second);
7983     return true;
7984   }
7985 
7986   return false;
7987 }
7988 
7989 /// See if we can lower a strcmp call into an optimized form.  If so, return
7990 /// true and lower it, otherwise return false and it will be lowered like a
7991 /// normal call.
7992 /// The caller already checked that \p I calls the appropriate LibFunc with a
7993 /// correct prototype.
7994 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7995   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7996 
7997   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7998   std::pair<SDValue, SDValue> Res =
7999     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8000                                 getValue(Arg0), getValue(Arg1),
8001                                 MachinePointerInfo(Arg0),
8002                                 MachinePointerInfo(Arg1));
8003   if (Res.first.getNode()) {
8004     processIntegerCallValue(I, Res.first, true);
8005     PendingLoads.push_back(Res.second);
8006     return true;
8007   }
8008 
8009   return false;
8010 }
8011 
8012 /// See if we can lower a strlen call into an optimized form.  If so, return
8013 /// true and lower it, otherwise return false and it will be lowered like a
8014 /// normal call.
8015 /// The caller already checked that \p I calls the appropriate LibFunc with a
8016 /// correct prototype.
8017 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8018   const Value *Arg0 = I.getArgOperand(0);
8019 
8020   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8021   std::pair<SDValue, SDValue> Res =
8022     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8023                                 getValue(Arg0), MachinePointerInfo(Arg0));
8024   if (Res.first.getNode()) {
8025     processIntegerCallValue(I, Res.first, false);
8026     PendingLoads.push_back(Res.second);
8027     return true;
8028   }
8029 
8030   return false;
8031 }
8032 
8033 /// See if we can lower a strnlen call into an optimized form.  If so, return
8034 /// true and lower it, otherwise return false and it will be lowered like a
8035 /// normal call.
8036 /// The caller already checked that \p I calls the appropriate LibFunc with a
8037 /// correct prototype.
8038 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8039   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8040 
8041   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8042   std::pair<SDValue, SDValue> Res =
8043     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8044                                  getValue(Arg0), getValue(Arg1),
8045                                  MachinePointerInfo(Arg0));
8046   if (Res.first.getNode()) {
8047     processIntegerCallValue(I, Res.first, false);
8048     PendingLoads.push_back(Res.second);
8049     return true;
8050   }
8051 
8052   return false;
8053 }
8054 
8055 /// See if we can lower a unary floating-point operation into an SDNode with
8056 /// the specified Opcode.  If so, return true and lower it, otherwise return
8057 /// false and it will be lowered like a normal call.
8058 /// The caller already checked that \p I calls the appropriate LibFunc with a
8059 /// correct prototype.
8060 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8061                                               unsigned Opcode) {
8062   // We already checked this call's prototype; verify it doesn't modify errno.
8063   if (!I.onlyReadsMemory())
8064     return false;
8065 
8066   SDNodeFlags Flags;
8067   Flags.copyFMF(cast<FPMathOperator>(I));
8068 
8069   SDValue Tmp = getValue(I.getArgOperand(0));
8070   setValue(&I,
8071            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8072   return true;
8073 }
8074 
8075 /// See if we can lower a binary floating-point operation into an SDNode with
8076 /// the specified Opcode. If so, return true and lower it. Otherwise return
8077 /// false, and it will be lowered like a normal call.
8078 /// The caller already checked that \p I calls the appropriate LibFunc with a
8079 /// correct prototype.
8080 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8081                                                unsigned Opcode) {
8082   // We already checked this call's prototype; verify it doesn't modify errno.
8083   if (!I.onlyReadsMemory())
8084     return false;
8085 
8086   SDNodeFlags Flags;
8087   Flags.copyFMF(cast<FPMathOperator>(I));
8088 
8089   SDValue Tmp0 = getValue(I.getArgOperand(0));
8090   SDValue Tmp1 = getValue(I.getArgOperand(1));
8091   EVT VT = Tmp0.getValueType();
8092   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8093   return true;
8094 }
8095 
8096 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8097   // Handle inline assembly differently.
8098   if (I.isInlineAsm()) {
8099     visitInlineAsm(I);
8100     return;
8101   }
8102 
8103   if (Function *F = I.getCalledFunction()) {
8104     diagnoseDontCall(I);
8105 
8106     if (F->isDeclaration()) {
8107       // Is this an LLVM intrinsic or a target-specific intrinsic?
8108       unsigned IID = F->getIntrinsicID();
8109       if (!IID)
8110         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8111           IID = II->getIntrinsicID(F);
8112 
8113       if (IID) {
8114         visitIntrinsicCall(I, IID);
8115         return;
8116       }
8117     }
8118 
8119     // Check for well-known libc/libm calls.  If the function is internal, it
8120     // can't be a library call.  Don't do the check if marked as nobuiltin for
8121     // some reason or the call site requires strict floating point semantics.
8122     LibFunc Func;
8123     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8124         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8125         LibInfo->hasOptimizedCodeGen(Func)) {
8126       switch (Func) {
8127       default: break;
8128       case LibFunc_bcmp:
8129         if (visitMemCmpBCmpCall(I))
8130           return;
8131         break;
8132       case LibFunc_copysign:
8133       case LibFunc_copysignf:
8134       case LibFunc_copysignl:
8135         // We already checked this call's prototype; verify it doesn't modify
8136         // errno.
8137         if (I.onlyReadsMemory()) {
8138           SDValue LHS = getValue(I.getArgOperand(0));
8139           SDValue RHS = getValue(I.getArgOperand(1));
8140           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8141                                    LHS.getValueType(), LHS, RHS));
8142           return;
8143         }
8144         break;
8145       case LibFunc_fabs:
8146       case LibFunc_fabsf:
8147       case LibFunc_fabsl:
8148         if (visitUnaryFloatCall(I, ISD::FABS))
8149           return;
8150         break;
8151       case LibFunc_fmin:
8152       case LibFunc_fminf:
8153       case LibFunc_fminl:
8154         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8155           return;
8156         break;
8157       case LibFunc_fmax:
8158       case LibFunc_fmaxf:
8159       case LibFunc_fmaxl:
8160         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8161           return;
8162         break;
8163       case LibFunc_sin:
8164       case LibFunc_sinf:
8165       case LibFunc_sinl:
8166         if (visitUnaryFloatCall(I, ISD::FSIN))
8167           return;
8168         break;
8169       case LibFunc_cos:
8170       case LibFunc_cosf:
8171       case LibFunc_cosl:
8172         if (visitUnaryFloatCall(I, ISD::FCOS))
8173           return;
8174         break;
8175       case LibFunc_sqrt:
8176       case LibFunc_sqrtf:
8177       case LibFunc_sqrtl:
8178       case LibFunc_sqrt_finite:
8179       case LibFunc_sqrtf_finite:
8180       case LibFunc_sqrtl_finite:
8181         if (visitUnaryFloatCall(I, ISD::FSQRT))
8182           return;
8183         break;
8184       case LibFunc_floor:
8185       case LibFunc_floorf:
8186       case LibFunc_floorl:
8187         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8188           return;
8189         break;
8190       case LibFunc_nearbyint:
8191       case LibFunc_nearbyintf:
8192       case LibFunc_nearbyintl:
8193         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8194           return;
8195         break;
8196       case LibFunc_ceil:
8197       case LibFunc_ceilf:
8198       case LibFunc_ceill:
8199         if (visitUnaryFloatCall(I, ISD::FCEIL))
8200           return;
8201         break;
8202       case LibFunc_rint:
8203       case LibFunc_rintf:
8204       case LibFunc_rintl:
8205         if (visitUnaryFloatCall(I, ISD::FRINT))
8206           return;
8207         break;
8208       case LibFunc_round:
8209       case LibFunc_roundf:
8210       case LibFunc_roundl:
8211         if (visitUnaryFloatCall(I, ISD::FROUND))
8212           return;
8213         break;
8214       case LibFunc_trunc:
8215       case LibFunc_truncf:
8216       case LibFunc_truncl:
8217         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8218           return;
8219         break;
8220       case LibFunc_log2:
8221       case LibFunc_log2f:
8222       case LibFunc_log2l:
8223         if (visitUnaryFloatCall(I, ISD::FLOG2))
8224           return;
8225         break;
8226       case LibFunc_exp2:
8227       case LibFunc_exp2f:
8228       case LibFunc_exp2l:
8229         if (visitUnaryFloatCall(I, ISD::FEXP2))
8230           return;
8231         break;
8232       case LibFunc_memcmp:
8233         if (visitMemCmpBCmpCall(I))
8234           return;
8235         break;
8236       case LibFunc_mempcpy:
8237         if (visitMemPCpyCall(I))
8238           return;
8239         break;
8240       case LibFunc_memchr:
8241         if (visitMemChrCall(I))
8242           return;
8243         break;
8244       case LibFunc_strcpy:
8245         if (visitStrCpyCall(I, false))
8246           return;
8247         break;
8248       case LibFunc_stpcpy:
8249         if (visitStrCpyCall(I, true))
8250           return;
8251         break;
8252       case LibFunc_strcmp:
8253         if (visitStrCmpCall(I))
8254           return;
8255         break;
8256       case LibFunc_strlen:
8257         if (visitStrLenCall(I))
8258           return;
8259         break;
8260       case LibFunc_strnlen:
8261         if (visitStrNLenCall(I))
8262           return;
8263         break;
8264       }
8265     }
8266   }
8267 
8268   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8269   // have to do anything here to lower funclet bundles.
8270   // CFGuardTarget bundles are lowered in LowerCallTo.
8271   assert(!I.hasOperandBundlesOtherThan(
8272              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8273               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8274               LLVMContext::OB_clang_arc_attachedcall}) &&
8275          "Cannot lower calls with arbitrary operand bundles!");
8276 
8277   SDValue Callee = getValue(I.getCalledOperand());
8278 
8279   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8280     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8281   else
8282     // Check if we can potentially perform a tail call. More detailed checking
8283     // is be done within LowerCallTo, after more information about the call is
8284     // known.
8285     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8286 }
8287 
8288 namespace {
8289 
8290 /// AsmOperandInfo - This contains information for each constraint that we are
8291 /// lowering.
8292 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8293 public:
8294   /// CallOperand - If this is the result output operand or a clobber
8295   /// this is null, otherwise it is the incoming operand to the CallInst.
8296   /// This gets modified as the asm is processed.
8297   SDValue CallOperand;
8298 
8299   /// AssignedRegs - If this is a register or register class operand, this
8300   /// contains the set of register corresponding to the operand.
8301   RegsForValue AssignedRegs;
8302 
8303   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8304     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8305   }
8306 
8307   /// Whether or not this operand accesses memory
8308   bool hasMemory(const TargetLowering &TLI) const {
8309     // Indirect operand accesses access memory.
8310     if (isIndirect)
8311       return true;
8312 
8313     for (const auto &Code : Codes)
8314       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8315         return true;
8316 
8317     return false;
8318   }
8319 
8320   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
8321   /// corresponds to.  If there is no Value* for this operand, it returns
8322   /// MVT::Other.
8323   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
8324                            const DataLayout &DL,
8325                            llvm::Type *ParamElemType) const {
8326     if (!CallOperandVal) return MVT::Other;
8327 
8328     if (isa<BasicBlock>(CallOperandVal))
8329       return TLI.getProgramPointerTy(DL);
8330 
8331     llvm::Type *OpTy = CallOperandVal->getType();
8332 
8333     // FIXME: code duplicated from TargetLowering::ParseConstraints().
8334     // If this is an indirect operand, the operand is a pointer to the
8335     // accessed type.
8336     if (isIndirect) {
8337       OpTy = ParamElemType;
8338       assert(OpTy && "Indirect operand must have elementtype attribute");
8339     }
8340 
8341     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
8342     if (StructType *STy = dyn_cast<StructType>(OpTy))
8343       if (STy->getNumElements() == 1)
8344         OpTy = STy->getElementType(0);
8345 
8346     // If OpTy is not a single value, it may be a struct/union that we
8347     // can tile with integers.
8348     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
8349       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
8350       switch (BitSize) {
8351       default: break;
8352       case 1:
8353       case 8:
8354       case 16:
8355       case 32:
8356       case 64:
8357       case 128:
8358         OpTy = IntegerType::get(Context, BitSize);
8359         break;
8360       }
8361     }
8362 
8363     return TLI.getAsmOperandValueType(DL, OpTy, true);
8364   }
8365 };
8366 
8367 
8368 } // end anonymous namespace
8369 
8370 /// Make sure that the output operand \p OpInfo and its corresponding input
8371 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8372 /// out).
8373 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8374                                SDISelAsmOperandInfo &MatchingOpInfo,
8375                                SelectionDAG &DAG) {
8376   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8377     return;
8378 
8379   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8380   const auto &TLI = DAG.getTargetLoweringInfo();
8381 
8382   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8383       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8384                                        OpInfo.ConstraintVT);
8385   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8386       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8387                                        MatchingOpInfo.ConstraintVT);
8388   if ((OpInfo.ConstraintVT.isInteger() !=
8389        MatchingOpInfo.ConstraintVT.isInteger()) ||
8390       (MatchRC.second != InputRC.second)) {
8391     // FIXME: error out in a more elegant fashion
8392     report_fatal_error("Unsupported asm: input constraint"
8393                        " with a matching output constraint of"
8394                        " incompatible type!");
8395   }
8396   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8397 }
8398 
8399 /// Get a direct memory input to behave well as an indirect operand.
8400 /// This may introduce stores, hence the need for a \p Chain.
8401 /// \return The (possibly updated) chain.
8402 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8403                                         SDISelAsmOperandInfo &OpInfo,
8404                                         SelectionDAG &DAG) {
8405   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8406 
8407   // If we don't have an indirect input, put it in the constpool if we can,
8408   // otherwise spill it to a stack slot.
8409   // TODO: This isn't quite right. We need to handle these according to
8410   // the addressing mode that the constraint wants. Also, this may take
8411   // an additional register for the computation and we don't want that
8412   // either.
8413 
8414   // If the operand is a float, integer, or vector constant, spill to a
8415   // constant pool entry to get its address.
8416   const Value *OpVal = OpInfo.CallOperandVal;
8417   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8418       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8419     OpInfo.CallOperand = DAG.getConstantPool(
8420         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8421     return Chain;
8422   }
8423 
8424   // Otherwise, create a stack slot and emit a store to it before the asm.
8425   Type *Ty = OpVal->getType();
8426   auto &DL = DAG.getDataLayout();
8427   uint64_t TySize = DL.getTypeAllocSize(Ty);
8428   MachineFunction &MF = DAG.getMachineFunction();
8429   int SSFI = MF.getFrameInfo().CreateStackObject(
8430       TySize, DL.getPrefTypeAlign(Ty), false);
8431   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8432   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8433                             MachinePointerInfo::getFixedStack(MF, SSFI),
8434                             TLI.getMemValueType(DL, Ty));
8435   OpInfo.CallOperand = StackSlot;
8436 
8437   return Chain;
8438 }
8439 
8440 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8441 /// specified operand.  We prefer to assign virtual registers, to allow the
8442 /// register allocator to handle the assignment process.  However, if the asm
8443 /// uses features that we can't model on machineinstrs, we have SDISel do the
8444 /// allocation.  This produces generally horrible, but correct, code.
8445 ///
8446 ///   OpInfo describes the operand
8447 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8448 static llvm::Optional<unsigned>
8449 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8450                      SDISelAsmOperandInfo &OpInfo,
8451                      SDISelAsmOperandInfo &RefOpInfo) {
8452   LLVMContext &Context = *DAG.getContext();
8453   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8454 
8455   MachineFunction &MF = DAG.getMachineFunction();
8456   SmallVector<unsigned, 4> Regs;
8457   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8458 
8459   // No work to do for memory operations.
8460   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8461     return None;
8462 
8463   // If this is a constraint for a single physreg, or a constraint for a
8464   // register class, find it.
8465   unsigned AssignedReg;
8466   const TargetRegisterClass *RC;
8467   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8468       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8469   // RC is unset only on failure. Return immediately.
8470   if (!RC)
8471     return None;
8472 
8473   // Get the actual register value type.  This is important, because the user
8474   // may have asked for (e.g.) the AX register in i32 type.  We need to
8475   // remember that AX is actually i16 to get the right extension.
8476   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8477 
8478   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8479     // If this is an FP operand in an integer register (or visa versa), or more
8480     // generally if the operand value disagrees with the register class we plan
8481     // to stick it in, fix the operand type.
8482     //
8483     // If this is an input value, the bitcast to the new type is done now.
8484     // Bitcast for output value is done at the end of visitInlineAsm().
8485     if ((OpInfo.Type == InlineAsm::isOutput ||
8486          OpInfo.Type == InlineAsm::isInput) &&
8487         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8488       // Try to convert to the first EVT that the reg class contains.  If the
8489       // types are identical size, use a bitcast to convert (e.g. two differing
8490       // vector types).  Note: output bitcast is done at the end of
8491       // visitInlineAsm().
8492       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8493         // Exclude indirect inputs while they are unsupported because the code
8494         // to perform the load is missing and thus OpInfo.CallOperand still
8495         // refers to the input address rather than the pointed-to value.
8496         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8497           OpInfo.CallOperand =
8498               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8499         OpInfo.ConstraintVT = RegVT;
8500         // If the operand is an FP value and we want it in integer registers,
8501         // use the corresponding integer type. This turns an f64 value into
8502         // i64, which can be passed with two i32 values on a 32-bit machine.
8503       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8504         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8505         if (OpInfo.Type == InlineAsm::isInput)
8506           OpInfo.CallOperand =
8507               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8508         OpInfo.ConstraintVT = VT;
8509       }
8510     }
8511   }
8512 
8513   // No need to allocate a matching input constraint since the constraint it's
8514   // matching to has already been allocated.
8515   if (OpInfo.isMatchingInputConstraint())
8516     return None;
8517 
8518   EVT ValueVT = OpInfo.ConstraintVT;
8519   if (OpInfo.ConstraintVT == MVT::Other)
8520     ValueVT = RegVT;
8521 
8522   // Initialize NumRegs.
8523   unsigned NumRegs = 1;
8524   if (OpInfo.ConstraintVT != MVT::Other)
8525     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8526 
8527   // If this is a constraint for a specific physical register, like {r17},
8528   // assign it now.
8529 
8530   // If this associated to a specific register, initialize iterator to correct
8531   // place. If virtual, make sure we have enough registers
8532 
8533   // Initialize iterator if necessary
8534   TargetRegisterClass::iterator I = RC->begin();
8535   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8536 
8537   // Do not check for single registers.
8538   if (AssignedReg) {
8539     I = std::find(I, RC->end(), AssignedReg);
8540     if (I == RC->end()) {
8541       // RC does not contain the selected register, which indicates a
8542       // mismatch between the register and the required type/bitwidth.
8543       return {AssignedReg};
8544     }
8545   }
8546 
8547   for (; NumRegs; --NumRegs, ++I) {
8548     assert(I != RC->end() && "Ran out of registers to allocate!");
8549     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8550     Regs.push_back(R);
8551   }
8552 
8553   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8554   return None;
8555 }
8556 
8557 static unsigned
8558 findMatchingInlineAsmOperand(unsigned OperandNo,
8559                              const std::vector<SDValue> &AsmNodeOperands) {
8560   // Scan until we find the definition we already emitted of this operand.
8561   unsigned CurOp = InlineAsm::Op_FirstOperand;
8562   for (; OperandNo; --OperandNo) {
8563     // Advance to the next operand.
8564     unsigned OpFlag =
8565         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8566     assert((InlineAsm::isRegDefKind(OpFlag) ||
8567             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8568             InlineAsm::isMemKind(OpFlag)) &&
8569            "Skipped past definitions?");
8570     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8571   }
8572   return CurOp;
8573 }
8574 
8575 namespace {
8576 
8577 class ExtraFlags {
8578   unsigned Flags = 0;
8579 
8580 public:
8581   explicit ExtraFlags(const CallBase &Call) {
8582     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8583     if (IA->hasSideEffects())
8584       Flags |= InlineAsm::Extra_HasSideEffects;
8585     if (IA->isAlignStack())
8586       Flags |= InlineAsm::Extra_IsAlignStack;
8587     if (Call.isConvergent())
8588       Flags |= InlineAsm::Extra_IsConvergent;
8589     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8590   }
8591 
8592   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8593     // Ideally, we would only check against memory constraints.  However, the
8594     // meaning of an Other constraint can be target-specific and we can't easily
8595     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8596     // for Other constraints as well.
8597     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8598         OpInfo.ConstraintType == TargetLowering::C_Other) {
8599       if (OpInfo.Type == InlineAsm::isInput)
8600         Flags |= InlineAsm::Extra_MayLoad;
8601       else if (OpInfo.Type == InlineAsm::isOutput)
8602         Flags |= InlineAsm::Extra_MayStore;
8603       else if (OpInfo.Type == InlineAsm::isClobber)
8604         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8605     }
8606   }
8607 
8608   unsigned get() const { return Flags; }
8609 };
8610 
8611 } // end anonymous namespace
8612 
8613 /// visitInlineAsm - Handle a call to an InlineAsm object.
8614 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8615                                          const BasicBlock *EHPadBB) {
8616   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8617 
8618   /// ConstraintOperands - Information about all of the constraints.
8619   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8620 
8621   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8622   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8623       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8624 
8625   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8626   // AsmDialect, MayLoad, MayStore).
8627   bool HasSideEffect = IA->hasSideEffects();
8628   ExtraFlags ExtraInfo(Call);
8629 
8630   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8631   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8632   for (auto &T : TargetConstraints) {
8633     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8634     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8635 
8636     // Compute the value type for each operand.
8637     if (OpInfo.hasArg()) {
8638       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
8639       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8640       Type *ParamElemTy = Call.getParamElementType(ArgNo);
8641       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8642                                            DAG.getDataLayout(), ParamElemTy);
8643       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8644       ArgNo++;
8645     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8646       // The return value of the call is this value.  As such, there is no
8647       // corresponding argument.
8648       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8649       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8650         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8651             DAG.getDataLayout(), STy->getElementType(ResNo));
8652       } else {
8653         assert(ResNo == 0 && "Asm only has one result!");
8654         OpInfo.ConstraintVT = TLI.getAsmOperandValueType(
8655             DAG.getDataLayout(), Call.getType()).getSimpleVT();
8656       }
8657       ++ResNo;
8658     } else {
8659       OpInfo.ConstraintVT = MVT::Other;
8660     }
8661 
8662     if (!HasSideEffect)
8663       HasSideEffect = OpInfo.hasMemory(TLI);
8664 
8665     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8666     // FIXME: Could we compute this on OpInfo rather than T?
8667 
8668     // Compute the constraint code and ConstraintType to use.
8669     TLI.ComputeConstraintToUse(T, SDValue());
8670 
8671     if (T.ConstraintType == TargetLowering::C_Immediate &&
8672         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8673       // We've delayed emitting a diagnostic like the "n" constraint because
8674       // inlining could cause an integer showing up.
8675       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8676                                           "' expects an integer constant "
8677                                           "expression");
8678 
8679     ExtraInfo.update(T);
8680   }
8681 
8682   // We won't need to flush pending loads if this asm doesn't touch
8683   // memory and is nonvolatile.
8684   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8685 
8686   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8687   if (EmitEHLabels) {
8688     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8689   }
8690   bool IsCallBr = isa<CallBrInst>(Call);
8691 
8692   if (IsCallBr || EmitEHLabels) {
8693     // If this is a callbr or invoke we need to flush pending exports since
8694     // inlineasm_br and invoke are terminators.
8695     // We need to do this before nodes are glued to the inlineasm_br node.
8696     Chain = getControlRoot();
8697   }
8698 
8699   MCSymbol *BeginLabel = nullptr;
8700   if (EmitEHLabels) {
8701     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8702   }
8703 
8704   // Second pass over the constraints: compute which constraint option to use.
8705   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8706     // If this is an output operand with a matching input operand, look up the
8707     // matching input. If their types mismatch, e.g. one is an integer, the
8708     // other is floating point, or their sizes are different, flag it as an
8709     // error.
8710     if (OpInfo.hasMatchingInput()) {
8711       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8712       patchMatchingInput(OpInfo, Input, DAG);
8713     }
8714 
8715     // Compute the constraint code and ConstraintType to use.
8716     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8717 
8718     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8719         OpInfo.Type == InlineAsm::isClobber)
8720       continue;
8721 
8722     // If this is a memory input, and if the operand is not indirect, do what we
8723     // need to provide an address for the memory input.
8724     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8725         !OpInfo.isIndirect) {
8726       assert((OpInfo.isMultipleAlternative ||
8727               (OpInfo.Type == InlineAsm::isInput)) &&
8728              "Can only indirectify direct input operands!");
8729 
8730       // Memory operands really want the address of the value.
8731       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8732 
8733       // There is no longer a Value* corresponding to this operand.
8734       OpInfo.CallOperandVal = nullptr;
8735 
8736       // It is now an indirect operand.
8737       OpInfo.isIndirect = true;
8738     }
8739 
8740   }
8741 
8742   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8743   std::vector<SDValue> AsmNodeOperands;
8744   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8745   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8746       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8747 
8748   // If we have a !srcloc metadata node associated with it, we want to attach
8749   // this to the ultimately generated inline asm machineinstr.  To do this, we
8750   // pass in the third operand as this (potentially null) inline asm MDNode.
8751   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8752   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8753 
8754   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8755   // bits as operand 3.
8756   AsmNodeOperands.push_back(DAG.getTargetConstant(
8757       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8758 
8759   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8760   // this, assign virtual and physical registers for inputs and otput.
8761   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8762     // Assign Registers.
8763     SDISelAsmOperandInfo &RefOpInfo =
8764         OpInfo.isMatchingInputConstraint()
8765             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8766             : OpInfo;
8767     const auto RegError =
8768         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8769     if (RegError.hasValue()) {
8770       const MachineFunction &MF = DAG.getMachineFunction();
8771       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8772       const char *RegName = TRI.getName(RegError.getValue());
8773       emitInlineAsmError(Call, "register '" + Twine(RegName) +
8774                                    "' allocated for constraint '" +
8775                                    Twine(OpInfo.ConstraintCode) +
8776                                    "' does not match required type");
8777       return;
8778     }
8779 
8780     auto DetectWriteToReservedRegister = [&]() {
8781       const MachineFunction &MF = DAG.getMachineFunction();
8782       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8783       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8784         if (Register::isPhysicalRegister(Reg) &&
8785             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8786           const char *RegName = TRI.getName(Reg);
8787           emitInlineAsmError(Call, "write to reserved register '" +
8788                                        Twine(RegName) + "'");
8789           return true;
8790         }
8791       }
8792       return false;
8793     };
8794 
8795     switch (OpInfo.Type) {
8796     case InlineAsm::isOutput:
8797       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8798         unsigned ConstraintID =
8799             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8800         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8801                "Failed to convert memory constraint code to constraint id.");
8802 
8803         // Add information to the INLINEASM node to know about this output.
8804         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8805         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8806         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8807                                                         MVT::i32));
8808         AsmNodeOperands.push_back(OpInfo.CallOperand);
8809       } else {
8810         // Otherwise, this outputs to a register (directly for C_Register /
8811         // C_RegisterClass, and a target-defined fashion for
8812         // C_Immediate/C_Other). Find a register that we can use.
8813         if (OpInfo.AssignedRegs.Regs.empty()) {
8814           emitInlineAsmError(
8815               Call, "couldn't allocate output register for constraint '" +
8816                         Twine(OpInfo.ConstraintCode) + "'");
8817           return;
8818         }
8819 
8820         if (DetectWriteToReservedRegister())
8821           return;
8822 
8823         // Add information to the INLINEASM node to know that this register is
8824         // set.
8825         OpInfo.AssignedRegs.AddInlineAsmOperands(
8826             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8827                                   : InlineAsm::Kind_RegDef,
8828             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8829       }
8830       break;
8831 
8832     case InlineAsm::isInput: {
8833       SDValue InOperandVal = OpInfo.CallOperand;
8834 
8835       if (OpInfo.isMatchingInputConstraint()) {
8836         // If this is required to match an output register we have already set,
8837         // just use its register.
8838         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8839                                                   AsmNodeOperands);
8840         unsigned OpFlag =
8841           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8842         if (InlineAsm::isRegDefKind(OpFlag) ||
8843             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8844           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8845           if (OpInfo.isIndirect) {
8846             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8847             emitInlineAsmError(Call, "inline asm not supported yet: "
8848                                      "don't know how to handle tied "
8849                                      "indirect register inputs");
8850             return;
8851           }
8852 
8853           SmallVector<unsigned, 4> Regs;
8854           MachineFunction &MF = DAG.getMachineFunction();
8855           MachineRegisterInfo &MRI = MF.getRegInfo();
8856           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8857           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
8858           Register TiedReg = R->getReg();
8859           MVT RegVT = R->getSimpleValueType(0);
8860           const TargetRegisterClass *RC =
8861               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
8862               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
8863                                       : TRI.getMinimalPhysRegClass(TiedReg);
8864           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8865           for (unsigned i = 0; i != NumRegs; ++i)
8866             Regs.push_back(MRI.createVirtualRegister(RC));
8867 
8868           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8869 
8870           SDLoc dl = getCurSDLoc();
8871           // Use the produced MatchedRegs object to
8872           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8873           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8874                                            true, OpInfo.getMatchedOperand(), dl,
8875                                            DAG, AsmNodeOperands);
8876           break;
8877         }
8878 
8879         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8880         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8881                "Unexpected number of operands");
8882         // Add information to the INLINEASM node to know about this input.
8883         // See InlineAsm.h isUseOperandTiedToDef.
8884         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8885         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8886                                                     OpInfo.getMatchedOperand());
8887         AsmNodeOperands.push_back(DAG.getTargetConstant(
8888             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8889         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8890         break;
8891       }
8892 
8893       // Treat indirect 'X' constraint as memory.
8894       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8895           OpInfo.isIndirect)
8896         OpInfo.ConstraintType = TargetLowering::C_Memory;
8897 
8898       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8899           OpInfo.ConstraintType == TargetLowering::C_Other) {
8900         std::vector<SDValue> Ops;
8901         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8902                                           Ops, DAG);
8903         if (Ops.empty()) {
8904           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8905             if (isa<ConstantSDNode>(InOperandVal)) {
8906               emitInlineAsmError(Call, "value out of range for constraint '" +
8907                                            Twine(OpInfo.ConstraintCode) + "'");
8908               return;
8909             }
8910 
8911           emitInlineAsmError(Call,
8912                              "invalid operand for inline asm constraint '" +
8913                                  Twine(OpInfo.ConstraintCode) + "'");
8914           return;
8915         }
8916 
8917         // Add information to the INLINEASM node to know about this input.
8918         unsigned ResOpType =
8919           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8920         AsmNodeOperands.push_back(DAG.getTargetConstant(
8921             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8922         llvm::append_range(AsmNodeOperands, Ops);
8923         break;
8924       }
8925 
8926       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8927         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8928         assert(InOperandVal.getValueType() ==
8929                    TLI.getPointerTy(DAG.getDataLayout()) &&
8930                "Memory operands expect pointer values");
8931 
8932         unsigned ConstraintID =
8933             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8934         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8935                "Failed to convert memory constraint code to constraint id.");
8936 
8937         // Add information to the INLINEASM node to know about this input.
8938         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8939         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8940         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8941                                                         getCurSDLoc(),
8942                                                         MVT::i32));
8943         AsmNodeOperands.push_back(InOperandVal);
8944         break;
8945       }
8946 
8947       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8948               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8949              "Unknown constraint type!");
8950 
8951       // TODO: Support this.
8952       if (OpInfo.isIndirect) {
8953         emitInlineAsmError(
8954             Call, "Don't know how to handle indirect register inputs yet "
8955                   "for constraint '" +
8956                       Twine(OpInfo.ConstraintCode) + "'");
8957         return;
8958       }
8959 
8960       // Copy the input into the appropriate registers.
8961       if (OpInfo.AssignedRegs.Regs.empty()) {
8962         emitInlineAsmError(Call,
8963                            "couldn't allocate input reg for constraint '" +
8964                                Twine(OpInfo.ConstraintCode) + "'");
8965         return;
8966       }
8967 
8968       if (DetectWriteToReservedRegister())
8969         return;
8970 
8971       SDLoc dl = getCurSDLoc();
8972 
8973       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8974                                         &Call);
8975 
8976       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8977                                                dl, DAG, AsmNodeOperands);
8978       break;
8979     }
8980     case InlineAsm::isClobber:
8981       // Add the clobbered value to the operand list, so that the register
8982       // allocator is aware that the physreg got clobbered.
8983       if (!OpInfo.AssignedRegs.Regs.empty())
8984         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8985                                                  false, 0, getCurSDLoc(), DAG,
8986                                                  AsmNodeOperands);
8987       break;
8988     }
8989   }
8990 
8991   // Finish up input operands.  Set the input chain and add the flag last.
8992   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8993   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8994 
8995   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8996   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8997                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8998   Flag = Chain.getValue(1);
8999 
9000   // Do additional work to generate outputs.
9001 
9002   SmallVector<EVT, 1> ResultVTs;
9003   SmallVector<SDValue, 1> ResultValues;
9004   SmallVector<SDValue, 8> OutChains;
9005 
9006   llvm::Type *CallResultType = Call.getType();
9007   ArrayRef<Type *> ResultTypes;
9008   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9009     ResultTypes = StructResult->elements();
9010   else if (!CallResultType->isVoidTy())
9011     ResultTypes = makeArrayRef(CallResultType);
9012 
9013   auto CurResultType = ResultTypes.begin();
9014   auto handleRegAssign = [&](SDValue V) {
9015     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9016     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9017     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9018     ++CurResultType;
9019     // If the type of the inline asm call site return value is different but has
9020     // same size as the type of the asm output bitcast it.  One example of this
9021     // is for vectors with different width / number of elements.  This can
9022     // happen for register classes that can contain multiple different value
9023     // types.  The preg or vreg allocated may not have the same VT as was
9024     // expected.
9025     //
9026     // This can also happen for a return value that disagrees with the register
9027     // class it is put in, eg. a double in a general-purpose register on a
9028     // 32-bit machine.
9029     if (ResultVT != V.getValueType() &&
9030         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9031       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9032     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9033              V.getValueType().isInteger()) {
9034       // If a result value was tied to an input value, the computed result
9035       // may have a wider width than the expected result.  Extract the
9036       // relevant portion.
9037       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9038     }
9039     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9040     ResultVTs.push_back(ResultVT);
9041     ResultValues.push_back(V);
9042   };
9043 
9044   // Deal with output operands.
9045   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9046     if (OpInfo.Type == InlineAsm::isOutput) {
9047       SDValue Val;
9048       // Skip trivial output operands.
9049       if (OpInfo.AssignedRegs.Regs.empty())
9050         continue;
9051 
9052       switch (OpInfo.ConstraintType) {
9053       case TargetLowering::C_Register:
9054       case TargetLowering::C_RegisterClass:
9055         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9056                                                   Chain, &Flag, &Call);
9057         break;
9058       case TargetLowering::C_Immediate:
9059       case TargetLowering::C_Other:
9060         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9061                                               OpInfo, DAG);
9062         break;
9063       case TargetLowering::C_Memory:
9064         break; // Already handled.
9065       case TargetLowering::C_Unknown:
9066         assert(false && "Unexpected unknown constraint");
9067       }
9068 
9069       // Indirect output manifest as stores. Record output chains.
9070       if (OpInfo.isIndirect) {
9071         const Value *Ptr = OpInfo.CallOperandVal;
9072         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9073         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9074                                      MachinePointerInfo(Ptr));
9075         OutChains.push_back(Store);
9076       } else {
9077         // generate CopyFromRegs to associated registers.
9078         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9079         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9080           for (const SDValue &V : Val->op_values())
9081             handleRegAssign(V);
9082         } else
9083           handleRegAssign(Val);
9084       }
9085     }
9086   }
9087 
9088   // Set results.
9089   if (!ResultValues.empty()) {
9090     assert(CurResultType == ResultTypes.end() &&
9091            "Mismatch in number of ResultTypes");
9092     assert(ResultValues.size() == ResultTypes.size() &&
9093            "Mismatch in number of output operands in asm result");
9094 
9095     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9096                             DAG.getVTList(ResultVTs), ResultValues);
9097     setValue(&Call, V);
9098   }
9099 
9100   // Collect store chains.
9101   if (!OutChains.empty())
9102     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9103 
9104   if (EmitEHLabels) {
9105     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9106   }
9107 
9108   // Only Update Root if inline assembly has a memory effect.
9109   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9110       EmitEHLabels)
9111     DAG.setRoot(Chain);
9112 }
9113 
9114 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9115                                              const Twine &Message) {
9116   LLVMContext &Ctx = *DAG.getContext();
9117   Ctx.emitError(&Call, Message);
9118 
9119   // Make sure we leave the DAG in a valid state
9120   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9121   SmallVector<EVT, 1> ValueVTs;
9122   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9123 
9124   if (ValueVTs.empty())
9125     return;
9126 
9127   SmallVector<SDValue, 1> Ops;
9128   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9129     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9130 
9131   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9132 }
9133 
9134 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9135   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9136                           MVT::Other, getRoot(),
9137                           getValue(I.getArgOperand(0)),
9138                           DAG.getSrcValue(I.getArgOperand(0))));
9139 }
9140 
9141 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9142   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9143   const DataLayout &DL = DAG.getDataLayout();
9144   SDValue V = DAG.getVAArg(
9145       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9146       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9147       DL.getABITypeAlign(I.getType()).value());
9148   DAG.setRoot(V.getValue(1));
9149 
9150   if (I.getType()->isPointerTy())
9151     V = DAG.getPtrExtOrTrunc(
9152         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9153   setValue(&I, V);
9154 }
9155 
9156 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9157   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9158                           MVT::Other, getRoot(),
9159                           getValue(I.getArgOperand(0)),
9160                           DAG.getSrcValue(I.getArgOperand(0))));
9161 }
9162 
9163 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9164   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9165                           MVT::Other, getRoot(),
9166                           getValue(I.getArgOperand(0)),
9167                           getValue(I.getArgOperand(1)),
9168                           DAG.getSrcValue(I.getArgOperand(0)),
9169                           DAG.getSrcValue(I.getArgOperand(1))));
9170 }
9171 
9172 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9173                                                     const Instruction &I,
9174                                                     SDValue Op) {
9175   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9176   if (!Range)
9177     return Op;
9178 
9179   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9180   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9181     return Op;
9182 
9183   APInt Lo = CR.getUnsignedMin();
9184   if (!Lo.isMinValue())
9185     return Op;
9186 
9187   APInt Hi = CR.getUnsignedMax();
9188   unsigned Bits = std::max(Hi.getActiveBits(),
9189                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9190 
9191   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9192 
9193   SDLoc SL = getCurSDLoc();
9194 
9195   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9196                              DAG.getValueType(SmallVT));
9197   unsigned NumVals = Op.getNode()->getNumValues();
9198   if (NumVals == 1)
9199     return ZExt;
9200 
9201   SmallVector<SDValue, 4> Ops;
9202 
9203   Ops.push_back(ZExt);
9204   for (unsigned I = 1; I != NumVals; ++I)
9205     Ops.push_back(Op.getValue(I));
9206 
9207   return DAG.getMergeValues(Ops, SL);
9208 }
9209 
9210 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9211 /// the call being lowered.
9212 ///
9213 /// This is a helper for lowering intrinsics that follow a target calling
9214 /// convention or require stack pointer adjustment. Only a subset of the
9215 /// intrinsic's operands need to participate in the calling convention.
9216 void SelectionDAGBuilder::populateCallLoweringInfo(
9217     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9218     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9219     bool IsPatchPoint) {
9220   TargetLowering::ArgListTy Args;
9221   Args.reserve(NumArgs);
9222 
9223   // Populate the argument list.
9224   // Attributes for args start at offset 1, after the return attribute.
9225   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9226        ArgI != ArgE; ++ArgI) {
9227     const Value *V = Call->getOperand(ArgI);
9228 
9229     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9230 
9231     TargetLowering::ArgListEntry Entry;
9232     Entry.Node = getValue(V);
9233     Entry.Ty = V->getType();
9234     Entry.setAttributes(Call, ArgI);
9235     Args.push_back(Entry);
9236   }
9237 
9238   CLI.setDebugLoc(getCurSDLoc())
9239       .setChain(getRoot())
9240       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9241       .setDiscardResult(Call->use_empty())
9242       .setIsPatchPoint(IsPatchPoint)
9243       .setIsPreallocated(
9244           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9245 }
9246 
9247 /// Add a stack map intrinsic call's live variable operands to a stackmap
9248 /// or patchpoint target node's operand list.
9249 ///
9250 /// Constants are converted to TargetConstants purely as an optimization to
9251 /// avoid constant materialization and register allocation.
9252 ///
9253 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9254 /// generate addess computation nodes, and so FinalizeISel can convert the
9255 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9256 /// address materialization and register allocation, but may also be required
9257 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9258 /// alloca in the entry block, then the runtime may assume that the alloca's
9259 /// StackMap location can be read immediately after compilation and that the
9260 /// location is valid at any point during execution (this is similar to the
9261 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9262 /// only available in a register, then the runtime would need to trap when
9263 /// execution reaches the StackMap in order to read the alloca's location.
9264 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9265                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9266                                 SelectionDAGBuilder &Builder) {
9267   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
9268     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
9269     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
9270       Ops.push_back(
9271         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
9272       Ops.push_back(
9273         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
9274     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
9275       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
9276       Ops.push_back(Builder.DAG.getTargetFrameIndex(
9277           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
9278     } else
9279       Ops.push_back(OpVal);
9280   }
9281 }
9282 
9283 /// Lower llvm.experimental.stackmap directly to its target opcode.
9284 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9285   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
9286   //                                  [live variables...])
9287 
9288   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9289 
9290   SDValue Chain, InFlag, Callee, NullPtr;
9291   SmallVector<SDValue, 32> Ops;
9292 
9293   SDLoc DL = getCurSDLoc();
9294   Callee = getValue(CI.getCalledOperand());
9295   NullPtr = DAG.getIntPtrConstant(0, DL, true);
9296 
9297   // The stackmap intrinsic only records the live variables (the arguments
9298   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9299   // intrinsic, this won't be lowered to a function call. This means we don't
9300   // have to worry about calling conventions and target specific lowering code.
9301   // Instead we perform the call lowering right here.
9302   //
9303   // chain, flag = CALLSEQ_START(chain, 0, 0)
9304   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9305   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9306   //
9307   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9308   InFlag = Chain.getValue(1);
9309 
9310   // Add the <id> and <numBytes> constants.
9311   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
9312   Ops.push_back(DAG.getTargetConstant(
9313                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
9314   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
9315   Ops.push_back(DAG.getTargetConstant(
9316                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
9317                   MVT::i32));
9318 
9319   // Push live variables for the stack map.
9320   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9321 
9322   // We are not pushing any register mask info here on the operands list,
9323   // because the stackmap doesn't clobber anything.
9324 
9325   // Push the chain and the glue flag.
9326   Ops.push_back(Chain);
9327   Ops.push_back(InFlag);
9328 
9329   // Create the STACKMAP node.
9330   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9331   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
9332   Chain = SDValue(SM, 0);
9333   InFlag = Chain.getValue(1);
9334 
9335   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9336 
9337   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9338 
9339   // Set the root to the target-lowered call chain.
9340   DAG.setRoot(Chain);
9341 
9342   // Inform the Frame Information that we have a stackmap in this function.
9343   FuncInfo.MF->getFrameInfo().setHasStackMap();
9344 }
9345 
9346 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9347 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9348                                           const BasicBlock *EHPadBB) {
9349   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9350   //                                                 i32 <numBytes>,
9351   //                                                 i8* <target>,
9352   //                                                 i32 <numArgs>,
9353   //                                                 [Args...],
9354   //                                                 [live variables...])
9355 
9356   CallingConv::ID CC = CB.getCallingConv();
9357   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9358   bool HasDef = !CB.getType()->isVoidTy();
9359   SDLoc dl = getCurSDLoc();
9360   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9361 
9362   // Handle immediate and symbolic callees.
9363   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9364     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9365                                    /*isTarget=*/true);
9366   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9367     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9368                                          SDLoc(SymbolicCallee),
9369                                          SymbolicCallee->getValueType(0));
9370 
9371   // Get the real number of arguments participating in the call <numArgs>
9372   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9373   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9374 
9375   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9376   // Intrinsics include all meta-operands up to but not including CC.
9377   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9378   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9379          "Not enough arguments provided to the patchpoint intrinsic");
9380 
9381   // For AnyRegCC the arguments are lowered later on manually.
9382   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9383   Type *ReturnTy =
9384       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9385 
9386   TargetLowering::CallLoweringInfo CLI(DAG);
9387   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9388                            ReturnTy, true);
9389   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9390 
9391   SDNode *CallEnd = Result.second.getNode();
9392   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9393     CallEnd = CallEnd->getOperand(0).getNode();
9394 
9395   /// Get a call instruction from the call sequence chain.
9396   /// Tail calls are not allowed.
9397   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9398          "Expected a callseq node.");
9399   SDNode *Call = CallEnd->getOperand(0).getNode();
9400   bool HasGlue = Call->getGluedNode();
9401 
9402   // Replace the target specific call node with the patchable intrinsic.
9403   SmallVector<SDValue, 8> Ops;
9404 
9405   // Add the <id> and <numBytes> constants.
9406   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9407   Ops.push_back(DAG.getTargetConstant(
9408                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9409   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9410   Ops.push_back(DAG.getTargetConstant(
9411                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9412                   MVT::i32));
9413 
9414   // Add the callee.
9415   Ops.push_back(Callee);
9416 
9417   // Adjust <numArgs> to account for any arguments that have been passed on the
9418   // stack instead.
9419   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9420   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9421   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9422   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9423 
9424   // Add the calling convention
9425   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9426 
9427   // Add the arguments we omitted previously. The register allocator should
9428   // place these in any free register.
9429   if (IsAnyRegCC)
9430     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9431       Ops.push_back(getValue(CB.getArgOperand(i)));
9432 
9433   // Push the arguments from the call instruction up to the register mask.
9434   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9435   Ops.append(Call->op_begin() + 2, e);
9436 
9437   // Push live variables for the stack map.
9438   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9439 
9440   // Push the register mask info.
9441   if (HasGlue)
9442     Ops.push_back(*(Call->op_end()-2));
9443   else
9444     Ops.push_back(*(Call->op_end()-1));
9445 
9446   // Push the chain (this is originally the first operand of the call, but
9447   // becomes now the last or second to last operand).
9448   Ops.push_back(*(Call->op_begin()));
9449 
9450   // Push the glue flag (last operand).
9451   if (HasGlue)
9452     Ops.push_back(*(Call->op_end()-1));
9453 
9454   SDVTList NodeTys;
9455   if (IsAnyRegCC && HasDef) {
9456     // Create the return types based on the intrinsic definition
9457     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9458     SmallVector<EVT, 3> ValueVTs;
9459     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9460     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9461 
9462     // There is always a chain and a glue type at the end
9463     ValueVTs.push_back(MVT::Other);
9464     ValueVTs.push_back(MVT::Glue);
9465     NodeTys = DAG.getVTList(ValueVTs);
9466   } else
9467     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9468 
9469   // Replace the target specific call node with a PATCHPOINT node.
9470   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9471                                          dl, NodeTys, Ops);
9472 
9473   // Update the NodeMap.
9474   if (HasDef) {
9475     if (IsAnyRegCC)
9476       setValue(&CB, SDValue(MN, 0));
9477     else
9478       setValue(&CB, Result.first);
9479   }
9480 
9481   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9482   // call sequence. Furthermore the location of the chain and glue can change
9483   // when the AnyReg calling convention is used and the intrinsic returns a
9484   // value.
9485   if (IsAnyRegCC && HasDef) {
9486     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9487     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9488     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9489   } else
9490     DAG.ReplaceAllUsesWith(Call, MN);
9491   DAG.DeleteNode(Call);
9492 
9493   // Inform the Frame Information that we have a patchpoint in this function.
9494   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9495 }
9496 
9497 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9498                                             unsigned Intrinsic) {
9499   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9500   SDValue Op1 = getValue(I.getArgOperand(0));
9501   SDValue Op2;
9502   if (I.arg_size() > 1)
9503     Op2 = getValue(I.getArgOperand(1));
9504   SDLoc dl = getCurSDLoc();
9505   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9506   SDValue Res;
9507   SDNodeFlags SDFlags;
9508   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9509     SDFlags.copyFMF(*FPMO);
9510 
9511   switch (Intrinsic) {
9512   case Intrinsic::vector_reduce_fadd:
9513     if (SDFlags.hasAllowReassociation())
9514       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9515                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9516                         SDFlags);
9517     else
9518       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9519     break;
9520   case Intrinsic::vector_reduce_fmul:
9521     if (SDFlags.hasAllowReassociation())
9522       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9523                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9524                         SDFlags);
9525     else
9526       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9527     break;
9528   case Intrinsic::vector_reduce_add:
9529     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9530     break;
9531   case Intrinsic::vector_reduce_mul:
9532     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9533     break;
9534   case Intrinsic::vector_reduce_and:
9535     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9536     break;
9537   case Intrinsic::vector_reduce_or:
9538     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9539     break;
9540   case Intrinsic::vector_reduce_xor:
9541     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9542     break;
9543   case Intrinsic::vector_reduce_smax:
9544     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9545     break;
9546   case Intrinsic::vector_reduce_smin:
9547     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9548     break;
9549   case Intrinsic::vector_reduce_umax:
9550     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9551     break;
9552   case Intrinsic::vector_reduce_umin:
9553     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9554     break;
9555   case Intrinsic::vector_reduce_fmax:
9556     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9557     break;
9558   case Intrinsic::vector_reduce_fmin:
9559     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9560     break;
9561   default:
9562     llvm_unreachable("Unhandled vector reduce intrinsic");
9563   }
9564   setValue(&I, Res);
9565 }
9566 
9567 /// Returns an AttributeList representing the attributes applied to the return
9568 /// value of the given call.
9569 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9570   SmallVector<Attribute::AttrKind, 2> Attrs;
9571   if (CLI.RetSExt)
9572     Attrs.push_back(Attribute::SExt);
9573   if (CLI.RetZExt)
9574     Attrs.push_back(Attribute::ZExt);
9575   if (CLI.IsInReg)
9576     Attrs.push_back(Attribute::InReg);
9577 
9578   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9579                             Attrs);
9580 }
9581 
9582 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9583 /// implementation, which just calls LowerCall.
9584 /// FIXME: When all targets are
9585 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9586 std::pair<SDValue, SDValue>
9587 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9588   // Handle the incoming return values from the call.
9589   CLI.Ins.clear();
9590   Type *OrigRetTy = CLI.RetTy;
9591   SmallVector<EVT, 4> RetTys;
9592   SmallVector<uint64_t, 4> Offsets;
9593   auto &DL = CLI.DAG.getDataLayout();
9594   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9595 
9596   if (CLI.IsPostTypeLegalization) {
9597     // If we are lowering a libcall after legalization, split the return type.
9598     SmallVector<EVT, 4> OldRetTys;
9599     SmallVector<uint64_t, 4> OldOffsets;
9600     RetTys.swap(OldRetTys);
9601     Offsets.swap(OldOffsets);
9602 
9603     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9604       EVT RetVT = OldRetTys[i];
9605       uint64_t Offset = OldOffsets[i];
9606       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9607       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9608       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9609       RetTys.append(NumRegs, RegisterVT);
9610       for (unsigned j = 0; j != NumRegs; ++j)
9611         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9612     }
9613   }
9614 
9615   SmallVector<ISD::OutputArg, 4> Outs;
9616   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9617 
9618   bool CanLowerReturn =
9619       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9620                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9621 
9622   SDValue DemoteStackSlot;
9623   int DemoteStackIdx = -100;
9624   if (!CanLowerReturn) {
9625     // FIXME: equivalent assert?
9626     // assert(!CS.hasInAllocaArgument() &&
9627     //        "sret demotion is incompatible with inalloca");
9628     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9629     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9630     MachineFunction &MF = CLI.DAG.getMachineFunction();
9631     DemoteStackIdx =
9632         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9633     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9634                                               DL.getAllocaAddrSpace());
9635 
9636     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9637     ArgListEntry Entry;
9638     Entry.Node = DemoteStackSlot;
9639     Entry.Ty = StackSlotPtrType;
9640     Entry.IsSExt = false;
9641     Entry.IsZExt = false;
9642     Entry.IsInReg = false;
9643     Entry.IsSRet = true;
9644     Entry.IsNest = false;
9645     Entry.IsByVal = false;
9646     Entry.IsByRef = false;
9647     Entry.IsReturned = false;
9648     Entry.IsSwiftSelf = false;
9649     Entry.IsSwiftAsync = false;
9650     Entry.IsSwiftError = false;
9651     Entry.IsCFGuardTarget = false;
9652     Entry.Alignment = Alignment;
9653     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9654     CLI.NumFixedArgs += 1;
9655     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9656 
9657     // sret demotion isn't compatible with tail-calls, since the sret argument
9658     // points into the callers stack frame.
9659     CLI.IsTailCall = false;
9660   } else {
9661     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9662         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9663     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9664       ISD::ArgFlagsTy Flags;
9665       if (NeedsRegBlock) {
9666         Flags.setInConsecutiveRegs();
9667         if (I == RetTys.size() - 1)
9668           Flags.setInConsecutiveRegsLast();
9669       }
9670       EVT VT = RetTys[I];
9671       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9672                                                      CLI.CallConv, VT);
9673       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9674                                                        CLI.CallConv, VT);
9675       for (unsigned i = 0; i != NumRegs; ++i) {
9676         ISD::InputArg MyFlags;
9677         MyFlags.Flags = Flags;
9678         MyFlags.VT = RegisterVT;
9679         MyFlags.ArgVT = VT;
9680         MyFlags.Used = CLI.IsReturnValueUsed;
9681         if (CLI.RetTy->isPointerTy()) {
9682           MyFlags.Flags.setPointer();
9683           MyFlags.Flags.setPointerAddrSpace(
9684               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9685         }
9686         if (CLI.RetSExt)
9687           MyFlags.Flags.setSExt();
9688         if (CLI.RetZExt)
9689           MyFlags.Flags.setZExt();
9690         if (CLI.IsInReg)
9691           MyFlags.Flags.setInReg();
9692         CLI.Ins.push_back(MyFlags);
9693       }
9694     }
9695   }
9696 
9697   // We push in swifterror return as the last element of CLI.Ins.
9698   ArgListTy &Args = CLI.getArgs();
9699   if (supportSwiftError()) {
9700     for (const ArgListEntry &Arg : Args) {
9701       if (Arg.IsSwiftError) {
9702         ISD::InputArg MyFlags;
9703         MyFlags.VT = getPointerTy(DL);
9704         MyFlags.ArgVT = EVT(getPointerTy(DL));
9705         MyFlags.Flags.setSwiftError();
9706         CLI.Ins.push_back(MyFlags);
9707       }
9708     }
9709   }
9710 
9711   // Handle all of the outgoing arguments.
9712   CLI.Outs.clear();
9713   CLI.OutVals.clear();
9714   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9715     SmallVector<EVT, 4> ValueVTs;
9716     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9717     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9718     Type *FinalType = Args[i].Ty;
9719     if (Args[i].IsByVal)
9720       FinalType = Args[i].IndirectType;
9721     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9722         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9723     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9724          ++Value) {
9725       EVT VT = ValueVTs[Value];
9726       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9727       SDValue Op = SDValue(Args[i].Node.getNode(),
9728                            Args[i].Node.getResNo() + Value);
9729       ISD::ArgFlagsTy Flags;
9730 
9731       // Certain targets (such as MIPS), may have a different ABI alignment
9732       // for a type depending on the context. Give the target a chance to
9733       // specify the alignment it wants.
9734       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9735       Flags.setOrigAlign(OriginalAlignment);
9736 
9737       if (Args[i].Ty->isPointerTy()) {
9738         Flags.setPointer();
9739         Flags.setPointerAddrSpace(
9740             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9741       }
9742       if (Args[i].IsZExt)
9743         Flags.setZExt();
9744       if (Args[i].IsSExt)
9745         Flags.setSExt();
9746       if (Args[i].IsInReg) {
9747         // If we are using vectorcall calling convention, a structure that is
9748         // passed InReg - is surely an HVA
9749         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9750             isa<StructType>(FinalType)) {
9751           // The first value of a structure is marked
9752           if (0 == Value)
9753             Flags.setHvaStart();
9754           Flags.setHva();
9755         }
9756         // Set InReg Flag
9757         Flags.setInReg();
9758       }
9759       if (Args[i].IsSRet)
9760         Flags.setSRet();
9761       if (Args[i].IsSwiftSelf)
9762         Flags.setSwiftSelf();
9763       if (Args[i].IsSwiftAsync)
9764         Flags.setSwiftAsync();
9765       if (Args[i].IsSwiftError)
9766         Flags.setSwiftError();
9767       if (Args[i].IsCFGuardTarget)
9768         Flags.setCFGuardTarget();
9769       if (Args[i].IsByVal)
9770         Flags.setByVal();
9771       if (Args[i].IsByRef)
9772         Flags.setByRef();
9773       if (Args[i].IsPreallocated) {
9774         Flags.setPreallocated();
9775         // Set the byval flag for CCAssignFn callbacks that don't know about
9776         // preallocated.  This way we can know how many bytes we should've
9777         // allocated and how many bytes a callee cleanup function will pop.  If
9778         // we port preallocated to more targets, we'll have to add custom
9779         // preallocated handling in the various CC lowering callbacks.
9780         Flags.setByVal();
9781       }
9782       if (Args[i].IsInAlloca) {
9783         Flags.setInAlloca();
9784         // Set the byval flag for CCAssignFn callbacks that don't know about
9785         // inalloca.  This way we can know how many bytes we should've allocated
9786         // and how many bytes a callee cleanup function will pop.  If we port
9787         // inalloca to more targets, we'll have to add custom inalloca handling
9788         // in the various CC lowering callbacks.
9789         Flags.setByVal();
9790       }
9791       Align MemAlign;
9792       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9793         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9794         Flags.setByValSize(FrameSize);
9795 
9796         // info is not there but there are cases it cannot get right.
9797         if (auto MA = Args[i].Alignment)
9798           MemAlign = *MA;
9799         else
9800           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
9801       } else if (auto MA = Args[i].Alignment) {
9802         MemAlign = *MA;
9803       } else {
9804         MemAlign = OriginalAlignment;
9805       }
9806       Flags.setMemAlign(MemAlign);
9807       if (Args[i].IsNest)
9808         Flags.setNest();
9809       if (NeedsRegBlock)
9810         Flags.setInConsecutiveRegs();
9811 
9812       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9813                                                  CLI.CallConv, VT);
9814       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9815                                                         CLI.CallConv, VT);
9816       SmallVector<SDValue, 4> Parts(NumParts);
9817       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9818 
9819       if (Args[i].IsSExt)
9820         ExtendKind = ISD::SIGN_EXTEND;
9821       else if (Args[i].IsZExt)
9822         ExtendKind = ISD::ZERO_EXTEND;
9823 
9824       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9825       // for now.
9826       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9827           CanLowerReturn) {
9828         assert((CLI.RetTy == Args[i].Ty ||
9829                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9830                  CLI.RetTy->getPointerAddressSpace() ==
9831                      Args[i].Ty->getPointerAddressSpace())) &&
9832                RetTys.size() == NumValues && "unexpected use of 'returned'");
9833         // Before passing 'returned' to the target lowering code, ensure that
9834         // either the register MVT and the actual EVT are the same size or that
9835         // the return value and argument are extended in the same way; in these
9836         // cases it's safe to pass the argument register value unchanged as the
9837         // return register value (although it's at the target's option whether
9838         // to do so)
9839         // TODO: allow code generation to take advantage of partially preserved
9840         // registers rather than clobbering the entire register when the
9841         // parameter extension method is not compatible with the return
9842         // extension method
9843         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9844             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9845              CLI.RetZExt == Args[i].IsZExt))
9846           Flags.setReturned();
9847       }
9848 
9849       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9850                      CLI.CallConv, ExtendKind);
9851 
9852       for (unsigned j = 0; j != NumParts; ++j) {
9853         // if it isn't first piece, alignment must be 1
9854         // For scalable vectors the scalable part is currently handled
9855         // by individual targets, so we just use the known minimum size here.
9856         ISD::OutputArg MyFlags(
9857             Flags, Parts[j].getValueType().getSimpleVT(), VT,
9858             i < CLI.NumFixedArgs, i,
9859             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
9860         if (NumParts > 1 && j == 0)
9861           MyFlags.Flags.setSplit();
9862         else if (j != 0) {
9863           MyFlags.Flags.setOrigAlign(Align(1));
9864           if (j == NumParts - 1)
9865             MyFlags.Flags.setSplitEnd();
9866         }
9867 
9868         CLI.Outs.push_back(MyFlags);
9869         CLI.OutVals.push_back(Parts[j]);
9870       }
9871 
9872       if (NeedsRegBlock && Value == NumValues - 1)
9873         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9874     }
9875   }
9876 
9877   SmallVector<SDValue, 4> InVals;
9878   CLI.Chain = LowerCall(CLI, InVals);
9879 
9880   // Update CLI.InVals to use outside of this function.
9881   CLI.InVals = InVals;
9882 
9883   // Verify that the target's LowerCall behaved as expected.
9884   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9885          "LowerCall didn't return a valid chain!");
9886   assert((!CLI.IsTailCall || InVals.empty()) &&
9887          "LowerCall emitted a return value for a tail call!");
9888   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9889          "LowerCall didn't emit the correct number of values!");
9890 
9891   // For a tail call, the return value is merely live-out and there aren't
9892   // any nodes in the DAG representing it. Return a special value to
9893   // indicate that a tail call has been emitted and no more Instructions
9894   // should be processed in the current block.
9895   if (CLI.IsTailCall) {
9896     CLI.DAG.setRoot(CLI.Chain);
9897     return std::make_pair(SDValue(), SDValue());
9898   }
9899 
9900 #ifndef NDEBUG
9901   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9902     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9903     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9904            "LowerCall emitted a value with the wrong type!");
9905   }
9906 #endif
9907 
9908   SmallVector<SDValue, 4> ReturnValues;
9909   if (!CanLowerReturn) {
9910     // The instruction result is the result of loading from the
9911     // hidden sret parameter.
9912     SmallVector<EVT, 1> PVTs;
9913     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9914 
9915     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9916     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9917     EVT PtrVT = PVTs[0];
9918 
9919     unsigned NumValues = RetTys.size();
9920     ReturnValues.resize(NumValues);
9921     SmallVector<SDValue, 4> Chains(NumValues);
9922 
9923     // An aggregate return value cannot wrap around the address space, so
9924     // offsets to its parts don't wrap either.
9925     SDNodeFlags Flags;
9926     Flags.setNoUnsignedWrap(true);
9927 
9928     MachineFunction &MF = CLI.DAG.getMachineFunction();
9929     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9930     for (unsigned i = 0; i < NumValues; ++i) {
9931       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9932                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9933                                                         PtrVT), Flags);
9934       SDValue L = CLI.DAG.getLoad(
9935           RetTys[i], CLI.DL, CLI.Chain, Add,
9936           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9937                                             DemoteStackIdx, Offsets[i]),
9938           HiddenSRetAlign);
9939       ReturnValues[i] = L;
9940       Chains[i] = L.getValue(1);
9941     }
9942 
9943     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9944   } else {
9945     // Collect the legal value parts into potentially illegal values
9946     // that correspond to the original function's return values.
9947     Optional<ISD::NodeType> AssertOp;
9948     if (CLI.RetSExt)
9949       AssertOp = ISD::AssertSext;
9950     else if (CLI.RetZExt)
9951       AssertOp = ISD::AssertZext;
9952     unsigned CurReg = 0;
9953     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9954       EVT VT = RetTys[I];
9955       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9956                                                      CLI.CallConv, VT);
9957       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9958                                                        CLI.CallConv, VT);
9959 
9960       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9961                                               NumRegs, RegisterVT, VT, nullptr,
9962                                               CLI.CallConv, AssertOp));
9963       CurReg += NumRegs;
9964     }
9965 
9966     // For a function returning void, there is no return value. We can't create
9967     // such a node, so we just return a null return value in that case. In
9968     // that case, nothing will actually look at the value.
9969     if (ReturnValues.empty())
9970       return std::make_pair(SDValue(), CLI.Chain);
9971   }
9972 
9973   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9974                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9975   return std::make_pair(Res, CLI.Chain);
9976 }
9977 
9978 /// Places new result values for the node in Results (their number
9979 /// and types must exactly match those of the original return values of
9980 /// the node), or leaves Results empty, which indicates that the node is not
9981 /// to be custom lowered after all.
9982 void TargetLowering::LowerOperationWrapper(SDNode *N,
9983                                            SmallVectorImpl<SDValue> &Results,
9984                                            SelectionDAG &DAG) const {
9985   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9986 
9987   if (!Res.getNode())
9988     return;
9989 
9990   // If the original node has one result, take the return value from
9991   // LowerOperation as is. It might not be result number 0.
9992   if (N->getNumValues() == 1) {
9993     Results.push_back(Res);
9994     return;
9995   }
9996 
9997   // If the original node has multiple results, then the return node should
9998   // have the same number of results.
9999   assert((N->getNumValues() == Res->getNumValues()) &&
10000       "Lowering returned the wrong number of results!");
10001 
10002   // Places new result values base on N result number.
10003   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10004     Results.push_back(Res.getValue(I));
10005 }
10006 
10007 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10008   llvm_unreachable("LowerOperation not implemented for this target!");
10009 }
10010 
10011 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10012                                                      unsigned Reg,
10013                                                      ISD::NodeType ExtendType) {
10014   SDValue Op = getNonRegisterValue(V);
10015   assert((Op.getOpcode() != ISD::CopyFromReg ||
10016           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10017          "Copy from a reg to the same reg!");
10018   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10019 
10020   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10021   // If this is an InlineAsm we have to match the registers required, not the
10022   // notional registers required by the type.
10023 
10024   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10025                    None); // This is not an ABI copy.
10026   SDValue Chain = DAG.getEntryNode();
10027 
10028   if (ExtendType == ISD::ANY_EXTEND) {
10029     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10030     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10031       ExtendType = PreferredExtendIt->second;
10032   }
10033   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10034   PendingExports.push_back(Chain);
10035 }
10036 
10037 #include "llvm/CodeGen/SelectionDAGISel.h"
10038 
10039 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10040 /// entry block, return true.  This includes arguments used by switches, since
10041 /// the switch may expand into multiple basic blocks.
10042 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10043   // With FastISel active, we may be splitting blocks, so force creation
10044   // of virtual registers for all non-dead arguments.
10045   if (FastISel)
10046     return A->use_empty();
10047 
10048   const BasicBlock &Entry = A->getParent()->front();
10049   for (const User *U : A->users())
10050     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10051       return false;  // Use not in entry block.
10052 
10053   return true;
10054 }
10055 
10056 using ArgCopyElisionMapTy =
10057     DenseMap<const Argument *,
10058              std::pair<const AllocaInst *, const StoreInst *>>;
10059 
10060 /// Scan the entry block of the function in FuncInfo for arguments that look
10061 /// like copies into a local alloca. Record any copied arguments in
10062 /// ArgCopyElisionCandidates.
10063 static void
10064 findArgumentCopyElisionCandidates(const DataLayout &DL,
10065                                   FunctionLoweringInfo *FuncInfo,
10066                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10067   // Record the state of every static alloca used in the entry block. Argument
10068   // allocas are all used in the entry block, so we need approximately as many
10069   // entries as we have arguments.
10070   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10071   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10072   unsigned NumArgs = FuncInfo->Fn->arg_size();
10073   StaticAllocas.reserve(NumArgs * 2);
10074 
10075   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10076     if (!V)
10077       return nullptr;
10078     V = V->stripPointerCasts();
10079     const auto *AI = dyn_cast<AllocaInst>(V);
10080     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10081       return nullptr;
10082     auto Iter = StaticAllocas.insert({AI, Unknown});
10083     return &Iter.first->second;
10084   };
10085 
10086   // Look for stores of arguments to static allocas. Look through bitcasts and
10087   // GEPs to handle type coercions, as long as the alloca is fully initialized
10088   // by the store. Any non-store use of an alloca escapes it and any subsequent
10089   // unanalyzed store might write it.
10090   // FIXME: Handle structs initialized with multiple stores.
10091   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10092     // Look for stores, and handle non-store uses conservatively.
10093     const auto *SI = dyn_cast<StoreInst>(&I);
10094     if (!SI) {
10095       // We will look through cast uses, so ignore them completely.
10096       if (I.isCast())
10097         continue;
10098       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10099       // to allocas.
10100       if (I.isDebugOrPseudoInst())
10101         continue;
10102       // This is an unknown instruction. Assume it escapes or writes to all
10103       // static alloca operands.
10104       for (const Use &U : I.operands()) {
10105         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10106           *Info = StaticAllocaInfo::Clobbered;
10107       }
10108       continue;
10109     }
10110 
10111     // If the stored value is a static alloca, mark it as escaped.
10112     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10113       *Info = StaticAllocaInfo::Clobbered;
10114 
10115     // Check if the destination is a static alloca.
10116     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10117     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10118     if (!Info)
10119       continue;
10120     const AllocaInst *AI = cast<AllocaInst>(Dst);
10121 
10122     // Skip allocas that have been initialized or clobbered.
10123     if (*Info != StaticAllocaInfo::Unknown)
10124       continue;
10125 
10126     // Check if the stored value is an argument, and that this store fully
10127     // initializes the alloca.
10128     // If the argument type has padding bits we can't directly forward a pointer
10129     // as the upper bits may contain garbage.
10130     // Don't elide copies from the same argument twice.
10131     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10132     const auto *Arg = dyn_cast<Argument>(Val);
10133     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10134         Arg->getType()->isEmptyTy() ||
10135         DL.getTypeStoreSize(Arg->getType()) !=
10136             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10137         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10138         ArgCopyElisionCandidates.count(Arg)) {
10139       *Info = StaticAllocaInfo::Clobbered;
10140       continue;
10141     }
10142 
10143     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10144                       << '\n');
10145 
10146     // Mark this alloca and store for argument copy elision.
10147     *Info = StaticAllocaInfo::Elidable;
10148     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10149 
10150     // Stop scanning if we've seen all arguments. This will happen early in -O0
10151     // builds, which is useful, because -O0 builds have large entry blocks and
10152     // many allocas.
10153     if (ArgCopyElisionCandidates.size() == NumArgs)
10154       break;
10155   }
10156 }
10157 
10158 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10159 /// ArgVal is a load from a suitable fixed stack object.
10160 static void tryToElideArgumentCopy(
10161     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10162     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10163     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10164     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10165     SDValue ArgVal, bool &ArgHasUses) {
10166   // Check if this is a load from a fixed stack object.
10167   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10168   if (!LNode)
10169     return;
10170   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10171   if (!FINode)
10172     return;
10173 
10174   // Check that the fixed stack object is the right size and alignment.
10175   // Look at the alignment that the user wrote on the alloca instead of looking
10176   // at the stack object.
10177   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10178   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10179   const AllocaInst *AI = ArgCopyIter->second.first;
10180   int FixedIndex = FINode->getIndex();
10181   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10182   int OldIndex = AllocaIndex;
10183   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10184   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10185     LLVM_DEBUG(
10186         dbgs() << "  argument copy elision failed due to bad fixed stack "
10187                   "object size\n");
10188     return;
10189   }
10190   Align RequiredAlignment = AI->getAlign();
10191   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10192     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10193                          "greater than stack argument alignment ("
10194                       << DebugStr(RequiredAlignment) << " vs "
10195                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10196     return;
10197   }
10198 
10199   // Perform the elision. Delete the old stack object and replace its only use
10200   // in the variable info map. Mark the stack object as mutable.
10201   LLVM_DEBUG({
10202     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10203            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10204            << '\n';
10205   });
10206   MFI.RemoveStackObject(OldIndex);
10207   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10208   AllocaIndex = FixedIndex;
10209   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10210   Chains.push_back(ArgVal.getValue(1));
10211 
10212   // Avoid emitting code for the store implementing the copy.
10213   const StoreInst *SI = ArgCopyIter->second.second;
10214   ElidedArgCopyInstrs.insert(SI);
10215 
10216   // Check for uses of the argument again so that we can avoid exporting ArgVal
10217   // if it is't used by anything other than the store.
10218   for (const Value *U : Arg.users()) {
10219     if (U != SI) {
10220       ArgHasUses = true;
10221       break;
10222     }
10223   }
10224 }
10225 
10226 void SelectionDAGISel::LowerArguments(const Function &F) {
10227   SelectionDAG &DAG = SDB->DAG;
10228   SDLoc dl = SDB->getCurSDLoc();
10229   const DataLayout &DL = DAG.getDataLayout();
10230   SmallVector<ISD::InputArg, 16> Ins;
10231 
10232   // In Naked functions we aren't going to save any registers.
10233   if (F.hasFnAttribute(Attribute::Naked))
10234     return;
10235 
10236   if (!FuncInfo->CanLowerReturn) {
10237     // Put in an sret pointer parameter before all the other parameters.
10238     SmallVector<EVT, 1> ValueVTs;
10239     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10240                     F.getReturnType()->getPointerTo(
10241                         DAG.getDataLayout().getAllocaAddrSpace()),
10242                     ValueVTs);
10243 
10244     // NOTE: Assuming that a pointer will never break down to more than one VT
10245     // or one register.
10246     ISD::ArgFlagsTy Flags;
10247     Flags.setSRet();
10248     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10249     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10250                          ISD::InputArg::NoArgIndex, 0);
10251     Ins.push_back(RetArg);
10252   }
10253 
10254   // Look for stores of arguments to static allocas. Mark such arguments with a
10255   // flag to ask the target to give us the memory location of that argument if
10256   // available.
10257   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10258   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10259                                     ArgCopyElisionCandidates);
10260 
10261   // Set up the incoming argument description vector.
10262   for (const Argument &Arg : F.args()) {
10263     unsigned ArgNo = Arg.getArgNo();
10264     SmallVector<EVT, 4> ValueVTs;
10265     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10266     bool isArgValueUsed = !Arg.use_empty();
10267     unsigned PartBase = 0;
10268     Type *FinalType = Arg.getType();
10269     if (Arg.hasAttribute(Attribute::ByVal))
10270       FinalType = Arg.getParamByValType();
10271     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10272         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10273     for (unsigned Value = 0, NumValues = ValueVTs.size();
10274          Value != NumValues; ++Value) {
10275       EVT VT = ValueVTs[Value];
10276       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10277       ISD::ArgFlagsTy Flags;
10278 
10279 
10280       if (Arg.getType()->isPointerTy()) {
10281         Flags.setPointer();
10282         Flags.setPointerAddrSpace(
10283             cast<PointerType>(Arg.getType())->getAddressSpace());
10284       }
10285       if (Arg.hasAttribute(Attribute::ZExt))
10286         Flags.setZExt();
10287       if (Arg.hasAttribute(Attribute::SExt))
10288         Flags.setSExt();
10289       if (Arg.hasAttribute(Attribute::InReg)) {
10290         // If we are using vectorcall calling convention, a structure that is
10291         // passed InReg - is surely an HVA
10292         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10293             isa<StructType>(Arg.getType())) {
10294           // The first value of a structure is marked
10295           if (0 == Value)
10296             Flags.setHvaStart();
10297           Flags.setHva();
10298         }
10299         // Set InReg Flag
10300         Flags.setInReg();
10301       }
10302       if (Arg.hasAttribute(Attribute::StructRet))
10303         Flags.setSRet();
10304       if (Arg.hasAttribute(Attribute::SwiftSelf))
10305         Flags.setSwiftSelf();
10306       if (Arg.hasAttribute(Attribute::SwiftAsync))
10307         Flags.setSwiftAsync();
10308       if (Arg.hasAttribute(Attribute::SwiftError))
10309         Flags.setSwiftError();
10310       if (Arg.hasAttribute(Attribute::ByVal))
10311         Flags.setByVal();
10312       if (Arg.hasAttribute(Attribute::ByRef))
10313         Flags.setByRef();
10314       if (Arg.hasAttribute(Attribute::InAlloca)) {
10315         Flags.setInAlloca();
10316         // Set the byval flag for CCAssignFn callbacks that don't know about
10317         // inalloca.  This way we can know how many bytes we should've allocated
10318         // and how many bytes a callee cleanup function will pop.  If we port
10319         // inalloca to more targets, we'll have to add custom inalloca handling
10320         // in the various CC lowering callbacks.
10321         Flags.setByVal();
10322       }
10323       if (Arg.hasAttribute(Attribute::Preallocated)) {
10324         Flags.setPreallocated();
10325         // Set the byval flag for CCAssignFn callbacks that don't know about
10326         // preallocated.  This way we can know how many bytes we should've
10327         // allocated and how many bytes a callee cleanup function will pop.  If
10328         // we port preallocated to more targets, we'll have to add custom
10329         // preallocated handling in the various CC lowering callbacks.
10330         Flags.setByVal();
10331       }
10332 
10333       // Certain targets (such as MIPS), may have a different ABI alignment
10334       // for a type depending on the context. Give the target a chance to
10335       // specify the alignment it wants.
10336       const Align OriginalAlignment(
10337           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10338       Flags.setOrigAlign(OriginalAlignment);
10339 
10340       Align MemAlign;
10341       Type *ArgMemTy = nullptr;
10342       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10343           Flags.isByRef()) {
10344         if (!ArgMemTy)
10345           ArgMemTy = Arg.getPointeeInMemoryValueType();
10346 
10347         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10348 
10349         // For in-memory arguments, size and alignment should be passed from FE.
10350         // BE will guess if this info is not there but there are cases it cannot
10351         // get right.
10352         if (auto ParamAlign = Arg.getParamStackAlign())
10353           MemAlign = *ParamAlign;
10354         else if ((ParamAlign = Arg.getParamAlign()))
10355           MemAlign = *ParamAlign;
10356         else
10357           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10358         if (Flags.isByRef())
10359           Flags.setByRefSize(MemSize);
10360         else
10361           Flags.setByValSize(MemSize);
10362       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10363         MemAlign = *ParamAlign;
10364       } else {
10365         MemAlign = OriginalAlignment;
10366       }
10367       Flags.setMemAlign(MemAlign);
10368 
10369       if (Arg.hasAttribute(Attribute::Nest))
10370         Flags.setNest();
10371       if (NeedsRegBlock)
10372         Flags.setInConsecutiveRegs();
10373       if (ArgCopyElisionCandidates.count(&Arg))
10374         Flags.setCopyElisionCandidate();
10375       if (Arg.hasAttribute(Attribute::Returned))
10376         Flags.setReturned();
10377 
10378       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10379           *CurDAG->getContext(), F.getCallingConv(), VT);
10380       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10381           *CurDAG->getContext(), F.getCallingConv(), VT);
10382       for (unsigned i = 0; i != NumRegs; ++i) {
10383         // For scalable vectors, use the minimum size; individual targets
10384         // are responsible for handling scalable vector arguments and
10385         // return values.
10386         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10387                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10388         if (NumRegs > 1 && i == 0)
10389           MyFlags.Flags.setSplit();
10390         // if it isn't first piece, alignment must be 1
10391         else if (i > 0) {
10392           MyFlags.Flags.setOrigAlign(Align(1));
10393           if (i == NumRegs - 1)
10394             MyFlags.Flags.setSplitEnd();
10395         }
10396         Ins.push_back(MyFlags);
10397       }
10398       if (NeedsRegBlock && Value == NumValues - 1)
10399         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10400       PartBase += VT.getStoreSize().getKnownMinSize();
10401     }
10402   }
10403 
10404   // Call the target to set up the argument values.
10405   SmallVector<SDValue, 8> InVals;
10406   SDValue NewRoot = TLI->LowerFormalArguments(
10407       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10408 
10409   // Verify that the target's LowerFormalArguments behaved as expected.
10410   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10411          "LowerFormalArguments didn't return a valid chain!");
10412   assert(InVals.size() == Ins.size() &&
10413          "LowerFormalArguments didn't emit the correct number of values!");
10414   LLVM_DEBUG({
10415     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10416       assert(InVals[i].getNode() &&
10417              "LowerFormalArguments emitted a null value!");
10418       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10419              "LowerFormalArguments emitted a value with the wrong type!");
10420     }
10421   });
10422 
10423   // Update the DAG with the new chain value resulting from argument lowering.
10424   DAG.setRoot(NewRoot);
10425 
10426   // Set up the argument values.
10427   unsigned i = 0;
10428   if (!FuncInfo->CanLowerReturn) {
10429     // Create a virtual register for the sret pointer, and put in a copy
10430     // from the sret argument into it.
10431     SmallVector<EVT, 1> ValueVTs;
10432     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10433                     F.getReturnType()->getPointerTo(
10434                         DAG.getDataLayout().getAllocaAddrSpace()),
10435                     ValueVTs);
10436     MVT VT = ValueVTs[0].getSimpleVT();
10437     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10438     Optional<ISD::NodeType> AssertOp = None;
10439     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10440                                         nullptr, F.getCallingConv(), AssertOp);
10441 
10442     MachineFunction& MF = SDB->DAG.getMachineFunction();
10443     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10444     Register SRetReg =
10445         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10446     FuncInfo->DemoteRegister = SRetReg;
10447     NewRoot =
10448         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10449     DAG.setRoot(NewRoot);
10450 
10451     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10452     ++i;
10453   }
10454 
10455   SmallVector<SDValue, 4> Chains;
10456   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10457   for (const Argument &Arg : F.args()) {
10458     SmallVector<SDValue, 4> ArgValues;
10459     SmallVector<EVT, 4> ValueVTs;
10460     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10461     unsigned NumValues = ValueVTs.size();
10462     if (NumValues == 0)
10463       continue;
10464 
10465     bool ArgHasUses = !Arg.use_empty();
10466 
10467     // Elide the copying store if the target loaded this argument from a
10468     // suitable fixed stack object.
10469     if (Ins[i].Flags.isCopyElisionCandidate()) {
10470       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10471                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10472                              InVals[i], ArgHasUses);
10473     }
10474 
10475     // If this argument is unused then remember its value. It is used to generate
10476     // debugging information.
10477     bool isSwiftErrorArg =
10478         TLI->supportSwiftError() &&
10479         Arg.hasAttribute(Attribute::SwiftError);
10480     if (!ArgHasUses && !isSwiftErrorArg) {
10481       SDB->setUnusedArgValue(&Arg, InVals[i]);
10482 
10483       // Also remember any frame index for use in FastISel.
10484       if (FrameIndexSDNode *FI =
10485           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10486         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10487     }
10488 
10489     for (unsigned Val = 0; Val != NumValues; ++Val) {
10490       EVT VT = ValueVTs[Val];
10491       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10492                                                       F.getCallingConv(), VT);
10493       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10494           *CurDAG->getContext(), F.getCallingConv(), VT);
10495 
10496       // Even an apparent 'unused' swifterror argument needs to be returned. So
10497       // we do generate a copy for it that can be used on return from the
10498       // function.
10499       if (ArgHasUses || isSwiftErrorArg) {
10500         Optional<ISD::NodeType> AssertOp;
10501         if (Arg.hasAttribute(Attribute::SExt))
10502           AssertOp = ISD::AssertSext;
10503         else if (Arg.hasAttribute(Attribute::ZExt))
10504           AssertOp = ISD::AssertZext;
10505 
10506         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10507                                              PartVT, VT, nullptr,
10508                                              F.getCallingConv(), AssertOp));
10509       }
10510 
10511       i += NumParts;
10512     }
10513 
10514     // We don't need to do anything else for unused arguments.
10515     if (ArgValues.empty())
10516       continue;
10517 
10518     // Note down frame index.
10519     if (FrameIndexSDNode *FI =
10520         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10521       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10522 
10523     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10524                                      SDB->getCurSDLoc());
10525 
10526     SDB->setValue(&Arg, Res);
10527     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10528       // We want to associate the argument with the frame index, among
10529       // involved operands, that correspond to the lowest address. The
10530       // getCopyFromParts function, called earlier, is swapping the order of
10531       // the operands to BUILD_PAIR depending on endianness. The result of
10532       // that swapping is that the least significant bits of the argument will
10533       // be in the first operand of the BUILD_PAIR node, and the most
10534       // significant bits will be in the second operand.
10535       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10536       if (LoadSDNode *LNode =
10537           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10538         if (FrameIndexSDNode *FI =
10539             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10540           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10541     }
10542 
10543     // Analyses past this point are naive and don't expect an assertion.
10544     if (Res.getOpcode() == ISD::AssertZext)
10545       Res = Res.getOperand(0);
10546 
10547     // Update the SwiftErrorVRegDefMap.
10548     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10549       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10550       if (Register::isVirtualRegister(Reg))
10551         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10552                                    Reg);
10553     }
10554 
10555     // If this argument is live outside of the entry block, insert a copy from
10556     // wherever we got it to the vreg that other BB's will reference it as.
10557     if (Res.getOpcode() == ISD::CopyFromReg) {
10558       // If we can, though, try to skip creating an unnecessary vreg.
10559       // FIXME: This isn't very clean... it would be nice to make this more
10560       // general.
10561       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10562       if (Register::isVirtualRegister(Reg)) {
10563         FuncInfo->ValueMap[&Arg] = Reg;
10564         continue;
10565       }
10566     }
10567     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10568       FuncInfo->InitializeRegForValue(&Arg);
10569       SDB->CopyToExportRegsIfNeeded(&Arg);
10570     }
10571   }
10572 
10573   if (!Chains.empty()) {
10574     Chains.push_back(NewRoot);
10575     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10576   }
10577 
10578   DAG.setRoot(NewRoot);
10579 
10580   assert(i == InVals.size() && "Argument register count mismatch!");
10581 
10582   // If any argument copy elisions occurred and we have debug info, update the
10583   // stale frame indices used in the dbg.declare variable info table.
10584   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10585   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10586     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10587       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10588       if (I != ArgCopyElisionFrameIndexMap.end())
10589         VI.Slot = I->second;
10590     }
10591   }
10592 
10593   // Finally, if the target has anything special to do, allow it to do so.
10594   emitFunctionEntryCode();
10595 }
10596 
10597 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10598 /// ensure constants are generated when needed.  Remember the virtual registers
10599 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10600 /// directly add them, because expansion might result in multiple MBB's for one
10601 /// BB.  As such, the start of the BB might correspond to a different MBB than
10602 /// the end.
10603 void
10604 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10605   const Instruction *TI = LLVMBB->getTerminator();
10606 
10607   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10608 
10609   // Check PHI nodes in successors that expect a value to be available from this
10610   // block.
10611   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10612     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10613     if (!isa<PHINode>(SuccBB->begin())) continue;
10614     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10615 
10616     // If this terminator has multiple identical successors (common for
10617     // switches), only handle each succ once.
10618     if (!SuccsHandled.insert(SuccMBB).second)
10619       continue;
10620 
10621     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10622 
10623     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10624     // nodes and Machine PHI nodes, but the incoming operands have not been
10625     // emitted yet.
10626     for (const PHINode &PN : SuccBB->phis()) {
10627       // Ignore dead phi's.
10628       if (PN.use_empty())
10629         continue;
10630 
10631       // Skip empty types
10632       if (PN.getType()->isEmptyTy())
10633         continue;
10634 
10635       unsigned Reg;
10636       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10637 
10638       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10639         unsigned &RegOut = ConstantsOut[C];
10640         if (RegOut == 0) {
10641           RegOut = FuncInfo.CreateRegs(C);
10642           // We need to zero extend ConstantInt phi operands to match
10643           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
10644           ISD::NodeType ExtendType =
10645               isa<ConstantInt>(PHIOp) ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND;
10646           CopyValueToVirtualRegister(C, RegOut, ExtendType);
10647         }
10648         Reg = RegOut;
10649       } else {
10650         DenseMap<const Value *, Register>::iterator I =
10651           FuncInfo.ValueMap.find(PHIOp);
10652         if (I != FuncInfo.ValueMap.end())
10653           Reg = I->second;
10654         else {
10655           assert(isa<AllocaInst>(PHIOp) &&
10656                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10657                  "Didn't codegen value into a register!??");
10658           Reg = FuncInfo.CreateRegs(PHIOp);
10659           CopyValueToVirtualRegister(PHIOp, Reg);
10660         }
10661       }
10662 
10663       // Remember that this register needs to added to the machine PHI node as
10664       // the input for this MBB.
10665       SmallVector<EVT, 4> ValueVTs;
10666       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10667       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10668       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10669         EVT VT = ValueVTs[vti];
10670         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10671         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10672           FuncInfo.PHINodesToUpdate.push_back(
10673               std::make_pair(&*MBBI++, Reg + i));
10674         Reg += NumRegisters;
10675       }
10676     }
10677   }
10678 
10679   ConstantsOut.clear();
10680 }
10681 
10682 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10683   MachineFunction::iterator I(MBB);
10684   if (++I == FuncInfo.MF->end())
10685     return nullptr;
10686   return &*I;
10687 }
10688 
10689 /// During lowering new call nodes can be created (such as memset, etc.).
10690 /// Those will become new roots of the current DAG, but complications arise
10691 /// when they are tail calls. In such cases, the call lowering will update
10692 /// the root, but the builder still needs to know that a tail call has been
10693 /// lowered in order to avoid generating an additional return.
10694 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10695   // If the node is null, we do have a tail call.
10696   if (MaybeTC.getNode() != nullptr)
10697     DAG.setRoot(MaybeTC);
10698   else
10699     HasTailCall = true;
10700 }
10701 
10702 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10703                                         MachineBasicBlock *SwitchMBB,
10704                                         MachineBasicBlock *DefaultMBB) {
10705   MachineFunction *CurMF = FuncInfo.MF;
10706   MachineBasicBlock *NextMBB = nullptr;
10707   MachineFunction::iterator BBI(W.MBB);
10708   if (++BBI != FuncInfo.MF->end())
10709     NextMBB = &*BBI;
10710 
10711   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10712 
10713   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10714 
10715   if (Size == 2 && W.MBB == SwitchMBB) {
10716     // If any two of the cases has the same destination, and if one value
10717     // is the same as the other, but has one bit unset that the other has set,
10718     // use bit manipulation to do two compares at once.  For example:
10719     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10720     // TODO: This could be extended to merge any 2 cases in switches with 3
10721     // cases.
10722     // TODO: Handle cases where W.CaseBB != SwitchBB.
10723     CaseCluster &Small = *W.FirstCluster;
10724     CaseCluster &Big = *W.LastCluster;
10725 
10726     if (Small.Low == Small.High && Big.Low == Big.High &&
10727         Small.MBB == Big.MBB) {
10728       const APInt &SmallValue = Small.Low->getValue();
10729       const APInt &BigValue = Big.Low->getValue();
10730 
10731       // Check that there is only one bit different.
10732       APInt CommonBit = BigValue ^ SmallValue;
10733       if (CommonBit.isPowerOf2()) {
10734         SDValue CondLHS = getValue(Cond);
10735         EVT VT = CondLHS.getValueType();
10736         SDLoc DL = getCurSDLoc();
10737 
10738         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10739                                  DAG.getConstant(CommonBit, DL, VT));
10740         SDValue Cond = DAG.getSetCC(
10741             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10742             ISD::SETEQ);
10743 
10744         // Update successor info.
10745         // Both Small and Big will jump to Small.BB, so we sum up the
10746         // probabilities.
10747         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10748         if (BPI)
10749           addSuccessorWithProb(
10750               SwitchMBB, DefaultMBB,
10751               // The default destination is the first successor in IR.
10752               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10753         else
10754           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10755 
10756         // Insert the true branch.
10757         SDValue BrCond =
10758             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10759                         DAG.getBasicBlock(Small.MBB));
10760         // Insert the false branch.
10761         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10762                              DAG.getBasicBlock(DefaultMBB));
10763 
10764         DAG.setRoot(BrCond);
10765         return;
10766       }
10767     }
10768   }
10769 
10770   if (TM.getOptLevel() != CodeGenOpt::None) {
10771     // Here, we order cases by probability so the most likely case will be
10772     // checked first. However, two clusters can have the same probability in
10773     // which case their relative ordering is non-deterministic. So we use Low
10774     // as a tie-breaker as clusters are guaranteed to never overlap.
10775     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10776                [](const CaseCluster &a, const CaseCluster &b) {
10777       return a.Prob != b.Prob ?
10778              a.Prob > b.Prob :
10779              a.Low->getValue().slt(b.Low->getValue());
10780     });
10781 
10782     // Rearrange the case blocks so that the last one falls through if possible
10783     // without changing the order of probabilities.
10784     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10785       --I;
10786       if (I->Prob > W.LastCluster->Prob)
10787         break;
10788       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10789         std::swap(*I, *W.LastCluster);
10790         break;
10791       }
10792     }
10793   }
10794 
10795   // Compute total probability.
10796   BranchProbability DefaultProb = W.DefaultProb;
10797   BranchProbability UnhandledProbs = DefaultProb;
10798   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10799     UnhandledProbs += I->Prob;
10800 
10801   MachineBasicBlock *CurMBB = W.MBB;
10802   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10803     bool FallthroughUnreachable = false;
10804     MachineBasicBlock *Fallthrough;
10805     if (I == W.LastCluster) {
10806       // For the last cluster, fall through to the default destination.
10807       Fallthrough = DefaultMBB;
10808       FallthroughUnreachable = isa<UnreachableInst>(
10809           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10810     } else {
10811       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10812       CurMF->insert(BBI, Fallthrough);
10813       // Put Cond in a virtual register to make it available from the new blocks.
10814       ExportFromCurrentBlock(Cond);
10815     }
10816     UnhandledProbs -= I->Prob;
10817 
10818     switch (I->Kind) {
10819       case CC_JumpTable: {
10820         // FIXME: Optimize away range check based on pivot comparisons.
10821         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10822         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10823 
10824         // The jump block hasn't been inserted yet; insert it here.
10825         MachineBasicBlock *JumpMBB = JT->MBB;
10826         CurMF->insert(BBI, JumpMBB);
10827 
10828         auto JumpProb = I->Prob;
10829         auto FallthroughProb = UnhandledProbs;
10830 
10831         // If the default statement is a target of the jump table, we evenly
10832         // distribute the default probability to successors of CurMBB. Also
10833         // update the probability on the edge from JumpMBB to Fallthrough.
10834         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10835                                               SE = JumpMBB->succ_end();
10836              SI != SE; ++SI) {
10837           if (*SI == DefaultMBB) {
10838             JumpProb += DefaultProb / 2;
10839             FallthroughProb -= DefaultProb / 2;
10840             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10841             JumpMBB->normalizeSuccProbs();
10842             break;
10843           }
10844         }
10845 
10846         if (FallthroughUnreachable)
10847           JTH->FallthroughUnreachable = true;
10848 
10849         if (!JTH->FallthroughUnreachable)
10850           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10851         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10852         CurMBB->normalizeSuccProbs();
10853 
10854         // The jump table header will be inserted in our current block, do the
10855         // range check, and fall through to our fallthrough block.
10856         JTH->HeaderBB = CurMBB;
10857         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10858 
10859         // If we're in the right place, emit the jump table header right now.
10860         if (CurMBB == SwitchMBB) {
10861           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10862           JTH->Emitted = true;
10863         }
10864         break;
10865       }
10866       case CC_BitTests: {
10867         // FIXME: Optimize away range check based on pivot comparisons.
10868         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10869 
10870         // The bit test blocks haven't been inserted yet; insert them here.
10871         for (BitTestCase &BTC : BTB->Cases)
10872           CurMF->insert(BBI, BTC.ThisBB);
10873 
10874         // Fill in fields of the BitTestBlock.
10875         BTB->Parent = CurMBB;
10876         BTB->Default = Fallthrough;
10877 
10878         BTB->DefaultProb = UnhandledProbs;
10879         // If the cases in bit test don't form a contiguous range, we evenly
10880         // distribute the probability on the edge to Fallthrough to two
10881         // successors of CurMBB.
10882         if (!BTB->ContiguousRange) {
10883           BTB->Prob += DefaultProb / 2;
10884           BTB->DefaultProb -= DefaultProb / 2;
10885         }
10886 
10887         if (FallthroughUnreachable)
10888           BTB->FallthroughUnreachable = true;
10889 
10890         // If we're in the right place, emit the bit test header right now.
10891         if (CurMBB == SwitchMBB) {
10892           visitBitTestHeader(*BTB, SwitchMBB);
10893           BTB->Emitted = true;
10894         }
10895         break;
10896       }
10897       case CC_Range: {
10898         const Value *RHS, *LHS, *MHS;
10899         ISD::CondCode CC;
10900         if (I->Low == I->High) {
10901           // Check Cond == I->Low.
10902           CC = ISD::SETEQ;
10903           LHS = Cond;
10904           RHS=I->Low;
10905           MHS = nullptr;
10906         } else {
10907           // Check I->Low <= Cond <= I->High.
10908           CC = ISD::SETLE;
10909           LHS = I->Low;
10910           MHS = Cond;
10911           RHS = I->High;
10912         }
10913 
10914         // If Fallthrough is unreachable, fold away the comparison.
10915         if (FallthroughUnreachable)
10916           CC = ISD::SETTRUE;
10917 
10918         // The false probability is the sum of all unhandled cases.
10919         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10920                      getCurSDLoc(), I->Prob, UnhandledProbs);
10921 
10922         if (CurMBB == SwitchMBB)
10923           visitSwitchCase(CB, SwitchMBB);
10924         else
10925           SL->SwitchCases.push_back(CB);
10926 
10927         break;
10928       }
10929     }
10930     CurMBB = Fallthrough;
10931   }
10932 }
10933 
10934 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10935                                               CaseClusterIt First,
10936                                               CaseClusterIt Last) {
10937   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10938     if (X.Prob != CC.Prob)
10939       return X.Prob > CC.Prob;
10940 
10941     // Ties are broken by comparing the case value.
10942     return X.Low->getValue().slt(CC.Low->getValue());
10943   });
10944 }
10945 
10946 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10947                                         const SwitchWorkListItem &W,
10948                                         Value *Cond,
10949                                         MachineBasicBlock *SwitchMBB) {
10950   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10951          "Clusters not sorted?");
10952 
10953   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10954 
10955   // Balance the tree based on branch probabilities to create a near-optimal (in
10956   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10957   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10958   CaseClusterIt LastLeft = W.FirstCluster;
10959   CaseClusterIt FirstRight = W.LastCluster;
10960   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10961   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10962 
10963   // Move LastLeft and FirstRight towards each other from opposite directions to
10964   // find a partitioning of the clusters which balances the probability on both
10965   // sides. If LeftProb and RightProb are equal, alternate which side is
10966   // taken to ensure 0-probability nodes are distributed evenly.
10967   unsigned I = 0;
10968   while (LastLeft + 1 < FirstRight) {
10969     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10970       LeftProb += (++LastLeft)->Prob;
10971     else
10972       RightProb += (--FirstRight)->Prob;
10973     I++;
10974   }
10975 
10976   while (true) {
10977     // Our binary search tree differs from a typical BST in that ours can have up
10978     // to three values in each leaf. The pivot selection above doesn't take that
10979     // into account, which means the tree might require more nodes and be less
10980     // efficient. We compensate for this here.
10981 
10982     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10983     unsigned NumRight = W.LastCluster - FirstRight + 1;
10984 
10985     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10986       // If one side has less than 3 clusters, and the other has more than 3,
10987       // consider taking a cluster from the other side.
10988 
10989       if (NumLeft < NumRight) {
10990         // Consider moving the first cluster on the right to the left side.
10991         CaseCluster &CC = *FirstRight;
10992         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10993         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10994         if (LeftSideRank <= RightSideRank) {
10995           // Moving the cluster to the left does not demote it.
10996           ++LastLeft;
10997           ++FirstRight;
10998           continue;
10999         }
11000       } else {
11001         assert(NumRight < NumLeft);
11002         // Consider moving the last element on the left to the right side.
11003         CaseCluster &CC = *LastLeft;
11004         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11005         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11006         if (RightSideRank <= LeftSideRank) {
11007           // Moving the cluster to the right does not demot it.
11008           --LastLeft;
11009           --FirstRight;
11010           continue;
11011         }
11012       }
11013     }
11014     break;
11015   }
11016 
11017   assert(LastLeft + 1 == FirstRight);
11018   assert(LastLeft >= W.FirstCluster);
11019   assert(FirstRight <= W.LastCluster);
11020 
11021   // Use the first element on the right as pivot since we will make less-than
11022   // comparisons against it.
11023   CaseClusterIt PivotCluster = FirstRight;
11024   assert(PivotCluster > W.FirstCluster);
11025   assert(PivotCluster <= W.LastCluster);
11026 
11027   CaseClusterIt FirstLeft = W.FirstCluster;
11028   CaseClusterIt LastRight = W.LastCluster;
11029 
11030   const ConstantInt *Pivot = PivotCluster->Low;
11031 
11032   // New blocks will be inserted immediately after the current one.
11033   MachineFunction::iterator BBI(W.MBB);
11034   ++BBI;
11035 
11036   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11037   // we can branch to its destination directly if it's squeezed exactly in
11038   // between the known lower bound and Pivot - 1.
11039   MachineBasicBlock *LeftMBB;
11040   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11041       FirstLeft->Low == W.GE &&
11042       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11043     LeftMBB = FirstLeft->MBB;
11044   } else {
11045     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11046     FuncInfo.MF->insert(BBI, LeftMBB);
11047     WorkList.push_back(
11048         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11049     // Put Cond in a virtual register to make it available from the new blocks.
11050     ExportFromCurrentBlock(Cond);
11051   }
11052 
11053   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11054   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11055   // directly if RHS.High equals the current upper bound.
11056   MachineBasicBlock *RightMBB;
11057   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11058       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11059     RightMBB = FirstRight->MBB;
11060   } else {
11061     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11062     FuncInfo.MF->insert(BBI, RightMBB);
11063     WorkList.push_back(
11064         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11065     // Put Cond in a virtual register to make it available from the new blocks.
11066     ExportFromCurrentBlock(Cond);
11067   }
11068 
11069   // Create the CaseBlock record that will be used to lower the branch.
11070   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11071                getCurSDLoc(), LeftProb, RightProb);
11072 
11073   if (W.MBB == SwitchMBB)
11074     visitSwitchCase(CB, SwitchMBB);
11075   else
11076     SL->SwitchCases.push_back(CB);
11077 }
11078 
11079 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11080 // from the swith statement.
11081 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11082                                             BranchProbability PeeledCaseProb) {
11083   if (PeeledCaseProb == BranchProbability::getOne())
11084     return BranchProbability::getZero();
11085   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11086 
11087   uint32_t Numerator = CaseProb.getNumerator();
11088   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11089   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11090 }
11091 
11092 // Try to peel the top probability case if it exceeds the threshold.
11093 // Return current MachineBasicBlock for the switch statement if the peeling
11094 // does not occur.
11095 // If the peeling is performed, return the newly created MachineBasicBlock
11096 // for the peeled switch statement. Also update Clusters to remove the peeled
11097 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11098 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11099     const SwitchInst &SI, CaseClusterVector &Clusters,
11100     BranchProbability &PeeledCaseProb) {
11101   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11102   // Don't perform if there is only one cluster or optimizing for size.
11103   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11104       TM.getOptLevel() == CodeGenOpt::None ||
11105       SwitchMBB->getParent()->getFunction().hasMinSize())
11106     return SwitchMBB;
11107 
11108   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11109   unsigned PeeledCaseIndex = 0;
11110   bool SwitchPeeled = false;
11111   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11112     CaseCluster &CC = Clusters[Index];
11113     if (CC.Prob < TopCaseProb)
11114       continue;
11115     TopCaseProb = CC.Prob;
11116     PeeledCaseIndex = Index;
11117     SwitchPeeled = true;
11118   }
11119   if (!SwitchPeeled)
11120     return SwitchMBB;
11121 
11122   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11123                     << TopCaseProb << "\n");
11124 
11125   // Record the MBB for the peeled switch statement.
11126   MachineFunction::iterator BBI(SwitchMBB);
11127   ++BBI;
11128   MachineBasicBlock *PeeledSwitchMBB =
11129       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11130   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11131 
11132   ExportFromCurrentBlock(SI.getCondition());
11133   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11134   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11135                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11136   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11137 
11138   Clusters.erase(PeeledCaseIt);
11139   for (CaseCluster &CC : Clusters) {
11140     LLVM_DEBUG(
11141         dbgs() << "Scale the probablity for one cluster, before scaling: "
11142                << CC.Prob << "\n");
11143     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11144     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11145   }
11146   PeeledCaseProb = TopCaseProb;
11147   return PeeledSwitchMBB;
11148 }
11149 
11150 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11151   // Extract cases from the switch.
11152   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11153   CaseClusterVector Clusters;
11154   Clusters.reserve(SI.getNumCases());
11155   for (auto I : SI.cases()) {
11156     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11157     const ConstantInt *CaseVal = I.getCaseValue();
11158     BranchProbability Prob =
11159         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11160             : BranchProbability(1, SI.getNumCases() + 1);
11161     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11162   }
11163 
11164   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11165 
11166   // Cluster adjacent cases with the same destination. We do this at all
11167   // optimization levels because it's cheap to do and will make codegen faster
11168   // if there are many clusters.
11169   sortAndRangeify(Clusters);
11170 
11171   // The branch probablity of the peeled case.
11172   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11173   MachineBasicBlock *PeeledSwitchMBB =
11174       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11175 
11176   // If there is only the default destination, jump there directly.
11177   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11178   if (Clusters.empty()) {
11179     assert(PeeledSwitchMBB == SwitchMBB);
11180     SwitchMBB->addSuccessor(DefaultMBB);
11181     if (DefaultMBB != NextBlock(SwitchMBB)) {
11182       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11183                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11184     }
11185     return;
11186   }
11187 
11188   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11189   SL->findBitTestClusters(Clusters, &SI);
11190 
11191   LLVM_DEBUG({
11192     dbgs() << "Case clusters: ";
11193     for (const CaseCluster &C : Clusters) {
11194       if (C.Kind == CC_JumpTable)
11195         dbgs() << "JT:";
11196       if (C.Kind == CC_BitTests)
11197         dbgs() << "BT:";
11198 
11199       C.Low->getValue().print(dbgs(), true);
11200       if (C.Low != C.High) {
11201         dbgs() << '-';
11202         C.High->getValue().print(dbgs(), true);
11203       }
11204       dbgs() << ' ';
11205     }
11206     dbgs() << '\n';
11207   });
11208 
11209   assert(!Clusters.empty());
11210   SwitchWorkList WorkList;
11211   CaseClusterIt First = Clusters.begin();
11212   CaseClusterIt Last = Clusters.end() - 1;
11213   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11214   // Scale the branchprobability for DefaultMBB if the peel occurs and
11215   // DefaultMBB is not replaced.
11216   if (PeeledCaseProb != BranchProbability::getZero() &&
11217       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11218     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11219   WorkList.push_back(
11220       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11221 
11222   while (!WorkList.empty()) {
11223     SwitchWorkListItem W = WorkList.pop_back_val();
11224     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11225 
11226     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11227         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11228       // For optimized builds, lower large range as a balanced binary tree.
11229       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11230       continue;
11231     }
11232 
11233     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11234   }
11235 }
11236 
11237 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11238   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11239   auto DL = getCurSDLoc();
11240   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11241   setValue(&I, DAG.getStepVector(DL, ResultVT));
11242 }
11243 
11244 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11245   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11246   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11247 
11248   SDLoc DL = getCurSDLoc();
11249   SDValue V = getValue(I.getOperand(0));
11250   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11251 
11252   if (VT.isScalableVector()) {
11253     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11254     return;
11255   }
11256 
11257   // Use VECTOR_SHUFFLE for the fixed-length vector
11258   // to maintain existing behavior.
11259   SmallVector<int, 8> Mask;
11260   unsigned NumElts = VT.getVectorMinNumElements();
11261   for (unsigned i = 0; i != NumElts; ++i)
11262     Mask.push_back(NumElts - 1 - i);
11263 
11264   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11265 }
11266 
11267 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11268   SmallVector<EVT, 4> ValueVTs;
11269   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11270                   ValueVTs);
11271   unsigned NumValues = ValueVTs.size();
11272   if (NumValues == 0) return;
11273 
11274   SmallVector<SDValue, 4> Values(NumValues);
11275   SDValue Op = getValue(I.getOperand(0));
11276 
11277   for (unsigned i = 0; i != NumValues; ++i)
11278     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11279                             SDValue(Op.getNode(), Op.getResNo() + i));
11280 
11281   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11282                            DAG.getVTList(ValueVTs), Values));
11283 }
11284 
11285 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11286   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11287   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11288 
11289   SDLoc DL = getCurSDLoc();
11290   SDValue V1 = getValue(I.getOperand(0));
11291   SDValue V2 = getValue(I.getOperand(1));
11292   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11293 
11294   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11295   if (VT.isScalableVector()) {
11296     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11297     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11298                              DAG.getConstant(Imm, DL, IdxVT)));
11299     return;
11300   }
11301 
11302   unsigned NumElts = VT.getVectorNumElements();
11303 
11304   uint64_t Idx = (NumElts + Imm) % NumElts;
11305 
11306   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11307   SmallVector<int, 8> Mask;
11308   for (unsigned i = 0; i < NumElts; ++i)
11309     Mask.push_back(Idx + i);
11310   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11311 }
11312