xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision b1e68f885b550cf006f5d84b43aa3a0b2905d4b3)
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/BlockFrequencyInfo.h"
27 #include "llvm/Analysis/BranchProbabilityInfo.h"
28 #include "llvm/Analysis/ConstantFolding.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/Analysis/Loads.h"
31 #include "llvm/Analysis/MemoryLocation.h"
32 #include "llvm/Analysis/ProfileSummaryInfo.h"
33 #include "llvm/Analysis/TargetLibraryInfo.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/Analysis/VectorUtils.h"
36 #include "llvm/CodeGen/Analysis.h"
37 #include "llvm/CodeGen/FunctionLoweringInfo.h"
38 #include "llvm/CodeGen/GCMetadata.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineJumpTableInfo.h"
45 #include "llvm/CodeGen/MachineMemOperand.h"
46 #include "llvm/CodeGen/MachineModuleInfo.h"
47 #include "llvm/CodeGen/MachineOperand.h"
48 #include "llvm/CodeGen/MachineRegisterInfo.h"
49 #include "llvm/CodeGen/RuntimeLibcalls.h"
50 #include "llvm/CodeGen/SelectionDAG.h"
51 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
52 #include "llvm/CodeGen/StackMaps.h"
53 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
54 #include "llvm/CodeGen/TargetFrameLowering.h"
55 #include "llvm/CodeGen/TargetInstrInfo.h"
56 #include "llvm/CodeGen/TargetOpcodes.h"
57 #include "llvm/CodeGen/TargetRegisterInfo.h"
58 #include "llvm/CodeGen/TargetSubtargetInfo.h"
59 #include "llvm/CodeGen/WinEHFuncInfo.h"
60 #include "llvm/IR/Argument.h"
61 #include "llvm/IR/Attributes.h"
62 #include "llvm/IR/BasicBlock.h"
63 #include "llvm/IR/CFG.h"
64 #include "llvm/IR/CallingConv.h"
65 #include "llvm/IR/Constant.h"
66 #include "llvm/IR/ConstantRange.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugInfoMetadata.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GetElementPtrTypeIterator.h"
73 #include "llvm/IR/InlineAsm.h"
74 #include "llvm/IR/InstrTypes.h"
75 #include "llvm/IR/Instructions.h"
76 #include "llvm/IR/IntrinsicInst.h"
77 #include "llvm/IR/Intrinsics.h"
78 #include "llvm/IR/IntrinsicsAArch64.h"
79 #include "llvm/IR/IntrinsicsWebAssembly.h"
80 #include "llvm/IR/LLVMContext.h"
81 #include "llvm/IR/Metadata.h"
82 #include "llvm/IR/Module.h"
83 #include "llvm/IR/Operator.h"
84 #include "llvm/IR/PatternMatch.h"
85 #include "llvm/IR/Type.h"
86 #include "llvm/IR/User.h"
87 #include "llvm/IR/Value.h"
88 #include "llvm/MC/MCContext.h"
89 #include "llvm/MC/MCSymbol.h"
90 #include "llvm/Support/AtomicOrdering.h"
91 #include "llvm/Support/Casting.h"
92 #include "llvm/Support/CommandLine.h"
93 #include "llvm/Support/Compiler.h"
94 #include "llvm/Support/Debug.h"
95 #include "llvm/Support/MathExtras.h"
96 #include "llvm/Support/raw_ostream.h"
97 #include "llvm/Target/TargetIntrinsicInfo.h"
98 #include "llvm/Target/TargetMachine.h"
99 #include "llvm/Target/TargetOptions.h"
100 #include "llvm/Transforms/Utils/Local.h"
101 #include <cstddef>
102 #include <cstring>
103 #include <iterator>
104 #include <limits>
105 #include <numeric>
106 #include <tuple>
107 
108 using namespace llvm;
109 using namespace PatternMatch;
110 using namespace SwitchCG;
111 
112 #define DEBUG_TYPE "isel"
113 
114 /// LimitFloatPrecision - Generate low-precision inline sequences for
115 /// some float libcalls (6, 8 or 12 bits).
116 static unsigned LimitFloatPrecision;
117 
118 static cl::opt<bool>
119     InsertAssertAlign("insert-assert-align", cl::init(true),
120                       cl::desc("Insert the experimental `assertalign` node."),
121                       cl::ReallyHidden);
122 
123 static cl::opt<unsigned, true>
124     LimitFPPrecision("limit-float-precision",
125                      cl::desc("Generate low-precision inline sequences "
126                               "for some float libcalls"),
127                      cl::location(LimitFloatPrecision), cl::Hidden,
128                      cl::init(0));
129 
130 static cl::opt<unsigned> SwitchPeelThreshold(
131     "switch-peel-threshold", cl::Hidden, cl::init(66),
132     cl::desc("Set the case probability threshold for peeling the case from a "
133              "switch statement. A value greater than 100 will void this "
134              "optimization"));
135 
136 // Limit the width of DAG chains. This is important in general to prevent
137 // DAG-based analysis from blowing up. For example, alias analysis and
138 // load clustering may not complete in reasonable time. It is difficult to
139 // recognize and avoid this situation within each individual analysis, and
140 // future analyses are likely to have the same behavior. Limiting DAG width is
141 // the safe approach and will be especially important with global DAGs.
142 //
143 // MaxParallelChains default is arbitrarily high to avoid affecting
144 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
145 // sequence over this should have been converted to llvm.memcpy by the
146 // frontend. It is easy to induce this behavior with .ll code such as:
147 // %buffer = alloca [4096 x i8]
148 // %data = load [4096 x i8]* %argPtr
149 // store [4096 x i8] %data, [4096 x i8]* %buffer
150 static const unsigned MaxParallelChains = 64;
151 
152 // Return the calling convention if the Value passed requires ABI mangling as it
153 // is a parameter to a function or a return value from a function which is not
154 // an intrinsic.
155 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
156   if (auto *R = dyn_cast<ReturnInst>(V))
157     return R->getParent()->getParent()->getCallingConv();
158 
159   if (auto *CI = dyn_cast<CallInst>(V)) {
160     const bool IsInlineAsm = CI->isInlineAsm();
161     const bool IsIndirectFunctionCall =
162         !IsInlineAsm && !CI->getCalledFunction();
163 
164     // It is possible that the call instruction is an inline asm statement or an
165     // indirect function call in which case the return value of
166     // getCalledFunction() would be nullptr.
167     const bool IsInstrinsicCall =
168         !IsInlineAsm && !IsIndirectFunctionCall &&
169         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
170 
171     if (!IsInlineAsm && !IsInstrinsicCall)
172       return CI->getCallingConv();
173   }
174 
175   return None;
176 }
177 
178 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
179                                       const SDValue *Parts, unsigned NumParts,
180                                       MVT PartVT, EVT ValueVT, const Value *V,
181                                       Optional<CallingConv::ID> CC);
182 
183 /// getCopyFromParts - Create a value that contains the specified legal parts
184 /// combined into the value they represent.  If the parts combine to a type
185 /// larger than ValueVT then AssertOp can be used to specify whether the extra
186 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
187 /// (ISD::AssertSext).
188 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
189                                 const SDValue *Parts, unsigned NumParts,
190                                 MVT PartVT, EVT ValueVT, const Value *V,
191                                 Optional<CallingConv::ID> CC = None,
192                                 Optional<ISD::NodeType> AssertOp = None) {
193   // Let the target assemble the parts if it wants to
194   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
195   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
196                                                    PartVT, ValueVT, CC))
197     return Val;
198 
199   if (ValueVT.isVector())
200     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
201                                   CC);
202 
203   assert(NumParts > 0 && "No parts to assemble!");
204   SDValue Val = Parts[0];
205 
206   if (NumParts > 1) {
207     // Assemble the value from multiple parts.
208     if (ValueVT.isInteger()) {
209       unsigned PartBits = PartVT.getSizeInBits();
210       unsigned ValueBits = ValueVT.getSizeInBits();
211 
212       // Assemble the power of 2 part.
213       unsigned RoundParts =
214           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
215       unsigned RoundBits = PartBits * RoundParts;
216       EVT RoundVT = RoundBits == ValueBits ?
217         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
218       SDValue Lo, Hi;
219 
220       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
221 
222       if (RoundParts > 2) {
223         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
224                               PartVT, HalfVT, V);
225         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
226                               RoundParts / 2, PartVT, HalfVT, V);
227       } else {
228         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
229         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
230       }
231 
232       if (DAG.getDataLayout().isBigEndian())
233         std::swap(Lo, Hi);
234 
235       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
236 
237       if (RoundParts < NumParts) {
238         // Assemble the trailing non-power-of-2 part.
239         unsigned OddParts = NumParts - RoundParts;
240         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
241         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
242                               OddVT, V, CC);
243 
244         // Combine the round and odd parts.
245         Lo = Val;
246         if (DAG.getDataLayout().isBigEndian())
247           std::swap(Lo, Hi);
248         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
249         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
250         Hi =
251             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
252                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
253                                         TLI.getPointerTy(DAG.getDataLayout())));
254         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
255         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
256       }
257     } else if (PartVT.isFloatingPoint()) {
258       // FP split into multiple FP parts (for ppcf128)
259       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
260              "Unexpected split");
261       SDValue Lo, Hi;
262       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
263       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
264       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
265         std::swap(Lo, Hi);
266       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
267     } else {
268       // FP split into integer parts (soft fp)
269       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
270              !PartVT.isVector() && "Unexpected split");
271       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
272       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
273     }
274   }
275 
276   // There is now one part, held in Val.  Correct it to match ValueVT.
277   // PartEVT is the type of the register class that holds the value.
278   // ValueVT is the type of the inline asm operation.
279   EVT PartEVT = Val.getValueType();
280 
281   if (PartEVT == ValueVT)
282     return Val;
283 
284   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
285       ValueVT.bitsLT(PartEVT)) {
286     // For an FP value in an integer part, we need to truncate to the right
287     // width first.
288     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
289     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
290   }
291 
292   // Handle types that have the same size.
293   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
294     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
295 
296   // Handle types with different sizes.
297   if (PartEVT.isInteger() && ValueVT.isInteger()) {
298     if (ValueVT.bitsLT(PartEVT)) {
299       // For a truncate, see if we have any information to
300       // indicate whether the truncated bits will always be
301       // zero or sign-extension.
302       if (AssertOp.hasValue())
303         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
304                           DAG.getValueType(ValueVT));
305       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
306     }
307     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
308   }
309 
310   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
311     // FP_ROUND's are always exact here.
312     if (ValueVT.bitsLT(Val.getValueType()))
313       return DAG.getNode(
314           ISD::FP_ROUND, DL, ValueVT, Val,
315           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
316 
317     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
318   }
319 
320   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
321   // then truncating.
322   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
323       ValueVT.bitsLT(PartEVT)) {
324     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
325     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
326   }
327 
328   report_fatal_error("Unknown mismatch in getCopyFromParts!");
329 }
330 
331 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
332                                               const Twine &ErrMsg) {
333   const Instruction *I = dyn_cast_or_null<Instruction>(V);
334   if (!V)
335     return Ctx.emitError(ErrMsg);
336 
337   const char *AsmError = ", possible invalid constraint for vector type";
338   if (const CallInst *CI = dyn_cast<CallInst>(I))
339     if (CI->isInlineAsm())
340       return Ctx.emitError(I, ErrMsg + AsmError);
341 
342   return Ctx.emitError(I, ErrMsg);
343 }
344 
345 /// getCopyFromPartsVector - Create a value that contains the specified legal
346 /// parts combined into the value they represent.  If the parts combine to a
347 /// type larger than ValueVT then AssertOp can be used to specify whether the
348 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
349 /// ValueVT (ISD::AssertSext).
350 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
351                                       const SDValue *Parts, unsigned NumParts,
352                                       MVT PartVT, EVT ValueVT, const Value *V,
353                                       Optional<CallingConv::ID> CallConv) {
354   assert(ValueVT.isVector() && "Not a vector value");
355   assert(NumParts > 0 && "No parts to assemble!");
356   const bool IsABIRegCopy = CallConv.hasValue();
357 
358   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
359   SDValue Val = Parts[0];
360 
361   // Handle a multi-element vector.
362   if (NumParts > 1) {
363     EVT IntermediateVT;
364     MVT RegisterVT;
365     unsigned NumIntermediates;
366     unsigned NumRegs;
367 
368     if (IsABIRegCopy) {
369       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
370           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
371           NumIntermediates, RegisterVT);
372     } else {
373       NumRegs =
374           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
375                                      NumIntermediates, RegisterVT);
376     }
377 
378     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
379     NumParts = NumRegs; // Silence a compiler warning.
380     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
381     assert(RegisterVT.getSizeInBits() ==
382            Parts[0].getSimpleValueType().getSizeInBits() &&
383            "Part type sizes don't match!");
384 
385     // Assemble the parts into intermediate operands.
386     SmallVector<SDValue, 8> Ops(NumIntermediates);
387     if (NumIntermediates == NumParts) {
388       // If the register was not expanded, truncate or copy the value,
389       // as appropriate.
390       for (unsigned i = 0; i != NumParts; ++i)
391         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
392                                   PartVT, IntermediateVT, V, CallConv);
393     } else if (NumParts > 0) {
394       // If the intermediate type was expanded, build the intermediate
395       // operands from the parts.
396       assert(NumParts % NumIntermediates == 0 &&
397              "Must expand into a divisible number of parts!");
398       unsigned Factor = NumParts / NumIntermediates;
399       for (unsigned i = 0; i != NumIntermediates; ++i)
400         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
401                                   PartVT, IntermediateVT, V, CallConv);
402     }
403 
404     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
405     // intermediate operands.
406     EVT BuiltVectorTy =
407         IntermediateVT.isVector()
408             ? EVT::getVectorVT(
409                   *DAG.getContext(), IntermediateVT.getScalarType(),
410                   IntermediateVT.getVectorElementCount() * NumParts)
411             : EVT::getVectorVT(*DAG.getContext(),
412                                IntermediateVT.getScalarType(),
413                                NumIntermediates);
414     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
415                                                 : ISD::BUILD_VECTOR,
416                       DL, BuiltVectorTy, Ops);
417   }
418 
419   // There is now one part, held in Val.  Correct it to match ValueVT.
420   EVT PartEVT = Val.getValueType();
421 
422   if (PartEVT == ValueVT)
423     return Val;
424 
425   if (PartEVT.isVector()) {
426     // If the element type of the source/dest vectors are the same, but the
427     // parts vector has more elements than the value vector, then we have a
428     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
429     // elements we want.
430     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
431       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
432               ValueVT.getVectorElementCount().getKnownMinValue()) &&
433              (PartEVT.getVectorElementCount().isScalable() ==
434               ValueVT.getVectorElementCount().isScalable()) &&
435              "Cannot narrow, it would be a lossy transformation");
436       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
437                          DAG.getVectorIdxConstant(0, DL));
438     }
439 
440     // Vector/Vector bitcast.
441     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
442       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
443 
444     assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() &&
445       "Cannot handle this kind of promotion");
446     // Promoted vector extract
447     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
448 
449   }
450 
451   // Trivial bitcast if the types are the same size and the destination
452   // vector type is legal.
453   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
454       TLI.isTypeLegal(ValueVT))
455     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
456 
457   if (ValueVT.getVectorNumElements() != 1) {
458      // Certain ABIs require that vectors are passed as integers. For vectors
459      // are the same size, this is an obvious bitcast.
460      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
461        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
462      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
463        // Bitcast Val back the original type and extract the corresponding
464        // vector we want.
465        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
466        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
467                                            ValueVT.getVectorElementType(), Elts);
468        Val = DAG.getBitcast(WiderVecType, Val);
469        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
470                           DAG.getVectorIdxConstant(0, DL));
471      }
472 
473      diagnosePossiblyInvalidConstraint(
474          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
475      return DAG.getUNDEF(ValueVT);
476   }
477 
478   // Handle cases such as i8 -> <1 x i1>
479   EVT ValueSVT = ValueVT.getVectorElementType();
480   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
481     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
482       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
483     else
484       Val = ValueVT.isFloatingPoint()
485                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
486                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
487   }
488 
489   return DAG.getBuildVector(ValueVT, DL, Val);
490 }
491 
492 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
493                                  SDValue Val, SDValue *Parts, unsigned NumParts,
494                                  MVT PartVT, const Value *V,
495                                  Optional<CallingConv::ID> CallConv);
496 
497 /// getCopyToParts - Create a series of nodes that contain the specified value
498 /// split into legal parts.  If the parts contain more bits than Val, then, for
499 /// integers, ExtendKind can be used to specify how to generate the extra bits.
500 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
501                            SDValue *Parts, unsigned NumParts, MVT PartVT,
502                            const Value *V,
503                            Optional<CallingConv::ID> CallConv = None,
504                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
505   // Let the target split the parts if it wants to
506   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
507   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
508                                       CallConv))
509     return;
510   EVT ValueVT = Val.getValueType();
511 
512   // Handle the vector case separately.
513   if (ValueVT.isVector())
514     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
515                                 CallConv);
516 
517   unsigned PartBits = PartVT.getSizeInBits();
518   unsigned OrigNumParts = NumParts;
519   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
520          "Copying to an illegal type!");
521 
522   if (NumParts == 0)
523     return;
524 
525   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
526   EVT PartEVT = PartVT;
527   if (PartEVT == ValueVT) {
528     assert(NumParts == 1 && "No-op copy with multiple parts!");
529     Parts[0] = Val;
530     return;
531   }
532 
533   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
534     // If the parts cover more bits than the value has, promote the value.
535     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
536       assert(NumParts == 1 && "Do not know what to promote to!");
537       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
538     } else {
539       if (ValueVT.isFloatingPoint()) {
540         // FP values need to be bitcast, then extended if they are being put
541         // into a larger container.
542         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
543         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
544       }
545       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
546              ValueVT.isInteger() &&
547              "Unknown mismatch!");
548       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
549       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
550       if (PartVT == MVT::x86mmx)
551         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
552     }
553   } else if (PartBits == ValueVT.getSizeInBits()) {
554     // Different types of the same size.
555     assert(NumParts == 1 && PartEVT != ValueVT);
556     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
557   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
558     // If the parts cover less bits than value has, truncate the value.
559     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
560            ValueVT.isInteger() &&
561            "Unknown mismatch!");
562     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
563     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
564     if (PartVT == MVT::x86mmx)
565       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
566   }
567 
568   // The value may have changed - recompute ValueVT.
569   ValueVT = Val.getValueType();
570   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
571          "Failed to tile the value with PartVT!");
572 
573   if (NumParts == 1) {
574     if (PartEVT != ValueVT) {
575       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
576                                         "scalar-to-vector conversion failed");
577       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
578     }
579 
580     Parts[0] = Val;
581     return;
582   }
583 
584   // Expand the value into multiple parts.
585   if (NumParts & (NumParts - 1)) {
586     // The number of parts is not a power of 2.  Split off and copy the tail.
587     assert(PartVT.isInteger() && ValueVT.isInteger() &&
588            "Do not know what to expand to!");
589     unsigned RoundParts = 1 << Log2_32(NumParts);
590     unsigned RoundBits = RoundParts * PartBits;
591     unsigned OddParts = NumParts - RoundParts;
592     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
593       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
594 
595     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
596                    CallConv);
597 
598     if (DAG.getDataLayout().isBigEndian())
599       // The odd parts were reversed by getCopyToParts - unreverse them.
600       std::reverse(Parts + RoundParts, Parts + NumParts);
601 
602     NumParts = RoundParts;
603     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
604     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
605   }
606 
607   // The number of parts is a power of 2.  Repeatedly bisect the value using
608   // EXTRACT_ELEMENT.
609   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
610                          EVT::getIntegerVT(*DAG.getContext(),
611                                            ValueVT.getSizeInBits()),
612                          Val);
613 
614   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
615     for (unsigned i = 0; i < NumParts; i += StepSize) {
616       unsigned ThisBits = StepSize * PartBits / 2;
617       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
618       SDValue &Part0 = Parts[i];
619       SDValue &Part1 = Parts[i+StepSize/2];
620 
621       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
622                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
623       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
624                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
625 
626       if (ThisBits == PartBits && ThisVT != PartVT) {
627         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
628         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
629       }
630     }
631   }
632 
633   if (DAG.getDataLayout().isBigEndian())
634     std::reverse(Parts, Parts + OrigNumParts);
635 }
636 
637 static SDValue widenVectorToPartType(SelectionDAG &DAG,
638                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
639   if (!PartVT.isFixedLengthVector())
640     return SDValue();
641 
642   EVT ValueVT = Val.getValueType();
643   unsigned PartNumElts = PartVT.getVectorNumElements();
644   unsigned ValueNumElts = ValueVT.getVectorNumElements();
645   if (PartNumElts > ValueNumElts &&
646       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
647     EVT ElementVT = PartVT.getVectorElementType();
648     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
649     // undef elements.
650     SmallVector<SDValue, 16> Ops;
651     DAG.ExtractVectorElements(Val, Ops);
652     SDValue EltUndef = DAG.getUNDEF(ElementVT);
653     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
654       Ops.push_back(EltUndef);
655 
656     // FIXME: Use CONCAT for 2x -> 4x.
657     return DAG.getBuildVector(PartVT, DL, Ops);
658   }
659 
660   return SDValue();
661 }
662 
663 /// getCopyToPartsVector - Create a series of nodes that contain the specified
664 /// value split into legal parts.
665 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
666                                  SDValue Val, SDValue *Parts, unsigned NumParts,
667                                  MVT PartVT, const Value *V,
668                                  Optional<CallingConv::ID> CallConv) {
669   EVT ValueVT = Val.getValueType();
670   assert(ValueVT.isVector() && "Not a vector");
671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
672   const bool IsABIRegCopy = CallConv.hasValue();
673 
674   if (NumParts == 1) {
675     EVT PartEVT = PartVT;
676     if (PartEVT == ValueVT) {
677       // Nothing to do.
678     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
679       // Bitconvert vector->vector case.
680       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
681     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
682       Val = Widened;
683     } else if (PartVT.isVector() &&
684                PartEVT.getVectorElementType().bitsGE(
685                    ValueVT.getVectorElementType()) &&
686                PartEVT.getVectorElementCount() ==
687                    ValueVT.getVectorElementCount()) {
688 
689       // Promoted vector extract
690       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
691     } else {
692       if (ValueVT.getVectorNumElements() == 1) {
693         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
694                           DAG.getVectorIdxConstant(0, DL));
695       } else {
696         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
697                "lossy conversion of vector to scalar type");
698         EVT IntermediateType =
699             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
700         Val = DAG.getBitcast(IntermediateType, Val);
701         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
702       }
703     }
704 
705     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
706     Parts[0] = Val;
707     return;
708   }
709 
710   // Handle a multi-element vector.
711   EVT IntermediateVT;
712   MVT RegisterVT;
713   unsigned NumIntermediates;
714   unsigned NumRegs;
715   if (IsABIRegCopy) {
716     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
717         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
718         NumIntermediates, RegisterVT);
719   } else {
720     NumRegs =
721         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
722                                    NumIntermediates, RegisterVT);
723   }
724 
725   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
726   NumParts = NumRegs; // Silence a compiler warning.
727   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
728 
729   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
730          "Mixing scalable and fixed vectors when copying in parts");
731 
732   Optional<ElementCount> DestEltCnt;
733 
734   if (IntermediateVT.isVector())
735     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
736   else
737     DestEltCnt = ElementCount::getFixed(NumIntermediates);
738 
739   EVT BuiltVectorTy = EVT::getVectorVT(
740       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
741   if (ValueVT != BuiltVectorTy) {
742     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
743       Val = Widened;
744 
745     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
746   }
747 
748   // Split the vector into intermediate operands.
749   SmallVector<SDValue, 8> Ops(NumIntermediates);
750   for (unsigned i = 0; i != NumIntermediates; ++i) {
751     if (IntermediateVT.isVector()) {
752       // This does something sensible for scalable vectors - see the
753       // definition of EXTRACT_SUBVECTOR for further details.
754       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
755       Ops[i] =
756           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
757                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
758     } else {
759       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
760                            DAG.getVectorIdxConstant(i, DL));
761     }
762   }
763 
764   // Split the intermediate operands into legal parts.
765   if (NumParts == NumIntermediates) {
766     // If the register was not expanded, promote or copy the value,
767     // as appropriate.
768     for (unsigned i = 0; i != NumParts; ++i)
769       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
770   } else if (NumParts > 0) {
771     // If the intermediate type was expanded, split each the value into
772     // legal parts.
773     assert(NumIntermediates != 0 && "division by zero");
774     assert(NumParts % NumIntermediates == 0 &&
775            "Must expand into a divisible number of parts!");
776     unsigned Factor = NumParts / NumIntermediates;
777     for (unsigned i = 0; i != NumIntermediates; ++i)
778       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
779                      CallConv);
780   }
781 }
782 
783 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
784                            EVT valuevt, Optional<CallingConv::ID> CC)
785     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
786       RegCount(1, regs.size()), CallConv(CC) {}
787 
788 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
789                            const DataLayout &DL, unsigned Reg, Type *Ty,
790                            Optional<CallingConv::ID> CC) {
791   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
792 
793   CallConv = CC;
794 
795   for (EVT ValueVT : ValueVTs) {
796     unsigned NumRegs =
797         isABIMangled()
798             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
799             : TLI.getNumRegisters(Context, ValueVT);
800     MVT RegisterVT =
801         isABIMangled()
802             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
803             : TLI.getRegisterType(Context, ValueVT);
804     for (unsigned i = 0; i != NumRegs; ++i)
805       Regs.push_back(Reg + i);
806     RegVTs.push_back(RegisterVT);
807     RegCount.push_back(NumRegs);
808     Reg += NumRegs;
809   }
810 }
811 
812 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
813                                       FunctionLoweringInfo &FuncInfo,
814                                       const SDLoc &dl, SDValue &Chain,
815                                       SDValue *Flag, const Value *V) const {
816   // A Value with type {} or [0 x %t] needs no registers.
817   if (ValueVTs.empty())
818     return SDValue();
819 
820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
821 
822   // Assemble the legal parts into the final values.
823   SmallVector<SDValue, 4> Values(ValueVTs.size());
824   SmallVector<SDValue, 8> Parts;
825   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
826     // Copy the legal parts from the registers.
827     EVT ValueVT = ValueVTs[Value];
828     unsigned NumRegs = RegCount[Value];
829     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
830                                           *DAG.getContext(),
831                                           CallConv.getValue(), RegVTs[Value])
832                                     : RegVTs[Value];
833 
834     Parts.resize(NumRegs);
835     for (unsigned i = 0; i != NumRegs; ++i) {
836       SDValue P;
837       if (!Flag) {
838         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
839       } else {
840         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
841         *Flag = P.getValue(2);
842       }
843 
844       Chain = P.getValue(1);
845       Parts[i] = P;
846 
847       // If the source register was virtual and if we know something about it,
848       // add an assert node.
849       if (!Register::isVirtualRegister(Regs[Part + i]) ||
850           !RegisterVT.isInteger())
851         continue;
852 
853       const FunctionLoweringInfo::LiveOutInfo *LOI =
854         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
855       if (!LOI)
856         continue;
857 
858       unsigned RegSize = RegisterVT.getScalarSizeInBits();
859       unsigned NumSignBits = LOI->NumSignBits;
860       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
861 
862       if (NumZeroBits == RegSize) {
863         // The current value is a zero.
864         // Explicitly express that as it would be easier for
865         // optimizations to kick in.
866         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
867         continue;
868       }
869 
870       // FIXME: We capture more information than the dag can represent.  For
871       // now, just use the tightest assertzext/assertsext possible.
872       bool isSExt;
873       EVT FromVT(MVT::Other);
874       if (NumZeroBits) {
875         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
876         isSExt = false;
877       } else if (NumSignBits > 1) {
878         FromVT =
879             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
880         isSExt = true;
881       } else {
882         continue;
883       }
884       // Add an assertion node.
885       assert(FromVT != MVT::Other);
886       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
887                              RegisterVT, P, DAG.getValueType(FromVT));
888     }
889 
890     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
891                                      RegisterVT, ValueVT, V, CallConv);
892     Part += NumRegs;
893     Parts.clear();
894   }
895 
896   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
897 }
898 
899 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
900                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
901                                  const Value *V,
902                                  ISD::NodeType PreferredExtendType) const {
903   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
904   ISD::NodeType ExtendKind = PreferredExtendType;
905 
906   // Get the list of the values's legal parts.
907   unsigned NumRegs = Regs.size();
908   SmallVector<SDValue, 8> Parts(NumRegs);
909   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
910     unsigned NumParts = RegCount[Value];
911 
912     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
913                                           *DAG.getContext(),
914                                           CallConv.getValue(), RegVTs[Value])
915                                     : RegVTs[Value];
916 
917     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
918       ExtendKind = ISD::ZERO_EXTEND;
919 
920     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
921                    NumParts, RegisterVT, V, CallConv, ExtendKind);
922     Part += NumParts;
923   }
924 
925   // Copy the parts into the registers.
926   SmallVector<SDValue, 8> Chains(NumRegs);
927   for (unsigned i = 0; i != NumRegs; ++i) {
928     SDValue Part;
929     if (!Flag) {
930       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
931     } else {
932       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
933       *Flag = Part.getValue(1);
934     }
935 
936     Chains[i] = Part.getValue(0);
937   }
938 
939   if (NumRegs == 1 || Flag)
940     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
941     // flagged to it. That is the CopyToReg nodes and the user are considered
942     // a single scheduling unit. If we create a TokenFactor and return it as
943     // chain, then the TokenFactor is both a predecessor (operand) of the
944     // user as well as a successor (the TF operands are flagged to the user).
945     // c1, f1 = CopyToReg
946     // c2, f2 = CopyToReg
947     // c3     = TokenFactor c1, c2
948     // ...
949     //        = op c3, ..., f2
950     Chain = Chains[NumRegs-1];
951   else
952     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
953 }
954 
955 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
956                                         unsigned MatchingIdx, const SDLoc &dl,
957                                         SelectionDAG &DAG,
958                                         std::vector<SDValue> &Ops) const {
959   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
960 
961   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
962   if (HasMatching)
963     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
964   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
965     // Put the register class of the virtual registers in the flag word.  That
966     // way, later passes can recompute register class constraints for inline
967     // assembly as well as normal instructions.
968     // Don't do this for tied operands that can use the regclass information
969     // from the def.
970     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
971     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
972     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
973   }
974 
975   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
976   Ops.push_back(Res);
977 
978   if (Code == InlineAsm::Kind_Clobber) {
979     // Clobbers should always have a 1:1 mapping with registers, and may
980     // reference registers that have illegal (e.g. vector) types. Hence, we
981     // shouldn't try to apply any sort of splitting logic to them.
982     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
983            "No 1:1 mapping from clobbers to regs?");
984     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
985     (void)SP;
986     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
987       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
988       assert(
989           (Regs[I] != SP ||
990            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
991           "If we clobbered the stack pointer, MFI should know about it.");
992     }
993     return;
994   }
995 
996   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
997     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
998     MVT RegisterVT = RegVTs[Value];
999     for (unsigned i = 0; i != NumRegs; ++i) {
1000       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1001       unsigned TheReg = Regs[Reg++];
1002       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1003     }
1004   }
1005 }
1006 
1007 SmallVector<std::pair<unsigned, unsigned>, 4>
1008 RegsForValue::getRegsAndSizes() const {
1009   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1010   unsigned I = 0;
1011   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1012     unsigned RegCount = std::get<0>(CountAndVT);
1013     MVT RegisterVT = std::get<1>(CountAndVT);
1014     unsigned RegisterSize = RegisterVT.getSizeInBits();
1015     for (unsigned E = I + RegCount; I != E; ++I)
1016       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1017   }
1018   return OutVec;
1019 }
1020 
1021 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1022                                const TargetLibraryInfo *li) {
1023   AA = aa;
1024   GFI = gfi;
1025   LibInfo = li;
1026   DL = &DAG.getDataLayout();
1027   Context = DAG.getContext();
1028   LPadToCallSiteMap.clear();
1029   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1030 }
1031 
1032 void SelectionDAGBuilder::clear() {
1033   NodeMap.clear();
1034   UnusedArgNodeMap.clear();
1035   PendingLoads.clear();
1036   PendingExports.clear();
1037   PendingConstrainedFP.clear();
1038   PendingConstrainedFPStrict.clear();
1039   CurInst = nullptr;
1040   HasTailCall = false;
1041   SDNodeOrder = LowestSDNodeOrder;
1042   StatepointLowering.clear();
1043 }
1044 
1045 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1046   DanglingDebugInfoMap.clear();
1047 }
1048 
1049 // Update DAG root to include dependencies on Pending chains.
1050 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1051   SDValue Root = DAG.getRoot();
1052 
1053   if (Pending.empty())
1054     return Root;
1055 
1056   // Add current root to PendingChains, unless we already indirectly
1057   // depend on it.
1058   if (Root.getOpcode() != ISD::EntryToken) {
1059     unsigned i = 0, e = Pending.size();
1060     for (; i != e; ++i) {
1061       assert(Pending[i].getNode()->getNumOperands() > 1);
1062       if (Pending[i].getNode()->getOperand(0) == Root)
1063         break;  // Don't add the root if we already indirectly depend on it.
1064     }
1065 
1066     if (i == e)
1067       Pending.push_back(Root);
1068   }
1069 
1070   if (Pending.size() == 1)
1071     Root = Pending[0];
1072   else
1073     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1074 
1075   DAG.setRoot(Root);
1076   Pending.clear();
1077   return Root;
1078 }
1079 
1080 SDValue SelectionDAGBuilder::getMemoryRoot() {
1081   return updateRoot(PendingLoads);
1082 }
1083 
1084 SDValue SelectionDAGBuilder::getRoot() {
1085   // Chain up all pending constrained intrinsics together with all
1086   // pending loads, by simply appending them to PendingLoads and
1087   // then calling getMemoryRoot().
1088   PendingLoads.reserve(PendingLoads.size() +
1089                        PendingConstrainedFP.size() +
1090                        PendingConstrainedFPStrict.size());
1091   PendingLoads.append(PendingConstrainedFP.begin(),
1092                       PendingConstrainedFP.end());
1093   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1094                       PendingConstrainedFPStrict.end());
1095   PendingConstrainedFP.clear();
1096   PendingConstrainedFPStrict.clear();
1097   return getMemoryRoot();
1098 }
1099 
1100 SDValue SelectionDAGBuilder::getControlRoot() {
1101   // We need to emit pending fpexcept.strict constrained intrinsics,
1102   // so append them to the PendingExports list.
1103   PendingExports.append(PendingConstrainedFPStrict.begin(),
1104                         PendingConstrainedFPStrict.end());
1105   PendingConstrainedFPStrict.clear();
1106   return updateRoot(PendingExports);
1107 }
1108 
1109 void SelectionDAGBuilder::visit(const Instruction &I) {
1110   // Set up outgoing PHI node register values before emitting the terminator.
1111   if (I.isTerminator()) {
1112     HandlePHINodesInSuccessorBlocks(I.getParent());
1113   }
1114 
1115   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1116   if (!isa<DbgInfoIntrinsic>(I))
1117     ++SDNodeOrder;
1118 
1119   CurInst = &I;
1120 
1121   visit(I.getOpcode(), I);
1122 
1123   if (!I.isTerminator() && !HasTailCall &&
1124       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1125     CopyToExportRegsIfNeeded(&I);
1126 
1127   CurInst = nullptr;
1128 }
1129 
1130 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1131   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1132 }
1133 
1134 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1135   // Note: this doesn't use InstVisitor, because it has to work with
1136   // ConstantExpr's in addition to instructions.
1137   switch (Opcode) {
1138   default: llvm_unreachable("Unknown instruction type encountered!");
1139     // Build the switch statement using the Instruction.def file.
1140 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1141     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1142 #include "llvm/IR/Instruction.def"
1143   }
1144 }
1145 
1146 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1147                                                 const DIExpression *Expr) {
1148   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1149     const DbgValueInst *DI = DDI.getDI();
1150     DIVariable *DanglingVariable = DI->getVariable();
1151     DIExpression *DanglingExpr = DI->getExpression();
1152     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1153       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1154       return true;
1155     }
1156     return false;
1157   };
1158 
1159   for (auto &DDIMI : DanglingDebugInfoMap) {
1160     DanglingDebugInfoVector &DDIV = DDIMI.second;
1161 
1162     // If debug info is to be dropped, run it through final checks to see
1163     // whether it can be salvaged.
1164     for (auto &DDI : DDIV)
1165       if (isMatchingDbgValue(DDI))
1166         salvageUnresolvedDbgValue(DDI);
1167 
1168     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1169   }
1170 }
1171 
1172 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1173 // generate the debug data structures now that we've seen its definition.
1174 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1175                                                    SDValue Val) {
1176   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1177   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1178     return;
1179 
1180   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1181   for (auto &DDI : DDIV) {
1182     const DbgValueInst *DI = DDI.getDI();
1183     assert(DI && "Ill-formed DanglingDebugInfo");
1184     DebugLoc dl = DDI.getdl();
1185     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1186     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1187     DILocalVariable *Variable = DI->getVariable();
1188     DIExpression *Expr = DI->getExpression();
1189     assert(Variable->isValidLocationForIntrinsic(dl) &&
1190            "Expected inlined-at fields to agree");
1191     SDDbgValue *SDV;
1192     if (Val.getNode()) {
1193       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1194       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1195       // we couldn't resolve it directly when examining the DbgValue intrinsic
1196       // in the first place we should not be more successful here). Unless we
1197       // have some test case that prove this to be correct we should avoid
1198       // calling EmitFuncArgumentDbgValue here.
1199       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1200         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1201                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1202         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1203         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1204         // inserted after the definition of Val when emitting the instructions
1205         // after ISel. An alternative could be to teach
1206         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1207         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1208                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1209                    << ValSDNodeOrder << "\n");
1210         SDV = getDbgValue(Val, Variable, Expr, dl,
1211                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1212         DAG.AddDbgValue(SDV, Val.getNode(), false);
1213       } else
1214         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1215                           << "in EmitFuncArgumentDbgValue\n");
1216     } else {
1217       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1218       auto Undef =
1219           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1220       auto SDV =
1221           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1222       DAG.AddDbgValue(SDV, nullptr, false);
1223     }
1224   }
1225   DDIV.clear();
1226 }
1227 
1228 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1229   Value *V = DDI.getDI()->getValue();
1230   DILocalVariable *Var = DDI.getDI()->getVariable();
1231   DIExpression *Expr = DDI.getDI()->getExpression();
1232   DebugLoc DL = DDI.getdl();
1233   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1234   unsigned SDOrder = DDI.getSDNodeOrder();
1235 
1236   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1237   // that DW_OP_stack_value is desired.
1238   assert(isa<DbgValueInst>(DDI.getDI()));
1239   bool StackValue = true;
1240 
1241   // Can this Value can be encoded without any further work?
1242   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1243     return;
1244 
1245   // Attempt to salvage back through as many instructions as possible. Bail if
1246   // a non-instruction is seen, such as a constant expression or global
1247   // variable. FIXME: Further work could recover those too.
1248   while (isa<Instruction>(V)) {
1249     Instruction &VAsInst = *cast<Instruction>(V);
1250     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1251 
1252     // If we cannot salvage any further, and haven't yet found a suitable debug
1253     // expression, bail out.
1254     if (!NewExpr)
1255       break;
1256 
1257     // New value and expr now represent this debuginfo.
1258     V = VAsInst.getOperand(0);
1259     Expr = NewExpr;
1260 
1261     // Some kind of simplification occurred: check whether the operand of the
1262     // salvaged debug expression can be encoded in this DAG.
1263     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1264       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1265                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1266       return;
1267     }
1268   }
1269 
1270   // This was the final opportunity to salvage this debug information, and it
1271   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1272   // any earlier variable location.
1273   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1274   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1275   DAG.AddDbgValue(SDV, nullptr, false);
1276 
1277   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1278                     << "\n");
1279   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1280                     << "\n");
1281 }
1282 
1283 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1284                                            DIExpression *Expr, DebugLoc dl,
1285                                            DebugLoc InstDL, unsigned Order) {
1286   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1287   SDDbgValue *SDV;
1288   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1289       isa<ConstantPointerNull>(V)) {
1290     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1291     DAG.AddDbgValue(SDV, nullptr, false);
1292     return true;
1293   }
1294 
1295   // If the Value is a frame index, we can create a FrameIndex debug value
1296   // without relying on the DAG at all.
1297   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1298     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1299     if (SI != FuncInfo.StaticAllocaMap.end()) {
1300       auto SDV =
1301           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1302                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1303       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1304       // is still available even if the SDNode gets optimized out.
1305       DAG.AddDbgValue(SDV, nullptr, false);
1306       return true;
1307     }
1308   }
1309 
1310   // Do not use getValue() in here; we don't want to generate code at
1311   // this point if it hasn't been done yet.
1312   SDValue N = NodeMap[V];
1313   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1314     N = UnusedArgNodeMap[V];
1315   if (N.getNode()) {
1316     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1317       return true;
1318     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1319     DAG.AddDbgValue(SDV, N.getNode(), false);
1320     return true;
1321   }
1322 
1323   // Special rules apply for the first dbg.values of parameter variables in a
1324   // function. Identify them by the fact they reference Argument Values, that
1325   // they're parameters, and they are parameters of the current function. We
1326   // need to let them dangle until they get an SDNode.
1327   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1328                        !InstDL.getInlinedAt();
1329   if (!IsParamOfFunc) {
1330     // The value is not used in this block yet (or it would have an SDNode).
1331     // We still want the value to appear for the user if possible -- if it has
1332     // an associated VReg, we can refer to that instead.
1333     auto VMI = FuncInfo.ValueMap.find(V);
1334     if (VMI != FuncInfo.ValueMap.end()) {
1335       unsigned Reg = VMI->second;
1336       // If this is a PHI node, it may be split up into several MI PHI nodes
1337       // (in FunctionLoweringInfo::set).
1338       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1339                        V->getType(), None);
1340       if (RFV.occupiesMultipleRegs()) {
1341         unsigned Offset = 0;
1342         unsigned BitsToDescribe = 0;
1343         if (auto VarSize = Var->getSizeInBits())
1344           BitsToDescribe = *VarSize;
1345         if (auto Fragment = Expr->getFragmentInfo())
1346           BitsToDescribe = Fragment->SizeInBits;
1347         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1348           unsigned RegisterSize = RegAndSize.second;
1349           // Bail out if all bits are described already.
1350           if (Offset >= BitsToDescribe)
1351             break;
1352           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1353               ? BitsToDescribe - Offset
1354               : RegisterSize;
1355           auto FragmentExpr = DIExpression::createFragmentExpression(
1356               Expr, Offset, FragmentSize);
1357           if (!FragmentExpr)
1358               continue;
1359           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1360                                     false, dl, SDNodeOrder);
1361           DAG.AddDbgValue(SDV, nullptr, false);
1362           Offset += RegisterSize;
1363         }
1364       } else {
1365         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1366         DAG.AddDbgValue(SDV, nullptr, false);
1367       }
1368       return true;
1369     }
1370   }
1371 
1372   return false;
1373 }
1374 
1375 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1376   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1377   for (auto &Pair : DanglingDebugInfoMap)
1378     for (auto &DDI : Pair.second)
1379       salvageUnresolvedDbgValue(DDI);
1380   clearDanglingDebugInfo();
1381 }
1382 
1383 /// getCopyFromRegs - If there was virtual register allocated for the value V
1384 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1385 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1386   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1387   SDValue Result;
1388 
1389   if (It != FuncInfo.ValueMap.end()) {
1390     Register InReg = It->second;
1391 
1392     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1393                      DAG.getDataLayout(), InReg, Ty,
1394                      None); // This is not an ABI copy.
1395     SDValue Chain = DAG.getEntryNode();
1396     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1397                                  V);
1398     resolveDanglingDebugInfo(V, Result);
1399   }
1400 
1401   return Result;
1402 }
1403 
1404 /// getValue - Return an SDValue for the given Value.
1405 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1406   // If we already have an SDValue for this value, use it. It's important
1407   // to do this first, so that we don't create a CopyFromReg if we already
1408   // have a regular SDValue.
1409   SDValue &N = NodeMap[V];
1410   if (N.getNode()) return N;
1411 
1412   // If there's a virtual register allocated and initialized for this
1413   // value, use it.
1414   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1415     return copyFromReg;
1416 
1417   // Otherwise create a new SDValue and remember it.
1418   SDValue Val = getValueImpl(V);
1419   NodeMap[V] = Val;
1420   resolveDanglingDebugInfo(V, Val);
1421   return Val;
1422 }
1423 
1424 /// getNonRegisterValue - Return an SDValue for the given Value, but
1425 /// don't look in FuncInfo.ValueMap for a virtual register.
1426 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1427   // If we already have an SDValue for this value, use it.
1428   SDValue &N = NodeMap[V];
1429   if (N.getNode()) {
1430     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1431       // Remove the debug location from the node as the node is about to be used
1432       // in a location which may differ from the original debug location.  This
1433       // is relevant to Constant and ConstantFP nodes because they can appear
1434       // as constant expressions inside PHI nodes.
1435       N->setDebugLoc(DebugLoc());
1436     }
1437     return N;
1438   }
1439 
1440   // Otherwise create a new SDValue and remember it.
1441   SDValue Val = getValueImpl(V);
1442   NodeMap[V] = Val;
1443   resolveDanglingDebugInfo(V, Val);
1444   return Val;
1445 }
1446 
1447 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1448 /// Create an SDValue for the given value.
1449 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1450   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1451 
1452   if (const Constant *C = dyn_cast<Constant>(V)) {
1453     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1454 
1455     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1456       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1457 
1458     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1459       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1460 
1461     if (isa<ConstantPointerNull>(C)) {
1462       unsigned AS = V->getType()->getPointerAddressSpace();
1463       return DAG.getConstant(0, getCurSDLoc(),
1464                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1465     }
1466 
1467     if (match(C, m_VScale(DAG.getDataLayout())))
1468       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1469 
1470     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1471       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1472 
1473     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1474       return DAG.getUNDEF(VT);
1475 
1476     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1477       visit(CE->getOpcode(), *CE);
1478       SDValue N1 = NodeMap[V];
1479       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1480       return N1;
1481     }
1482 
1483     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1484       SmallVector<SDValue, 4> Constants;
1485       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1486            OI != OE; ++OI) {
1487         SDNode *Val = getValue(*OI).getNode();
1488         // If the operand is an empty aggregate, there are no values.
1489         if (!Val) continue;
1490         // Add each leaf value from the operand to the Constants list
1491         // to form a flattened list of all the values.
1492         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1493           Constants.push_back(SDValue(Val, i));
1494       }
1495 
1496       return DAG.getMergeValues(Constants, getCurSDLoc());
1497     }
1498 
1499     if (const ConstantDataSequential *CDS =
1500           dyn_cast<ConstantDataSequential>(C)) {
1501       SmallVector<SDValue, 4> Ops;
1502       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1503         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1504         // Add each leaf value from the operand to the Constants list
1505         // to form a flattened list of all the values.
1506         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1507           Ops.push_back(SDValue(Val, i));
1508       }
1509 
1510       if (isa<ArrayType>(CDS->getType()))
1511         return DAG.getMergeValues(Ops, getCurSDLoc());
1512       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1513     }
1514 
1515     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1516       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1517              "Unknown struct or array constant!");
1518 
1519       SmallVector<EVT, 4> ValueVTs;
1520       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1521       unsigned NumElts = ValueVTs.size();
1522       if (NumElts == 0)
1523         return SDValue(); // empty struct
1524       SmallVector<SDValue, 4> Constants(NumElts);
1525       for (unsigned i = 0; i != NumElts; ++i) {
1526         EVT EltVT = ValueVTs[i];
1527         if (isa<UndefValue>(C))
1528           Constants[i] = DAG.getUNDEF(EltVT);
1529         else if (EltVT.isFloatingPoint())
1530           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1531         else
1532           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1533       }
1534 
1535       return DAG.getMergeValues(Constants, getCurSDLoc());
1536     }
1537 
1538     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1539       return DAG.getBlockAddress(BA, VT);
1540 
1541     VectorType *VecTy = cast<VectorType>(V->getType());
1542 
1543     // Now that we know the number and type of the elements, get that number of
1544     // elements into the Ops array based on what kind of constant it is.
1545     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1546       SmallVector<SDValue, 16> Ops;
1547       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1548       for (unsigned i = 0; i != NumElements; ++i)
1549         Ops.push_back(getValue(CV->getOperand(i)));
1550 
1551       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1552     } else if (isa<ConstantAggregateZero>(C)) {
1553       EVT EltVT =
1554           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1555 
1556       SDValue Op;
1557       if (EltVT.isFloatingPoint())
1558         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1559       else
1560         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1561 
1562       if (isa<ScalableVectorType>(VecTy))
1563         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1564       else {
1565         SmallVector<SDValue, 16> Ops;
1566         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1567         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1568       }
1569     }
1570     llvm_unreachable("Unknown vector constant");
1571   }
1572 
1573   // If this is a static alloca, generate it as the frameindex instead of
1574   // computation.
1575   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1576     DenseMap<const AllocaInst*, int>::iterator SI =
1577       FuncInfo.StaticAllocaMap.find(AI);
1578     if (SI != FuncInfo.StaticAllocaMap.end())
1579       return DAG.getFrameIndex(SI->second,
1580                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1581   }
1582 
1583   // If this is an instruction which fast-isel has deferred, select it now.
1584   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1585     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1586 
1587     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1588                      Inst->getType(), getABIRegCopyCC(V));
1589     SDValue Chain = DAG.getEntryNode();
1590     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1591   }
1592 
1593   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1594     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1595   }
1596   llvm_unreachable("Can't get register for value!");
1597 }
1598 
1599 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1600   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1601   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1602   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1603   bool IsSEH = isAsynchronousEHPersonality(Pers);
1604   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1605   if (!IsSEH)
1606     CatchPadMBB->setIsEHScopeEntry();
1607   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1608   if (IsMSVCCXX || IsCoreCLR)
1609     CatchPadMBB->setIsEHFuncletEntry();
1610 }
1611 
1612 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1613   // Update machine-CFG edge.
1614   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1615   FuncInfo.MBB->addSuccessor(TargetMBB);
1616 
1617   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1618   bool IsSEH = isAsynchronousEHPersonality(Pers);
1619   if (IsSEH) {
1620     // If this is not a fall-through branch or optimizations are switched off,
1621     // emit the branch.
1622     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1623         TM.getOptLevel() == CodeGenOpt::None)
1624       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1625                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1626     return;
1627   }
1628 
1629   // Figure out the funclet membership for the catchret's successor.
1630   // This will be used by the FuncletLayout pass to determine how to order the
1631   // BB's.
1632   // A 'catchret' returns to the outer scope's color.
1633   Value *ParentPad = I.getCatchSwitchParentPad();
1634   const BasicBlock *SuccessorColor;
1635   if (isa<ConstantTokenNone>(ParentPad))
1636     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1637   else
1638     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1639   assert(SuccessorColor && "No parent funclet for catchret!");
1640   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1641   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1642 
1643   // Create the terminator node.
1644   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1645                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1646                             DAG.getBasicBlock(SuccessorColorMBB));
1647   DAG.setRoot(Ret);
1648 }
1649 
1650 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1651   // Don't emit any special code for the cleanuppad instruction. It just marks
1652   // the start of an EH scope/funclet.
1653   FuncInfo.MBB->setIsEHScopeEntry();
1654   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1655   if (Pers != EHPersonality::Wasm_CXX) {
1656     FuncInfo.MBB->setIsEHFuncletEntry();
1657     FuncInfo.MBB->setIsCleanupFuncletEntry();
1658   }
1659 }
1660 
1661 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1662 // the control flow always stops at the single catch pad, as it does for a
1663 // cleanup pad. In case the exception caught is not of the types the catch pad
1664 // catches, it will be rethrown by a rethrow.
1665 static void findWasmUnwindDestinations(
1666     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1667     BranchProbability Prob,
1668     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1669         &UnwindDests) {
1670   while (EHPadBB) {
1671     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1672     if (isa<CleanupPadInst>(Pad)) {
1673       // Stop on cleanup pads.
1674       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1675       UnwindDests.back().first->setIsEHScopeEntry();
1676       break;
1677     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1678       // Add the catchpad handlers to the possible destinations. We don't
1679       // continue to the unwind destination of the catchswitch for wasm.
1680       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1681         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1682         UnwindDests.back().first->setIsEHScopeEntry();
1683       }
1684       break;
1685     } else {
1686       continue;
1687     }
1688   }
1689 }
1690 
1691 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1692 /// many places it could ultimately go. In the IR, we have a single unwind
1693 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1694 /// This function skips over imaginary basic blocks that hold catchswitch
1695 /// instructions, and finds all the "real" machine
1696 /// basic block destinations. As those destinations may not be successors of
1697 /// EHPadBB, here we also calculate the edge probability to those destinations.
1698 /// The passed-in Prob is the edge probability to EHPadBB.
1699 static void findUnwindDestinations(
1700     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1701     BranchProbability Prob,
1702     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1703         &UnwindDests) {
1704   EHPersonality Personality =
1705     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1706   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1707   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1708   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1709   bool IsSEH = isAsynchronousEHPersonality(Personality);
1710 
1711   if (IsWasmCXX) {
1712     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1713     assert(UnwindDests.size() <= 1 &&
1714            "There should be at most one unwind destination for wasm");
1715     return;
1716   }
1717 
1718   while (EHPadBB) {
1719     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1720     BasicBlock *NewEHPadBB = nullptr;
1721     if (isa<LandingPadInst>(Pad)) {
1722       // Stop on landingpads. They are not funclets.
1723       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1724       break;
1725     } else if (isa<CleanupPadInst>(Pad)) {
1726       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1727       // personalities.
1728       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1729       UnwindDests.back().first->setIsEHScopeEntry();
1730       UnwindDests.back().first->setIsEHFuncletEntry();
1731       break;
1732     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1733       // Add the catchpad handlers to the possible destinations.
1734       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1735         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1736         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1737         if (IsMSVCCXX || IsCoreCLR)
1738           UnwindDests.back().first->setIsEHFuncletEntry();
1739         if (!IsSEH)
1740           UnwindDests.back().first->setIsEHScopeEntry();
1741       }
1742       NewEHPadBB = CatchSwitch->getUnwindDest();
1743     } else {
1744       continue;
1745     }
1746 
1747     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1748     if (BPI && NewEHPadBB)
1749       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1750     EHPadBB = NewEHPadBB;
1751   }
1752 }
1753 
1754 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1755   // Update successor info.
1756   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1757   auto UnwindDest = I.getUnwindDest();
1758   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1759   BranchProbability UnwindDestProb =
1760       (BPI && UnwindDest)
1761           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1762           : BranchProbability::getZero();
1763   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1764   for (auto &UnwindDest : UnwindDests) {
1765     UnwindDest.first->setIsEHPad();
1766     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1767   }
1768   FuncInfo.MBB->normalizeSuccProbs();
1769 
1770   // Create the terminator node.
1771   SDValue Ret =
1772       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1773   DAG.setRoot(Ret);
1774 }
1775 
1776 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1777   report_fatal_error("visitCatchSwitch not yet implemented!");
1778 }
1779 
1780 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1781   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1782   auto &DL = DAG.getDataLayout();
1783   SDValue Chain = getControlRoot();
1784   SmallVector<ISD::OutputArg, 8> Outs;
1785   SmallVector<SDValue, 8> OutVals;
1786 
1787   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1788   // lower
1789   //
1790   //   %val = call <ty> @llvm.experimental.deoptimize()
1791   //   ret <ty> %val
1792   //
1793   // differently.
1794   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1795     LowerDeoptimizingReturn();
1796     return;
1797   }
1798 
1799   if (!FuncInfo.CanLowerReturn) {
1800     unsigned DemoteReg = FuncInfo.DemoteRegister;
1801     const Function *F = I.getParent()->getParent();
1802 
1803     // Emit a store of the return value through the virtual register.
1804     // Leave Outs empty so that LowerReturn won't try to load return
1805     // registers the usual way.
1806     SmallVector<EVT, 1> PtrValueVTs;
1807     ComputeValueVTs(TLI, DL,
1808                     F->getReturnType()->getPointerTo(
1809                         DAG.getDataLayout().getAllocaAddrSpace()),
1810                     PtrValueVTs);
1811 
1812     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1813                                         DemoteReg, PtrValueVTs[0]);
1814     SDValue RetOp = getValue(I.getOperand(0));
1815 
1816     SmallVector<EVT, 4> ValueVTs, MemVTs;
1817     SmallVector<uint64_t, 4> Offsets;
1818     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1819                     &Offsets);
1820     unsigned NumValues = ValueVTs.size();
1821 
1822     SmallVector<SDValue, 4> Chains(NumValues);
1823     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1824     for (unsigned i = 0; i != NumValues; ++i) {
1825       // An aggregate return value cannot wrap around the address space, so
1826       // offsets to its parts don't wrap either.
1827       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1828                                            TypeSize::Fixed(Offsets[i]));
1829 
1830       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1831       if (MemVTs[i] != ValueVTs[i])
1832         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1833       Chains[i] = DAG.getStore(
1834           Chain, getCurSDLoc(), Val,
1835           // FIXME: better loc info would be nice.
1836           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1837           commonAlignment(BaseAlign, Offsets[i]));
1838     }
1839 
1840     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1841                         MVT::Other, Chains);
1842   } else if (I.getNumOperands() != 0) {
1843     SmallVector<EVT, 4> ValueVTs;
1844     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1845     unsigned NumValues = ValueVTs.size();
1846     if (NumValues) {
1847       SDValue RetOp = getValue(I.getOperand(0));
1848 
1849       const Function *F = I.getParent()->getParent();
1850 
1851       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1852           I.getOperand(0)->getType(), F->getCallingConv(),
1853           /*IsVarArg*/ false);
1854 
1855       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1856       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1857                                           Attribute::SExt))
1858         ExtendKind = ISD::SIGN_EXTEND;
1859       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1860                                                Attribute::ZExt))
1861         ExtendKind = ISD::ZERO_EXTEND;
1862 
1863       LLVMContext &Context = F->getContext();
1864       bool RetInReg = F->getAttributes().hasAttribute(
1865           AttributeList::ReturnIndex, Attribute::InReg);
1866 
1867       for (unsigned j = 0; j != NumValues; ++j) {
1868         EVT VT = ValueVTs[j];
1869 
1870         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1871           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1872 
1873         CallingConv::ID CC = F->getCallingConv();
1874 
1875         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1876         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1877         SmallVector<SDValue, 4> Parts(NumParts);
1878         getCopyToParts(DAG, getCurSDLoc(),
1879                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1880                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1881 
1882         // 'inreg' on function refers to return value
1883         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1884         if (RetInReg)
1885           Flags.setInReg();
1886 
1887         if (I.getOperand(0)->getType()->isPointerTy()) {
1888           Flags.setPointer();
1889           Flags.setPointerAddrSpace(
1890               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1891         }
1892 
1893         if (NeedsRegBlock) {
1894           Flags.setInConsecutiveRegs();
1895           if (j == NumValues - 1)
1896             Flags.setInConsecutiveRegsLast();
1897         }
1898 
1899         // Propagate extension type if any
1900         if (ExtendKind == ISD::SIGN_EXTEND)
1901           Flags.setSExt();
1902         else if (ExtendKind == ISD::ZERO_EXTEND)
1903           Flags.setZExt();
1904 
1905         for (unsigned i = 0; i < NumParts; ++i) {
1906           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1907                                         VT, /*isfixed=*/true, 0, 0));
1908           OutVals.push_back(Parts[i]);
1909         }
1910       }
1911     }
1912   }
1913 
1914   // Push in swifterror virtual register as the last element of Outs. This makes
1915   // sure swifterror virtual register will be returned in the swifterror
1916   // physical register.
1917   const Function *F = I.getParent()->getParent();
1918   if (TLI.supportSwiftError() &&
1919       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1920     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1921     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1922     Flags.setSwiftError();
1923     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1924                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1925                                   true /*isfixed*/, 1 /*origidx*/,
1926                                   0 /*partOffs*/));
1927     // Create SDNode for the swifterror virtual register.
1928     OutVals.push_back(
1929         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1930                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1931                         EVT(TLI.getPointerTy(DL))));
1932   }
1933 
1934   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1935   CallingConv::ID CallConv =
1936     DAG.getMachineFunction().getFunction().getCallingConv();
1937   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1938       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1939 
1940   // Verify that the target's LowerReturn behaved as expected.
1941   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1942          "LowerReturn didn't return a valid chain!");
1943 
1944   // Update the DAG with the new chain value resulting from return lowering.
1945   DAG.setRoot(Chain);
1946 }
1947 
1948 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1949 /// created for it, emit nodes to copy the value into the virtual
1950 /// registers.
1951 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1952   // Skip empty types
1953   if (V->getType()->isEmptyTy())
1954     return;
1955 
1956   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
1957   if (VMI != FuncInfo.ValueMap.end()) {
1958     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1959     CopyValueToVirtualRegister(V, VMI->second);
1960   }
1961 }
1962 
1963 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1964 /// the current basic block, add it to ValueMap now so that we'll get a
1965 /// CopyTo/FromReg.
1966 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1967   // No need to export constants.
1968   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1969 
1970   // Already exported?
1971   if (FuncInfo.isExportedInst(V)) return;
1972 
1973   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1974   CopyValueToVirtualRegister(V, Reg);
1975 }
1976 
1977 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1978                                                      const BasicBlock *FromBB) {
1979   // The operands of the setcc have to be in this block.  We don't know
1980   // how to export them from some other block.
1981   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1982     // Can export from current BB.
1983     if (VI->getParent() == FromBB)
1984       return true;
1985 
1986     // Is already exported, noop.
1987     return FuncInfo.isExportedInst(V);
1988   }
1989 
1990   // If this is an argument, we can export it if the BB is the entry block or
1991   // if it is already exported.
1992   if (isa<Argument>(V)) {
1993     if (FromBB == &FromBB->getParent()->getEntryBlock())
1994       return true;
1995 
1996     // Otherwise, can only export this if it is already exported.
1997     return FuncInfo.isExportedInst(V);
1998   }
1999 
2000   // Otherwise, constants can always be exported.
2001   return true;
2002 }
2003 
2004 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2005 BranchProbability
2006 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2007                                         const MachineBasicBlock *Dst) const {
2008   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2009   const BasicBlock *SrcBB = Src->getBasicBlock();
2010   const BasicBlock *DstBB = Dst->getBasicBlock();
2011   if (!BPI) {
2012     // If BPI is not available, set the default probability as 1 / N, where N is
2013     // the number of successors.
2014     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2015     return BranchProbability(1, SuccSize);
2016   }
2017   return BPI->getEdgeProbability(SrcBB, DstBB);
2018 }
2019 
2020 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2021                                                MachineBasicBlock *Dst,
2022                                                BranchProbability Prob) {
2023   if (!FuncInfo.BPI)
2024     Src->addSuccessorWithoutProb(Dst);
2025   else {
2026     if (Prob.isUnknown())
2027       Prob = getEdgeProbability(Src, Dst);
2028     Src->addSuccessor(Dst, Prob);
2029   }
2030 }
2031 
2032 static bool InBlock(const Value *V, const BasicBlock *BB) {
2033   if (const Instruction *I = dyn_cast<Instruction>(V))
2034     return I->getParent() == BB;
2035   return true;
2036 }
2037 
2038 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2039 /// This function emits a branch and is used at the leaves of an OR or an
2040 /// AND operator tree.
2041 void
2042 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2043                                                   MachineBasicBlock *TBB,
2044                                                   MachineBasicBlock *FBB,
2045                                                   MachineBasicBlock *CurBB,
2046                                                   MachineBasicBlock *SwitchBB,
2047                                                   BranchProbability TProb,
2048                                                   BranchProbability FProb,
2049                                                   bool InvertCond) {
2050   const BasicBlock *BB = CurBB->getBasicBlock();
2051 
2052   // If the leaf of the tree is a comparison, merge the condition into
2053   // the caseblock.
2054   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2055     // The operands of the cmp have to be in this block.  We don't know
2056     // how to export them from some other block.  If this is the first block
2057     // of the sequence, no exporting is needed.
2058     if (CurBB == SwitchBB ||
2059         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2060          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2061       ISD::CondCode Condition;
2062       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2063         ICmpInst::Predicate Pred =
2064             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2065         Condition = getICmpCondCode(Pred);
2066       } else {
2067         const FCmpInst *FC = cast<FCmpInst>(Cond);
2068         FCmpInst::Predicate Pred =
2069             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2070         Condition = getFCmpCondCode(Pred);
2071         if (TM.Options.NoNaNsFPMath)
2072           Condition = getFCmpCodeWithoutNaN(Condition);
2073       }
2074 
2075       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2076                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2077       SL->SwitchCases.push_back(CB);
2078       return;
2079     }
2080   }
2081 
2082   // Create a CaseBlock record representing this branch.
2083   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2084   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2085                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2086   SL->SwitchCases.push_back(CB);
2087 }
2088 
2089 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2090                                                MachineBasicBlock *TBB,
2091                                                MachineBasicBlock *FBB,
2092                                                MachineBasicBlock *CurBB,
2093                                                MachineBasicBlock *SwitchBB,
2094                                                Instruction::BinaryOps Opc,
2095                                                BranchProbability TProb,
2096                                                BranchProbability FProb,
2097                                                bool InvertCond) {
2098   // Skip over not part of the tree and remember to invert op and operands at
2099   // next level.
2100   Value *NotCond;
2101   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2102       InBlock(NotCond, CurBB->getBasicBlock())) {
2103     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2104                          !InvertCond);
2105     return;
2106   }
2107 
2108   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2109   // Compute the effective opcode for Cond, taking into account whether it needs
2110   // to be inverted, e.g.
2111   //   and (not (or A, B)), C
2112   // gets lowered as
2113   //   and (and (not A, not B), C)
2114   unsigned BOpc = 0;
2115   if (BOp) {
2116     BOpc = BOp->getOpcode();
2117     if (InvertCond) {
2118       if (BOpc == Instruction::And)
2119         BOpc = Instruction::Or;
2120       else if (BOpc == Instruction::Or)
2121         BOpc = Instruction::And;
2122     }
2123   }
2124 
2125   // If this node is not part of the or/and tree, emit it as a branch.
2126   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2127       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2128       BOp->getParent() != CurBB->getBasicBlock() ||
2129       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2130       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2131     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2132                                  TProb, FProb, InvertCond);
2133     return;
2134   }
2135 
2136   //  Create TmpBB after CurBB.
2137   MachineFunction::iterator BBI(CurBB);
2138   MachineFunction &MF = DAG.getMachineFunction();
2139   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2140   CurBB->getParent()->insert(++BBI, TmpBB);
2141 
2142   if (Opc == Instruction::Or) {
2143     // Codegen X | Y as:
2144     // BB1:
2145     //   jmp_if_X TBB
2146     //   jmp TmpBB
2147     // TmpBB:
2148     //   jmp_if_Y TBB
2149     //   jmp FBB
2150     //
2151 
2152     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2153     // The requirement is that
2154     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2155     //     = TrueProb for original BB.
2156     // Assuming the original probabilities are A and B, one choice is to set
2157     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2158     // A/(1+B) and 2B/(1+B). This choice assumes that
2159     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2160     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2161     // TmpBB, but the math is more complicated.
2162 
2163     auto NewTrueProb = TProb / 2;
2164     auto NewFalseProb = TProb / 2 + FProb;
2165     // Emit the LHS condition.
2166     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2167                          NewTrueProb, NewFalseProb, InvertCond);
2168 
2169     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2170     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2171     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2172     // Emit the RHS condition into TmpBB.
2173     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2174                          Probs[0], Probs[1], InvertCond);
2175   } else {
2176     assert(Opc == Instruction::And && "Unknown merge op!");
2177     // Codegen X & Y as:
2178     // BB1:
2179     //   jmp_if_X TmpBB
2180     //   jmp FBB
2181     // TmpBB:
2182     //   jmp_if_Y TBB
2183     //   jmp FBB
2184     //
2185     //  This requires creation of TmpBB after CurBB.
2186 
2187     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2188     // The requirement is that
2189     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2190     //     = FalseProb for original BB.
2191     // Assuming the original probabilities are A and B, one choice is to set
2192     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2193     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2194     // TrueProb for BB1 * FalseProb for TmpBB.
2195 
2196     auto NewTrueProb = TProb + FProb / 2;
2197     auto NewFalseProb = FProb / 2;
2198     // Emit the LHS condition.
2199     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2200                          NewTrueProb, NewFalseProb, InvertCond);
2201 
2202     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2203     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2204     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2205     // Emit the RHS condition into TmpBB.
2206     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2207                          Probs[0], Probs[1], InvertCond);
2208   }
2209 }
2210 
2211 /// If the set of cases should be emitted as a series of branches, return true.
2212 /// If we should emit this as a bunch of and/or'd together conditions, return
2213 /// false.
2214 bool
2215 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2216   if (Cases.size() != 2) return true;
2217 
2218   // If this is two comparisons of the same values or'd or and'd together, they
2219   // will get folded into a single comparison, so don't emit two blocks.
2220   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2221        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2222       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2223        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2224     return false;
2225   }
2226 
2227   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2228   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2229   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2230       Cases[0].CC == Cases[1].CC &&
2231       isa<Constant>(Cases[0].CmpRHS) &&
2232       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2233     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2234       return false;
2235     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2236       return false;
2237   }
2238 
2239   return true;
2240 }
2241 
2242 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2243   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2244 
2245   // Update machine-CFG edges.
2246   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2247 
2248   if (I.isUnconditional()) {
2249     // Update machine-CFG edges.
2250     BrMBB->addSuccessor(Succ0MBB);
2251 
2252     // If this is not a fall-through branch or optimizations are switched off,
2253     // emit the branch.
2254     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2255       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2256                               MVT::Other, getControlRoot(),
2257                               DAG.getBasicBlock(Succ0MBB)));
2258 
2259     return;
2260   }
2261 
2262   // If this condition is one of the special cases we handle, do special stuff
2263   // now.
2264   const Value *CondVal = I.getCondition();
2265   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2266 
2267   // If this is a series of conditions that are or'd or and'd together, emit
2268   // this as a sequence of branches instead of setcc's with and/or operations.
2269   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2270   // unpredictable branches, and vector extracts because those jumps are likely
2271   // expensive for any target), this should improve performance.
2272   // For example, instead of something like:
2273   //     cmp A, B
2274   //     C = seteq
2275   //     cmp D, E
2276   //     F = setle
2277   //     or C, F
2278   //     jnz foo
2279   // Emit:
2280   //     cmp A, B
2281   //     je foo
2282   //     cmp D, E
2283   //     jle foo
2284   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2285     Instruction::BinaryOps Opcode = BOp->getOpcode();
2286     Value *Vec, *BOp0 = BOp->getOperand(0), *BOp1 = BOp->getOperand(1);
2287     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2288         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2289         (Opcode == Instruction::And || Opcode == Instruction::Or) &&
2290         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2291           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2292       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2293                            Opcode,
2294                            getEdgeProbability(BrMBB, Succ0MBB),
2295                            getEdgeProbability(BrMBB, Succ1MBB),
2296                            /*InvertCond=*/false);
2297       // If the compares in later blocks need to use values not currently
2298       // exported from this block, export them now.  This block should always
2299       // be the first entry.
2300       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2301 
2302       // Allow some cases to be rejected.
2303       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2304         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2305           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2306           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2307         }
2308 
2309         // Emit the branch for this block.
2310         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2311         SL->SwitchCases.erase(SL->SwitchCases.begin());
2312         return;
2313       }
2314 
2315       // Okay, we decided not to do this, remove any inserted MBB's and clear
2316       // SwitchCases.
2317       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2318         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2319 
2320       SL->SwitchCases.clear();
2321     }
2322   }
2323 
2324   // Create a CaseBlock record representing this branch.
2325   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2326                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2327 
2328   // Use visitSwitchCase to actually insert the fast branch sequence for this
2329   // cond branch.
2330   visitSwitchCase(CB, BrMBB);
2331 }
2332 
2333 /// visitSwitchCase - Emits the necessary code to represent a single node in
2334 /// the binary search tree resulting from lowering a switch instruction.
2335 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2336                                           MachineBasicBlock *SwitchBB) {
2337   SDValue Cond;
2338   SDValue CondLHS = getValue(CB.CmpLHS);
2339   SDLoc dl = CB.DL;
2340 
2341   if (CB.CC == ISD::SETTRUE) {
2342     // Branch or fall through to TrueBB.
2343     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2344     SwitchBB->normalizeSuccProbs();
2345     if (CB.TrueBB != NextBlock(SwitchBB)) {
2346       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2347                               DAG.getBasicBlock(CB.TrueBB)));
2348     }
2349     return;
2350   }
2351 
2352   auto &TLI = DAG.getTargetLoweringInfo();
2353   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2354 
2355   // Build the setcc now.
2356   if (!CB.CmpMHS) {
2357     // Fold "(X == true)" to X and "(X == false)" to !X to
2358     // handle common cases produced by branch lowering.
2359     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2360         CB.CC == ISD::SETEQ)
2361       Cond = CondLHS;
2362     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2363              CB.CC == ISD::SETEQ) {
2364       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2365       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2366     } else {
2367       SDValue CondRHS = getValue(CB.CmpRHS);
2368 
2369       // If a pointer's DAG type is larger than its memory type then the DAG
2370       // values are zero-extended. This breaks signed comparisons so truncate
2371       // back to the underlying type before doing the compare.
2372       if (CondLHS.getValueType() != MemVT) {
2373         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2374         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2375       }
2376       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2377     }
2378   } else {
2379     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2380 
2381     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2382     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2383 
2384     SDValue CmpOp = getValue(CB.CmpMHS);
2385     EVT VT = CmpOp.getValueType();
2386 
2387     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2388       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2389                           ISD::SETLE);
2390     } else {
2391       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2392                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2393       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2394                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2395     }
2396   }
2397 
2398   // Update successor info
2399   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2400   // TrueBB and FalseBB are always different unless the incoming IR is
2401   // degenerate. This only happens when running llc on weird IR.
2402   if (CB.TrueBB != CB.FalseBB)
2403     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2404   SwitchBB->normalizeSuccProbs();
2405 
2406   // If the lhs block is the next block, invert the condition so that we can
2407   // fall through to the lhs instead of the rhs block.
2408   if (CB.TrueBB == NextBlock(SwitchBB)) {
2409     std::swap(CB.TrueBB, CB.FalseBB);
2410     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2411     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2412   }
2413 
2414   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2415                                MVT::Other, getControlRoot(), Cond,
2416                                DAG.getBasicBlock(CB.TrueBB));
2417 
2418   // Insert the false branch. Do this even if it's a fall through branch,
2419   // this makes it easier to do DAG optimizations which require inverting
2420   // the branch condition.
2421   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2422                        DAG.getBasicBlock(CB.FalseBB));
2423 
2424   DAG.setRoot(BrCond);
2425 }
2426 
2427 /// visitJumpTable - Emit JumpTable node in the current MBB
2428 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2429   // Emit the code for the jump table
2430   assert(JT.Reg != -1U && "Should lower JT Header first!");
2431   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2432   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2433                                      JT.Reg, PTy);
2434   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2435   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2436                                     MVT::Other, Index.getValue(1),
2437                                     Table, Index);
2438   DAG.setRoot(BrJumpTable);
2439 }
2440 
2441 /// visitJumpTableHeader - This function emits necessary code to produce index
2442 /// in the JumpTable from switch case.
2443 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2444                                                JumpTableHeader &JTH,
2445                                                MachineBasicBlock *SwitchBB) {
2446   SDLoc dl = getCurSDLoc();
2447 
2448   // Subtract the lowest switch case value from the value being switched on.
2449   SDValue SwitchOp = getValue(JTH.SValue);
2450   EVT VT = SwitchOp.getValueType();
2451   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2452                             DAG.getConstant(JTH.First, dl, VT));
2453 
2454   // The SDNode we just created, which holds the value being switched on minus
2455   // the smallest case value, needs to be copied to a virtual register so it
2456   // can be used as an index into the jump table in a subsequent basic block.
2457   // This value may be smaller or larger than the target's pointer type, and
2458   // therefore require extension or truncating.
2459   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2460   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2461 
2462   unsigned JumpTableReg =
2463       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2464   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2465                                     JumpTableReg, SwitchOp);
2466   JT.Reg = JumpTableReg;
2467 
2468   if (!JTH.OmitRangeCheck) {
2469     // Emit the range check for the jump table, and branch to the default block
2470     // for the switch statement if the value being switched on exceeds the
2471     // largest case in the switch.
2472     SDValue CMP = DAG.getSetCC(
2473         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2474                                    Sub.getValueType()),
2475         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2476 
2477     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2478                                  MVT::Other, CopyTo, CMP,
2479                                  DAG.getBasicBlock(JT.Default));
2480 
2481     // Avoid emitting unnecessary branches to the next block.
2482     if (JT.MBB != NextBlock(SwitchBB))
2483       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2484                            DAG.getBasicBlock(JT.MBB));
2485 
2486     DAG.setRoot(BrCond);
2487   } else {
2488     // Avoid emitting unnecessary branches to the next block.
2489     if (JT.MBB != NextBlock(SwitchBB))
2490       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2491                               DAG.getBasicBlock(JT.MBB)));
2492     else
2493       DAG.setRoot(CopyTo);
2494   }
2495 }
2496 
2497 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2498 /// variable if there exists one.
2499 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2500                                  SDValue &Chain) {
2501   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2502   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2503   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2504   MachineFunction &MF = DAG.getMachineFunction();
2505   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2506   MachineSDNode *Node =
2507       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2508   if (Global) {
2509     MachinePointerInfo MPInfo(Global);
2510     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2511                  MachineMemOperand::MODereferenceable;
2512     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2513         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2514     DAG.setNodeMemRefs(Node, {MemRef});
2515   }
2516   if (PtrTy != PtrMemTy)
2517     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2518   return SDValue(Node, 0);
2519 }
2520 
2521 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2522 /// tail spliced into a stack protector check success bb.
2523 ///
2524 /// For a high level explanation of how this fits into the stack protector
2525 /// generation see the comment on the declaration of class
2526 /// StackProtectorDescriptor.
2527 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2528                                                   MachineBasicBlock *ParentBB) {
2529 
2530   // First create the loads to the guard/stack slot for the comparison.
2531   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2532   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2533   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2534 
2535   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2536   int FI = MFI.getStackProtectorIndex();
2537 
2538   SDValue Guard;
2539   SDLoc dl = getCurSDLoc();
2540   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2541   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2542   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2543 
2544   // Generate code to load the content of the guard slot.
2545   SDValue GuardVal = DAG.getLoad(
2546       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2547       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2548       MachineMemOperand::MOVolatile);
2549 
2550   if (TLI.useStackGuardXorFP())
2551     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2552 
2553   // Retrieve guard check function, nullptr if instrumentation is inlined.
2554   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2555     // The target provides a guard check function to validate the guard value.
2556     // Generate a call to that function with the content of the guard slot as
2557     // argument.
2558     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2559     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2560 
2561     TargetLowering::ArgListTy Args;
2562     TargetLowering::ArgListEntry Entry;
2563     Entry.Node = GuardVal;
2564     Entry.Ty = FnTy->getParamType(0);
2565     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2566       Entry.IsInReg = true;
2567     Args.push_back(Entry);
2568 
2569     TargetLowering::CallLoweringInfo CLI(DAG);
2570     CLI.setDebugLoc(getCurSDLoc())
2571         .setChain(DAG.getEntryNode())
2572         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2573                    getValue(GuardCheckFn), std::move(Args));
2574 
2575     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2576     DAG.setRoot(Result.second);
2577     return;
2578   }
2579 
2580   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2581   // Otherwise, emit a volatile load to retrieve the stack guard value.
2582   SDValue Chain = DAG.getEntryNode();
2583   if (TLI.useLoadStackGuardNode()) {
2584     Guard = getLoadStackGuard(DAG, dl, Chain);
2585   } else {
2586     const Value *IRGuard = TLI.getSDagStackGuard(M);
2587     SDValue GuardPtr = getValue(IRGuard);
2588 
2589     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2590                         MachinePointerInfo(IRGuard, 0), Align,
2591                         MachineMemOperand::MOVolatile);
2592   }
2593 
2594   // Perform the comparison via a getsetcc.
2595   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2596                                                         *DAG.getContext(),
2597                                                         Guard.getValueType()),
2598                              Guard, GuardVal, ISD::SETNE);
2599 
2600   // If the guard/stackslot do not equal, branch to failure MBB.
2601   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2602                                MVT::Other, GuardVal.getOperand(0),
2603                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2604   // Otherwise branch to success MBB.
2605   SDValue Br = DAG.getNode(ISD::BR, dl,
2606                            MVT::Other, BrCond,
2607                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2608 
2609   DAG.setRoot(Br);
2610 }
2611 
2612 /// Codegen the failure basic block for a stack protector check.
2613 ///
2614 /// A failure stack protector machine basic block consists simply of a call to
2615 /// __stack_chk_fail().
2616 ///
2617 /// For a high level explanation of how this fits into the stack protector
2618 /// generation see the comment on the declaration of class
2619 /// StackProtectorDescriptor.
2620 void
2621 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2622   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2623   TargetLowering::MakeLibCallOptions CallOptions;
2624   CallOptions.setDiscardResult(true);
2625   SDValue Chain =
2626       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2627                       None, CallOptions, getCurSDLoc()).second;
2628   // On PS4, the "return address" must still be within the calling function,
2629   // even if it's at the very end, so emit an explicit TRAP here.
2630   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2631   if (TM.getTargetTriple().isPS4CPU())
2632     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2633   // WebAssembly needs an unreachable instruction after a non-returning call,
2634   // because the function return type can be different from __stack_chk_fail's
2635   // return type (void).
2636   if (TM.getTargetTriple().isWasm())
2637     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2638 
2639   DAG.setRoot(Chain);
2640 }
2641 
2642 /// visitBitTestHeader - This function emits necessary code to produce value
2643 /// suitable for "bit tests"
2644 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2645                                              MachineBasicBlock *SwitchBB) {
2646   SDLoc dl = getCurSDLoc();
2647 
2648   // Subtract the minimum value.
2649   SDValue SwitchOp = getValue(B.SValue);
2650   EVT VT = SwitchOp.getValueType();
2651   SDValue RangeSub =
2652       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2653 
2654   // Determine the type of the test operands.
2655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2656   bool UsePtrType = false;
2657   if (!TLI.isTypeLegal(VT)) {
2658     UsePtrType = true;
2659   } else {
2660     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2661       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2662         // Switch table case range are encoded into series of masks.
2663         // Just use pointer type, it's guaranteed to fit.
2664         UsePtrType = true;
2665         break;
2666       }
2667   }
2668   SDValue Sub = RangeSub;
2669   if (UsePtrType) {
2670     VT = TLI.getPointerTy(DAG.getDataLayout());
2671     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2672   }
2673 
2674   B.RegVT = VT.getSimpleVT();
2675   B.Reg = FuncInfo.CreateReg(B.RegVT);
2676   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2677 
2678   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2679 
2680   if (!B.OmitRangeCheck)
2681     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2682   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2683   SwitchBB->normalizeSuccProbs();
2684 
2685   SDValue Root = CopyTo;
2686   if (!B.OmitRangeCheck) {
2687     // Conditional branch to the default block.
2688     SDValue RangeCmp = DAG.getSetCC(dl,
2689         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2690                                RangeSub.getValueType()),
2691         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2692         ISD::SETUGT);
2693 
2694     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2695                        DAG.getBasicBlock(B.Default));
2696   }
2697 
2698   // Avoid emitting unnecessary branches to the next block.
2699   if (MBB != NextBlock(SwitchBB))
2700     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2701 
2702   DAG.setRoot(Root);
2703 }
2704 
2705 /// visitBitTestCase - this function produces one "bit test"
2706 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2707                                            MachineBasicBlock* NextMBB,
2708                                            BranchProbability BranchProbToNext,
2709                                            unsigned Reg,
2710                                            BitTestCase &B,
2711                                            MachineBasicBlock *SwitchBB) {
2712   SDLoc dl = getCurSDLoc();
2713   MVT VT = BB.RegVT;
2714   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2715   SDValue Cmp;
2716   unsigned PopCount = countPopulation(B.Mask);
2717   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2718   if (PopCount == 1) {
2719     // Testing for a single bit; just compare the shift count with what it
2720     // would need to be to shift a 1 bit in that position.
2721     Cmp = DAG.getSetCC(
2722         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2723         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2724         ISD::SETEQ);
2725   } else if (PopCount == BB.Range) {
2726     // There is only one zero bit in the range, test for it directly.
2727     Cmp = DAG.getSetCC(
2728         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2729         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2730         ISD::SETNE);
2731   } else {
2732     // Make desired shift
2733     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2734                                     DAG.getConstant(1, dl, VT), ShiftOp);
2735 
2736     // Emit bit tests and jumps
2737     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2738                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2739     Cmp = DAG.getSetCC(
2740         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2741         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2742   }
2743 
2744   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2745   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2746   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2747   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2748   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2749   // one as they are relative probabilities (and thus work more like weights),
2750   // and hence we need to normalize them to let the sum of them become one.
2751   SwitchBB->normalizeSuccProbs();
2752 
2753   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2754                               MVT::Other, getControlRoot(),
2755                               Cmp, DAG.getBasicBlock(B.TargetBB));
2756 
2757   // Avoid emitting unnecessary branches to the next block.
2758   if (NextMBB != NextBlock(SwitchBB))
2759     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2760                         DAG.getBasicBlock(NextMBB));
2761 
2762   DAG.setRoot(BrAnd);
2763 }
2764 
2765 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2766   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2767 
2768   // Retrieve successors. Look through artificial IR level blocks like
2769   // catchswitch for successors.
2770   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2771   const BasicBlock *EHPadBB = I.getSuccessor(1);
2772 
2773   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2774   // have to do anything here to lower funclet bundles.
2775   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2776                                         LLVMContext::OB_gc_transition,
2777                                         LLVMContext::OB_gc_live,
2778                                         LLVMContext::OB_funclet,
2779                                         LLVMContext::OB_cfguardtarget}) &&
2780          "Cannot lower invokes with arbitrary operand bundles yet!");
2781 
2782   const Value *Callee(I.getCalledOperand());
2783   const Function *Fn = dyn_cast<Function>(Callee);
2784   if (isa<InlineAsm>(Callee))
2785     visitInlineAsm(I);
2786   else if (Fn && Fn->isIntrinsic()) {
2787     switch (Fn->getIntrinsicID()) {
2788     default:
2789       llvm_unreachable("Cannot invoke this intrinsic");
2790     case Intrinsic::donothing:
2791       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2792       break;
2793     case Intrinsic::experimental_patchpoint_void:
2794     case Intrinsic::experimental_patchpoint_i64:
2795       visitPatchpoint(I, EHPadBB);
2796       break;
2797     case Intrinsic::experimental_gc_statepoint:
2798       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2799       break;
2800     case Intrinsic::wasm_rethrow_in_catch: {
2801       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2802       // special because it can be invoked, so we manually lower it to a DAG
2803       // node here.
2804       SmallVector<SDValue, 8> Ops;
2805       Ops.push_back(getRoot()); // inchain
2806       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2807       Ops.push_back(
2808           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2809                                 TLI.getPointerTy(DAG.getDataLayout())));
2810       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2811       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2812       break;
2813     }
2814     }
2815   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2816     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2817     // Eventually we will support lowering the @llvm.experimental.deoptimize
2818     // intrinsic, and right now there are no plans to support other intrinsics
2819     // with deopt state.
2820     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2821   } else {
2822     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2823   }
2824 
2825   // If the value of the invoke is used outside of its defining block, make it
2826   // available as a virtual register.
2827   // We already took care of the exported value for the statepoint instruction
2828   // during call to the LowerStatepoint.
2829   if (!isa<GCStatepointInst>(I)) {
2830     CopyToExportRegsIfNeeded(&I);
2831   }
2832 
2833   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2834   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2835   BranchProbability EHPadBBProb =
2836       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2837           : BranchProbability::getZero();
2838   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2839 
2840   // Update successor info.
2841   addSuccessorWithProb(InvokeMBB, Return);
2842   for (auto &UnwindDest : UnwindDests) {
2843     UnwindDest.first->setIsEHPad();
2844     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2845   }
2846   InvokeMBB->normalizeSuccProbs();
2847 
2848   // Drop into normal successor.
2849   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2850                           DAG.getBasicBlock(Return)));
2851 }
2852 
2853 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2854   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2855 
2856   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2857   // have to do anything here to lower funclet bundles.
2858   assert(!I.hasOperandBundlesOtherThan(
2859              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2860          "Cannot lower callbrs with arbitrary operand bundles yet!");
2861 
2862   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2863   visitInlineAsm(I);
2864   CopyToExportRegsIfNeeded(&I);
2865 
2866   // Retrieve successors.
2867   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2868 
2869   // Update successor info.
2870   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2871   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2872     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2873     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2874     Target->setIsInlineAsmBrIndirectTarget();
2875   }
2876   CallBrMBB->normalizeSuccProbs();
2877 
2878   // Drop into default successor.
2879   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2880                           MVT::Other, getControlRoot(),
2881                           DAG.getBasicBlock(Return)));
2882 }
2883 
2884 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2885   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2886 }
2887 
2888 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2889   assert(FuncInfo.MBB->isEHPad() &&
2890          "Call to landingpad not in landing pad!");
2891 
2892   // If there aren't registers to copy the values into (e.g., during SjLj
2893   // exceptions), then don't bother to create these DAG nodes.
2894   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2895   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2896   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2897       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2898     return;
2899 
2900   // If landingpad's return type is token type, we don't create DAG nodes
2901   // for its exception pointer and selector value. The extraction of exception
2902   // pointer or selector value from token type landingpads is not currently
2903   // supported.
2904   if (LP.getType()->isTokenTy())
2905     return;
2906 
2907   SmallVector<EVT, 2> ValueVTs;
2908   SDLoc dl = getCurSDLoc();
2909   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2910   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2911 
2912   // Get the two live-in registers as SDValues. The physregs have already been
2913   // copied into virtual registers.
2914   SDValue Ops[2];
2915   if (FuncInfo.ExceptionPointerVirtReg) {
2916     Ops[0] = DAG.getZExtOrTrunc(
2917         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2918                            FuncInfo.ExceptionPointerVirtReg,
2919                            TLI.getPointerTy(DAG.getDataLayout())),
2920         dl, ValueVTs[0]);
2921   } else {
2922     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2923   }
2924   Ops[1] = DAG.getZExtOrTrunc(
2925       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2926                          FuncInfo.ExceptionSelectorVirtReg,
2927                          TLI.getPointerTy(DAG.getDataLayout())),
2928       dl, ValueVTs[1]);
2929 
2930   // Merge into one.
2931   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2932                             DAG.getVTList(ValueVTs), Ops);
2933   setValue(&LP, Res);
2934 }
2935 
2936 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2937                                            MachineBasicBlock *Last) {
2938   // Update JTCases.
2939   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2940     if (SL->JTCases[i].first.HeaderBB == First)
2941       SL->JTCases[i].first.HeaderBB = Last;
2942 
2943   // Update BitTestCases.
2944   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2945     if (SL->BitTestCases[i].Parent == First)
2946       SL->BitTestCases[i].Parent = Last;
2947 }
2948 
2949 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2950   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2951 
2952   // Update machine-CFG edges with unique successors.
2953   SmallSet<BasicBlock*, 32> Done;
2954   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2955     BasicBlock *BB = I.getSuccessor(i);
2956     bool Inserted = Done.insert(BB).second;
2957     if (!Inserted)
2958         continue;
2959 
2960     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2961     addSuccessorWithProb(IndirectBrMBB, Succ);
2962   }
2963   IndirectBrMBB->normalizeSuccProbs();
2964 
2965   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2966                           MVT::Other, getControlRoot(),
2967                           getValue(I.getAddress())));
2968 }
2969 
2970 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2971   if (!DAG.getTarget().Options.TrapUnreachable)
2972     return;
2973 
2974   // We may be able to ignore unreachable behind a noreturn call.
2975   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2976     const BasicBlock &BB = *I.getParent();
2977     if (&I != &BB.front()) {
2978       BasicBlock::const_iterator PredI =
2979         std::prev(BasicBlock::const_iterator(&I));
2980       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2981         if (Call->doesNotReturn())
2982           return;
2983       }
2984     }
2985   }
2986 
2987   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2988 }
2989 
2990 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
2991   SDNodeFlags Flags;
2992 
2993   SDValue Op = getValue(I.getOperand(0));
2994   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
2995                                     Op, Flags);
2996   setValue(&I, UnNodeValue);
2997 }
2998 
2999 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3000   SDNodeFlags Flags;
3001   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3002     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3003     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3004   }
3005   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3006     Flags.setExact(ExactOp->isExact());
3007   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3008     Flags.copyFMF(*FPOp);
3009 
3010   SDValue Op1 = getValue(I.getOperand(0));
3011   SDValue Op2 = getValue(I.getOperand(1));
3012   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3013                                      Op1, Op2, Flags);
3014   setValue(&I, BinNodeValue);
3015 }
3016 
3017 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3018   SDValue Op1 = getValue(I.getOperand(0));
3019   SDValue Op2 = getValue(I.getOperand(1));
3020 
3021   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3022       Op1.getValueType(), DAG.getDataLayout());
3023 
3024   // Coerce the shift amount to the right type if we can.
3025   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3026     unsigned ShiftSize = ShiftTy.getSizeInBits();
3027     unsigned Op2Size = Op2.getValueSizeInBits();
3028     SDLoc DL = getCurSDLoc();
3029 
3030     // If the operand is smaller than the shift count type, promote it.
3031     if (ShiftSize > Op2Size)
3032       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3033 
3034     // If the operand is larger than the shift count type but the shift
3035     // count type has enough bits to represent any shift value, truncate
3036     // it now. This is a common case and it exposes the truncate to
3037     // optimization early.
3038     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3039       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3040     // Otherwise we'll need to temporarily settle for some other convenient
3041     // type.  Type legalization will make adjustments once the shiftee is split.
3042     else
3043       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3044   }
3045 
3046   bool nuw = false;
3047   bool nsw = false;
3048   bool exact = false;
3049 
3050   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3051 
3052     if (const OverflowingBinaryOperator *OFBinOp =
3053             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3054       nuw = OFBinOp->hasNoUnsignedWrap();
3055       nsw = OFBinOp->hasNoSignedWrap();
3056     }
3057     if (const PossiblyExactOperator *ExactOp =
3058             dyn_cast<const PossiblyExactOperator>(&I))
3059       exact = ExactOp->isExact();
3060   }
3061   SDNodeFlags Flags;
3062   Flags.setExact(exact);
3063   Flags.setNoSignedWrap(nsw);
3064   Flags.setNoUnsignedWrap(nuw);
3065   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3066                             Flags);
3067   setValue(&I, Res);
3068 }
3069 
3070 void SelectionDAGBuilder::visitSDiv(const User &I) {
3071   SDValue Op1 = getValue(I.getOperand(0));
3072   SDValue Op2 = getValue(I.getOperand(1));
3073 
3074   SDNodeFlags Flags;
3075   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3076                  cast<PossiblyExactOperator>(&I)->isExact());
3077   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3078                            Op2, Flags));
3079 }
3080 
3081 void SelectionDAGBuilder::visitICmp(const User &I) {
3082   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3083   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3084     predicate = IC->getPredicate();
3085   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3086     predicate = ICmpInst::Predicate(IC->getPredicate());
3087   SDValue Op1 = getValue(I.getOperand(0));
3088   SDValue Op2 = getValue(I.getOperand(1));
3089   ISD::CondCode Opcode = getICmpCondCode(predicate);
3090 
3091   auto &TLI = DAG.getTargetLoweringInfo();
3092   EVT MemVT =
3093       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3094 
3095   // If a pointer's DAG type is larger than its memory type then the DAG values
3096   // are zero-extended. This breaks signed comparisons so truncate back to the
3097   // underlying type before doing the compare.
3098   if (Op1.getValueType() != MemVT) {
3099     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3100     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3101   }
3102 
3103   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3104                                                         I.getType());
3105   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3106 }
3107 
3108 void SelectionDAGBuilder::visitFCmp(const User &I) {
3109   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3110   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3111     predicate = FC->getPredicate();
3112   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3113     predicate = FCmpInst::Predicate(FC->getPredicate());
3114   SDValue Op1 = getValue(I.getOperand(0));
3115   SDValue Op2 = getValue(I.getOperand(1));
3116 
3117   ISD::CondCode Condition = getFCmpCondCode(predicate);
3118   auto *FPMO = cast<FPMathOperator>(&I);
3119   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3120     Condition = getFCmpCodeWithoutNaN(Condition);
3121 
3122   SDNodeFlags Flags;
3123   Flags.copyFMF(*FPMO);
3124 
3125   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3126                                                         I.getType());
3127   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition, Flags));
3128 }
3129 
3130 // Check if the condition of the select has one use or two users that are both
3131 // selects with the same condition.
3132 static bool hasOnlySelectUsers(const Value *Cond) {
3133   return llvm::all_of(Cond->users(), [](const Value *V) {
3134     return isa<SelectInst>(V);
3135   });
3136 }
3137 
3138 void SelectionDAGBuilder::visitSelect(const User &I) {
3139   SmallVector<EVT, 4> ValueVTs;
3140   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3141                   ValueVTs);
3142   unsigned NumValues = ValueVTs.size();
3143   if (NumValues == 0) return;
3144 
3145   SmallVector<SDValue, 4> Values(NumValues);
3146   SDValue Cond     = getValue(I.getOperand(0));
3147   SDValue LHSVal   = getValue(I.getOperand(1));
3148   SDValue RHSVal   = getValue(I.getOperand(2));
3149   SmallVector<SDValue, 1> BaseOps(1, Cond);
3150   ISD::NodeType OpCode =
3151       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3152 
3153   bool IsUnaryAbs = false;
3154 
3155   SDNodeFlags Flags;
3156   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3157     Flags.copyFMF(*FPOp);
3158 
3159   // Min/max matching is only viable if all output VTs are the same.
3160   if (is_splat(ValueVTs)) {
3161     EVT VT = ValueVTs[0];
3162     LLVMContext &Ctx = *DAG.getContext();
3163     auto &TLI = DAG.getTargetLoweringInfo();
3164 
3165     // We care about the legality of the operation after it has been type
3166     // legalized.
3167     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3168       VT = TLI.getTypeToTransformTo(Ctx, VT);
3169 
3170     // If the vselect is legal, assume we want to leave this as a vector setcc +
3171     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3172     // min/max is legal on the scalar type.
3173     bool UseScalarMinMax = VT.isVector() &&
3174       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3175 
3176     Value *LHS, *RHS;
3177     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3178     ISD::NodeType Opc = ISD::DELETED_NODE;
3179     switch (SPR.Flavor) {
3180     case SPF_UMAX:    Opc = ISD::UMAX; break;
3181     case SPF_UMIN:    Opc = ISD::UMIN; break;
3182     case SPF_SMAX:    Opc = ISD::SMAX; break;
3183     case SPF_SMIN:    Opc = ISD::SMIN; break;
3184     case SPF_FMINNUM:
3185       switch (SPR.NaNBehavior) {
3186       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3187       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3188       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3189       case SPNB_RETURNS_ANY: {
3190         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3191           Opc = ISD::FMINNUM;
3192         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3193           Opc = ISD::FMINIMUM;
3194         else if (UseScalarMinMax)
3195           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3196             ISD::FMINNUM : ISD::FMINIMUM;
3197         break;
3198       }
3199       }
3200       break;
3201     case SPF_FMAXNUM:
3202       switch (SPR.NaNBehavior) {
3203       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3204       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3205       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3206       case SPNB_RETURNS_ANY:
3207 
3208         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3209           Opc = ISD::FMAXNUM;
3210         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3211           Opc = ISD::FMAXIMUM;
3212         else if (UseScalarMinMax)
3213           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3214             ISD::FMAXNUM : ISD::FMAXIMUM;
3215         break;
3216       }
3217       break;
3218     case SPF_ABS:
3219       IsUnaryAbs = true;
3220       Opc = ISD::ABS;
3221       break;
3222     case SPF_NABS:
3223       // TODO: we need to produce sub(0, abs(X)).
3224     default: break;
3225     }
3226 
3227     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3228         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3229          (UseScalarMinMax &&
3230           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3231         // If the underlying comparison instruction is used by any other
3232         // instruction, the consumed instructions won't be destroyed, so it is
3233         // not profitable to convert to a min/max.
3234         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3235       OpCode = Opc;
3236       LHSVal = getValue(LHS);
3237       RHSVal = getValue(RHS);
3238       BaseOps.clear();
3239     }
3240 
3241     if (IsUnaryAbs) {
3242       OpCode = Opc;
3243       LHSVal = getValue(LHS);
3244       BaseOps.clear();
3245     }
3246   }
3247 
3248   if (IsUnaryAbs) {
3249     for (unsigned i = 0; i != NumValues; ++i) {
3250       Values[i] =
3251           DAG.getNode(OpCode, getCurSDLoc(),
3252                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3253                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3254     }
3255   } else {
3256     for (unsigned i = 0; i != NumValues; ++i) {
3257       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3258       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3259       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3260       Values[i] = DAG.getNode(
3261           OpCode, getCurSDLoc(),
3262           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3263     }
3264   }
3265 
3266   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3267                            DAG.getVTList(ValueVTs), Values));
3268 }
3269 
3270 void SelectionDAGBuilder::visitTrunc(const User &I) {
3271   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3272   SDValue N = getValue(I.getOperand(0));
3273   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3274                                                         I.getType());
3275   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3276 }
3277 
3278 void SelectionDAGBuilder::visitZExt(const User &I) {
3279   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3280   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3281   SDValue N = getValue(I.getOperand(0));
3282   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3283                                                         I.getType());
3284   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3285 }
3286 
3287 void SelectionDAGBuilder::visitSExt(const User &I) {
3288   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3289   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3290   SDValue N = getValue(I.getOperand(0));
3291   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3292                                                         I.getType());
3293   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3294 }
3295 
3296 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3297   // FPTrunc is never a no-op cast, no need to check
3298   SDValue N = getValue(I.getOperand(0));
3299   SDLoc dl = getCurSDLoc();
3300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3301   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3302   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3303                            DAG.getTargetConstant(
3304                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3305 }
3306 
3307 void SelectionDAGBuilder::visitFPExt(const User &I) {
3308   // FPExt is never a no-op cast, no need to check
3309   SDValue N = getValue(I.getOperand(0));
3310   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3311                                                         I.getType());
3312   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3313 }
3314 
3315 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3316   // FPToUI is never a no-op cast, no need to check
3317   SDValue N = getValue(I.getOperand(0));
3318   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3319                                                         I.getType());
3320   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3321 }
3322 
3323 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3324   // FPToSI is never a no-op cast, no need to check
3325   SDValue N = getValue(I.getOperand(0));
3326   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3327                                                         I.getType());
3328   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3329 }
3330 
3331 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3332   // UIToFP is never a no-op cast, no need to check
3333   SDValue N = getValue(I.getOperand(0));
3334   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3335                                                         I.getType());
3336   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3337 }
3338 
3339 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3340   // SIToFP is never a no-op cast, no need to check
3341   SDValue N = getValue(I.getOperand(0));
3342   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3343                                                         I.getType());
3344   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3345 }
3346 
3347 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3348   // What to do depends on the size of the integer and the size of the pointer.
3349   // We can either truncate, zero extend, or no-op, accordingly.
3350   SDValue N = getValue(I.getOperand(0));
3351   auto &TLI = DAG.getTargetLoweringInfo();
3352   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3353                                                         I.getType());
3354   EVT PtrMemVT =
3355       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3356   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3357   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3358   setValue(&I, N);
3359 }
3360 
3361 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3362   // What to do depends on the size of the integer and the size of the pointer.
3363   // We can either truncate, zero extend, or no-op, accordingly.
3364   SDValue N = getValue(I.getOperand(0));
3365   auto &TLI = DAG.getTargetLoweringInfo();
3366   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3367   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3368   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3369   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3370   setValue(&I, N);
3371 }
3372 
3373 void SelectionDAGBuilder::visitBitCast(const User &I) {
3374   SDValue N = getValue(I.getOperand(0));
3375   SDLoc dl = getCurSDLoc();
3376   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3377                                                         I.getType());
3378 
3379   // BitCast assures us that source and destination are the same size so this is
3380   // either a BITCAST or a no-op.
3381   if (DestVT != N.getValueType())
3382     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3383                              DestVT, N)); // convert types.
3384   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3385   // might fold any kind of constant expression to an integer constant and that
3386   // is not what we are looking for. Only recognize a bitcast of a genuine
3387   // constant integer as an opaque constant.
3388   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3389     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3390                                  /*isOpaque*/true));
3391   else
3392     setValue(&I, N);            // noop cast.
3393 }
3394 
3395 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3396   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3397   const Value *SV = I.getOperand(0);
3398   SDValue N = getValue(SV);
3399   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3400 
3401   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3402   unsigned DestAS = I.getType()->getPointerAddressSpace();
3403 
3404   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3405     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3406 
3407   setValue(&I, N);
3408 }
3409 
3410 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3411   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3412   SDValue InVec = getValue(I.getOperand(0));
3413   SDValue InVal = getValue(I.getOperand(1));
3414   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3415                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3416   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3417                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3418                            InVec, InVal, InIdx));
3419 }
3420 
3421 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3422   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3423   SDValue InVec = getValue(I.getOperand(0));
3424   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3425                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3426   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3427                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3428                            InVec, InIdx));
3429 }
3430 
3431 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3432   SDValue Src1 = getValue(I.getOperand(0));
3433   SDValue Src2 = getValue(I.getOperand(1));
3434   ArrayRef<int> Mask;
3435   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3436     Mask = SVI->getShuffleMask();
3437   else
3438     Mask = cast<ConstantExpr>(I).getShuffleMask();
3439   SDLoc DL = getCurSDLoc();
3440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3441   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3442   EVT SrcVT = Src1.getValueType();
3443 
3444   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3445       VT.isScalableVector()) {
3446     // Canonical splat form of first element of first input vector.
3447     SDValue FirstElt =
3448         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3449                     DAG.getVectorIdxConstant(0, DL));
3450     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3451     return;
3452   }
3453 
3454   // For now, we only handle splats for scalable vectors.
3455   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3456   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3457   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3458 
3459   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3460   unsigned MaskNumElts = Mask.size();
3461 
3462   if (SrcNumElts == MaskNumElts) {
3463     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3464     return;
3465   }
3466 
3467   // Normalize the shuffle vector since mask and vector length don't match.
3468   if (SrcNumElts < MaskNumElts) {
3469     // Mask is longer than the source vectors. We can use concatenate vector to
3470     // make the mask and vectors lengths match.
3471 
3472     if (MaskNumElts % SrcNumElts == 0) {
3473       // Mask length is a multiple of the source vector length.
3474       // Check if the shuffle is some kind of concatenation of the input
3475       // vectors.
3476       unsigned NumConcat = MaskNumElts / SrcNumElts;
3477       bool IsConcat = true;
3478       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3479       for (unsigned i = 0; i != MaskNumElts; ++i) {
3480         int Idx = Mask[i];
3481         if (Idx < 0)
3482           continue;
3483         // Ensure the indices in each SrcVT sized piece are sequential and that
3484         // the same source is used for the whole piece.
3485         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3486             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3487              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3488           IsConcat = false;
3489           break;
3490         }
3491         // Remember which source this index came from.
3492         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3493       }
3494 
3495       // The shuffle is concatenating multiple vectors together. Just emit
3496       // a CONCAT_VECTORS operation.
3497       if (IsConcat) {
3498         SmallVector<SDValue, 8> ConcatOps;
3499         for (auto Src : ConcatSrcs) {
3500           if (Src < 0)
3501             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3502           else if (Src == 0)
3503             ConcatOps.push_back(Src1);
3504           else
3505             ConcatOps.push_back(Src2);
3506         }
3507         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3508         return;
3509       }
3510     }
3511 
3512     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3513     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3514     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3515                                     PaddedMaskNumElts);
3516 
3517     // Pad both vectors with undefs to make them the same length as the mask.
3518     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3519 
3520     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3521     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3522     MOps1[0] = Src1;
3523     MOps2[0] = Src2;
3524 
3525     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3526     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3527 
3528     // Readjust mask for new input vector length.
3529     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3530     for (unsigned i = 0; i != MaskNumElts; ++i) {
3531       int Idx = Mask[i];
3532       if (Idx >= (int)SrcNumElts)
3533         Idx -= SrcNumElts - PaddedMaskNumElts;
3534       MappedOps[i] = Idx;
3535     }
3536 
3537     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3538 
3539     // If the concatenated vector was padded, extract a subvector with the
3540     // correct number of elements.
3541     if (MaskNumElts != PaddedMaskNumElts)
3542       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3543                            DAG.getVectorIdxConstant(0, DL));
3544 
3545     setValue(&I, Result);
3546     return;
3547   }
3548 
3549   if (SrcNumElts > MaskNumElts) {
3550     // Analyze the access pattern of the vector to see if we can extract
3551     // two subvectors and do the shuffle.
3552     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3553     bool CanExtract = true;
3554     for (int Idx : Mask) {
3555       unsigned Input = 0;
3556       if (Idx < 0)
3557         continue;
3558 
3559       if (Idx >= (int)SrcNumElts) {
3560         Input = 1;
3561         Idx -= SrcNumElts;
3562       }
3563 
3564       // If all the indices come from the same MaskNumElts sized portion of
3565       // the sources we can use extract. Also make sure the extract wouldn't
3566       // extract past the end of the source.
3567       int NewStartIdx = alignDown(Idx, MaskNumElts);
3568       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3569           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3570         CanExtract = false;
3571       // Make sure we always update StartIdx as we use it to track if all
3572       // elements are undef.
3573       StartIdx[Input] = NewStartIdx;
3574     }
3575 
3576     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3577       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3578       return;
3579     }
3580     if (CanExtract) {
3581       // Extract appropriate subvector and generate a vector shuffle
3582       for (unsigned Input = 0; Input < 2; ++Input) {
3583         SDValue &Src = Input == 0 ? Src1 : Src2;
3584         if (StartIdx[Input] < 0)
3585           Src = DAG.getUNDEF(VT);
3586         else {
3587           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3588                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3589         }
3590       }
3591 
3592       // Calculate new mask.
3593       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3594       for (int &Idx : MappedOps) {
3595         if (Idx >= (int)SrcNumElts)
3596           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3597         else if (Idx >= 0)
3598           Idx -= StartIdx[0];
3599       }
3600 
3601       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3602       return;
3603     }
3604   }
3605 
3606   // We can't use either concat vectors or extract subvectors so fall back to
3607   // replacing the shuffle with extract and build vector.
3608   // to insert and build vector.
3609   EVT EltVT = VT.getVectorElementType();
3610   SmallVector<SDValue,8> Ops;
3611   for (int Idx : Mask) {
3612     SDValue Res;
3613 
3614     if (Idx < 0) {
3615       Res = DAG.getUNDEF(EltVT);
3616     } else {
3617       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3618       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3619 
3620       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3621                         DAG.getVectorIdxConstant(Idx, DL));
3622     }
3623 
3624     Ops.push_back(Res);
3625   }
3626 
3627   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3628 }
3629 
3630 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3631   ArrayRef<unsigned> Indices;
3632   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3633     Indices = IV->getIndices();
3634   else
3635     Indices = cast<ConstantExpr>(&I)->getIndices();
3636 
3637   const Value *Op0 = I.getOperand(0);
3638   const Value *Op1 = I.getOperand(1);
3639   Type *AggTy = I.getType();
3640   Type *ValTy = Op1->getType();
3641   bool IntoUndef = isa<UndefValue>(Op0);
3642   bool FromUndef = isa<UndefValue>(Op1);
3643 
3644   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3645 
3646   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3647   SmallVector<EVT, 4> AggValueVTs;
3648   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3649   SmallVector<EVT, 4> ValValueVTs;
3650   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3651 
3652   unsigned NumAggValues = AggValueVTs.size();
3653   unsigned NumValValues = ValValueVTs.size();
3654   SmallVector<SDValue, 4> Values(NumAggValues);
3655 
3656   // Ignore an insertvalue that produces an empty object
3657   if (!NumAggValues) {
3658     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3659     return;
3660   }
3661 
3662   SDValue Agg = getValue(Op0);
3663   unsigned i = 0;
3664   // Copy the beginning value(s) from the original aggregate.
3665   for (; i != LinearIndex; ++i)
3666     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3667                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3668   // Copy values from the inserted value(s).
3669   if (NumValValues) {
3670     SDValue Val = getValue(Op1);
3671     for (; i != LinearIndex + NumValValues; ++i)
3672       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3673                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3674   }
3675   // Copy remaining value(s) from the original aggregate.
3676   for (; i != NumAggValues; ++i)
3677     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3678                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3679 
3680   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3681                            DAG.getVTList(AggValueVTs), Values));
3682 }
3683 
3684 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3685   ArrayRef<unsigned> Indices;
3686   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3687     Indices = EV->getIndices();
3688   else
3689     Indices = cast<ConstantExpr>(&I)->getIndices();
3690 
3691   const Value *Op0 = I.getOperand(0);
3692   Type *AggTy = Op0->getType();
3693   Type *ValTy = I.getType();
3694   bool OutOfUndef = isa<UndefValue>(Op0);
3695 
3696   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3697 
3698   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3699   SmallVector<EVT, 4> ValValueVTs;
3700   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3701 
3702   unsigned NumValValues = ValValueVTs.size();
3703 
3704   // Ignore a extractvalue that produces an empty object
3705   if (!NumValValues) {
3706     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3707     return;
3708   }
3709 
3710   SmallVector<SDValue, 4> Values(NumValValues);
3711 
3712   SDValue Agg = getValue(Op0);
3713   // Copy out the selected value(s).
3714   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3715     Values[i - LinearIndex] =
3716       OutOfUndef ?
3717         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3718         SDValue(Agg.getNode(), Agg.getResNo() + i);
3719 
3720   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3721                            DAG.getVTList(ValValueVTs), Values));
3722 }
3723 
3724 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3725   Value *Op0 = I.getOperand(0);
3726   // Note that the pointer operand may be a vector of pointers. Take the scalar
3727   // element which holds a pointer.
3728   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3729   SDValue N = getValue(Op0);
3730   SDLoc dl = getCurSDLoc();
3731   auto &TLI = DAG.getTargetLoweringInfo();
3732 
3733   // Normalize Vector GEP - all scalar operands should be converted to the
3734   // splat vector.
3735   bool IsVectorGEP = I.getType()->isVectorTy();
3736   ElementCount VectorElementCount =
3737       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3738                   : ElementCount::getFixed(0);
3739 
3740   if (IsVectorGEP && !N.getValueType().isVector()) {
3741     LLVMContext &Context = *DAG.getContext();
3742     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3743     if (VectorElementCount.isScalable())
3744       N = DAG.getSplatVector(VT, dl, N);
3745     else
3746       N = DAG.getSplatBuildVector(VT, dl, N);
3747   }
3748 
3749   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3750        GTI != E; ++GTI) {
3751     const Value *Idx = GTI.getOperand();
3752     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3753       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3754       if (Field) {
3755         // N = N + Offset
3756         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3757 
3758         // In an inbounds GEP with an offset that is nonnegative even when
3759         // interpreted as signed, assume there is no unsigned overflow.
3760         SDNodeFlags Flags;
3761         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3762           Flags.setNoUnsignedWrap(true);
3763 
3764         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3765                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3766       }
3767     } else {
3768       // IdxSize is the width of the arithmetic according to IR semantics.
3769       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3770       // (and fix up the result later).
3771       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3772       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3773       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3774       // We intentionally mask away the high bits here; ElementSize may not
3775       // fit in IdxTy.
3776       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3777       bool ElementScalable = ElementSize.isScalable();
3778 
3779       // If this is a scalar constant or a splat vector of constants,
3780       // handle it quickly.
3781       const auto *C = dyn_cast<Constant>(Idx);
3782       if (C && isa<VectorType>(C->getType()))
3783         C = C->getSplatValue();
3784 
3785       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3786       if (CI && CI->isZero())
3787         continue;
3788       if (CI && !ElementScalable) {
3789         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3790         LLVMContext &Context = *DAG.getContext();
3791         SDValue OffsVal;
3792         if (IsVectorGEP)
3793           OffsVal = DAG.getConstant(
3794               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3795         else
3796           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3797 
3798         // In an inbounds GEP with an offset that is nonnegative even when
3799         // interpreted as signed, assume there is no unsigned overflow.
3800         SDNodeFlags Flags;
3801         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3802           Flags.setNoUnsignedWrap(true);
3803 
3804         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3805 
3806         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3807         continue;
3808       }
3809 
3810       // N = N + Idx * ElementMul;
3811       SDValue IdxN = getValue(Idx);
3812 
3813       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3814         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3815                                   VectorElementCount);
3816         if (VectorElementCount.isScalable())
3817           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3818         else
3819           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3820       }
3821 
3822       // If the index is smaller or larger than intptr_t, truncate or extend
3823       // it.
3824       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3825 
3826       if (ElementScalable) {
3827         EVT VScaleTy = N.getValueType().getScalarType();
3828         SDValue VScale = DAG.getNode(
3829             ISD::VSCALE, dl, VScaleTy,
3830             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3831         if (IsVectorGEP)
3832           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3833         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3834       } else {
3835         // If this is a multiply by a power of two, turn it into a shl
3836         // immediately.  This is a very common case.
3837         if (ElementMul != 1) {
3838           if (ElementMul.isPowerOf2()) {
3839             unsigned Amt = ElementMul.logBase2();
3840             IdxN = DAG.getNode(ISD::SHL, dl,
3841                                N.getValueType(), IdxN,
3842                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3843           } else {
3844             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3845                                             IdxN.getValueType());
3846             IdxN = DAG.getNode(ISD::MUL, dl,
3847                                N.getValueType(), IdxN, Scale);
3848           }
3849         }
3850       }
3851 
3852       N = DAG.getNode(ISD::ADD, dl,
3853                       N.getValueType(), N, IdxN);
3854     }
3855   }
3856 
3857   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3858   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3859   if (IsVectorGEP) {
3860     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3861     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3862   }
3863 
3864   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3865     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3866 
3867   setValue(&I, N);
3868 }
3869 
3870 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3871   // If this is a fixed sized alloca in the entry block of the function,
3872   // allocate it statically on the stack.
3873   if (FuncInfo.StaticAllocaMap.count(&I))
3874     return;   // getValue will auto-populate this.
3875 
3876   SDLoc dl = getCurSDLoc();
3877   Type *Ty = I.getAllocatedType();
3878   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3879   auto &DL = DAG.getDataLayout();
3880   uint64_t TySize = DL.getTypeAllocSize(Ty);
3881   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3882 
3883   SDValue AllocSize = getValue(I.getArraySize());
3884 
3885   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3886   if (AllocSize.getValueType() != IntPtr)
3887     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3888 
3889   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3890                           AllocSize,
3891                           DAG.getConstant(TySize, dl, IntPtr));
3892 
3893   // Handle alignment.  If the requested alignment is less than or equal to
3894   // the stack alignment, ignore it.  If the size is greater than or equal to
3895   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3896   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3897   if (*Alignment <= StackAlign)
3898     Alignment = None;
3899 
3900   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3901   // Round the size of the allocation up to the stack alignment size
3902   // by add SA-1 to the size. This doesn't overflow because we're computing
3903   // an address inside an alloca.
3904   SDNodeFlags Flags;
3905   Flags.setNoUnsignedWrap(true);
3906   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3907                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3908 
3909   // Mask out the low bits for alignment purposes.
3910   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3911                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
3912 
3913   SDValue Ops[] = {
3914       getRoot(), AllocSize,
3915       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
3916   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3917   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3918   setValue(&I, DSA);
3919   DAG.setRoot(DSA.getValue(1));
3920 
3921   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3922 }
3923 
3924 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3925   if (I.isAtomic())
3926     return visitAtomicLoad(I);
3927 
3928   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3929   const Value *SV = I.getOperand(0);
3930   if (TLI.supportSwiftError()) {
3931     // Swifterror values can come from either a function parameter with
3932     // swifterror attribute or an alloca with swifterror attribute.
3933     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3934       if (Arg->hasSwiftErrorAttr())
3935         return visitLoadFromSwiftError(I);
3936     }
3937 
3938     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3939       if (Alloca->isSwiftError())
3940         return visitLoadFromSwiftError(I);
3941     }
3942   }
3943 
3944   SDValue Ptr = getValue(SV);
3945 
3946   Type *Ty = I.getType();
3947   Align Alignment = I.getAlign();
3948 
3949   AAMDNodes AAInfo;
3950   I.getAAMetadata(AAInfo);
3951   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3952 
3953   SmallVector<EVT, 4> ValueVTs, MemVTs;
3954   SmallVector<uint64_t, 4> Offsets;
3955   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
3956   unsigned NumValues = ValueVTs.size();
3957   if (NumValues == 0)
3958     return;
3959 
3960   bool isVolatile = I.isVolatile();
3961 
3962   SDValue Root;
3963   bool ConstantMemory = false;
3964   if (isVolatile)
3965     // Serialize volatile loads with other side effects.
3966     Root = getRoot();
3967   else if (NumValues > MaxParallelChains)
3968     Root = getMemoryRoot();
3969   else if (AA &&
3970            AA->pointsToConstantMemory(MemoryLocation(
3971                SV,
3972                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3973                AAInfo))) {
3974     // Do not serialize (non-volatile) loads of constant memory with anything.
3975     Root = DAG.getEntryNode();
3976     ConstantMemory = true;
3977   } else {
3978     // Do not serialize non-volatile loads against each other.
3979     Root = DAG.getRoot();
3980   }
3981 
3982   SDLoc dl = getCurSDLoc();
3983 
3984   if (isVolatile)
3985     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3986 
3987   // An aggregate load cannot wrap around the address space, so offsets to its
3988   // parts don't wrap either.
3989   SDNodeFlags Flags;
3990   Flags.setNoUnsignedWrap(true);
3991 
3992   SmallVector<SDValue, 4> Values(NumValues);
3993   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3994   EVT PtrVT = Ptr.getValueType();
3995 
3996   MachineMemOperand::Flags MMOFlags
3997     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
3998 
3999   unsigned ChainI = 0;
4000   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4001     // Serializing loads here may result in excessive register pressure, and
4002     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4003     // could recover a bit by hoisting nodes upward in the chain by recognizing
4004     // they are side-effect free or do not alias. The optimizer should really
4005     // avoid this case by converting large object/array copies to llvm.memcpy
4006     // (MaxParallelChains should always remain as failsafe).
4007     if (ChainI == MaxParallelChains) {
4008       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4009       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4010                                   makeArrayRef(Chains.data(), ChainI));
4011       Root = Chain;
4012       ChainI = 0;
4013     }
4014     SDValue A = DAG.getNode(ISD::ADD, dl,
4015                             PtrVT, Ptr,
4016                             DAG.getConstant(Offsets[i], dl, PtrVT),
4017                             Flags);
4018 
4019     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4020                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4021                             MMOFlags, AAInfo, Ranges);
4022     Chains[ChainI] = L.getValue(1);
4023 
4024     if (MemVTs[i] != ValueVTs[i])
4025       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4026 
4027     Values[i] = L;
4028   }
4029 
4030   if (!ConstantMemory) {
4031     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4032                                 makeArrayRef(Chains.data(), ChainI));
4033     if (isVolatile)
4034       DAG.setRoot(Chain);
4035     else
4036       PendingLoads.push_back(Chain);
4037   }
4038 
4039   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4040                            DAG.getVTList(ValueVTs), Values));
4041 }
4042 
4043 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4044   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4045          "call visitStoreToSwiftError when backend supports swifterror");
4046 
4047   SmallVector<EVT, 4> ValueVTs;
4048   SmallVector<uint64_t, 4> Offsets;
4049   const Value *SrcV = I.getOperand(0);
4050   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4051                   SrcV->getType(), ValueVTs, &Offsets);
4052   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4053          "expect a single EVT for swifterror");
4054 
4055   SDValue Src = getValue(SrcV);
4056   // Create a virtual register, then update the virtual register.
4057   Register VReg =
4058       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4059   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4060   // Chain can be getRoot or getControlRoot.
4061   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4062                                       SDValue(Src.getNode(), Src.getResNo()));
4063   DAG.setRoot(CopyNode);
4064 }
4065 
4066 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4067   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4068          "call visitLoadFromSwiftError when backend supports swifterror");
4069 
4070   assert(!I.isVolatile() &&
4071          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4072          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4073          "Support volatile, non temporal, invariant for load_from_swift_error");
4074 
4075   const Value *SV = I.getOperand(0);
4076   Type *Ty = I.getType();
4077   AAMDNodes AAInfo;
4078   I.getAAMetadata(AAInfo);
4079   assert(
4080       (!AA ||
4081        !AA->pointsToConstantMemory(MemoryLocation(
4082            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4083            AAInfo))) &&
4084       "load_from_swift_error should not be constant memory");
4085 
4086   SmallVector<EVT, 4> ValueVTs;
4087   SmallVector<uint64_t, 4> Offsets;
4088   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4089                   ValueVTs, &Offsets);
4090   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4091          "expect a single EVT for swifterror");
4092 
4093   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4094   SDValue L = DAG.getCopyFromReg(
4095       getRoot(), getCurSDLoc(),
4096       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4097 
4098   setValue(&I, L);
4099 }
4100 
4101 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4102   if (I.isAtomic())
4103     return visitAtomicStore(I);
4104 
4105   const Value *SrcV = I.getOperand(0);
4106   const Value *PtrV = I.getOperand(1);
4107 
4108   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4109   if (TLI.supportSwiftError()) {
4110     // Swifterror values can come from either a function parameter with
4111     // swifterror attribute or an alloca with swifterror attribute.
4112     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4113       if (Arg->hasSwiftErrorAttr())
4114         return visitStoreToSwiftError(I);
4115     }
4116 
4117     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4118       if (Alloca->isSwiftError())
4119         return visitStoreToSwiftError(I);
4120     }
4121   }
4122 
4123   SmallVector<EVT, 4> ValueVTs, MemVTs;
4124   SmallVector<uint64_t, 4> Offsets;
4125   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4126                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4127   unsigned NumValues = ValueVTs.size();
4128   if (NumValues == 0)
4129     return;
4130 
4131   // Get the lowered operands. Note that we do this after
4132   // checking if NumResults is zero, because with zero results
4133   // the operands won't have values in the map.
4134   SDValue Src = getValue(SrcV);
4135   SDValue Ptr = getValue(PtrV);
4136 
4137   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4138   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4139   SDLoc dl = getCurSDLoc();
4140   Align Alignment = I.getAlign();
4141   AAMDNodes AAInfo;
4142   I.getAAMetadata(AAInfo);
4143 
4144   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4145 
4146   // An aggregate load cannot wrap around the address space, so offsets to its
4147   // parts don't wrap either.
4148   SDNodeFlags Flags;
4149   Flags.setNoUnsignedWrap(true);
4150 
4151   unsigned ChainI = 0;
4152   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4153     // See visitLoad comments.
4154     if (ChainI == MaxParallelChains) {
4155       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4156                                   makeArrayRef(Chains.data(), ChainI));
4157       Root = Chain;
4158       ChainI = 0;
4159     }
4160     SDValue Add =
4161         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4162     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4163     if (MemVTs[i] != ValueVTs[i])
4164       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4165     SDValue St =
4166         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4167                      Alignment, MMOFlags, AAInfo);
4168     Chains[ChainI] = St;
4169   }
4170 
4171   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4172                                   makeArrayRef(Chains.data(), ChainI));
4173   DAG.setRoot(StoreNode);
4174 }
4175 
4176 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4177                                            bool IsCompressing) {
4178   SDLoc sdl = getCurSDLoc();
4179 
4180   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4181                                MaybeAlign &Alignment) {
4182     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4183     Src0 = I.getArgOperand(0);
4184     Ptr = I.getArgOperand(1);
4185     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4186     Mask = I.getArgOperand(3);
4187   };
4188   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4189                                     MaybeAlign &Alignment) {
4190     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4191     Src0 = I.getArgOperand(0);
4192     Ptr = I.getArgOperand(1);
4193     Mask = I.getArgOperand(2);
4194     Alignment = None;
4195   };
4196 
4197   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4198   MaybeAlign Alignment;
4199   if (IsCompressing)
4200     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4201   else
4202     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4203 
4204   SDValue Ptr = getValue(PtrOperand);
4205   SDValue Src0 = getValue(Src0Operand);
4206   SDValue Mask = getValue(MaskOperand);
4207   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4208 
4209   EVT VT = Src0.getValueType();
4210   if (!Alignment)
4211     Alignment = DAG.getEVTAlign(VT);
4212 
4213   AAMDNodes AAInfo;
4214   I.getAAMetadata(AAInfo);
4215 
4216   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4217       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4218       // TODO: Make MachineMemOperands aware of scalable
4219       // vectors.
4220       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4221   SDValue StoreNode =
4222       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4223                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4224   DAG.setRoot(StoreNode);
4225   setValue(&I, StoreNode);
4226 }
4227 
4228 // Get a uniform base for the Gather/Scatter intrinsic.
4229 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4230 // We try to represent it as a base pointer + vector of indices.
4231 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4232 // The first operand of the GEP may be a single pointer or a vector of pointers
4233 // Example:
4234 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4235 //  or
4236 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4237 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4238 //
4239 // When the first GEP operand is a single pointer - it is the uniform base we
4240 // are looking for. If first operand of the GEP is a splat vector - we
4241 // extract the splat value and use it as a uniform base.
4242 // In all other cases the function returns 'false'.
4243 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4244                            ISD::MemIndexType &IndexType, SDValue &Scale,
4245                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4246   SelectionDAG& DAG = SDB->DAG;
4247   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4248   const DataLayout &DL = DAG.getDataLayout();
4249 
4250   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4251 
4252   // Handle splat constant pointer.
4253   if (auto *C = dyn_cast<Constant>(Ptr)) {
4254     C = C->getSplatValue();
4255     if (!C)
4256       return false;
4257 
4258     Base = SDB->getValue(C);
4259 
4260     unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements();
4261     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4262     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4263     IndexType = ISD::SIGNED_SCALED;
4264     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4265     return true;
4266   }
4267 
4268   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4269   if (!GEP || GEP->getParent() != CurBB)
4270     return false;
4271 
4272   if (GEP->getNumOperands() != 2)
4273     return false;
4274 
4275   const Value *BasePtr = GEP->getPointerOperand();
4276   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4277 
4278   // Make sure the base is scalar and the index is a vector.
4279   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4280     return false;
4281 
4282   Base = SDB->getValue(BasePtr);
4283   Index = SDB->getValue(IndexVal);
4284   IndexType = ISD::SIGNED_SCALED;
4285   Scale = DAG.getTargetConstant(
4286               DL.getTypeAllocSize(GEP->getResultElementType()),
4287               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4288   return true;
4289 }
4290 
4291 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4292   SDLoc sdl = getCurSDLoc();
4293 
4294   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4295   const Value *Ptr = I.getArgOperand(1);
4296   SDValue Src0 = getValue(I.getArgOperand(0));
4297   SDValue Mask = getValue(I.getArgOperand(3));
4298   EVT VT = Src0.getValueType();
4299   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4300                         ->getMaybeAlignValue()
4301                         .getValueOr(DAG.getEVTAlign(VT));
4302   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4303 
4304   AAMDNodes AAInfo;
4305   I.getAAMetadata(AAInfo);
4306 
4307   SDValue Base;
4308   SDValue Index;
4309   ISD::MemIndexType IndexType;
4310   SDValue Scale;
4311   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4312                                     I.getParent());
4313 
4314   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4315   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4316       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4317       // TODO: Make MachineMemOperands aware of scalable
4318       // vectors.
4319       MemoryLocation::UnknownSize, Alignment, AAInfo);
4320   if (!UniformBase) {
4321     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4322     Index = getValue(Ptr);
4323     IndexType = ISD::SIGNED_SCALED;
4324     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4325   }
4326   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4327   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4328                                          Ops, MMO, IndexType);
4329   DAG.setRoot(Scatter);
4330   setValue(&I, Scatter);
4331 }
4332 
4333 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4334   SDLoc sdl = getCurSDLoc();
4335 
4336   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4337                               MaybeAlign &Alignment) {
4338     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4339     Ptr = I.getArgOperand(0);
4340     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4341     Mask = I.getArgOperand(2);
4342     Src0 = I.getArgOperand(3);
4343   };
4344   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4345                                  MaybeAlign &Alignment) {
4346     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4347     Ptr = I.getArgOperand(0);
4348     Alignment = None;
4349     Mask = I.getArgOperand(1);
4350     Src0 = I.getArgOperand(2);
4351   };
4352 
4353   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4354   MaybeAlign Alignment;
4355   if (IsExpanding)
4356     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4357   else
4358     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4359 
4360   SDValue Ptr = getValue(PtrOperand);
4361   SDValue Src0 = getValue(Src0Operand);
4362   SDValue Mask = getValue(MaskOperand);
4363   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4364 
4365   EVT VT = Src0.getValueType();
4366   if (!Alignment)
4367     Alignment = DAG.getEVTAlign(VT);
4368 
4369   AAMDNodes AAInfo;
4370   I.getAAMetadata(AAInfo);
4371   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4372 
4373   // Do not serialize masked loads of constant memory with anything.
4374   MemoryLocation ML;
4375   if (VT.isScalableVector())
4376     ML = MemoryLocation(PtrOperand);
4377   else
4378     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4379                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4380                            AAInfo);
4381   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4382 
4383   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4384 
4385   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4386       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4387       // TODO: Make MachineMemOperands aware of scalable
4388       // vectors.
4389       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4390 
4391   SDValue Load =
4392       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4393                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4394   if (AddToChain)
4395     PendingLoads.push_back(Load.getValue(1));
4396   setValue(&I, Load);
4397 }
4398 
4399 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4400   SDLoc sdl = getCurSDLoc();
4401 
4402   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4403   const Value *Ptr = I.getArgOperand(0);
4404   SDValue Src0 = getValue(I.getArgOperand(3));
4405   SDValue Mask = getValue(I.getArgOperand(2));
4406 
4407   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4408   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4409   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4410                         ->getMaybeAlignValue()
4411                         .getValueOr(DAG.getEVTAlign(VT));
4412 
4413   AAMDNodes AAInfo;
4414   I.getAAMetadata(AAInfo);
4415   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4416 
4417   SDValue Root = DAG.getRoot();
4418   SDValue Base;
4419   SDValue Index;
4420   ISD::MemIndexType IndexType;
4421   SDValue Scale;
4422   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4423                                     I.getParent());
4424   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4425   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4426       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4427       // TODO: Make MachineMemOperands aware of scalable
4428       // vectors.
4429       MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges);
4430 
4431   if (!UniformBase) {
4432     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4433     Index = getValue(Ptr);
4434     IndexType = ISD::SIGNED_SCALED;
4435     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4436   }
4437   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4438   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4439                                        Ops, MMO, IndexType);
4440 
4441   PendingLoads.push_back(Gather.getValue(1));
4442   setValue(&I, Gather);
4443 }
4444 
4445 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4446   SDLoc dl = getCurSDLoc();
4447   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4448   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4449   SyncScope::ID SSID = I.getSyncScopeID();
4450 
4451   SDValue InChain = getRoot();
4452 
4453   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4454   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4455 
4456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4457   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4458 
4459   MachineFunction &MF = DAG.getMachineFunction();
4460   MachineMemOperand *MMO = MF.getMachineMemOperand(
4461       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4462       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4463       FailureOrdering);
4464 
4465   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4466                                    dl, MemVT, VTs, InChain,
4467                                    getValue(I.getPointerOperand()),
4468                                    getValue(I.getCompareOperand()),
4469                                    getValue(I.getNewValOperand()), MMO);
4470 
4471   SDValue OutChain = L.getValue(2);
4472 
4473   setValue(&I, L);
4474   DAG.setRoot(OutChain);
4475 }
4476 
4477 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4478   SDLoc dl = getCurSDLoc();
4479   ISD::NodeType NT;
4480   switch (I.getOperation()) {
4481   default: llvm_unreachable("Unknown atomicrmw operation");
4482   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4483   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4484   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4485   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4486   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4487   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4488   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4489   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4490   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4491   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4492   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4493   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4494   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4495   }
4496   AtomicOrdering Ordering = I.getOrdering();
4497   SyncScope::ID SSID = I.getSyncScopeID();
4498 
4499   SDValue InChain = getRoot();
4500 
4501   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4502   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4503   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4504 
4505   MachineFunction &MF = DAG.getMachineFunction();
4506   MachineMemOperand *MMO = MF.getMachineMemOperand(
4507       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4508       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4509 
4510   SDValue L =
4511     DAG.getAtomic(NT, dl, MemVT, InChain,
4512                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4513                   MMO);
4514 
4515   SDValue OutChain = L.getValue(1);
4516 
4517   setValue(&I, L);
4518   DAG.setRoot(OutChain);
4519 }
4520 
4521 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4522   SDLoc dl = getCurSDLoc();
4523   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4524   SDValue Ops[3];
4525   Ops[0] = getRoot();
4526   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4527                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4528   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4529                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4530   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4531 }
4532 
4533 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4534   SDLoc dl = getCurSDLoc();
4535   AtomicOrdering Order = I.getOrdering();
4536   SyncScope::ID SSID = I.getSyncScopeID();
4537 
4538   SDValue InChain = getRoot();
4539 
4540   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4541   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4542   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4543 
4544   if (!TLI.supportsUnalignedAtomics() &&
4545       I.getAlignment() < MemVT.getSizeInBits() / 8)
4546     report_fatal_error("Cannot generate unaligned atomic load");
4547 
4548   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4549 
4550   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4551       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4552       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4553 
4554   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4555 
4556   SDValue Ptr = getValue(I.getPointerOperand());
4557 
4558   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4559     // TODO: Once this is better exercised by tests, it should be merged with
4560     // the normal path for loads to prevent future divergence.
4561     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4562     if (MemVT != VT)
4563       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4564 
4565     setValue(&I, L);
4566     SDValue OutChain = L.getValue(1);
4567     if (!I.isUnordered())
4568       DAG.setRoot(OutChain);
4569     else
4570       PendingLoads.push_back(OutChain);
4571     return;
4572   }
4573 
4574   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4575                             Ptr, MMO);
4576 
4577   SDValue OutChain = L.getValue(1);
4578   if (MemVT != VT)
4579     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4580 
4581   setValue(&I, L);
4582   DAG.setRoot(OutChain);
4583 }
4584 
4585 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4586   SDLoc dl = getCurSDLoc();
4587 
4588   AtomicOrdering Ordering = I.getOrdering();
4589   SyncScope::ID SSID = I.getSyncScopeID();
4590 
4591   SDValue InChain = getRoot();
4592 
4593   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4594   EVT MemVT =
4595       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4596 
4597   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4598     report_fatal_error("Cannot generate unaligned atomic store");
4599 
4600   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4601 
4602   MachineFunction &MF = DAG.getMachineFunction();
4603   MachineMemOperand *MMO = MF.getMachineMemOperand(
4604       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4605       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4606 
4607   SDValue Val = getValue(I.getValueOperand());
4608   if (Val.getValueType() != MemVT)
4609     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4610   SDValue Ptr = getValue(I.getPointerOperand());
4611 
4612   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4613     // TODO: Once this is better exercised by tests, it should be merged with
4614     // the normal path for stores to prevent future divergence.
4615     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4616     DAG.setRoot(S);
4617     return;
4618   }
4619   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4620                                    Ptr, Val, MMO);
4621 
4622 
4623   DAG.setRoot(OutChain);
4624 }
4625 
4626 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4627 /// node.
4628 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4629                                                unsigned Intrinsic) {
4630   // Ignore the callsite's attributes. A specific call site may be marked with
4631   // readnone, but the lowering code will expect the chain based on the
4632   // definition.
4633   const Function *F = I.getCalledFunction();
4634   bool HasChain = !F->doesNotAccessMemory();
4635   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4636 
4637   // Build the operand list.
4638   SmallVector<SDValue, 8> Ops;
4639   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4640     if (OnlyLoad) {
4641       // We don't need to serialize loads against other loads.
4642       Ops.push_back(DAG.getRoot());
4643     } else {
4644       Ops.push_back(getRoot());
4645     }
4646   }
4647 
4648   // Info is set by getTgtMemInstrinsic
4649   TargetLowering::IntrinsicInfo Info;
4650   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4651   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4652                                                DAG.getMachineFunction(),
4653                                                Intrinsic);
4654 
4655   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4656   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4657       Info.opc == ISD::INTRINSIC_W_CHAIN)
4658     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4659                                         TLI.getPointerTy(DAG.getDataLayout())));
4660 
4661   // Add all operands of the call to the operand list.
4662   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4663     const Value *Arg = I.getArgOperand(i);
4664     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4665       Ops.push_back(getValue(Arg));
4666       continue;
4667     }
4668 
4669     // Use TargetConstant instead of a regular constant for immarg.
4670     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4671     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4672       assert(CI->getBitWidth() <= 64 &&
4673              "large intrinsic immediates not handled");
4674       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4675     } else {
4676       Ops.push_back(
4677           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4678     }
4679   }
4680 
4681   SmallVector<EVT, 4> ValueVTs;
4682   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4683 
4684   if (HasChain)
4685     ValueVTs.push_back(MVT::Other);
4686 
4687   SDVTList VTs = DAG.getVTList(ValueVTs);
4688 
4689   // Create the node.
4690   SDValue Result;
4691   if (IsTgtIntrinsic) {
4692     // This is target intrinsic that touches memory
4693     AAMDNodes AAInfo;
4694     I.getAAMetadata(AAInfo);
4695     Result =
4696         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4697                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4698                                 Info.align, Info.flags, Info.size, AAInfo);
4699   } else if (!HasChain) {
4700     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4701   } else if (!I.getType()->isVoidTy()) {
4702     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4703   } else {
4704     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4705   }
4706 
4707   if (HasChain) {
4708     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4709     if (OnlyLoad)
4710       PendingLoads.push_back(Chain);
4711     else
4712       DAG.setRoot(Chain);
4713   }
4714 
4715   if (!I.getType()->isVoidTy()) {
4716     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4717       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4718       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4719     } else
4720       Result = lowerRangeToAssertZExt(DAG, I, Result);
4721 
4722     MaybeAlign Alignment = I.getRetAlign();
4723     if (!Alignment)
4724       Alignment = F->getAttributes().getRetAlignment();
4725     // Insert `assertalign` node if there's an alignment.
4726     if (InsertAssertAlign && Alignment) {
4727       Result =
4728           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4729     }
4730 
4731     setValue(&I, Result);
4732   }
4733 }
4734 
4735 /// GetSignificand - Get the significand and build it into a floating-point
4736 /// number with exponent of 1:
4737 ///
4738 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4739 ///
4740 /// where Op is the hexadecimal representation of floating point value.
4741 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4742   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4743                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4744   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4745                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4746   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4747 }
4748 
4749 /// GetExponent - Get the exponent:
4750 ///
4751 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4752 ///
4753 /// where Op is the hexadecimal representation of floating point value.
4754 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4755                            const TargetLowering &TLI, const SDLoc &dl) {
4756   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4757                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4758   SDValue t1 = DAG.getNode(
4759       ISD::SRL, dl, MVT::i32, t0,
4760       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4761   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4762                            DAG.getConstant(127, dl, MVT::i32));
4763   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4764 }
4765 
4766 /// getF32Constant - Get 32-bit floating point constant.
4767 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4768                               const SDLoc &dl) {
4769   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4770                            MVT::f32);
4771 }
4772 
4773 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4774                                        SelectionDAG &DAG) {
4775   // TODO: What fast-math-flags should be set on the floating-point nodes?
4776 
4777   //   IntegerPartOfX = ((int32_t)(t0);
4778   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4779 
4780   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4781   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4782   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4783 
4784   //   IntegerPartOfX <<= 23;
4785   IntegerPartOfX = DAG.getNode(
4786       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4787       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4788                                   DAG.getDataLayout())));
4789 
4790   SDValue TwoToFractionalPartOfX;
4791   if (LimitFloatPrecision <= 6) {
4792     // For floating-point precision of 6:
4793     //
4794     //   TwoToFractionalPartOfX =
4795     //     0.997535578f +
4796     //       (0.735607626f + 0.252464424f * x) * x;
4797     //
4798     // error 0.0144103317, which is 6 bits
4799     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4800                              getF32Constant(DAG, 0x3e814304, dl));
4801     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4802                              getF32Constant(DAG, 0x3f3c50c8, dl));
4803     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4804     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4805                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4806   } else if (LimitFloatPrecision <= 12) {
4807     // For floating-point precision of 12:
4808     //
4809     //   TwoToFractionalPartOfX =
4810     //     0.999892986f +
4811     //       (0.696457318f +
4812     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4813     //
4814     // error 0.000107046256, which is 13 to 14 bits
4815     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4816                              getF32Constant(DAG, 0x3da235e3, dl));
4817     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4818                              getF32Constant(DAG, 0x3e65b8f3, dl));
4819     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4820     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4821                              getF32Constant(DAG, 0x3f324b07, dl));
4822     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4823     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4824                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4825   } else { // LimitFloatPrecision <= 18
4826     // For floating-point precision of 18:
4827     //
4828     //   TwoToFractionalPartOfX =
4829     //     0.999999982f +
4830     //       (0.693148872f +
4831     //         (0.240227044f +
4832     //           (0.554906021e-1f +
4833     //             (0.961591928e-2f +
4834     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4835     // error 2.47208000*10^(-7), which is better than 18 bits
4836     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4837                              getF32Constant(DAG, 0x3924b03e, dl));
4838     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4839                              getF32Constant(DAG, 0x3ab24b87, dl));
4840     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4841     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4842                              getF32Constant(DAG, 0x3c1d8c17, dl));
4843     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4844     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4845                              getF32Constant(DAG, 0x3d634a1d, dl));
4846     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4847     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4848                              getF32Constant(DAG, 0x3e75fe14, dl));
4849     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4850     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4851                               getF32Constant(DAG, 0x3f317234, dl));
4852     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4853     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4854                                          getF32Constant(DAG, 0x3f800000, dl));
4855   }
4856 
4857   // Add the exponent into the result in integer domain.
4858   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4859   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4860                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4861 }
4862 
4863 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4864 /// limited-precision mode.
4865 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4866                          const TargetLowering &TLI, SDNodeFlags Flags) {
4867   if (Op.getValueType() == MVT::f32 &&
4868       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4869 
4870     // Put the exponent in the right bit position for later addition to the
4871     // final result:
4872     //
4873     // t0 = Op * log2(e)
4874 
4875     // TODO: What fast-math-flags should be set here?
4876     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4877                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4878     return getLimitedPrecisionExp2(t0, dl, DAG);
4879   }
4880 
4881   // No special expansion.
4882   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
4883 }
4884 
4885 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4886 /// limited-precision mode.
4887 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4888                          const TargetLowering &TLI, SDNodeFlags Flags) {
4889   // TODO: What fast-math-flags should be set on the floating-point nodes?
4890 
4891   if (Op.getValueType() == MVT::f32 &&
4892       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4893     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4894 
4895     // Scale the exponent by log(2).
4896     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4897     SDValue LogOfExponent =
4898         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4899                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
4900 
4901     // Get the significand and build it into a floating-point number with
4902     // exponent of 1.
4903     SDValue X = GetSignificand(DAG, Op1, dl);
4904 
4905     SDValue LogOfMantissa;
4906     if (LimitFloatPrecision <= 6) {
4907       // For floating-point precision of 6:
4908       //
4909       //   LogofMantissa =
4910       //     -1.1609546f +
4911       //       (1.4034025f - 0.23903021f * x) * x;
4912       //
4913       // error 0.0034276066, which is better than 8 bits
4914       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4915                                getF32Constant(DAG, 0xbe74c456, dl));
4916       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4917                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4918       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4919       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4920                                   getF32Constant(DAG, 0x3f949a29, dl));
4921     } else if (LimitFloatPrecision <= 12) {
4922       // For floating-point precision of 12:
4923       //
4924       //   LogOfMantissa =
4925       //     -1.7417939f +
4926       //       (2.8212026f +
4927       //         (-1.4699568f +
4928       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4929       //
4930       // error 0.000061011436, which is 14 bits
4931       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4932                                getF32Constant(DAG, 0xbd67b6d6, dl));
4933       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4934                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4935       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4936       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4937                                getF32Constant(DAG, 0x3fbc278b, 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, 0x40348e95, dl));
4941       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4942       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4943                                   getF32Constant(DAG, 0x3fdef31a, dl));
4944     } else { // LimitFloatPrecision <= 18
4945       // For floating-point precision of 18:
4946       //
4947       //   LogOfMantissa =
4948       //     -2.1072184f +
4949       //       (4.2372794f +
4950       //         (-3.7029485f +
4951       //           (2.2781945f +
4952       //             (-0.87823314f +
4953       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4954       //
4955       // error 0.0000023660568, which is better than 18 bits
4956       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4957                                getF32Constant(DAG, 0xbc91e5ac, dl));
4958       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4959                                getF32Constant(DAG, 0x3e4350aa, dl));
4960       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4961       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4962                                getF32Constant(DAG, 0x3f60d3e3, dl));
4963       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4964       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4965                                getF32Constant(DAG, 0x4011cdf0, dl));
4966       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4967       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4968                                getF32Constant(DAG, 0x406cfd1c, dl));
4969       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4970       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4971                                getF32Constant(DAG, 0x408797cb, dl));
4972       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4973       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4974                                   getF32Constant(DAG, 0x4006dcab, dl));
4975     }
4976 
4977     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4978   }
4979 
4980   // No special expansion.
4981   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
4982 }
4983 
4984 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4985 /// limited-precision mode.
4986 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4987                           const TargetLowering &TLI, SDNodeFlags Flags) {
4988   // TODO: What fast-math-flags should be set on the floating-point nodes?
4989 
4990   if (Op.getValueType() == MVT::f32 &&
4991       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4992     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4993 
4994     // Get the exponent.
4995     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4996 
4997     // Get the significand and build it into a floating-point number with
4998     // exponent of 1.
4999     SDValue X = GetSignificand(DAG, Op1, dl);
5000 
5001     // Different possible minimax approximations of significand in
5002     // floating-point for various degrees of accuracy over [1,2].
5003     SDValue Log2ofMantissa;
5004     if (LimitFloatPrecision <= 6) {
5005       // For floating-point precision of 6:
5006       //
5007       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5008       //
5009       // error 0.0049451742, which is more than 7 bits
5010       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5011                                getF32Constant(DAG, 0xbeb08fe0, dl));
5012       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5013                                getF32Constant(DAG, 0x40019463, dl));
5014       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5015       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5016                                    getF32Constant(DAG, 0x3fd6633d, dl));
5017     } else if (LimitFloatPrecision <= 12) {
5018       // For floating-point precision of 12:
5019       //
5020       //   Log2ofMantissa =
5021       //     -2.51285454f +
5022       //       (4.07009056f +
5023       //         (-2.12067489f +
5024       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5025       //
5026       // error 0.0000876136000, which is better than 13 bits
5027       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5028                                getF32Constant(DAG, 0xbda7262e, dl));
5029       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5030                                getF32Constant(DAG, 0x3f25280b, dl));
5031       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5032       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5033                                getF32Constant(DAG, 0x4007b923, dl));
5034       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5035       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5036                                getF32Constant(DAG, 0x40823e2f, dl));
5037       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5038       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5039                                    getF32Constant(DAG, 0x4020d29c, dl));
5040     } else { // LimitFloatPrecision <= 18
5041       // For floating-point precision of 18:
5042       //
5043       //   Log2ofMantissa =
5044       //     -3.0400495f +
5045       //       (6.1129976f +
5046       //         (-5.3420409f +
5047       //           (3.2865683f +
5048       //             (-1.2669343f +
5049       //               (0.27515199f -
5050       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5051       //
5052       // error 0.0000018516, which is better than 18 bits
5053       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5054                                getF32Constant(DAG, 0xbcd2769e, dl));
5055       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5056                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5057       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5058       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5059                                getF32Constant(DAG, 0x3fa22ae7, dl));
5060       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5061       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5062                                getF32Constant(DAG, 0x40525723, dl));
5063       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5064       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5065                                getF32Constant(DAG, 0x40aaf200, dl));
5066       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5067       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5068                                getF32Constant(DAG, 0x40c39dad, dl));
5069       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5070       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5071                                    getF32Constant(DAG, 0x4042902c, dl));
5072     }
5073 
5074     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5075   }
5076 
5077   // No special expansion.
5078   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5079 }
5080 
5081 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5082 /// limited-precision mode.
5083 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5084                            const TargetLowering &TLI, SDNodeFlags Flags) {
5085   // TODO: What fast-math-flags should be set on the floating-point nodes?
5086 
5087   if (Op.getValueType() == MVT::f32 &&
5088       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5089     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5090 
5091     // Scale the exponent by log10(2) [0.30102999f].
5092     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5093     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5094                                         getF32Constant(DAG, 0x3e9a209a, dl));
5095 
5096     // Get the significand and build it into a floating-point number with
5097     // exponent of 1.
5098     SDValue X = GetSignificand(DAG, Op1, dl);
5099 
5100     SDValue Log10ofMantissa;
5101     if (LimitFloatPrecision <= 6) {
5102       // For floating-point precision of 6:
5103       //
5104       //   Log10ofMantissa =
5105       //     -0.50419619f +
5106       //       (0.60948995f - 0.10380950f * x) * x;
5107       //
5108       // error 0.0014886165, which is 6 bits
5109       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5110                                getF32Constant(DAG, 0xbdd49a13, dl));
5111       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5112                                getF32Constant(DAG, 0x3f1c0789, dl));
5113       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5114       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5115                                     getF32Constant(DAG, 0x3f011300, dl));
5116     } else if (LimitFloatPrecision <= 12) {
5117       // For floating-point precision of 12:
5118       //
5119       //   Log10ofMantissa =
5120       //     -0.64831180f +
5121       //       (0.91751397f +
5122       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5123       //
5124       // error 0.00019228036, which is better than 12 bits
5125       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5126                                getF32Constant(DAG, 0x3d431f31, dl));
5127       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5128                                getF32Constant(DAG, 0x3ea21fb2, dl));
5129       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5130       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5131                                getF32Constant(DAG, 0x3f6ae232, dl));
5132       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5133       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5134                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5135     } else { // LimitFloatPrecision <= 18
5136       // For floating-point precision of 18:
5137       //
5138       //   Log10ofMantissa =
5139       //     -0.84299375f +
5140       //       (1.5327582f +
5141       //         (-1.0688956f +
5142       //           (0.49102474f +
5143       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5144       //
5145       // error 0.0000037995730, which is better than 18 bits
5146       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5147                                getF32Constant(DAG, 0x3c5d51ce, dl));
5148       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5149                                getF32Constant(DAG, 0x3e00685a, dl));
5150       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5151       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5152                                getF32Constant(DAG, 0x3efb6798, dl));
5153       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5154       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5155                                getF32Constant(DAG, 0x3f88d192, dl));
5156       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5157       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5158                                getF32Constant(DAG, 0x3fc4316c, dl));
5159       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5160       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5161                                     getF32Constant(DAG, 0x3f57ce70, dl));
5162     }
5163 
5164     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5165   }
5166 
5167   // No special expansion.
5168   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5169 }
5170 
5171 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5172 /// limited-precision mode.
5173 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5174                           const TargetLowering &TLI, SDNodeFlags Flags) {
5175   if (Op.getValueType() == MVT::f32 &&
5176       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5177     return getLimitedPrecisionExp2(Op, dl, DAG);
5178 
5179   // No special expansion.
5180   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5181 }
5182 
5183 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5184 /// limited-precision mode with x == 10.0f.
5185 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5186                          SelectionDAG &DAG, const TargetLowering &TLI,
5187                          SDNodeFlags Flags) {
5188   bool IsExp10 = false;
5189   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5190       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5191     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5192       APFloat Ten(10.0f);
5193       IsExp10 = LHSC->isExactlyValue(Ten);
5194     }
5195   }
5196 
5197   // TODO: What fast-math-flags should be set on the FMUL node?
5198   if (IsExp10) {
5199     // Put the exponent in the right bit position for later addition to the
5200     // final result:
5201     //
5202     //   #define LOG2OF10 3.3219281f
5203     //   t0 = Op * LOG2OF10;
5204     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5205                              getF32Constant(DAG, 0x40549a78, dl));
5206     return getLimitedPrecisionExp2(t0, dl, DAG);
5207   }
5208 
5209   // No special expansion.
5210   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5211 }
5212 
5213 /// ExpandPowI - Expand a llvm.powi intrinsic.
5214 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5215                           SelectionDAG &DAG) {
5216   // If RHS is a constant, we can expand this out to a multiplication tree,
5217   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5218   // optimizing for size, we only want to do this if the expansion would produce
5219   // a small number of multiplies, otherwise we do the full expansion.
5220   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5221     // Get the exponent as a positive value.
5222     unsigned Val = RHSC->getSExtValue();
5223     if ((int)Val < 0) Val = -Val;
5224 
5225     // powi(x, 0) -> 1.0
5226     if (Val == 0)
5227       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5228 
5229     bool OptForSize = DAG.shouldOptForSize();
5230     if (!OptForSize ||
5231         // If optimizing for size, don't insert too many multiplies.
5232         // This inserts up to 5 multiplies.
5233         countPopulation(Val) + Log2_32(Val) < 7) {
5234       // We use the simple binary decomposition method to generate the multiply
5235       // sequence.  There are more optimal ways to do this (for example,
5236       // powi(x,15) generates one more multiply than it should), but this has
5237       // the benefit of being both really simple and much better than a libcall.
5238       SDValue Res;  // Logically starts equal to 1.0
5239       SDValue CurSquare = LHS;
5240       // TODO: Intrinsics should have fast-math-flags that propagate to these
5241       // nodes.
5242       while (Val) {
5243         if (Val & 1) {
5244           if (Res.getNode())
5245             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5246           else
5247             Res = CurSquare;  // 1.0*CurSquare.
5248         }
5249 
5250         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5251                                 CurSquare, CurSquare);
5252         Val >>= 1;
5253       }
5254 
5255       // If the original was negative, invert the result, producing 1/(x*x*x).
5256       if (RHSC->getSExtValue() < 0)
5257         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5258                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5259       return Res;
5260     }
5261   }
5262 
5263   // Otherwise, expand to a libcall.
5264   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5265 }
5266 
5267 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5268                             SDValue LHS, SDValue RHS, SDValue Scale,
5269                             SelectionDAG &DAG, const TargetLowering &TLI) {
5270   EVT VT = LHS.getValueType();
5271   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5272   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5273   LLVMContext &Ctx = *DAG.getContext();
5274 
5275   // If the type is legal but the operation isn't, this node might survive all
5276   // the way to operation legalization. If we end up there and we do not have
5277   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5278   // node.
5279 
5280   // Coax the legalizer into expanding the node during type legalization instead
5281   // by bumping the size by one bit. This will force it to Promote, enabling the
5282   // early expansion and avoiding the need to expand later.
5283 
5284   // We don't have to do this if Scale is 0; that can always be expanded, unless
5285   // it's a saturating signed operation. Those can experience true integer
5286   // division overflow, a case which we must avoid.
5287 
5288   // FIXME: We wouldn't have to do this (or any of the early
5289   // expansion/promotion) if it was possible to expand a libcall of an
5290   // illegal type during operation legalization. But it's not, so things
5291   // get a bit hacky.
5292   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5293   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5294       (TLI.isTypeLegal(VT) ||
5295        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5296     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5297         Opcode, VT, ScaleInt);
5298     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5299       EVT PromVT;
5300       if (VT.isScalarInteger())
5301         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5302       else if (VT.isVector()) {
5303         PromVT = VT.getVectorElementType();
5304         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5305         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5306       } else
5307         llvm_unreachable("Wrong VT for DIVFIX?");
5308       if (Signed) {
5309         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5310         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5311       } else {
5312         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5313         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5314       }
5315       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5316       // For saturating operations, we need to shift up the LHS to get the
5317       // proper saturation width, and then shift down again afterwards.
5318       if (Saturating)
5319         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5320                           DAG.getConstant(1, DL, ShiftTy));
5321       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5322       if (Saturating)
5323         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5324                           DAG.getConstant(1, DL, ShiftTy));
5325       return DAG.getZExtOrTrunc(Res, DL, VT);
5326     }
5327   }
5328 
5329   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5330 }
5331 
5332 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5333 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5334 static void
5335 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5336                      const SDValue &N) {
5337   switch (N.getOpcode()) {
5338   case ISD::CopyFromReg: {
5339     SDValue Op = N.getOperand(1);
5340     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5341                       Op.getValueType().getSizeInBits());
5342     return;
5343   }
5344   case ISD::BITCAST:
5345   case ISD::AssertZext:
5346   case ISD::AssertSext:
5347   case ISD::TRUNCATE:
5348     getUnderlyingArgRegs(Regs, N.getOperand(0));
5349     return;
5350   case ISD::BUILD_PAIR:
5351   case ISD::BUILD_VECTOR:
5352   case ISD::CONCAT_VECTORS:
5353     for (SDValue Op : N->op_values())
5354       getUnderlyingArgRegs(Regs, Op);
5355     return;
5356   default:
5357     return;
5358   }
5359 }
5360 
5361 /// If the DbgValueInst is a dbg_value of a function argument, create the
5362 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5363 /// instruction selection, they will be inserted to the entry BB.
5364 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5365     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5366     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5367   const Argument *Arg = dyn_cast<Argument>(V);
5368   if (!Arg)
5369     return false;
5370 
5371   if (!IsDbgDeclare) {
5372     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5373     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5374     // the entry block.
5375     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5376     if (!IsInEntryBlock)
5377       return false;
5378 
5379     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5380     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5381     // variable that also is a param.
5382     //
5383     // Although, if we are at the top of the entry block already, we can still
5384     // emit using ArgDbgValue. This might catch some situations when the
5385     // dbg.value refers to an argument that isn't used in the entry block, so
5386     // any CopyToReg node would be optimized out and the only way to express
5387     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5388     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5389     // we should only emit as ArgDbgValue if the Variable is an argument to the
5390     // current function, and the dbg.value intrinsic is found in the entry
5391     // block.
5392     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5393         !DL->getInlinedAt();
5394     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5395     if (!IsInPrologue && !VariableIsFunctionInputArg)
5396       return false;
5397 
5398     // Here we assume that a function argument on IR level only can be used to
5399     // describe one input parameter on source level. If we for example have
5400     // source code like this
5401     //
5402     //    struct A { long x, y; };
5403     //    void foo(struct A a, long b) {
5404     //      ...
5405     //      b = a.x;
5406     //      ...
5407     //    }
5408     //
5409     // and IR like this
5410     //
5411     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5412     //  entry:
5413     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5414     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5415     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5416     //    ...
5417     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5418     //    ...
5419     //
5420     // then the last dbg.value is describing a parameter "b" using a value that
5421     // is an argument. But since we already has used %a1 to describe a parameter
5422     // we should not handle that last dbg.value here (that would result in an
5423     // incorrect hoisting of the DBG_VALUE to the function entry).
5424     // Notice that we allow one dbg.value per IR level argument, to accommodate
5425     // for the situation with fragments above.
5426     if (VariableIsFunctionInputArg) {
5427       unsigned ArgNo = Arg->getArgNo();
5428       if (ArgNo >= FuncInfo.DescribedArgs.size())
5429         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5430       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5431         return false;
5432       FuncInfo.DescribedArgs.set(ArgNo);
5433     }
5434   }
5435 
5436   MachineFunction &MF = DAG.getMachineFunction();
5437   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5438 
5439   bool IsIndirect = false;
5440   Optional<MachineOperand> Op;
5441   // Some arguments' frame index is recorded during argument lowering.
5442   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5443   if (FI != std::numeric_limits<int>::max())
5444     Op = MachineOperand::CreateFI(FI);
5445 
5446   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5447   if (!Op && N.getNode()) {
5448     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5449     Register Reg;
5450     if (ArgRegsAndSizes.size() == 1)
5451       Reg = ArgRegsAndSizes.front().first;
5452 
5453     if (Reg && Reg.isVirtual()) {
5454       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5455       Register PR = RegInfo.getLiveInPhysReg(Reg);
5456       if (PR)
5457         Reg = PR;
5458     }
5459     if (Reg) {
5460       Op = MachineOperand::CreateReg(Reg, false);
5461       IsIndirect = IsDbgDeclare;
5462     }
5463   }
5464 
5465   if (!Op && N.getNode()) {
5466     // Check if frame index is available.
5467     SDValue LCandidate = peekThroughBitcasts(N);
5468     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5469       if (FrameIndexSDNode *FINode =
5470           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5471         Op = MachineOperand::CreateFI(FINode->getIndex());
5472   }
5473 
5474   if (!Op) {
5475     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5476     auto splitMultiRegDbgValue
5477       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5478       unsigned Offset = 0;
5479       for (auto RegAndSize : SplitRegs) {
5480         // If the expression is already a fragment, the current register
5481         // offset+size might extend beyond the fragment. In this case, only
5482         // the register bits that are inside the fragment are relevant.
5483         int RegFragmentSizeInBits = RegAndSize.second;
5484         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5485           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5486           // The register is entirely outside the expression fragment,
5487           // so is irrelevant for debug info.
5488           if (Offset >= ExprFragmentSizeInBits)
5489             break;
5490           // The register is partially outside the expression fragment, only
5491           // the low bits within the fragment are relevant for debug info.
5492           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5493             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5494           }
5495         }
5496 
5497         auto FragmentExpr = DIExpression::createFragmentExpression(
5498             Expr, Offset, RegFragmentSizeInBits);
5499         Offset += RegAndSize.second;
5500         // If a valid fragment expression cannot be created, the variable's
5501         // correct value cannot be determined and so it is set as Undef.
5502         if (!FragmentExpr) {
5503           SDDbgValue *SDV = DAG.getConstantDbgValue(
5504               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5505           DAG.AddDbgValue(SDV, nullptr, false);
5506           continue;
5507         }
5508         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5509         FuncInfo.ArgDbgValues.push_back(
5510           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5511                   RegAndSize.first, Variable, *FragmentExpr));
5512       }
5513     };
5514 
5515     // Check if ValueMap has reg number.
5516     DenseMap<const Value *, Register>::const_iterator
5517       VMI = FuncInfo.ValueMap.find(V);
5518     if (VMI != FuncInfo.ValueMap.end()) {
5519       const auto &TLI = DAG.getTargetLoweringInfo();
5520       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5521                        V->getType(), getABIRegCopyCC(V));
5522       if (RFV.occupiesMultipleRegs()) {
5523         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5524         return true;
5525       }
5526 
5527       Op = MachineOperand::CreateReg(VMI->second, false);
5528       IsIndirect = IsDbgDeclare;
5529     } else if (ArgRegsAndSizes.size() > 1) {
5530       // This was split due to the calling convention, and no virtual register
5531       // mapping exists for the value.
5532       splitMultiRegDbgValue(ArgRegsAndSizes);
5533       return true;
5534     }
5535   }
5536 
5537   if (!Op)
5538     return false;
5539 
5540   assert(Variable->isValidLocationForIntrinsic(DL) &&
5541          "Expected inlined-at fields to agree");
5542   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5543   FuncInfo.ArgDbgValues.push_back(
5544       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5545               *Op, Variable, Expr));
5546 
5547   return true;
5548 }
5549 
5550 /// Return the appropriate SDDbgValue based on N.
5551 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5552                                              DILocalVariable *Variable,
5553                                              DIExpression *Expr,
5554                                              const DebugLoc &dl,
5555                                              unsigned DbgSDNodeOrder) {
5556   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5557     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5558     // stack slot locations.
5559     //
5560     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5561     // debug values here after optimization:
5562     //
5563     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5564     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5565     //
5566     // Both describe the direct values of their associated variables.
5567     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5568                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5569   }
5570   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5571                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5572 }
5573 
5574 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5575   switch (Intrinsic) {
5576   case Intrinsic::smul_fix:
5577     return ISD::SMULFIX;
5578   case Intrinsic::umul_fix:
5579     return ISD::UMULFIX;
5580   case Intrinsic::smul_fix_sat:
5581     return ISD::SMULFIXSAT;
5582   case Intrinsic::umul_fix_sat:
5583     return ISD::UMULFIXSAT;
5584   case Intrinsic::sdiv_fix:
5585     return ISD::SDIVFIX;
5586   case Intrinsic::udiv_fix:
5587     return ISD::UDIVFIX;
5588   case Intrinsic::sdiv_fix_sat:
5589     return ISD::SDIVFIXSAT;
5590   case Intrinsic::udiv_fix_sat:
5591     return ISD::UDIVFIXSAT;
5592   default:
5593     llvm_unreachable("Unhandled fixed point intrinsic");
5594   }
5595 }
5596 
5597 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5598                                            const char *FunctionName) {
5599   assert(FunctionName && "FunctionName must not be nullptr");
5600   SDValue Callee = DAG.getExternalSymbol(
5601       FunctionName,
5602       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5603   LowerCallTo(I, Callee, I.isTailCall());
5604 }
5605 
5606 /// Given a @llvm.call.preallocated.setup, return the corresponding
5607 /// preallocated call.
5608 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5609   assert(cast<CallBase>(PreallocatedSetup)
5610                  ->getCalledFunction()
5611                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5612          "expected call_preallocated_setup Value");
5613   for (auto *U : PreallocatedSetup->users()) {
5614     auto *UseCall = cast<CallBase>(U);
5615     const Function *Fn = UseCall->getCalledFunction();
5616     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5617       return UseCall;
5618     }
5619   }
5620   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5621 }
5622 
5623 /// Lower the call to the specified intrinsic function.
5624 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5625                                              unsigned Intrinsic) {
5626   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5627   SDLoc sdl = getCurSDLoc();
5628   DebugLoc dl = getCurDebugLoc();
5629   SDValue Res;
5630 
5631   SDNodeFlags Flags;
5632   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5633     Flags.copyFMF(*FPOp);
5634 
5635   switch (Intrinsic) {
5636   default:
5637     // By default, turn this into a target intrinsic node.
5638     visitTargetIntrinsic(I, Intrinsic);
5639     return;
5640   case Intrinsic::vscale: {
5641     match(&I, m_VScale(DAG.getDataLayout()));
5642     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5643     setValue(&I,
5644              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5645     return;
5646   }
5647   case Intrinsic::vastart:  visitVAStart(I); return;
5648   case Intrinsic::vaend:    visitVAEnd(I); return;
5649   case Intrinsic::vacopy:   visitVACopy(I); return;
5650   case Intrinsic::returnaddress:
5651     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5652                              TLI.getPointerTy(DAG.getDataLayout()),
5653                              getValue(I.getArgOperand(0))));
5654     return;
5655   case Intrinsic::addressofreturnaddress:
5656     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5657                              TLI.getPointerTy(DAG.getDataLayout())));
5658     return;
5659   case Intrinsic::sponentry:
5660     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5661                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5662     return;
5663   case Intrinsic::frameaddress:
5664     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5665                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5666                              getValue(I.getArgOperand(0))));
5667     return;
5668   case Intrinsic::read_volatile_register:
5669   case Intrinsic::read_register: {
5670     Value *Reg = I.getArgOperand(0);
5671     SDValue Chain = getRoot();
5672     SDValue RegName =
5673         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5674     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5675     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5676       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5677     setValue(&I, Res);
5678     DAG.setRoot(Res.getValue(1));
5679     return;
5680   }
5681   case Intrinsic::write_register: {
5682     Value *Reg = I.getArgOperand(0);
5683     Value *RegValue = I.getArgOperand(1);
5684     SDValue Chain = getRoot();
5685     SDValue RegName =
5686         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5687     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5688                             RegName, getValue(RegValue)));
5689     return;
5690   }
5691   case Intrinsic::memcpy: {
5692     const auto &MCI = cast<MemCpyInst>(I);
5693     SDValue Op1 = getValue(I.getArgOperand(0));
5694     SDValue Op2 = getValue(I.getArgOperand(1));
5695     SDValue Op3 = getValue(I.getArgOperand(2));
5696     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5697     Align DstAlign = MCI.getDestAlign().valueOrOne();
5698     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5699     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5700     bool isVol = MCI.isVolatile();
5701     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5702     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5703     // node.
5704     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5705     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5706                                /* AlwaysInline */ false, isTC,
5707                                MachinePointerInfo(I.getArgOperand(0)),
5708                                MachinePointerInfo(I.getArgOperand(1)));
5709     updateDAGForMaybeTailCall(MC);
5710     return;
5711   }
5712   case Intrinsic::memcpy_inline: {
5713     const auto &MCI = cast<MemCpyInlineInst>(I);
5714     SDValue Dst = getValue(I.getArgOperand(0));
5715     SDValue Src = getValue(I.getArgOperand(1));
5716     SDValue Size = getValue(I.getArgOperand(2));
5717     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5718     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5719     Align DstAlign = MCI.getDestAlign().valueOrOne();
5720     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5721     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5722     bool isVol = MCI.isVolatile();
5723     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5724     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5725     // node.
5726     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5727                                /* AlwaysInline */ true, isTC,
5728                                MachinePointerInfo(I.getArgOperand(0)),
5729                                MachinePointerInfo(I.getArgOperand(1)));
5730     updateDAGForMaybeTailCall(MC);
5731     return;
5732   }
5733   case Intrinsic::memset: {
5734     const auto &MSI = cast<MemSetInst>(I);
5735     SDValue Op1 = getValue(I.getArgOperand(0));
5736     SDValue Op2 = getValue(I.getArgOperand(1));
5737     SDValue Op3 = getValue(I.getArgOperand(2));
5738     // @llvm.memset defines 0 and 1 to both mean no alignment.
5739     Align Alignment = MSI.getDestAlign().valueOrOne();
5740     bool isVol = MSI.isVolatile();
5741     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5742     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5743     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5744                                MachinePointerInfo(I.getArgOperand(0)));
5745     updateDAGForMaybeTailCall(MS);
5746     return;
5747   }
5748   case Intrinsic::memmove: {
5749     const auto &MMI = cast<MemMoveInst>(I);
5750     SDValue Op1 = getValue(I.getArgOperand(0));
5751     SDValue Op2 = getValue(I.getArgOperand(1));
5752     SDValue Op3 = getValue(I.getArgOperand(2));
5753     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5754     Align DstAlign = MMI.getDestAlign().valueOrOne();
5755     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5756     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5757     bool isVol = MMI.isVolatile();
5758     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5759     // FIXME: Support passing different dest/src alignments to the memmove DAG
5760     // node.
5761     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5762     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5763                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5764                                 MachinePointerInfo(I.getArgOperand(1)));
5765     updateDAGForMaybeTailCall(MM);
5766     return;
5767   }
5768   case Intrinsic::memcpy_element_unordered_atomic: {
5769     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5770     SDValue Dst = getValue(MI.getRawDest());
5771     SDValue Src = getValue(MI.getRawSource());
5772     SDValue Length = getValue(MI.getLength());
5773 
5774     unsigned DstAlign = MI.getDestAlignment();
5775     unsigned SrcAlign = MI.getSourceAlignment();
5776     Type *LengthTy = MI.getLength()->getType();
5777     unsigned ElemSz = MI.getElementSizeInBytes();
5778     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5779     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5780                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5781                                      MachinePointerInfo(MI.getRawDest()),
5782                                      MachinePointerInfo(MI.getRawSource()));
5783     updateDAGForMaybeTailCall(MC);
5784     return;
5785   }
5786   case Intrinsic::memmove_element_unordered_atomic: {
5787     auto &MI = cast<AtomicMemMoveInst>(I);
5788     SDValue Dst = getValue(MI.getRawDest());
5789     SDValue Src = getValue(MI.getRawSource());
5790     SDValue Length = getValue(MI.getLength());
5791 
5792     unsigned DstAlign = MI.getDestAlignment();
5793     unsigned SrcAlign = MI.getSourceAlignment();
5794     Type *LengthTy = MI.getLength()->getType();
5795     unsigned ElemSz = MI.getElementSizeInBytes();
5796     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5797     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5798                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5799                                       MachinePointerInfo(MI.getRawDest()),
5800                                       MachinePointerInfo(MI.getRawSource()));
5801     updateDAGForMaybeTailCall(MC);
5802     return;
5803   }
5804   case Intrinsic::memset_element_unordered_atomic: {
5805     auto &MI = cast<AtomicMemSetInst>(I);
5806     SDValue Dst = getValue(MI.getRawDest());
5807     SDValue Val = getValue(MI.getValue());
5808     SDValue Length = getValue(MI.getLength());
5809 
5810     unsigned DstAlign = MI.getDestAlignment();
5811     Type *LengthTy = MI.getLength()->getType();
5812     unsigned ElemSz = MI.getElementSizeInBytes();
5813     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5814     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5815                                      LengthTy, ElemSz, isTC,
5816                                      MachinePointerInfo(MI.getRawDest()));
5817     updateDAGForMaybeTailCall(MC);
5818     return;
5819   }
5820   case Intrinsic::call_preallocated_setup: {
5821     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5822     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5823     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5824                               getRoot(), SrcValue);
5825     setValue(&I, Res);
5826     DAG.setRoot(Res);
5827     return;
5828   }
5829   case Intrinsic::call_preallocated_arg: {
5830     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5831     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5832     SDValue Ops[3];
5833     Ops[0] = getRoot();
5834     Ops[1] = SrcValue;
5835     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5836                                    MVT::i32); // arg index
5837     SDValue Res = DAG.getNode(
5838         ISD::PREALLOCATED_ARG, sdl,
5839         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5840     setValue(&I, Res);
5841     DAG.setRoot(Res.getValue(1));
5842     return;
5843   }
5844   case Intrinsic::dbg_addr:
5845   case Intrinsic::dbg_declare: {
5846     const auto &DI = cast<DbgVariableIntrinsic>(I);
5847     DILocalVariable *Variable = DI.getVariable();
5848     DIExpression *Expression = DI.getExpression();
5849     dropDanglingDebugInfo(Variable, Expression);
5850     assert(Variable && "Missing variable");
5851     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5852                       << "\n");
5853     // Check if address has undef value.
5854     const Value *Address = DI.getVariableLocation();
5855     if (!Address || isa<UndefValue>(Address) ||
5856         (Address->use_empty() && !isa<Argument>(Address))) {
5857       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5858                         << " (bad/undef/unused-arg address)\n");
5859       return;
5860     }
5861 
5862     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5863 
5864     // Check if this variable can be described by a frame index, typically
5865     // either as a static alloca or a byval parameter.
5866     int FI = std::numeric_limits<int>::max();
5867     if (const auto *AI =
5868             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5869       if (AI->isStaticAlloca()) {
5870         auto I = FuncInfo.StaticAllocaMap.find(AI);
5871         if (I != FuncInfo.StaticAllocaMap.end())
5872           FI = I->second;
5873       }
5874     } else if (const auto *Arg = dyn_cast<Argument>(
5875                    Address->stripInBoundsConstantOffsets())) {
5876       FI = FuncInfo.getArgumentFrameIndex(Arg);
5877     }
5878 
5879     // llvm.dbg.addr is control dependent and always generates indirect
5880     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5881     // the MachineFunction variable table.
5882     if (FI != std::numeric_limits<int>::max()) {
5883       if (Intrinsic == Intrinsic::dbg_addr) {
5884         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5885             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5886         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5887       } else {
5888         LLVM_DEBUG(dbgs() << "Skipping " << DI
5889                           << " (variable info stashed in MF side table)\n");
5890       }
5891       return;
5892     }
5893 
5894     SDValue &N = NodeMap[Address];
5895     if (!N.getNode() && isa<Argument>(Address))
5896       // Check unused arguments map.
5897       N = UnusedArgNodeMap[Address];
5898     SDDbgValue *SDV;
5899     if (N.getNode()) {
5900       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5901         Address = BCI->getOperand(0);
5902       // Parameters are handled specially.
5903       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5904       if (isParameter && FINode) {
5905         // Byval parameter. We have a frame index at this point.
5906         SDV =
5907             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5908                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5909       } else if (isa<Argument>(Address)) {
5910         // Address is an argument, so try to emit its dbg value using
5911         // virtual register info from the FuncInfo.ValueMap.
5912         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5913         return;
5914       } else {
5915         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5916                               true, dl, SDNodeOrder);
5917       }
5918       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5919     } else {
5920       // If Address is an argument then try to emit its dbg value using
5921       // virtual register info from the FuncInfo.ValueMap.
5922       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5923                                     N)) {
5924         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5925                           << " (could not emit func-arg dbg_value)\n");
5926       }
5927     }
5928     return;
5929   }
5930   case Intrinsic::dbg_label: {
5931     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5932     DILabel *Label = DI.getLabel();
5933     assert(Label && "Missing label");
5934 
5935     SDDbgLabel *SDV;
5936     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5937     DAG.AddDbgLabel(SDV);
5938     return;
5939   }
5940   case Intrinsic::dbg_value: {
5941     const DbgValueInst &DI = cast<DbgValueInst>(I);
5942     assert(DI.getVariable() && "Missing variable");
5943 
5944     DILocalVariable *Variable = DI.getVariable();
5945     DIExpression *Expression = DI.getExpression();
5946     dropDanglingDebugInfo(Variable, Expression);
5947     const Value *V = DI.getValue();
5948     if (!V)
5949       return;
5950 
5951     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5952         SDNodeOrder))
5953       return;
5954 
5955     // TODO: Dangling debug info will eventually either be resolved or produce
5956     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5957     // between the original dbg.value location and its resolved DBG_VALUE, which
5958     // we should ideally fill with an extra Undef DBG_VALUE.
5959 
5960     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5961     return;
5962   }
5963 
5964   case Intrinsic::eh_typeid_for: {
5965     // Find the type id for the given typeinfo.
5966     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5967     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5968     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5969     setValue(&I, Res);
5970     return;
5971   }
5972 
5973   case Intrinsic::eh_return_i32:
5974   case Intrinsic::eh_return_i64:
5975     DAG.getMachineFunction().setCallsEHReturn(true);
5976     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5977                             MVT::Other,
5978                             getControlRoot(),
5979                             getValue(I.getArgOperand(0)),
5980                             getValue(I.getArgOperand(1))));
5981     return;
5982   case Intrinsic::eh_unwind_init:
5983     DAG.getMachineFunction().setCallsUnwindInit(true);
5984     return;
5985   case Intrinsic::eh_dwarf_cfa:
5986     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5987                              TLI.getPointerTy(DAG.getDataLayout()),
5988                              getValue(I.getArgOperand(0))));
5989     return;
5990   case Intrinsic::eh_sjlj_callsite: {
5991     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5992     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5993     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5994     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5995 
5996     MMI.setCurrentCallSite(CI->getZExtValue());
5997     return;
5998   }
5999   case Intrinsic::eh_sjlj_functioncontext: {
6000     // Get and store the index of the function context.
6001     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6002     AllocaInst *FnCtx =
6003       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6004     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6005     MFI.setFunctionContextIndex(FI);
6006     return;
6007   }
6008   case Intrinsic::eh_sjlj_setjmp: {
6009     SDValue Ops[2];
6010     Ops[0] = getRoot();
6011     Ops[1] = getValue(I.getArgOperand(0));
6012     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6013                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6014     setValue(&I, Op.getValue(0));
6015     DAG.setRoot(Op.getValue(1));
6016     return;
6017   }
6018   case Intrinsic::eh_sjlj_longjmp:
6019     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6020                             getRoot(), getValue(I.getArgOperand(0))));
6021     return;
6022   case Intrinsic::eh_sjlj_setup_dispatch:
6023     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6024                             getRoot()));
6025     return;
6026   case Intrinsic::masked_gather:
6027     visitMaskedGather(I);
6028     return;
6029   case Intrinsic::masked_load:
6030     visitMaskedLoad(I);
6031     return;
6032   case Intrinsic::masked_scatter:
6033     visitMaskedScatter(I);
6034     return;
6035   case Intrinsic::masked_store:
6036     visitMaskedStore(I);
6037     return;
6038   case Intrinsic::masked_expandload:
6039     visitMaskedLoad(I, true /* IsExpanding */);
6040     return;
6041   case Intrinsic::masked_compressstore:
6042     visitMaskedStore(I, true /* IsCompressing */);
6043     return;
6044   case Intrinsic::powi:
6045     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6046                             getValue(I.getArgOperand(1)), DAG));
6047     return;
6048   case Intrinsic::log:
6049     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6050     return;
6051   case Intrinsic::log2:
6052     setValue(&I,
6053              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6054     return;
6055   case Intrinsic::log10:
6056     setValue(&I,
6057              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6058     return;
6059   case Intrinsic::exp:
6060     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6061     return;
6062   case Intrinsic::exp2:
6063     setValue(&I,
6064              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6065     return;
6066   case Intrinsic::pow:
6067     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6068                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6069     return;
6070   case Intrinsic::sqrt:
6071   case Intrinsic::fabs:
6072   case Intrinsic::sin:
6073   case Intrinsic::cos:
6074   case Intrinsic::floor:
6075   case Intrinsic::ceil:
6076   case Intrinsic::trunc:
6077   case Intrinsic::rint:
6078   case Intrinsic::nearbyint:
6079   case Intrinsic::round:
6080   case Intrinsic::roundeven:
6081   case Intrinsic::canonicalize: {
6082     unsigned Opcode;
6083     switch (Intrinsic) {
6084     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6085     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6086     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6087     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6088     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6089     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6090     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6091     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6092     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6093     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6094     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6095     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6096     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6097     }
6098 
6099     setValue(&I, DAG.getNode(Opcode, sdl,
6100                              getValue(I.getArgOperand(0)).getValueType(),
6101                              getValue(I.getArgOperand(0)), Flags));
6102     return;
6103   }
6104   case Intrinsic::lround:
6105   case Intrinsic::llround:
6106   case Intrinsic::lrint:
6107   case Intrinsic::llrint: {
6108     unsigned Opcode;
6109     switch (Intrinsic) {
6110     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6111     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6112     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6113     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6114     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6115     }
6116 
6117     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6118     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6119                              getValue(I.getArgOperand(0))));
6120     return;
6121   }
6122   case Intrinsic::minnum:
6123     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6124                              getValue(I.getArgOperand(0)).getValueType(),
6125                              getValue(I.getArgOperand(0)),
6126                              getValue(I.getArgOperand(1)), Flags));
6127     return;
6128   case Intrinsic::maxnum:
6129     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6130                              getValue(I.getArgOperand(0)).getValueType(),
6131                              getValue(I.getArgOperand(0)),
6132                              getValue(I.getArgOperand(1)), Flags));
6133     return;
6134   case Intrinsic::minimum:
6135     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6136                              getValue(I.getArgOperand(0)).getValueType(),
6137                              getValue(I.getArgOperand(0)),
6138                              getValue(I.getArgOperand(1)), Flags));
6139     return;
6140   case Intrinsic::maximum:
6141     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6142                              getValue(I.getArgOperand(0)).getValueType(),
6143                              getValue(I.getArgOperand(0)),
6144                              getValue(I.getArgOperand(1)), Flags));
6145     return;
6146   case Intrinsic::copysign:
6147     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6148                              getValue(I.getArgOperand(0)).getValueType(),
6149                              getValue(I.getArgOperand(0)),
6150                              getValue(I.getArgOperand(1)), Flags));
6151     return;
6152   case Intrinsic::fma:
6153     setValue(&I, DAG.getNode(
6154                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6155                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6156                      getValue(I.getArgOperand(2)), Flags));
6157     return;
6158 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6159   case Intrinsic::INTRINSIC:
6160 #include "llvm/IR/ConstrainedOps.def"
6161     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6162     return;
6163   case Intrinsic::fmuladd: {
6164     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6165     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6166         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6167       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6168                                getValue(I.getArgOperand(0)).getValueType(),
6169                                getValue(I.getArgOperand(0)),
6170                                getValue(I.getArgOperand(1)),
6171                                getValue(I.getArgOperand(2)), Flags));
6172     } else {
6173       // TODO: Intrinsic calls should have fast-math-flags.
6174       SDValue Mul = DAG.getNode(
6175           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6176           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6177       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6178                                 getValue(I.getArgOperand(0)).getValueType(),
6179                                 Mul, getValue(I.getArgOperand(2)), Flags);
6180       setValue(&I, Add);
6181     }
6182     return;
6183   }
6184   case Intrinsic::convert_to_fp16:
6185     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6186                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6187                                          getValue(I.getArgOperand(0)),
6188                                          DAG.getTargetConstant(0, sdl,
6189                                                                MVT::i32))));
6190     return;
6191   case Intrinsic::convert_from_fp16:
6192     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6193                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6194                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6195                                          getValue(I.getArgOperand(0)))));
6196     return;
6197   case Intrinsic::pcmarker: {
6198     SDValue Tmp = getValue(I.getArgOperand(0));
6199     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6200     return;
6201   }
6202   case Intrinsic::readcyclecounter: {
6203     SDValue Op = getRoot();
6204     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6205                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6206     setValue(&I, Res);
6207     DAG.setRoot(Res.getValue(1));
6208     return;
6209   }
6210   case Intrinsic::bitreverse:
6211     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6212                              getValue(I.getArgOperand(0)).getValueType(),
6213                              getValue(I.getArgOperand(0))));
6214     return;
6215   case Intrinsic::bswap:
6216     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6217                              getValue(I.getArgOperand(0)).getValueType(),
6218                              getValue(I.getArgOperand(0))));
6219     return;
6220   case Intrinsic::cttz: {
6221     SDValue Arg = getValue(I.getArgOperand(0));
6222     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6223     EVT Ty = Arg.getValueType();
6224     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6225                              sdl, Ty, Arg));
6226     return;
6227   }
6228   case Intrinsic::ctlz: {
6229     SDValue Arg = getValue(I.getArgOperand(0));
6230     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6231     EVT Ty = Arg.getValueType();
6232     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6233                              sdl, Ty, Arg));
6234     return;
6235   }
6236   case Intrinsic::ctpop: {
6237     SDValue Arg = getValue(I.getArgOperand(0));
6238     EVT Ty = Arg.getValueType();
6239     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6240     return;
6241   }
6242   case Intrinsic::fshl:
6243   case Intrinsic::fshr: {
6244     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6245     SDValue X = getValue(I.getArgOperand(0));
6246     SDValue Y = getValue(I.getArgOperand(1));
6247     SDValue Z = getValue(I.getArgOperand(2));
6248     EVT VT = X.getValueType();
6249 
6250     if (X == Y) {
6251       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6252       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6253     } else {
6254       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6255       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6256     }
6257     return;
6258   }
6259   case Intrinsic::sadd_sat: {
6260     SDValue Op1 = getValue(I.getArgOperand(0));
6261     SDValue Op2 = getValue(I.getArgOperand(1));
6262     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6263     return;
6264   }
6265   case Intrinsic::uadd_sat: {
6266     SDValue Op1 = getValue(I.getArgOperand(0));
6267     SDValue Op2 = getValue(I.getArgOperand(1));
6268     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6269     return;
6270   }
6271   case Intrinsic::ssub_sat: {
6272     SDValue Op1 = getValue(I.getArgOperand(0));
6273     SDValue Op2 = getValue(I.getArgOperand(1));
6274     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6275     return;
6276   }
6277   case Intrinsic::usub_sat: {
6278     SDValue Op1 = getValue(I.getArgOperand(0));
6279     SDValue Op2 = getValue(I.getArgOperand(1));
6280     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6281     return;
6282   }
6283   case Intrinsic::sshl_sat: {
6284     SDValue Op1 = getValue(I.getArgOperand(0));
6285     SDValue Op2 = getValue(I.getArgOperand(1));
6286     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6287     return;
6288   }
6289   case Intrinsic::ushl_sat: {
6290     SDValue Op1 = getValue(I.getArgOperand(0));
6291     SDValue Op2 = getValue(I.getArgOperand(1));
6292     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6293     return;
6294   }
6295   case Intrinsic::smul_fix:
6296   case Intrinsic::umul_fix:
6297   case Intrinsic::smul_fix_sat:
6298   case Intrinsic::umul_fix_sat: {
6299     SDValue Op1 = getValue(I.getArgOperand(0));
6300     SDValue Op2 = getValue(I.getArgOperand(1));
6301     SDValue Op3 = getValue(I.getArgOperand(2));
6302     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6303                              Op1.getValueType(), Op1, Op2, Op3));
6304     return;
6305   }
6306   case Intrinsic::sdiv_fix:
6307   case Intrinsic::udiv_fix:
6308   case Intrinsic::sdiv_fix_sat:
6309   case Intrinsic::udiv_fix_sat: {
6310     SDValue Op1 = getValue(I.getArgOperand(0));
6311     SDValue Op2 = getValue(I.getArgOperand(1));
6312     SDValue Op3 = getValue(I.getArgOperand(2));
6313     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6314                               Op1, Op2, Op3, DAG, TLI));
6315     return;
6316   }
6317   case Intrinsic::smax: {
6318     SDValue Op1 = getValue(I.getArgOperand(0));
6319     SDValue Op2 = getValue(I.getArgOperand(1));
6320     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6321     return;
6322   }
6323   case Intrinsic::smin: {
6324     SDValue Op1 = getValue(I.getArgOperand(0));
6325     SDValue Op2 = getValue(I.getArgOperand(1));
6326     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6327     return;
6328   }
6329   case Intrinsic::umax: {
6330     SDValue Op1 = getValue(I.getArgOperand(0));
6331     SDValue Op2 = getValue(I.getArgOperand(1));
6332     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6333     return;
6334   }
6335   case Intrinsic::umin: {
6336     SDValue Op1 = getValue(I.getArgOperand(0));
6337     SDValue Op2 = getValue(I.getArgOperand(1));
6338     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6339     return;
6340   }
6341   case Intrinsic::abs: {
6342     // TODO: Preserve "int min is poison" arg in SDAG?
6343     SDValue Op1 = getValue(I.getArgOperand(0));
6344     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6345     return;
6346   }
6347   case Intrinsic::stacksave: {
6348     SDValue Op = getRoot();
6349     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6350     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6351     setValue(&I, Res);
6352     DAG.setRoot(Res.getValue(1));
6353     return;
6354   }
6355   case Intrinsic::stackrestore:
6356     Res = getValue(I.getArgOperand(0));
6357     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6358     return;
6359   case Intrinsic::get_dynamic_area_offset: {
6360     SDValue Op = getRoot();
6361     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6362     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6363     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6364     // target.
6365     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6366       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6367                          " intrinsic!");
6368     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6369                       Op);
6370     DAG.setRoot(Op);
6371     setValue(&I, Res);
6372     return;
6373   }
6374   case Intrinsic::stackguard: {
6375     MachineFunction &MF = DAG.getMachineFunction();
6376     const Module &M = *MF.getFunction().getParent();
6377     SDValue Chain = getRoot();
6378     if (TLI.useLoadStackGuardNode()) {
6379       Res = getLoadStackGuard(DAG, sdl, Chain);
6380     } else {
6381       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6382       const Value *Global = TLI.getSDagStackGuard(M);
6383       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6384       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6385                         MachinePointerInfo(Global, 0), Align,
6386                         MachineMemOperand::MOVolatile);
6387     }
6388     if (TLI.useStackGuardXorFP())
6389       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6390     DAG.setRoot(Chain);
6391     setValue(&I, Res);
6392     return;
6393   }
6394   case Intrinsic::stackprotector: {
6395     // Emit code into the DAG to store the stack guard onto the stack.
6396     MachineFunction &MF = DAG.getMachineFunction();
6397     MachineFrameInfo &MFI = MF.getFrameInfo();
6398     SDValue Src, Chain = getRoot();
6399 
6400     if (TLI.useLoadStackGuardNode())
6401       Src = getLoadStackGuard(DAG, sdl, Chain);
6402     else
6403       Src = getValue(I.getArgOperand(0));   // The guard's value.
6404 
6405     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6406 
6407     int FI = FuncInfo.StaticAllocaMap[Slot];
6408     MFI.setStackProtectorIndex(FI);
6409     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6410 
6411     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6412 
6413     // Store the stack protector onto the stack.
6414     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6415                                                  DAG.getMachineFunction(), FI),
6416                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6417     setValue(&I, Res);
6418     DAG.setRoot(Res);
6419     return;
6420   }
6421   case Intrinsic::objectsize:
6422     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6423 
6424   case Intrinsic::is_constant:
6425     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6426 
6427   case Intrinsic::annotation:
6428   case Intrinsic::ptr_annotation:
6429   case Intrinsic::launder_invariant_group:
6430   case Intrinsic::strip_invariant_group:
6431     // Drop the intrinsic, but forward the value
6432     setValue(&I, getValue(I.getOperand(0)));
6433     return;
6434   case Intrinsic::assume:
6435   case Intrinsic::var_annotation:
6436   case Intrinsic::sideeffect:
6437     // Discard annotate attributes, assumptions, and artificial side-effects.
6438     return;
6439 
6440   case Intrinsic::codeview_annotation: {
6441     // Emit a label associated with this metadata.
6442     MachineFunction &MF = DAG.getMachineFunction();
6443     MCSymbol *Label =
6444         MF.getMMI().getContext().createTempSymbol("annotation", true);
6445     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6446     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6447     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6448     DAG.setRoot(Res);
6449     return;
6450   }
6451 
6452   case Intrinsic::init_trampoline: {
6453     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6454 
6455     SDValue Ops[6];
6456     Ops[0] = getRoot();
6457     Ops[1] = getValue(I.getArgOperand(0));
6458     Ops[2] = getValue(I.getArgOperand(1));
6459     Ops[3] = getValue(I.getArgOperand(2));
6460     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6461     Ops[5] = DAG.getSrcValue(F);
6462 
6463     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6464 
6465     DAG.setRoot(Res);
6466     return;
6467   }
6468   case Intrinsic::adjust_trampoline:
6469     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6470                              TLI.getPointerTy(DAG.getDataLayout()),
6471                              getValue(I.getArgOperand(0))));
6472     return;
6473   case Intrinsic::gcroot: {
6474     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6475            "only valid in functions with gc specified, enforced by Verifier");
6476     assert(GFI && "implied by previous");
6477     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6478     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6479 
6480     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6481     GFI->addStackRoot(FI->getIndex(), TypeMap);
6482     return;
6483   }
6484   case Intrinsic::gcread:
6485   case Intrinsic::gcwrite:
6486     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6487   case Intrinsic::flt_rounds:
6488     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6489     setValue(&I, Res);
6490     DAG.setRoot(Res.getValue(1));
6491     return;
6492 
6493   case Intrinsic::expect:
6494     // Just replace __builtin_expect(exp, c) with EXP.
6495     setValue(&I, getValue(I.getArgOperand(0)));
6496     return;
6497 
6498   case Intrinsic::debugtrap:
6499   case Intrinsic::trap: {
6500     StringRef TrapFuncName =
6501         I.getAttributes()
6502             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6503             .getValueAsString();
6504     if (TrapFuncName.empty()) {
6505       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6506         ISD::TRAP : ISD::DEBUGTRAP;
6507       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6508       return;
6509     }
6510     TargetLowering::ArgListTy Args;
6511 
6512     TargetLowering::CallLoweringInfo CLI(DAG);
6513     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6514         CallingConv::C, I.getType(),
6515         DAG.getExternalSymbol(TrapFuncName.data(),
6516                               TLI.getPointerTy(DAG.getDataLayout())),
6517         std::move(Args));
6518 
6519     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6520     DAG.setRoot(Result.second);
6521     return;
6522   }
6523 
6524   case Intrinsic::uadd_with_overflow:
6525   case Intrinsic::sadd_with_overflow:
6526   case Intrinsic::usub_with_overflow:
6527   case Intrinsic::ssub_with_overflow:
6528   case Intrinsic::umul_with_overflow:
6529   case Intrinsic::smul_with_overflow: {
6530     ISD::NodeType Op;
6531     switch (Intrinsic) {
6532     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6533     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6534     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6535     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6536     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6537     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6538     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6539     }
6540     SDValue Op1 = getValue(I.getArgOperand(0));
6541     SDValue Op2 = getValue(I.getArgOperand(1));
6542 
6543     EVT ResultVT = Op1.getValueType();
6544     EVT OverflowVT = MVT::i1;
6545     if (ResultVT.isVector())
6546       OverflowVT = EVT::getVectorVT(
6547           *Context, OverflowVT, ResultVT.getVectorNumElements());
6548 
6549     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6550     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6551     return;
6552   }
6553   case Intrinsic::prefetch: {
6554     SDValue Ops[5];
6555     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6556     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6557     Ops[0] = DAG.getRoot();
6558     Ops[1] = getValue(I.getArgOperand(0));
6559     Ops[2] = getValue(I.getArgOperand(1));
6560     Ops[3] = getValue(I.getArgOperand(2));
6561     Ops[4] = getValue(I.getArgOperand(3));
6562     SDValue Result = DAG.getMemIntrinsicNode(
6563         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6564         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6565         /* align */ None, Flags);
6566 
6567     // Chain the prefetch in parallell with any pending loads, to stay out of
6568     // the way of later optimizations.
6569     PendingLoads.push_back(Result);
6570     Result = getRoot();
6571     DAG.setRoot(Result);
6572     return;
6573   }
6574   case Intrinsic::lifetime_start:
6575   case Intrinsic::lifetime_end: {
6576     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6577     // Stack coloring is not enabled in O0, discard region information.
6578     if (TM.getOptLevel() == CodeGenOpt::None)
6579       return;
6580 
6581     const int64_t ObjectSize =
6582         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6583     Value *const ObjectPtr = I.getArgOperand(1);
6584     SmallVector<const Value *, 4> Allocas;
6585     getUnderlyingObjects(ObjectPtr, Allocas);
6586 
6587     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6588            E = Allocas.end(); Object != E; ++Object) {
6589       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6590 
6591       // Could not find an Alloca.
6592       if (!LifetimeObject)
6593         continue;
6594 
6595       // First check that the Alloca is static, otherwise it won't have a
6596       // valid frame index.
6597       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6598       if (SI == FuncInfo.StaticAllocaMap.end())
6599         return;
6600 
6601       const int FrameIndex = SI->second;
6602       int64_t Offset;
6603       if (GetPointerBaseWithConstantOffset(
6604               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6605         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6606       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6607                                 Offset);
6608       DAG.setRoot(Res);
6609     }
6610     return;
6611   }
6612   case Intrinsic::invariant_start:
6613     // Discard region information.
6614     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6615     return;
6616   case Intrinsic::invariant_end:
6617     // Discard region information.
6618     return;
6619   case Intrinsic::clear_cache:
6620     /// FunctionName may be null.
6621     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6622       lowerCallToExternalSymbol(I, FunctionName);
6623     return;
6624   case Intrinsic::donothing:
6625     // ignore
6626     return;
6627   case Intrinsic::experimental_stackmap:
6628     visitStackmap(I);
6629     return;
6630   case Intrinsic::experimental_patchpoint_void:
6631   case Intrinsic::experimental_patchpoint_i64:
6632     visitPatchpoint(I);
6633     return;
6634   case Intrinsic::experimental_gc_statepoint:
6635     LowerStatepoint(cast<GCStatepointInst>(I));
6636     return;
6637   case Intrinsic::experimental_gc_result:
6638     visitGCResult(cast<GCResultInst>(I));
6639     return;
6640   case Intrinsic::experimental_gc_relocate:
6641     visitGCRelocate(cast<GCRelocateInst>(I));
6642     return;
6643   case Intrinsic::instrprof_increment:
6644     llvm_unreachable("instrprof failed to lower an increment");
6645   case Intrinsic::instrprof_value_profile:
6646     llvm_unreachable("instrprof failed to lower a value profiling call");
6647   case Intrinsic::localescape: {
6648     MachineFunction &MF = DAG.getMachineFunction();
6649     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6650 
6651     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6652     // is the same on all targets.
6653     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6654       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6655       if (isa<ConstantPointerNull>(Arg))
6656         continue; // Skip null pointers. They represent a hole in index space.
6657       AllocaInst *Slot = cast<AllocaInst>(Arg);
6658       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6659              "can only escape static allocas");
6660       int FI = FuncInfo.StaticAllocaMap[Slot];
6661       MCSymbol *FrameAllocSym =
6662           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6663               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6664       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6665               TII->get(TargetOpcode::LOCAL_ESCAPE))
6666           .addSym(FrameAllocSym)
6667           .addFrameIndex(FI);
6668     }
6669 
6670     return;
6671   }
6672 
6673   case Intrinsic::localrecover: {
6674     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6675     MachineFunction &MF = DAG.getMachineFunction();
6676 
6677     // Get the symbol that defines the frame offset.
6678     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6679     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6680     unsigned IdxVal =
6681         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6682     MCSymbol *FrameAllocSym =
6683         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6684             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6685 
6686     Value *FP = I.getArgOperand(1);
6687     SDValue FPVal = getValue(FP);
6688     EVT PtrVT = FPVal.getValueType();
6689 
6690     // Create a MCSymbol for the label to avoid any target lowering
6691     // that would make this PC relative.
6692     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6693     SDValue OffsetVal =
6694         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6695 
6696     // Add the offset to the FP.
6697     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6698     setValue(&I, Add);
6699 
6700     return;
6701   }
6702 
6703   case Intrinsic::eh_exceptionpointer:
6704   case Intrinsic::eh_exceptioncode: {
6705     // Get the exception pointer vreg, copy from it, and resize it to fit.
6706     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6707     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6708     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6709     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6710     SDValue N =
6711         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6712     if (Intrinsic == Intrinsic::eh_exceptioncode)
6713       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6714     setValue(&I, N);
6715     return;
6716   }
6717   case Intrinsic::xray_customevent: {
6718     // Here we want to make sure that the intrinsic behaves as if it has a
6719     // specific calling convention, and only for x86_64.
6720     // FIXME: Support other platforms later.
6721     const auto &Triple = DAG.getTarget().getTargetTriple();
6722     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6723       return;
6724 
6725     SDLoc DL = getCurSDLoc();
6726     SmallVector<SDValue, 8> Ops;
6727 
6728     // We want to say that we always want the arguments in registers.
6729     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6730     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6731     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6732     SDValue Chain = getRoot();
6733     Ops.push_back(LogEntryVal);
6734     Ops.push_back(StrSizeVal);
6735     Ops.push_back(Chain);
6736 
6737     // We need to enforce the calling convention for the callsite, so that
6738     // argument ordering is enforced correctly, and that register allocation can
6739     // see that some registers may be assumed clobbered and have to preserve
6740     // them across calls to the intrinsic.
6741     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6742                                            DL, NodeTys, Ops);
6743     SDValue patchableNode = SDValue(MN, 0);
6744     DAG.setRoot(patchableNode);
6745     setValue(&I, patchableNode);
6746     return;
6747   }
6748   case Intrinsic::xray_typedevent: {
6749     // Here we want to make sure that the intrinsic behaves as if it has a
6750     // specific calling convention, and only for x86_64.
6751     // FIXME: Support other platforms later.
6752     const auto &Triple = DAG.getTarget().getTargetTriple();
6753     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6754       return;
6755 
6756     SDLoc DL = getCurSDLoc();
6757     SmallVector<SDValue, 8> Ops;
6758 
6759     // We want to say that we always want the arguments in registers.
6760     // It's unclear to me how manipulating the selection DAG here forces callers
6761     // to provide arguments in registers instead of on the stack.
6762     SDValue LogTypeId = getValue(I.getArgOperand(0));
6763     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6764     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6765     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6766     SDValue Chain = getRoot();
6767     Ops.push_back(LogTypeId);
6768     Ops.push_back(LogEntryVal);
6769     Ops.push_back(StrSizeVal);
6770     Ops.push_back(Chain);
6771 
6772     // We need to enforce the calling convention for the callsite, so that
6773     // argument ordering is enforced correctly, and that register allocation can
6774     // see that some registers may be assumed clobbered and have to preserve
6775     // them across calls to the intrinsic.
6776     MachineSDNode *MN = DAG.getMachineNode(
6777         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6778     SDValue patchableNode = SDValue(MN, 0);
6779     DAG.setRoot(patchableNode);
6780     setValue(&I, patchableNode);
6781     return;
6782   }
6783   case Intrinsic::experimental_deoptimize:
6784     LowerDeoptimizeCall(&I);
6785     return;
6786 
6787   case Intrinsic::experimental_vector_reduce_v2_fadd:
6788   case Intrinsic::experimental_vector_reduce_v2_fmul:
6789   case Intrinsic::experimental_vector_reduce_add:
6790   case Intrinsic::experimental_vector_reduce_mul:
6791   case Intrinsic::experimental_vector_reduce_and:
6792   case Intrinsic::experimental_vector_reduce_or:
6793   case Intrinsic::experimental_vector_reduce_xor:
6794   case Intrinsic::experimental_vector_reduce_smax:
6795   case Intrinsic::experimental_vector_reduce_smin:
6796   case Intrinsic::experimental_vector_reduce_umax:
6797   case Intrinsic::experimental_vector_reduce_umin:
6798   case Intrinsic::experimental_vector_reduce_fmax:
6799   case Intrinsic::experimental_vector_reduce_fmin:
6800     visitVectorReduce(I, Intrinsic);
6801     return;
6802 
6803   case Intrinsic::icall_branch_funnel: {
6804     SmallVector<SDValue, 16> Ops;
6805     Ops.push_back(getValue(I.getArgOperand(0)));
6806 
6807     int64_t Offset;
6808     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6809         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6810     if (!Base)
6811       report_fatal_error(
6812           "llvm.icall.branch.funnel operand must be a GlobalValue");
6813     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6814 
6815     struct BranchFunnelTarget {
6816       int64_t Offset;
6817       SDValue Target;
6818     };
6819     SmallVector<BranchFunnelTarget, 8> Targets;
6820 
6821     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6822       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6823           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6824       if (ElemBase != Base)
6825         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6826                            "to the same GlobalValue");
6827 
6828       SDValue Val = getValue(I.getArgOperand(Op + 1));
6829       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6830       if (!GA)
6831         report_fatal_error(
6832             "llvm.icall.branch.funnel operand must be a GlobalValue");
6833       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6834                                      GA->getGlobal(), getCurSDLoc(),
6835                                      Val.getValueType(), GA->getOffset())});
6836     }
6837     llvm::sort(Targets,
6838                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6839                  return T1.Offset < T2.Offset;
6840                });
6841 
6842     for (auto &T : Targets) {
6843       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6844       Ops.push_back(T.Target);
6845     }
6846 
6847     Ops.push_back(DAG.getRoot()); // Chain
6848     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6849                                  getCurSDLoc(), MVT::Other, Ops),
6850               0);
6851     DAG.setRoot(N);
6852     setValue(&I, N);
6853     HasTailCall = true;
6854     return;
6855   }
6856 
6857   case Intrinsic::wasm_landingpad_index:
6858     // Information this intrinsic contained has been transferred to
6859     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6860     // delete it now.
6861     return;
6862 
6863   case Intrinsic::aarch64_settag:
6864   case Intrinsic::aarch64_settag_zero: {
6865     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6866     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6867     SDValue Val = TSI.EmitTargetCodeForSetTag(
6868         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6869         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6870         ZeroMemory);
6871     DAG.setRoot(Val);
6872     setValue(&I, Val);
6873     return;
6874   }
6875   case Intrinsic::ptrmask: {
6876     SDValue Ptr = getValue(I.getOperand(0));
6877     SDValue Const = getValue(I.getOperand(1));
6878 
6879     EVT PtrVT = Ptr.getValueType();
6880     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
6881                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
6882     return;
6883   }
6884   case Intrinsic::get_active_lane_mask: {
6885     auto DL = getCurSDLoc();
6886     SDValue Index = getValue(I.getOperand(0));
6887     SDValue TripCount = getValue(I.getOperand(1));
6888     Type *ElementTy = I.getOperand(0)->getType();
6889     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6890     unsigned VecWidth = VT.getVectorNumElements();
6891 
6892     SmallVector<SDValue, 16> OpsTripCount;
6893     SmallVector<SDValue, 16> OpsIndex;
6894     SmallVector<SDValue, 16> OpsStepConstants;
6895     for (unsigned i = 0; i < VecWidth; i++) {
6896       OpsTripCount.push_back(TripCount);
6897       OpsIndex.push_back(Index);
6898       OpsStepConstants.push_back(
6899           DAG.getConstant(i, DL, EVT::getEVT(ElementTy)));
6900     }
6901 
6902     EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth);
6903 
6904     auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth));
6905     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
6906     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
6907     SDValue VectorInduction = DAG.getNode(
6908        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
6909     SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount);
6910     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
6911                                  VectorTripCount, ISD::CondCode::SETULT);
6912     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
6913                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
6914                              SetCC));
6915     return;
6916   }
6917   }
6918 }
6919 
6920 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6921     const ConstrainedFPIntrinsic &FPI) {
6922   SDLoc sdl = getCurSDLoc();
6923 
6924   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6925   SmallVector<EVT, 4> ValueVTs;
6926   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6927   ValueVTs.push_back(MVT::Other); // Out chain
6928 
6929   // We do not need to serialize constrained FP intrinsics against
6930   // each other or against (nonvolatile) loads, so they can be
6931   // chained like loads.
6932   SDValue Chain = DAG.getRoot();
6933   SmallVector<SDValue, 4> Opers;
6934   Opers.push_back(Chain);
6935   if (FPI.isUnaryOp()) {
6936     Opers.push_back(getValue(FPI.getArgOperand(0)));
6937   } else if (FPI.isTernaryOp()) {
6938     Opers.push_back(getValue(FPI.getArgOperand(0)));
6939     Opers.push_back(getValue(FPI.getArgOperand(1)));
6940     Opers.push_back(getValue(FPI.getArgOperand(2)));
6941   } else {
6942     Opers.push_back(getValue(FPI.getArgOperand(0)));
6943     Opers.push_back(getValue(FPI.getArgOperand(1)));
6944   }
6945 
6946   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
6947     assert(Result.getNode()->getNumValues() == 2);
6948 
6949     // Push node to the appropriate list so that future instructions can be
6950     // chained up correctly.
6951     SDValue OutChain = Result.getValue(1);
6952     switch (EB) {
6953     case fp::ExceptionBehavior::ebIgnore:
6954       // The only reason why ebIgnore nodes still need to be chained is that
6955       // they might depend on the current rounding mode, and therefore must
6956       // not be moved across instruction that may change that mode.
6957       LLVM_FALLTHROUGH;
6958     case fp::ExceptionBehavior::ebMayTrap:
6959       // These must not be moved across calls or instructions that may change
6960       // floating-point exception masks.
6961       PendingConstrainedFP.push_back(OutChain);
6962       break;
6963     case fp::ExceptionBehavior::ebStrict:
6964       // These must not be moved across calls or instructions that may change
6965       // floating-point exception masks or read floating-point exception flags.
6966       // In addition, they cannot be optimized out even if unused.
6967       PendingConstrainedFPStrict.push_back(OutChain);
6968       break;
6969     }
6970   };
6971 
6972   SDVTList VTs = DAG.getVTList(ValueVTs);
6973   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
6974 
6975   SDNodeFlags Flags;
6976   if (EB == fp::ExceptionBehavior::ebIgnore)
6977     Flags.setNoFPExcept(true);
6978 
6979   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
6980     Flags.copyFMF(*FPOp);
6981 
6982   unsigned Opcode;
6983   switch (FPI.getIntrinsicID()) {
6984   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6985 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
6986   case Intrinsic::INTRINSIC:                                                   \
6987     Opcode = ISD::STRICT_##DAGN;                                               \
6988     break;
6989 #include "llvm/IR/ConstrainedOps.def"
6990   case Intrinsic::experimental_constrained_fmuladd: {
6991     Opcode = ISD::STRICT_FMA;
6992     // Break fmuladd into fmul and fadd.
6993     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
6994         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
6995                                         ValueVTs[0])) {
6996       Opers.pop_back();
6997       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
6998       pushOutChain(Mul, EB);
6999       Opcode = ISD::STRICT_FADD;
7000       Opers.clear();
7001       Opers.push_back(Mul.getValue(1));
7002       Opers.push_back(Mul.getValue(0));
7003       Opers.push_back(getValue(FPI.getArgOperand(2)));
7004     }
7005     break;
7006   }
7007   }
7008 
7009   // A few strict DAG nodes carry additional operands that are not
7010   // set up by the default code above.
7011   switch (Opcode) {
7012   default: break;
7013   case ISD::STRICT_FP_ROUND:
7014     Opers.push_back(
7015         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7016     break;
7017   case ISD::STRICT_FSETCC:
7018   case ISD::STRICT_FSETCCS: {
7019     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7020     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
7021     break;
7022   }
7023   }
7024 
7025   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7026   pushOutChain(Result, EB);
7027 
7028   SDValue FPResult = Result.getValue(0);
7029   setValue(&FPI, FPResult);
7030 }
7031 
7032 std::pair<SDValue, SDValue>
7033 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7034                                     const BasicBlock *EHPadBB) {
7035   MachineFunction &MF = DAG.getMachineFunction();
7036   MachineModuleInfo &MMI = MF.getMMI();
7037   MCSymbol *BeginLabel = nullptr;
7038 
7039   if (EHPadBB) {
7040     // Insert a label before the invoke call to mark the try range.  This can be
7041     // used to detect deletion of the invoke via the MachineModuleInfo.
7042     BeginLabel = MMI.getContext().createTempSymbol();
7043 
7044     // For SjLj, keep track of which landing pads go with which invokes
7045     // so as to maintain the ordering of pads in the LSDA.
7046     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7047     if (CallSiteIndex) {
7048       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7049       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7050 
7051       // Now that the call site is handled, stop tracking it.
7052       MMI.setCurrentCallSite(0);
7053     }
7054 
7055     // Both PendingLoads and PendingExports must be flushed here;
7056     // this call might not return.
7057     (void)getRoot();
7058     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7059 
7060     CLI.setChain(getRoot());
7061   }
7062   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7063   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7064 
7065   assert((CLI.IsTailCall || Result.second.getNode()) &&
7066          "Non-null chain expected with non-tail call!");
7067   assert((Result.second.getNode() || !Result.first.getNode()) &&
7068          "Null value expected with tail call!");
7069 
7070   if (!Result.second.getNode()) {
7071     // As a special case, a null chain means that a tail call has been emitted
7072     // and the DAG root is already updated.
7073     HasTailCall = true;
7074 
7075     // Since there's no actual continuation from this block, nothing can be
7076     // relying on us setting vregs for them.
7077     PendingExports.clear();
7078   } else {
7079     DAG.setRoot(Result.second);
7080   }
7081 
7082   if (EHPadBB) {
7083     // Insert a label at the end of the invoke call to mark the try range.  This
7084     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7085     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7086     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7087 
7088     // Inform MachineModuleInfo of range.
7089     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7090     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7091     // actually use outlined funclets and their LSDA info style.
7092     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7093       assert(CLI.CB);
7094       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7095       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7096     } else if (!isScopedEHPersonality(Pers)) {
7097       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7098     }
7099   }
7100 
7101   return Result;
7102 }
7103 
7104 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7105                                       bool isTailCall,
7106                                       const BasicBlock *EHPadBB) {
7107   auto &DL = DAG.getDataLayout();
7108   FunctionType *FTy = CB.getFunctionType();
7109   Type *RetTy = CB.getType();
7110 
7111   TargetLowering::ArgListTy Args;
7112   Args.reserve(CB.arg_size());
7113 
7114   const Value *SwiftErrorVal = nullptr;
7115   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7116 
7117   if (isTailCall) {
7118     // Avoid emitting tail calls in functions with the disable-tail-calls
7119     // attribute.
7120     auto *Caller = CB.getParent()->getParent();
7121     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7122         "true")
7123       isTailCall = false;
7124 
7125     // We can't tail call inside a function with a swifterror argument. Lowering
7126     // does not support this yet. It would have to move into the swifterror
7127     // register before the call.
7128     if (TLI.supportSwiftError() &&
7129         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7130       isTailCall = false;
7131   }
7132 
7133   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7134     TargetLowering::ArgListEntry Entry;
7135     const Value *V = *I;
7136 
7137     // Skip empty types
7138     if (V->getType()->isEmptyTy())
7139       continue;
7140 
7141     SDValue ArgNode = getValue(V);
7142     Entry.Node = ArgNode; Entry.Ty = V->getType();
7143 
7144     Entry.setAttributes(&CB, I - CB.arg_begin());
7145 
7146     // Use swifterror virtual register as input to the call.
7147     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7148       SwiftErrorVal = V;
7149       // We find the virtual register for the actual swifterror argument.
7150       // Instead of using the Value, we use the virtual register instead.
7151       Entry.Node =
7152           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7153                           EVT(TLI.getPointerTy(DL)));
7154     }
7155 
7156     Args.push_back(Entry);
7157 
7158     // If we have an explicit sret argument that is an Instruction, (i.e., it
7159     // might point to function-local memory), we can't meaningfully tail-call.
7160     if (Entry.IsSRet && isa<Instruction>(V))
7161       isTailCall = false;
7162   }
7163 
7164   // If call site has a cfguardtarget operand bundle, create and add an
7165   // additional ArgListEntry.
7166   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7167     TargetLowering::ArgListEntry Entry;
7168     Value *V = Bundle->Inputs[0];
7169     SDValue ArgNode = getValue(V);
7170     Entry.Node = ArgNode;
7171     Entry.Ty = V->getType();
7172     Entry.IsCFGuardTarget = true;
7173     Args.push_back(Entry);
7174   }
7175 
7176   // Check if target-independent constraints permit a tail call here.
7177   // Target-dependent constraints are checked within TLI->LowerCallTo.
7178   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7179     isTailCall = false;
7180 
7181   // Disable tail calls if there is an swifterror argument. Targets have not
7182   // been updated to support tail calls.
7183   if (TLI.supportSwiftError() && SwiftErrorVal)
7184     isTailCall = false;
7185 
7186   TargetLowering::CallLoweringInfo CLI(DAG);
7187   CLI.setDebugLoc(getCurSDLoc())
7188       .setChain(getRoot())
7189       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7190       .setTailCall(isTailCall)
7191       .setConvergent(CB.isConvergent())
7192       .setIsPreallocated(
7193           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7194   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7195 
7196   if (Result.first.getNode()) {
7197     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7198     setValue(&CB, Result.first);
7199   }
7200 
7201   // The last element of CLI.InVals has the SDValue for swifterror return.
7202   // Here we copy it to a virtual register and update SwiftErrorMap for
7203   // book-keeping.
7204   if (SwiftErrorVal && TLI.supportSwiftError()) {
7205     // Get the last element of InVals.
7206     SDValue Src = CLI.InVals.back();
7207     Register VReg =
7208         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7209     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7210     DAG.setRoot(CopyNode);
7211   }
7212 }
7213 
7214 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7215                              SelectionDAGBuilder &Builder) {
7216   // Check to see if this load can be trivially constant folded, e.g. if the
7217   // input is from a string literal.
7218   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7219     // Cast pointer to the type we really want to load.
7220     Type *LoadTy =
7221         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7222     if (LoadVT.isVector())
7223       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7224 
7225     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7226                                          PointerType::getUnqual(LoadTy));
7227 
7228     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7229             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7230       return Builder.getValue(LoadCst);
7231   }
7232 
7233   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7234   // still constant memory, the input chain can be the entry node.
7235   SDValue Root;
7236   bool ConstantMemory = false;
7237 
7238   // Do not serialize (non-volatile) loads of constant memory with anything.
7239   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7240     Root = Builder.DAG.getEntryNode();
7241     ConstantMemory = true;
7242   } else {
7243     // Do not serialize non-volatile loads against each other.
7244     Root = Builder.DAG.getRoot();
7245   }
7246 
7247   SDValue Ptr = Builder.getValue(PtrVal);
7248   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7249                                         Ptr, MachinePointerInfo(PtrVal),
7250                                         /* Alignment = */ 1);
7251 
7252   if (!ConstantMemory)
7253     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7254   return LoadVal;
7255 }
7256 
7257 /// Record the value for an instruction that produces an integer result,
7258 /// converting the type where necessary.
7259 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7260                                                   SDValue Value,
7261                                                   bool IsSigned) {
7262   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7263                                                     I.getType(), true);
7264   if (IsSigned)
7265     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7266   else
7267     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7268   setValue(&I, Value);
7269 }
7270 
7271 /// See if we can lower a memcmp call into an optimized form. If so, return
7272 /// true and lower it. Otherwise return false, and it will be lowered like a
7273 /// normal call.
7274 /// The caller already checked that \p I calls the appropriate LibFunc with a
7275 /// correct prototype.
7276 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7277   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7278   const Value *Size = I.getArgOperand(2);
7279   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7280   if (CSize && CSize->getZExtValue() == 0) {
7281     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7282                                                           I.getType(), true);
7283     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7284     return true;
7285   }
7286 
7287   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7288   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7289       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7290       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7291   if (Res.first.getNode()) {
7292     processIntegerCallValue(I, Res.first, true);
7293     PendingLoads.push_back(Res.second);
7294     return true;
7295   }
7296 
7297   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7298   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7299   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7300     return false;
7301 
7302   // If the target has a fast compare for the given size, it will return a
7303   // preferred load type for that size. Require that the load VT is legal and
7304   // that the target supports unaligned loads of that type. Otherwise, return
7305   // INVALID.
7306   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7307     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7308     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7309     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7310       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7311       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7312       // TODO: Check alignment of src and dest ptrs.
7313       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7314       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7315       if (!TLI.isTypeLegal(LVT) ||
7316           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7317           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7318         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7319     }
7320 
7321     return LVT;
7322   };
7323 
7324   // This turns into unaligned loads. We only do this if the target natively
7325   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7326   // we'll only produce a small number of byte loads.
7327   MVT LoadVT;
7328   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7329   switch (NumBitsToCompare) {
7330   default:
7331     return false;
7332   case 16:
7333     LoadVT = MVT::i16;
7334     break;
7335   case 32:
7336     LoadVT = MVT::i32;
7337     break;
7338   case 64:
7339   case 128:
7340   case 256:
7341     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7342     break;
7343   }
7344 
7345   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7346     return false;
7347 
7348   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7349   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7350 
7351   // Bitcast to a wide integer type if the loads are vectors.
7352   if (LoadVT.isVector()) {
7353     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7354     LoadL = DAG.getBitcast(CmpVT, LoadL);
7355     LoadR = DAG.getBitcast(CmpVT, LoadR);
7356   }
7357 
7358   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7359   processIntegerCallValue(I, Cmp, false);
7360   return true;
7361 }
7362 
7363 /// See if we can lower a memchr call into an optimized form. If so, return
7364 /// true and lower it. Otherwise return false, and it will be lowered like a
7365 /// normal call.
7366 /// The caller already checked that \p I calls the appropriate LibFunc with a
7367 /// correct prototype.
7368 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7369   const Value *Src = I.getArgOperand(0);
7370   const Value *Char = I.getArgOperand(1);
7371   const Value *Length = I.getArgOperand(2);
7372 
7373   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7374   std::pair<SDValue, SDValue> Res =
7375     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7376                                 getValue(Src), getValue(Char), getValue(Length),
7377                                 MachinePointerInfo(Src));
7378   if (Res.first.getNode()) {
7379     setValue(&I, Res.first);
7380     PendingLoads.push_back(Res.second);
7381     return true;
7382   }
7383 
7384   return false;
7385 }
7386 
7387 /// See if we can lower a mempcpy call into an optimized form. If so, return
7388 /// true and lower it. Otherwise return false, and it will be lowered like a
7389 /// normal call.
7390 /// The caller already checked that \p I calls the appropriate LibFunc with a
7391 /// correct prototype.
7392 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7393   SDValue Dst = getValue(I.getArgOperand(0));
7394   SDValue Src = getValue(I.getArgOperand(1));
7395   SDValue Size = getValue(I.getArgOperand(2));
7396 
7397   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7398   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7399   // DAG::getMemcpy needs Alignment to be defined.
7400   Align Alignment = std::min(DstAlign, SrcAlign);
7401 
7402   bool isVol = false;
7403   SDLoc sdl = getCurSDLoc();
7404 
7405   // In the mempcpy context we need to pass in a false value for isTailCall
7406   // because the return pointer needs to be adjusted by the size of
7407   // the copied memory.
7408   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7409   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7410                              /*isTailCall=*/false,
7411                              MachinePointerInfo(I.getArgOperand(0)),
7412                              MachinePointerInfo(I.getArgOperand(1)));
7413   assert(MC.getNode() != nullptr &&
7414          "** memcpy should not be lowered as TailCall in mempcpy context **");
7415   DAG.setRoot(MC);
7416 
7417   // Check if Size needs to be truncated or extended.
7418   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7419 
7420   // Adjust return pointer to point just past the last dst byte.
7421   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7422                                     Dst, Size);
7423   setValue(&I, DstPlusSize);
7424   return true;
7425 }
7426 
7427 /// See if we can lower a strcpy call into an optimized form.  If so, return
7428 /// true and lower it, otherwise return false and it will be lowered like a
7429 /// normal call.
7430 /// The caller already checked that \p I calls the appropriate LibFunc with a
7431 /// correct prototype.
7432 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7433   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7434 
7435   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7436   std::pair<SDValue, SDValue> Res =
7437     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7438                                 getValue(Arg0), getValue(Arg1),
7439                                 MachinePointerInfo(Arg0),
7440                                 MachinePointerInfo(Arg1), isStpcpy);
7441   if (Res.first.getNode()) {
7442     setValue(&I, Res.first);
7443     DAG.setRoot(Res.second);
7444     return true;
7445   }
7446 
7447   return false;
7448 }
7449 
7450 /// See if we can lower a strcmp call into an optimized form.  If so, return
7451 /// true and lower it, otherwise return false and it will be lowered like a
7452 /// normal call.
7453 /// The caller already checked that \p I calls the appropriate LibFunc with a
7454 /// correct prototype.
7455 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7456   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7457 
7458   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7459   std::pair<SDValue, SDValue> Res =
7460     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7461                                 getValue(Arg0), getValue(Arg1),
7462                                 MachinePointerInfo(Arg0),
7463                                 MachinePointerInfo(Arg1));
7464   if (Res.first.getNode()) {
7465     processIntegerCallValue(I, Res.first, true);
7466     PendingLoads.push_back(Res.second);
7467     return true;
7468   }
7469 
7470   return false;
7471 }
7472 
7473 /// See if we can lower a strlen call into an optimized form.  If so, return
7474 /// true and lower it, otherwise return false and it will be lowered like a
7475 /// normal call.
7476 /// The caller already checked that \p I calls the appropriate LibFunc with a
7477 /// correct prototype.
7478 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7479   const Value *Arg0 = I.getArgOperand(0);
7480 
7481   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7482   std::pair<SDValue, SDValue> Res =
7483     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7484                                 getValue(Arg0), MachinePointerInfo(Arg0));
7485   if (Res.first.getNode()) {
7486     processIntegerCallValue(I, Res.first, false);
7487     PendingLoads.push_back(Res.second);
7488     return true;
7489   }
7490 
7491   return false;
7492 }
7493 
7494 /// See if we can lower a strnlen call into an optimized form.  If so, return
7495 /// true and lower it, otherwise return false and it will be lowered like a
7496 /// normal call.
7497 /// The caller already checked that \p I calls the appropriate LibFunc with a
7498 /// correct prototype.
7499 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7500   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7501 
7502   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7503   std::pair<SDValue, SDValue> Res =
7504     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7505                                  getValue(Arg0), getValue(Arg1),
7506                                  MachinePointerInfo(Arg0));
7507   if (Res.first.getNode()) {
7508     processIntegerCallValue(I, Res.first, false);
7509     PendingLoads.push_back(Res.second);
7510     return true;
7511   }
7512 
7513   return false;
7514 }
7515 
7516 /// See if we can lower a unary floating-point operation into an SDNode with
7517 /// the specified Opcode.  If so, return true and lower it, otherwise return
7518 /// false and it will be lowered like a normal call.
7519 /// The caller already checked that \p I calls the appropriate LibFunc with a
7520 /// correct prototype.
7521 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7522                                               unsigned Opcode) {
7523   // We already checked this call's prototype; verify it doesn't modify errno.
7524   if (!I.onlyReadsMemory())
7525     return false;
7526 
7527   SDNodeFlags Flags;
7528   Flags.copyFMF(cast<FPMathOperator>(I));
7529 
7530   SDValue Tmp = getValue(I.getArgOperand(0));
7531   setValue(&I,
7532            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
7533   return true;
7534 }
7535 
7536 /// See if we can lower a binary floating-point operation into an SDNode with
7537 /// the specified Opcode. If so, return true and lower it. Otherwise return
7538 /// false, and it will be lowered like a normal call.
7539 /// The caller already checked that \p I calls the appropriate LibFunc with a
7540 /// correct prototype.
7541 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7542                                                unsigned Opcode) {
7543   // We already checked this call's prototype; verify it doesn't modify errno.
7544   if (!I.onlyReadsMemory())
7545     return false;
7546 
7547   SDNodeFlags Flags;
7548   Flags.copyFMF(cast<FPMathOperator>(I));
7549 
7550   SDValue Tmp0 = getValue(I.getArgOperand(0));
7551   SDValue Tmp1 = getValue(I.getArgOperand(1));
7552   EVT VT = Tmp0.getValueType();
7553   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
7554   return true;
7555 }
7556 
7557 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7558   // Handle inline assembly differently.
7559   if (I.isInlineAsm()) {
7560     visitInlineAsm(I);
7561     return;
7562   }
7563 
7564   if (Function *F = I.getCalledFunction()) {
7565     if (F->isDeclaration()) {
7566       // Is this an LLVM intrinsic or a target-specific intrinsic?
7567       unsigned IID = F->getIntrinsicID();
7568       if (!IID)
7569         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7570           IID = II->getIntrinsicID(F);
7571 
7572       if (IID) {
7573         visitIntrinsicCall(I, IID);
7574         return;
7575       }
7576     }
7577 
7578     // Check for well-known libc/libm calls.  If the function is internal, it
7579     // can't be a library call.  Don't do the check if marked as nobuiltin for
7580     // some reason or the call site requires strict floating point semantics.
7581     LibFunc Func;
7582     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7583         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7584         LibInfo->hasOptimizedCodeGen(Func)) {
7585       switch (Func) {
7586       default: break;
7587       case LibFunc_copysign:
7588       case LibFunc_copysignf:
7589       case LibFunc_copysignl:
7590         // We already checked this call's prototype; verify it doesn't modify
7591         // errno.
7592         if (I.onlyReadsMemory()) {
7593           SDValue LHS = getValue(I.getArgOperand(0));
7594           SDValue RHS = getValue(I.getArgOperand(1));
7595           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7596                                    LHS.getValueType(), LHS, RHS));
7597           return;
7598         }
7599         break;
7600       case LibFunc_fabs:
7601       case LibFunc_fabsf:
7602       case LibFunc_fabsl:
7603         if (visitUnaryFloatCall(I, ISD::FABS))
7604           return;
7605         break;
7606       case LibFunc_fmin:
7607       case LibFunc_fminf:
7608       case LibFunc_fminl:
7609         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7610           return;
7611         break;
7612       case LibFunc_fmax:
7613       case LibFunc_fmaxf:
7614       case LibFunc_fmaxl:
7615         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7616           return;
7617         break;
7618       case LibFunc_sin:
7619       case LibFunc_sinf:
7620       case LibFunc_sinl:
7621         if (visitUnaryFloatCall(I, ISD::FSIN))
7622           return;
7623         break;
7624       case LibFunc_cos:
7625       case LibFunc_cosf:
7626       case LibFunc_cosl:
7627         if (visitUnaryFloatCall(I, ISD::FCOS))
7628           return;
7629         break;
7630       case LibFunc_sqrt:
7631       case LibFunc_sqrtf:
7632       case LibFunc_sqrtl:
7633       case LibFunc_sqrt_finite:
7634       case LibFunc_sqrtf_finite:
7635       case LibFunc_sqrtl_finite:
7636         if (visitUnaryFloatCall(I, ISD::FSQRT))
7637           return;
7638         break;
7639       case LibFunc_floor:
7640       case LibFunc_floorf:
7641       case LibFunc_floorl:
7642         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7643           return;
7644         break;
7645       case LibFunc_nearbyint:
7646       case LibFunc_nearbyintf:
7647       case LibFunc_nearbyintl:
7648         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7649           return;
7650         break;
7651       case LibFunc_ceil:
7652       case LibFunc_ceilf:
7653       case LibFunc_ceill:
7654         if (visitUnaryFloatCall(I, ISD::FCEIL))
7655           return;
7656         break;
7657       case LibFunc_rint:
7658       case LibFunc_rintf:
7659       case LibFunc_rintl:
7660         if (visitUnaryFloatCall(I, ISD::FRINT))
7661           return;
7662         break;
7663       case LibFunc_round:
7664       case LibFunc_roundf:
7665       case LibFunc_roundl:
7666         if (visitUnaryFloatCall(I, ISD::FROUND))
7667           return;
7668         break;
7669       case LibFunc_trunc:
7670       case LibFunc_truncf:
7671       case LibFunc_truncl:
7672         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7673           return;
7674         break;
7675       case LibFunc_log2:
7676       case LibFunc_log2f:
7677       case LibFunc_log2l:
7678         if (visitUnaryFloatCall(I, ISD::FLOG2))
7679           return;
7680         break;
7681       case LibFunc_exp2:
7682       case LibFunc_exp2f:
7683       case LibFunc_exp2l:
7684         if (visitUnaryFloatCall(I, ISD::FEXP2))
7685           return;
7686         break;
7687       case LibFunc_memcmp:
7688         if (visitMemCmpCall(I))
7689           return;
7690         break;
7691       case LibFunc_mempcpy:
7692         if (visitMemPCpyCall(I))
7693           return;
7694         break;
7695       case LibFunc_memchr:
7696         if (visitMemChrCall(I))
7697           return;
7698         break;
7699       case LibFunc_strcpy:
7700         if (visitStrCpyCall(I, false))
7701           return;
7702         break;
7703       case LibFunc_stpcpy:
7704         if (visitStrCpyCall(I, true))
7705           return;
7706         break;
7707       case LibFunc_strcmp:
7708         if (visitStrCmpCall(I))
7709           return;
7710         break;
7711       case LibFunc_strlen:
7712         if (visitStrLenCall(I))
7713           return;
7714         break;
7715       case LibFunc_strnlen:
7716         if (visitStrNLenCall(I))
7717           return;
7718         break;
7719       }
7720     }
7721   }
7722 
7723   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7724   // have to do anything here to lower funclet bundles.
7725   // CFGuardTarget bundles are lowered in LowerCallTo.
7726   assert(!I.hasOperandBundlesOtherThan(
7727              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
7728               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) &&
7729          "Cannot lower calls with arbitrary operand bundles!");
7730 
7731   SDValue Callee = getValue(I.getCalledOperand());
7732 
7733   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7734     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7735   else
7736     // Check if we can potentially perform a tail call. More detailed checking
7737     // is be done within LowerCallTo, after more information about the call is
7738     // known.
7739     LowerCallTo(I, Callee, I.isTailCall());
7740 }
7741 
7742 namespace {
7743 
7744 /// AsmOperandInfo - This contains information for each constraint that we are
7745 /// lowering.
7746 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7747 public:
7748   /// CallOperand - If this is the result output operand or a clobber
7749   /// this is null, otherwise it is the incoming operand to the CallInst.
7750   /// This gets modified as the asm is processed.
7751   SDValue CallOperand;
7752 
7753   /// AssignedRegs - If this is a register or register class operand, this
7754   /// contains the set of register corresponding to the operand.
7755   RegsForValue AssignedRegs;
7756 
7757   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7758     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7759   }
7760 
7761   /// Whether or not this operand accesses memory
7762   bool hasMemory(const TargetLowering &TLI) const {
7763     // Indirect operand accesses access memory.
7764     if (isIndirect)
7765       return true;
7766 
7767     for (const auto &Code : Codes)
7768       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7769         return true;
7770 
7771     return false;
7772   }
7773 
7774   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7775   /// corresponds to.  If there is no Value* for this operand, it returns
7776   /// MVT::Other.
7777   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7778                            const DataLayout &DL) const {
7779     if (!CallOperandVal) return MVT::Other;
7780 
7781     if (isa<BasicBlock>(CallOperandVal))
7782       return TLI.getProgramPointerTy(DL);
7783 
7784     llvm::Type *OpTy = CallOperandVal->getType();
7785 
7786     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7787     // If this is an indirect operand, the operand is a pointer to the
7788     // accessed type.
7789     if (isIndirect) {
7790       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7791       if (!PtrTy)
7792         report_fatal_error("Indirect operand for inline asm not a pointer!");
7793       OpTy = PtrTy->getElementType();
7794     }
7795 
7796     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7797     if (StructType *STy = dyn_cast<StructType>(OpTy))
7798       if (STy->getNumElements() == 1)
7799         OpTy = STy->getElementType(0);
7800 
7801     // If OpTy is not a single value, it may be a struct/union that we
7802     // can tile with integers.
7803     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7804       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7805       switch (BitSize) {
7806       default: break;
7807       case 1:
7808       case 8:
7809       case 16:
7810       case 32:
7811       case 64:
7812       case 128:
7813         OpTy = IntegerType::get(Context, BitSize);
7814         break;
7815       }
7816     }
7817 
7818     return TLI.getValueType(DL, OpTy, true);
7819   }
7820 };
7821 
7822 
7823 } // end anonymous namespace
7824 
7825 /// Make sure that the output operand \p OpInfo and its corresponding input
7826 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7827 /// out).
7828 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7829                                SDISelAsmOperandInfo &MatchingOpInfo,
7830                                SelectionDAG &DAG) {
7831   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7832     return;
7833 
7834   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7835   const auto &TLI = DAG.getTargetLoweringInfo();
7836 
7837   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7838       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7839                                        OpInfo.ConstraintVT);
7840   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7841       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7842                                        MatchingOpInfo.ConstraintVT);
7843   if ((OpInfo.ConstraintVT.isInteger() !=
7844        MatchingOpInfo.ConstraintVT.isInteger()) ||
7845       (MatchRC.second != InputRC.second)) {
7846     // FIXME: error out in a more elegant fashion
7847     report_fatal_error("Unsupported asm: input constraint"
7848                        " with a matching output constraint of"
7849                        " incompatible type!");
7850   }
7851   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7852 }
7853 
7854 /// Get a direct memory input to behave well as an indirect operand.
7855 /// This may introduce stores, hence the need for a \p Chain.
7856 /// \return The (possibly updated) chain.
7857 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7858                                         SDISelAsmOperandInfo &OpInfo,
7859                                         SelectionDAG &DAG) {
7860   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7861 
7862   // If we don't have an indirect input, put it in the constpool if we can,
7863   // otherwise spill it to a stack slot.
7864   // TODO: This isn't quite right. We need to handle these according to
7865   // the addressing mode that the constraint wants. Also, this may take
7866   // an additional register for the computation and we don't want that
7867   // either.
7868 
7869   // If the operand is a float, integer, or vector constant, spill to a
7870   // constant pool entry to get its address.
7871   const Value *OpVal = OpInfo.CallOperandVal;
7872   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7873       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7874     OpInfo.CallOperand = DAG.getConstantPool(
7875         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7876     return Chain;
7877   }
7878 
7879   // Otherwise, create a stack slot and emit a store to it before the asm.
7880   Type *Ty = OpVal->getType();
7881   auto &DL = DAG.getDataLayout();
7882   uint64_t TySize = DL.getTypeAllocSize(Ty);
7883   MachineFunction &MF = DAG.getMachineFunction();
7884   int SSFI = MF.getFrameInfo().CreateStackObject(
7885       TySize, DL.getPrefTypeAlign(Ty), false);
7886   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7887   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7888                             MachinePointerInfo::getFixedStack(MF, SSFI),
7889                             TLI.getMemValueType(DL, Ty));
7890   OpInfo.CallOperand = StackSlot;
7891 
7892   return Chain;
7893 }
7894 
7895 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7896 /// specified operand.  We prefer to assign virtual registers, to allow the
7897 /// register allocator to handle the assignment process.  However, if the asm
7898 /// uses features that we can't model on machineinstrs, we have SDISel do the
7899 /// allocation.  This produces generally horrible, but correct, code.
7900 ///
7901 ///   OpInfo describes the operand
7902 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7903 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7904                                  SDISelAsmOperandInfo &OpInfo,
7905                                  SDISelAsmOperandInfo &RefOpInfo) {
7906   LLVMContext &Context = *DAG.getContext();
7907   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7908 
7909   MachineFunction &MF = DAG.getMachineFunction();
7910   SmallVector<unsigned, 4> Regs;
7911   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7912 
7913   // No work to do for memory operations.
7914   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7915     return;
7916 
7917   // If this is a constraint for a single physreg, or a constraint for a
7918   // register class, find it.
7919   unsigned AssignedReg;
7920   const TargetRegisterClass *RC;
7921   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7922       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7923   // RC is unset only on failure. Return immediately.
7924   if (!RC)
7925     return;
7926 
7927   // Get the actual register value type.  This is important, because the user
7928   // may have asked for (e.g.) the AX register in i32 type.  We need to
7929   // remember that AX is actually i16 to get the right extension.
7930   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7931 
7932   if (OpInfo.ConstraintVT != MVT::Other) {
7933     // If this is an FP operand in an integer register (or visa versa), or more
7934     // generally if the operand value disagrees with the register class we plan
7935     // to stick it in, fix the operand type.
7936     //
7937     // If this is an input value, the bitcast to the new type is done now.
7938     // Bitcast for output value is done at the end of visitInlineAsm().
7939     if ((OpInfo.Type == InlineAsm::isOutput ||
7940          OpInfo.Type == InlineAsm::isInput) &&
7941         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7942       // Try to convert to the first EVT that the reg class contains.  If the
7943       // types are identical size, use a bitcast to convert (e.g. two differing
7944       // vector types).  Note: output bitcast is done at the end of
7945       // visitInlineAsm().
7946       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7947         // Exclude indirect inputs while they are unsupported because the code
7948         // to perform the load is missing and thus OpInfo.CallOperand still
7949         // refers to the input address rather than the pointed-to value.
7950         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7951           OpInfo.CallOperand =
7952               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7953         OpInfo.ConstraintVT = RegVT;
7954         // If the operand is an FP value and we want it in integer registers,
7955         // use the corresponding integer type. This turns an f64 value into
7956         // i64, which can be passed with two i32 values on a 32-bit machine.
7957       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7958         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7959         if (OpInfo.Type == InlineAsm::isInput)
7960           OpInfo.CallOperand =
7961               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7962         OpInfo.ConstraintVT = VT;
7963       }
7964     }
7965   }
7966 
7967   // No need to allocate a matching input constraint since the constraint it's
7968   // matching to has already been allocated.
7969   if (OpInfo.isMatchingInputConstraint())
7970     return;
7971 
7972   EVT ValueVT = OpInfo.ConstraintVT;
7973   if (OpInfo.ConstraintVT == MVT::Other)
7974     ValueVT = RegVT;
7975 
7976   // Initialize NumRegs.
7977   unsigned NumRegs = 1;
7978   if (OpInfo.ConstraintVT != MVT::Other)
7979     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7980 
7981   // If this is a constraint for a specific physical register, like {r17},
7982   // assign it now.
7983 
7984   // If this associated to a specific register, initialize iterator to correct
7985   // place. If virtual, make sure we have enough registers
7986 
7987   // Initialize iterator if necessary
7988   TargetRegisterClass::iterator I = RC->begin();
7989   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7990 
7991   // Do not check for single registers.
7992   if (AssignedReg) {
7993       for (; *I != AssignedReg; ++I)
7994         assert(I != RC->end() && "AssignedReg should be member of RC");
7995   }
7996 
7997   for (; NumRegs; --NumRegs, ++I) {
7998     assert(I != RC->end() && "Ran out of registers to allocate!");
7999     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8000     Regs.push_back(R);
8001   }
8002 
8003   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8004 }
8005 
8006 static unsigned
8007 findMatchingInlineAsmOperand(unsigned OperandNo,
8008                              const std::vector<SDValue> &AsmNodeOperands) {
8009   // Scan until we find the definition we already emitted of this operand.
8010   unsigned CurOp = InlineAsm::Op_FirstOperand;
8011   for (; OperandNo; --OperandNo) {
8012     // Advance to the next operand.
8013     unsigned OpFlag =
8014         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8015     assert((InlineAsm::isRegDefKind(OpFlag) ||
8016             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8017             InlineAsm::isMemKind(OpFlag)) &&
8018            "Skipped past definitions?");
8019     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8020   }
8021   return CurOp;
8022 }
8023 
8024 namespace {
8025 
8026 class ExtraFlags {
8027   unsigned Flags = 0;
8028 
8029 public:
8030   explicit ExtraFlags(const CallBase &Call) {
8031     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8032     if (IA->hasSideEffects())
8033       Flags |= InlineAsm::Extra_HasSideEffects;
8034     if (IA->isAlignStack())
8035       Flags |= InlineAsm::Extra_IsAlignStack;
8036     if (Call.isConvergent())
8037       Flags |= InlineAsm::Extra_IsConvergent;
8038     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8039   }
8040 
8041   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8042     // Ideally, we would only check against memory constraints.  However, the
8043     // meaning of an Other constraint can be target-specific and we can't easily
8044     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8045     // for Other constraints as well.
8046     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8047         OpInfo.ConstraintType == TargetLowering::C_Other) {
8048       if (OpInfo.Type == InlineAsm::isInput)
8049         Flags |= InlineAsm::Extra_MayLoad;
8050       else if (OpInfo.Type == InlineAsm::isOutput)
8051         Flags |= InlineAsm::Extra_MayStore;
8052       else if (OpInfo.Type == InlineAsm::isClobber)
8053         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8054     }
8055   }
8056 
8057   unsigned get() const { return Flags; }
8058 };
8059 
8060 } // end anonymous namespace
8061 
8062 /// visitInlineAsm - Handle a call to an InlineAsm object.
8063 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
8064   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8065 
8066   /// ConstraintOperands - Information about all of the constraints.
8067   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8068 
8069   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8070   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8071       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8072 
8073   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8074   // AsmDialect, MayLoad, MayStore).
8075   bool HasSideEffect = IA->hasSideEffects();
8076   ExtraFlags ExtraInfo(Call);
8077 
8078   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8079   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8080   unsigned NumMatchingOps = 0;
8081   for (auto &T : TargetConstraints) {
8082     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8083     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8084 
8085     // Compute the value type for each operand.
8086     if (OpInfo.Type == InlineAsm::isInput ||
8087         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8088       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8089 
8090       // Process the call argument. BasicBlocks are labels, currently appearing
8091       // only in asm's.
8092       if (isa<CallBrInst>(Call) &&
8093           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8094                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8095                         NumMatchingOps) &&
8096           (NumMatchingOps == 0 ||
8097            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8098                         NumMatchingOps))) {
8099         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8100         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8101         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8102       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8103         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8104       } else {
8105         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8106       }
8107 
8108       OpInfo.ConstraintVT =
8109           OpInfo
8110               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8111               .getSimpleVT();
8112     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8113       // The return value of the call is this value.  As such, there is no
8114       // corresponding argument.
8115       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8116       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8117         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8118             DAG.getDataLayout(), STy->getElementType(ResNo));
8119       } else {
8120         assert(ResNo == 0 && "Asm only has one result!");
8121         OpInfo.ConstraintVT =
8122             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8123       }
8124       ++ResNo;
8125     } else {
8126       OpInfo.ConstraintVT = MVT::Other;
8127     }
8128 
8129     if (OpInfo.hasMatchingInput())
8130       ++NumMatchingOps;
8131 
8132     if (!HasSideEffect)
8133       HasSideEffect = OpInfo.hasMemory(TLI);
8134 
8135     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8136     // FIXME: Could we compute this on OpInfo rather than T?
8137 
8138     // Compute the constraint code and ConstraintType to use.
8139     TLI.ComputeConstraintToUse(T, SDValue());
8140 
8141     if (T.ConstraintType == TargetLowering::C_Immediate &&
8142         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8143       // We've delayed emitting a diagnostic like the "n" constraint because
8144       // inlining could cause an integer showing up.
8145       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8146                                           "' expects an integer constant "
8147                                           "expression");
8148 
8149     ExtraInfo.update(T);
8150   }
8151 
8152 
8153   // We won't need to flush pending loads if this asm doesn't touch
8154   // memory and is nonvolatile.
8155   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8156 
8157   bool IsCallBr = isa<CallBrInst>(Call);
8158   if (IsCallBr) {
8159     // If this is a callbr we need to flush pending exports since inlineasm_br
8160     // is a terminator. We need to do this before nodes are glued to
8161     // the inlineasm_br node.
8162     Chain = getControlRoot();
8163   }
8164 
8165   // Second pass over the constraints: compute which constraint option to use.
8166   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8167     // If this is an output operand with a matching input operand, look up the
8168     // matching input. If their types mismatch, e.g. one is an integer, the
8169     // other is floating point, or their sizes are different, flag it as an
8170     // error.
8171     if (OpInfo.hasMatchingInput()) {
8172       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8173       patchMatchingInput(OpInfo, Input, DAG);
8174     }
8175 
8176     // Compute the constraint code and ConstraintType to use.
8177     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8178 
8179     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8180         OpInfo.Type == InlineAsm::isClobber)
8181       continue;
8182 
8183     // If this is a memory input, and if the operand is not indirect, do what we
8184     // need to provide an address for the memory input.
8185     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8186         !OpInfo.isIndirect) {
8187       assert((OpInfo.isMultipleAlternative ||
8188               (OpInfo.Type == InlineAsm::isInput)) &&
8189              "Can only indirectify direct input operands!");
8190 
8191       // Memory operands really want the address of the value.
8192       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8193 
8194       // There is no longer a Value* corresponding to this operand.
8195       OpInfo.CallOperandVal = nullptr;
8196 
8197       // It is now an indirect operand.
8198       OpInfo.isIndirect = true;
8199     }
8200 
8201   }
8202 
8203   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8204   std::vector<SDValue> AsmNodeOperands;
8205   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8206   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8207       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8208 
8209   // If we have a !srcloc metadata node associated with it, we want to attach
8210   // this to the ultimately generated inline asm machineinstr.  To do this, we
8211   // pass in the third operand as this (potentially null) inline asm MDNode.
8212   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8213   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8214 
8215   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8216   // bits as operand 3.
8217   AsmNodeOperands.push_back(DAG.getTargetConstant(
8218       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8219 
8220   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8221   // this, assign virtual and physical registers for inputs and otput.
8222   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8223     // Assign Registers.
8224     SDISelAsmOperandInfo &RefOpInfo =
8225         OpInfo.isMatchingInputConstraint()
8226             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8227             : OpInfo;
8228     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8229 
8230     auto DetectWriteToReservedRegister = [&]() {
8231       const MachineFunction &MF = DAG.getMachineFunction();
8232       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8233       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8234         if (Register::isPhysicalRegister(Reg) &&
8235             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8236           const char *RegName = TRI.getName(Reg);
8237           emitInlineAsmError(Call, "write to reserved register '" +
8238                                        Twine(RegName) + "'");
8239           return true;
8240         }
8241       }
8242       return false;
8243     };
8244 
8245     switch (OpInfo.Type) {
8246     case InlineAsm::isOutput:
8247       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8248         unsigned ConstraintID =
8249             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8250         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8251                "Failed to convert memory constraint code to constraint id.");
8252 
8253         // Add information to the INLINEASM node to know about this output.
8254         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8255         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8256         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8257                                                         MVT::i32));
8258         AsmNodeOperands.push_back(OpInfo.CallOperand);
8259       } else {
8260         // Otherwise, this outputs to a register (directly for C_Register /
8261         // C_RegisterClass, and a target-defined fashion for
8262         // C_Immediate/C_Other). Find a register that we can use.
8263         if (OpInfo.AssignedRegs.Regs.empty()) {
8264           emitInlineAsmError(
8265               Call, "couldn't allocate output register for constraint '" +
8266                         Twine(OpInfo.ConstraintCode) + "'");
8267           return;
8268         }
8269 
8270         if (DetectWriteToReservedRegister())
8271           return;
8272 
8273         // Add information to the INLINEASM node to know that this register is
8274         // set.
8275         OpInfo.AssignedRegs.AddInlineAsmOperands(
8276             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8277                                   : InlineAsm::Kind_RegDef,
8278             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8279       }
8280       break;
8281 
8282     case InlineAsm::isInput: {
8283       SDValue InOperandVal = OpInfo.CallOperand;
8284 
8285       if (OpInfo.isMatchingInputConstraint()) {
8286         // If this is required to match an output register we have already set,
8287         // just use its register.
8288         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8289                                                   AsmNodeOperands);
8290         unsigned OpFlag =
8291           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8292         if (InlineAsm::isRegDefKind(OpFlag) ||
8293             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8294           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8295           if (OpInfo.isIndirect) {
8296             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8297             emitInlineAsmError(Call, "inline asm not supported yet: "
8298                                      "don't know how to handle tied "
8299                                      "indirect register inputs");
8300             return;
8301           }
8302 
8303           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8304           SmallVector<unsigned, 4> Regs;
8305 
8306           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8307             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8308             MachineRegisterInfo &RegInfo =
8309                 DAG.getMachineFunction().getRegInfo();
8310             for (unsigned i = 0; i != NumRegs; ++i)
8311               Regs.push_back(RegInfo.createVirtualRegister(RC));
8312           } else {
8313             emitInlineAsmError(Call,
8314                                "inline asm error: This value type register "
8315                                "class is not natively supported!");
8316             return;
8317           }
8318 
8319           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8320 
8321           SDLoc dl = getCurSDLoc();
8322           // Use the produced MatchedRegs object to
8323           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8324           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8325                                            true, OpInfo.getMatchedOperand(), dl,
8326                                            DAG, AsmNodeOperands);
8327           break;
8328         }
8329 
8330         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8331         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8332                "Unexpected number of operands");
8333         // Add information to the INLINEASM node to know about this input.
8334         // See InlineAsm.h isUseOperandTiedToDef.
8335         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8336         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8337                                                     OpInfo.getMatchedOperand());
8338         AsmNodeOperands.push_back(DAG.getTargetConstant(
8339             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8340         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8341         break;
8342       }
8343 
8344       // Treat indirect 'X' constraint as memory.
8345       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8346           OpInfo.isIndirect)
8347         OpInfo.ConstraintType = TargetLowering::C_Memory;
8348 
8349       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8350           OpInfo.ConstraintType == TargetLowering::C_Other) {
8351         std::vector<SDValue> Ops;
8352         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8353                                           Ops, DAG);
8354         if (Ops.empty()) {
8355           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8356             if (isa<ConstantSDNode>(InOperandVal)) {
8357               emitInlineAsmError(Call, "value out of range for constraint '" +
8358                                            Twine(OpInfo.ConstraintCode) + "'");
8359               return;
8360             }
8361 
8362           emitInlineAsmError(Call,
8363                              "invalid operand for inline asm constraint '" +
8364                                  Twine(OpInfo.ConstraintCode) + "'");
8365           return;
8366         }
8367 
8368         // Add information to the INLINEASM node to know about this input.
8369         unsigned ResOpType =
8370           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8371         AsmNodeOperands.push_back(DAG.getTargetConstant(
8372             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8373         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8374         break;
8375       }
8376 
8377       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8378         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8379         assert(InOperandVal.getValueType() ==
8380                    TLI.getPointerTy(DAG.getDataLayout()) &&
8381                "Memory operands expect pointer values");
8382 
8383         unsigned ConstraintID =
8384             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8385         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8386                "Failed to convert memory constraint code to constraint id.");
8387 
8388         // Add information to the INLINEASM node to know about this input.
8389         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8390         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8391         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8392                                                         getCurSDLoc(),
8393                                                         MVT::i32));
8394         AsmNodeOperands.push_back(InOperandVal);
8395         break;
8396       }
8397 
8398       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8399               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8400              "Unknown constraint type!");
8401 
8402       // TODO: Support this.
8403       if (OpInfo.isIndirect) {
8404         emitInlineAsmError(
8405             Call, "Don't know how to handle indirect register inputs yet "
8406                   "for constraint '" +
8407                       Twine(OpInfo.ConstraintCode) + "'");
8408         return;
8409       }
8410 
8411       // Copy the input into the appropriate registers.
8412       if (OpInfo.AssignedRegs.Regs.empty()) {
8413         emitInlineAsmError(Call,
8414                            "couldn't allocate input reg for constraint '" +
8415                                Twine(OpInfo.ConstraintCode) + "'");
8416         return;
8417       }
8418 
8419       if (DetectWriteToReservedRegister())
8420         return;
8421 
8422       SDLoc dl = getCurSDLoc();
8423 
8424       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8425                                         &Call);
8426 
8427       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8428                                                dl, DAG, AsmNodeOperands);
8429       break;
8430     }
8431     case InlineAsm::isClobber:
8432       // Add the clobbered value to the operand list, so that the register
8433       // allocator is aware that the physreg got clobbered.
8434       if (!OpInfo.AssignedRegs.Regs.empty())
8435         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8436                                                  false, 0, getCurSDLoc(), DAG,
8437                                                  AsmNodeOperands);
8438       break;
8439     }
8440   }
8441 
8442   // Finish up input operands.  Set the input chain and add the flag last.
8443   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8444   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8445 
8446   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8447   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8448                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8449   Flag = Chain.getValue(1);
8450 
8451   // Do additional work to generate outputs.
8452 
8453   SmallVector<EVT, 1> ResultVTs;
8454   SmallVector<SDValue, 1> ResultValues;
8455   SmallVector<SDValue, 8> OutChains;
8456 
8457   llvm::Type *CallResultType = Call.getType();
8458   ArrayRef<Type *> ResultTypes;
8459   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8460     ResultTypes = StructResult->elements();
8461   else if (!CallResultType->isVoidTy())
8462     ResultTypes = makeArrayRef(CallResultType);
8463 
8464   auto CurResultType = ResultTypes.begin();
8465   auto handleRegAssign = [&](SDValue V) {
8466     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8467     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8468     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8469     ++CurResultType;
8470     // If the type of the inline asm call site return value is different but has
8471     // same size as the type of the asm output bitcast it.  One example of this
8472     // is for vectors with different width / number of elements.  This can
8473     // happen for register classes that can contain multiple different value
8474     // types.  The preg or vreg allocated may not have the same VT as was
8475     // expected.
8476     //
8477     // This can also happen for a return value that disagrees with the register
8478     // class it is put in, eg. a double in a general-purpose register on a
8479     // 32-bit machine.
8480     if (ResultVT != V.getValueType() &&
8481         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8482       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8483     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8484              V.getValueType().isInteger()) {
8485       // If a result value was tied to an input value, the computed result
8486       // may have a wider width than the expected result.  Extract the
8487       // relevant portion.
8488       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8489     }
8490     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8491     ResultVTs.push_back(ResultVT);
8492     ResultValues.push_back(V);
8493   };
8494 
8495   // Deal with output operands.
8496   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8497     if (OpInfo.Type == InlineAsm::isOutput) {
8498       SDValue Val;
8499       // Skip trivial output operands.
8500       if (OpInfo.AssignedRegs.Regs.empty())
8501         continue;
8502 
8503       switch (OpInfo.ConstraintType) {
8504       case TargetLowering::C_Register:
8505       case TargetLowering::C_RegisterClass:
8506         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8507                                                   Chain, &Flag, &Call);
8508         break;
8509       case TargetLowering::C_Immediate:
8510       case TargetLowering::C_Other:
8511         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8512                                               OpInfo, DAG);
8513         break;
8514       case TargetLowering::C_Memory:
8515         break; // Already handled.
8516       case TargetLowering::C_Unknown:
8517         assert(false && "Unexpected unknown constraint");
8518       }
8519 
8520       // Indirect output manifest as stores. Record output chains.
8521       if (OpInfo.isIndirect) {
8522         const Value *Ptr = OpInfo.CallOperandVal;
8523         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8524         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8525                                      MachinePointerInfo(Ptr));
8526         OutChains.push_back(Store);
8527       } else {
8528         // generate CopyFromRegs to associated registers.
8529         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8530         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8531           for (const SDValue &V : Val->op_values())
8532             handleRegAssign(V);
8533         } else
8534           handleRegAssign(Val);
8535       }
8536     }
8537   }
8538 
8539   // Set results.
8540   if (!ResultValues.empty()) {
8541     assert(CurResultType == ResultTypes.end() &&
8542            "Mismatch in number of ResultTypes");
8543     assert(ResultValues.size() == ResultTypes.size() &&
8544            "Mismatch in number of output operands in asm result");
8545 
8546     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8547                             DAG.getVTList(ResultVTs), ResultValues);
8548     setValue(&Call, V);
8549   }
8550 
8551   // Collect store chains.
8552   if (!OutChains.empty())
8553     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8554 
8555   // Only Update Root if inline assembly has a memory effect.
8556   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8557     DAG.setRoot(Chain);
8558 }
8559 
8560 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8561                                              const Twine &Message) {
8562   LLVMContext &Ctx = *DAG.getContext();
8563   Ctx.emitError(&Call, Message);
8564 
8565   // Make sure we leave the DAG in a valid state
8566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8567   SmallVector<EVT, 1> ValueVTs;
8568   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8569 
8570   if (ValueVTs.empty())
8571     return;
8572 
8573   SmallVector<SDValue, 1> Ops;
8574   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8575     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8576 
8577   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8578 }
8579 
8580 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8581   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8582                           MVT::Other, getRoot(),
8583                           getValue(I.getArgOperand(0)),
8584                           DAG.getSrcValue(I.getArgOperand(0))));
8585 }
8586 
8587 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8588   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8589   const DataLayout &DL = DAG.getDataLayout();
8590   SDValue V = DAG.getVAArg(
8591       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8592       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8593       DL.getABITypeAlign(I.getType()).value());
8594   DAG.setRoot(V.getValue(1));
8595 
8596   if (I.getType()->isPointerTy())
8597     V = DAG.getPtrExtOrTrunc(
8598         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8599   setValue(&I, V);
8600 }
8601 
8602 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8603   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8604                           MVT::Other, getRoot(),
8605                           getValue(I.getArgOperand(0)),
8606                           DAG.getSrcValue(I.getArgOperand(0))));
8607 }
8608 
8609 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8610   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8611                           MVT::Other, getRoot(),
8612                           getValue(I.getArgOperand(0)),
8613                           getValue(I.getArgOperand(1)),
8614                           DAG.getSrcValue(I.getArgOperand(0)),
8615                           DAG.getSrcValue(I.getArgOperand(1))));
8616 }
8617 
8618 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8619                                                     const Instruction &I,
8620                                                     SDValue Op) {
8621   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8622   if (!Range)
8623     return Op;
8624 
8625   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8626   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8627     return Op;
8628 
8629   APInt Lo = CR.getUnsignedMin();
8630   if (!Lo.isMinValue())
8631     return Op;
8632 
8633   APInt Hi = CR.getUnsignedMax();
8634   unsigned Bits = std::max(Hi.getActiveBits(),
8635                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8636 
8637   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8638 
8639   SDLoc SL = getCurSDLoc();
8640 
8641   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8642                              DAG.getValueType(SmallVT));
8643   unsigned NumVals = Op.getNode()->getNumValues();
8644   if (NumVals == 1)
8645     return ZExt;
8646 
8647   SmallVector<SDValue, 4> Ops;
8648 
8649   Ops.push_back(ZExt);
8650   for (unsigned I = 1; I != NumVals; ++I)
8651     Ops.push_back(Op.getValue(I));
8652 
8653   return DAG.getMergeValues(Ops, SL);
8654 }
8655 
8656 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8657 /// the call being lowered.
8658 ///
8659 /// This is a helper for lowering intrinsics that follow a target calling
8660 /// convention or require stack pointer adjustment. Only a subset of the
8661 /// intrinsic's operands need to participate in the calling convention.
8662 void SelectionDAGBuilder::populateCallLoweringInfo(
8663     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8664     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8665     bool IsPatchPoint) {
8666   TargetLowering::ArgListTy Args;
8667   Args.reserve(NumArgs);
8668 
8669   // Populate the argument list.
8670   // Attributes for args start at offset 1, after the return attribute.
8671   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8672        ArgI != ArgE; ++ArgI) {
8673     const Value *V = Call->getOperand(ArgI);
8674 
8675     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8676 
8677     TargetLowering::ArgListEntry Entry;
8678     Entry.Node = getValue(V);
8679     Entry.Ty = V->getType();
8680     Entry.setAttributes(Call, ArgI);
8681     Args.push_back(Entry);
8682   }
8683 
8684   CLI.setDebugLoc(getCurSDLoc())
8685       .setChain(getRoot())
8686       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8687       .setDiscardResult(Call->use_empty())
8688       .setIsPatchPoint(IsPatchPoint)
8689       .setIsPreallocated(
8690           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
8691 }
8692 
8693 /// Add a stack map intrinsic call's live variable operands to a stackmap
8694 /// or patchpoint target node's operand list.
8695 ///
8696 /// Constants are converted to TargetConstants purely as an optimization to
8697 /// avoid constant materialization and register allocation.
8698 ///
8699 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8700 /// generate addess computation nodes, and so FinalizeISel can convert the
8701 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8702 /// address materialization and register allocation, but may also be required
8703 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8704 /// alloca in the entry block, then the runtime may assume that the alloca's
8705 /// StackMap location can be read immediately after compilation and that the
8706 /// location is valid at any point during execution (this is similar to the
8707 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8708 /// only available in a register, then the runtime would need to trap when
8709 /// execution reaches the StackMap in order to read the alloca's location.
8710 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8711                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8712                                 SelectionDAGBuilder &Builder) {
8713   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8714     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8715     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8716       Ops.push_back(
8717         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8718       Ops.push_back(
8719         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8720     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8721       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8722       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8723           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8724     } else
8725       Ops.push_back(OpVal);
8726   }
8727 }
8728 
8729 /// Lower llvm.experimental.stackmap directly to its target opcode.
8730 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8731   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8732   //                                  [live variables...])
8733 
8734   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8735 
8736   SDValue Chain, InFlag, Callee, NullPtr;
8737   SmallVector<SDValue, 32> Ops;
8738 
8739   SDLoc DL = getCurSDLoc();
8740   Callee = getValue(CI.getCalledOperand());
8741   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8742 
8743   // The stackmap intrinsic only records the live variables (the arguments
8744   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8745   // intrinsic, this won't be lowered to a function call. This means we don't
8746   // have to worry about calling conventions and target specific lowering code.
8747   // Instead we perform the call lowering right here.
8748   //
8749   // chain, flag = CALLSEQ_START(chain, 0, 0)
8750   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8751   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8752   //
8753   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8754   InFlag = Chain.getValue(1);
8755 
8756   // Add the <id> and <numBytes> constants.
8757   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8758   Ops.push_back(DAG.getTargetConstant(
8759                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8760   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8761   Ops.push_back(DAG.getTargetConstant(
8762                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8763                   MVT::i32));
8764 
8765   // Push live variables for the stack map.
8766   addStackMapLiveVars(CI, 2, DL, Ops, *this);
8767 
8768   // We are not pushing any register mask info here on the operands list,
8769   // because the stackmap doesn't clobber anything.
8770 
8771   // Push the chain and the glue flag.
8772   Ops.push_back(Chain);
8773   Ops.push_back(InFlag);
8774 
8775   // Create the STACKMAP node.
8776   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8777   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8778   Chain = SDValue(SM, 0);
8779   InFlag = Chain.getValue(1);
8780 
8781   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8782 
8783   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8784 
8785   // Set the root to the target-lowered call chain.
8786   DAG.setRoot(Chain);
8787 
8788   // Inform the Frame Information that we have a stackmap in this function.
8789   FuncInfo.MF->getFrameInfo().setHasStackMap();
8790 }
8791 
8792 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8793 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
8794                                           const BasicBlock *EHPadBB) {
8795   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8796   //                                                 i32 <numBytes>,
8797   //                                                 i8* <target>,
8798   //                                                 i32 <numArgs>,
8799   //                                                 [Args...],
8800   //                                                 [live variables...])
8801 
8802   CallingConv::ID CC = CB.getCallingConv();
8803   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8804   bool HasDef = !CB.getType()->isVoidTy();
8805   SDLoc dl = getCurSDLoc();
8806   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
8807 
8808   // Handle immediate and symbolic callees.
8809   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8810     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8811                                    /*isTarget=*/true);
8812   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8813     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8814                                          SDLoc(SymbolicCallee),
8815                                          SymbolicCallee->getValueType(0));
8816 
8817   // Get the real number of arguments participating in the call <numArgs>
8818   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
8819   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8820 
8821   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8822   // Intrinsics include all meta-operands up to but not including CC.
8823   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8824   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
8825          "Not enough arguments provided to the patchpoint intrinsic");
8826 
8827   // For AnyRegCC the arguments are lowered later on manually.
8828   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8829   Type *ReturnTy =
8830       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
8831 
8832   TargetLowering::CallLoweringInfo CLI(DAG);
8833   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
8834                            ReturnTy, true);
8835   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8836 
8837   SDNode *CallEnd = Result.second.getNode();
8838   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8839     CallEnd = CallEnd->getOperand(0).getNode();
8840 
8841   /// Get a call instruction from the call sequence chain.
8842   /// Tail calls are not allowed.
8843   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8844          "Expected a callseq node.");
8845   SDNode *Call = CallEnd->getOperand(0).getNode();
8846   bool HasGlue = Call->getGluedNode();
8847 
8848   // Replace the target specific call node with the patchable intrinsic.
8849   SmallVector<SDValue, 8> Ops;
8850 
8851   // Add the <id> and <numBytes> constants.
8852   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
8853   Ops.push_back(DAG.getTargetConstant(
8854                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8855   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
8856   Ops.push_back(DAG.getTargetConstant(
8857                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8858                   MVT::i32));
8859 
8860   // Add the callee.
8861   Ops.push_back(Callee);
8862 
8863   // Adjust <numArgs> to account for any arguments that have been passed on the
8864   // stack instead.
8865   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8866   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8867   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8868   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8869 
8870   // Add the calling convention
8871   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8872 
8873   // Add the arguments we omitted previously. The register allocator should
8874   // place these in any free register.
8875   if (IsAnyRegCC)
8876     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8877       Ops.push_back(getValue(CB.getArgOperand(i)));
8878 
8879   // Push the arguments from the call instruction up to the register mask.
8880   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8881   Ops.append(Call->op_begin() + 2, e);
8882 
8883   // Push live variables for the stack map.
8884   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
8885 
8886   // Push the register mask info.
8887   if (HasGlue)
8888     Ops.push_back(*(Call->op_end()-2));
8889   else
8890     Ops.push_back(*(Call->op_end()-1));
8891 
8892   // Push the chain (this is originally the first operand of the call, but
8893   // becomes now the last or second to last operand).
8894   Ops.push_back(*(Call->op_begin()));
8895 
8896   // Push the glue flag (last operand).
8897   if (HasGlue)
8898     Ops.push_back(*(Call->op_end()-1));
8899 
8900   SDVTList NodeTys;
8901   if (IsAnyRegCC && HasDef) {
8902     // Create the return types based on the intrinsic definition
8903     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8904     SmallVector<EVT, 3> ValueVTs;
8905     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
8906     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8907 
8908     // There is always a chain and a glue type at the end
8909     ValueVTs.push_back(MVT::Other);
8910     ValueVTs.push_back(MVT::Glue);
8911     NodeTys = DAG.getVTList(ValueVTs);
8912   } else
8913     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8914 
8915   // Replace the target specific call node with a PATCHPOINT node.
8916   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8917                                          dl, NodeTys, Ops);
8918 
8919   // Update the NodeMap.
8920   if (HasDef) {
8921     if (IsAnyRegCC)
8922       setValue(&CB, SDValue(MN, 0));
8923     else
8924       setValue(&CB, Result.first);
8925   }
8926 
8927   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8928   // call sequence. Furthermore the location of the chain and glue can change
8929   // when the AnyReg calling convention is used and the intrinsic returns a
8930   // value.
8931   if (IsAnyRegCC && HasDef) {
8932     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8933     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8934     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8935   } else
8936     DAG.ReplaceAllUsesWith(Call, MN);
8937   DAG.DeleteNode(Call);
8938 
8939   // Inform the Frame Information that we have a patchpoint in this function.
8940   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8941 }
8942 
8943 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8944                                             unsigned Intrinsic) {
8945   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8946   SDValue Op1 = getValue(I.getArgOperand(0));
8947   SDValue Op2;
8948   if (I.getNumArgOperands() > 1)
8949     Op2 = getValue(I.getArgOperand(1));
8950   SDLoc dl = getCurSDLoc();
8951   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8952   SDValue Res;
8953   FastMathFlags FMF;
8954   SDNodeFlags SDFlags;
8955   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
8956     FMF = FPMO->getFastMathFlags();
8957     SDFlags.copyFMF(*FPMO);
8958   }
8959 
8960   switch (Intrinsic) {
8961   case Intrinsic::experimental_vector_reduce_v2_fadd:
8962     if (FMF.allowReassoc())
8963       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8964                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
8965                         SDFlags);
8966     else
8967       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2, SDFlags);
8968     break;
8969   case Intrinsic::experimental_vector_reduce_v2_fmul:
8970     if (FMF.allowReassoc())
8971       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8972                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
8973                         SDFlags);
8974     else
8975       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2, SDFlags);
8976     break;
8977   case Intrinsic::experimental_vector_reduce_add:
8978     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8979     break;
8980   case Intrinsic::experimental_vector_reduce_mul:
8981     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8982     break;
8983   case Intrinsic::experimental_vector_reduce_and:
8984     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8985     break;
8986   case Intrinsic::experimental_vector_reduce_or:
8987     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8988     break;
8989   case Intrinsic::experimental_vector_reduce_xor:
8990     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8991     break;
8992   case Intrinsic::experimental_vector_reduce_smax:
8993     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8994     break;
8995   case Intrinsic::experimental_vector_reduce_smin:
8996     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8997     break;
8998   case Intrinsic::experimental_vector_reduce_umax:
8999     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9000     break;
9001   case Intrinsic::experimental_vector_reduce_umin:
9002     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9003     break;
9004   case Intrinsic::experimental_vector_reduce_fmax:
9005     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9006     break;
9007   case Intrinsic::experimental_vector_reduce_fmin:
9008     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9009     break;
9010   default:
9011     llvm_unreachable("Unhandled vector reduce intrinsic");
9012   }
9013   setValue(&I, Res);
9014 }
9015 
9016 /// Returns an AttributeList representing the attributes applied to the return
9017 /// value of the given call.
9018 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9019   SmallVector<Attribute::AttrKind, 2> Attrs;
9020   if (CLI.RetSExt)
9021     Attrs.push_back(Attribute::SExt);
9022   if (CLI.RetZExt)
9023     Attrs.push_back(Attribute::ZExt);
9024   if (CLI.IsInReg)
9025     Attrs.push_back(Attribute::InReg);
9026 
9027   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9028                             Attrs);
9029 }
9030 
9031 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9032 /// implementation, which just calls LowerCall.
9033 /// FIXME: When all targets are
9034 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9035 std::pair<SDValue, SDValue>
9036 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9037   // Handle the incoming return values from the call.
9038   CLI.Ins.clear();
9039   Type *OrigRetTy = CLI.RetTy;
9040   SmallVector<EVT, 4> RetTys;
9041   SmallVector<uint64_t, 4> Offsets;
9042   auto &DL = CLI.DAG.getDataLayout();
9043   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9044 
9045   if (CLI.IsPostTypeLegalization) {
9046     // If we are lowering a libcall after legalization, split the return type.
9047     SmallVector<EVT, 4> OldRetTys;
9048     SmallVector<uint64_t, 4> OldOffsets;
9049     RetTys.swap(OldRetTys);
9050     Offsets.swap(OldOffsets);
9051 
9052     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9053       EVT RetVT = OldRetTys[i];
9054       uint64_t Offset = OldOffsets[i];
9055       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9056       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9057       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9058       RetTys.append(NumRegs, RegisterVT);
9059       for (unsigned j = 0; j != NumRegs; ++j)
9060         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9061     }
9062   }
9063 
9064   SmallVector<ISD::OutputArg, 4> Outs;
9065   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9066 
9067   bool CanLowerReturn =
9068       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9069                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9070 
9071   SDValue DemoteStackSlot;
9072   int DemoteStackIdx = -100;
9073   if (!CanLowerReturn) {
9074     // FIXME: equivalent assert?
9075     // assert(!CS.hasInAllocaArgument() &&
9076     //        "sret demotion is incompatible with inalloca");
9077     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9078     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9079     MachineFunction &MF = CLI.DAG.getMachineFunction();
9080     DemoteStackIdx =
9081         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9082     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9083                                               DL.getAllocaAddrSpace());
9084 
9085     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9086     ArgListEntry Entry;
9087     Entry.Node = DemoteStackSlot;
9088     Entry.Ty = StackSlotPtrType;
9089     Entry.IsSExt = false;
9090     Entry.IsZExt = false;
9091     Entry.IsInReg = false;
9092     Entry.IsSRet = true;
9093     Entry.IsNest = false;
9094     Entry.IsByVal = false;
9095     Entry.IsByRef = false;
9096     Entry.IsReturned = false;
9097     Entry.IsSwiftSelf = false;
9098     Entry.IsSwiftError = false;
9099     Entry.IsCFGuardTarget = false;
9100     Entry.Alignment = Alignment;
9101     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9102     CLI.NumFixedArgs += 1;
9103     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9104 
9105     // sret demotion isn't compatible with tail-calls, since the sret argument
9106     // points into the callers stack frame.
9107     CLI.IsTailCall = false;
9108   } else {
9109     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9110         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9111     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9112       ISD::ArgFlagsTy Flags;
9113       if (NeedsRegBlock) {
9114         Flags.setInConsecutiveRegs();
9115         if (I == RetTys.size() - 1)
9116           Flags.setInConsecutiveRegsLast();
9117       }
9118       EVT VT = RetTys[I];
9119       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9120                                                      CLI.CallConv, VT);
9121       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9122                                                        CLI.CallConv, VT);
9123       for (unsigned i = 0; i != NumRegs; ++i) {
9124         ISD::InputArg MyFlags;
9125         MyFlags.Flags = Flags;
9126         MyFlags.VT = RegisterVT;
9127         MyFlags.ArgVT = VT;
9128         MyFlags.Used = CLI.IsReturnValueUsed;
9129         if (CLI.RetTy->isPointerTy()) {
9130           MyFlags.Flags.setPointer();
9131           MyFlags.Flags.setPointerAddrSpace(
9132               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9133         }
9134         if (CLI.RetSExt)
9135           MyFlags.Flags.setSExt();
9136         if (CLI.RetZExt)
9137           MyFlags.Flags.setZExt();
9138         if (CLI.IsInReg)
9139           MyFlags.Flags.setInReg();
9140         CLI.Ins.push_back(MyFlags);
9141       }
9142     }
9143   }
9144 
9145   // We push in swifterror return as the last element of CLI.Ins.
9146   ArgListTy &Args = CLI.getArgs();
9147   if (supportSwiftError()) {
9148     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9149       if (Args[i].IsSwiftError) {
9150         ISD::InputArg MyFlags;
9151         MyFlags.VT = getPointerTy(DL);
9152         MyFlags.ArgVT = EVT(getPointerTy(DL));
9153         MyFlags.Flags.setSwiftError();
9154         CLI.Ins.push_back(MyFlags);
9155       }
9156     }
9157   }
9158 
9159   // Handle all of the outgoing arguments.
9160   CLI.Outs.clear();
9161   CLI.OutVals.clear();
9162   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9163     SmallVector<EVT, 4> ValueVTs;
9164     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9165     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9166     Type *FinalType = Args[i].Ty;
9167     if (Args[i].IsByVal)
9168       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9169     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9170         FinalType, CLI.CallConv, CLI.IsVarArg);
9171     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9172          ++Value) {
9173       EVT VT = ValueVTs[Value];
9174       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9175       SDValue Op = SDValue(Args[i].Node.getNode(),
9176                            Args[i].Node.getResNo() + Value);
9177       ISD::ArgFlagsTy Flags;
9178 
9179       // Certain targets (such as MIPS), may have a different ABI alignment
9180       // for a type depending on the context. Give the target a chance to
9181       // specify the alignment it wants.
9182       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9183 
9184       if (Args[i].Ty->isPointerTy()) {
9185         Flags.setPointer();
9186         Flags.setPointerAddrSpace(
9187             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9188       }
9189       if (Args[i].IsZExt)
9190         Flags.setZExt();
9191       if (Args[i].IsSExt)
9192         Flags.setSExt();
9193       if (Args[i].IsInReg) {
9194         // If we are using vectorcall calling convention, a structure that is
9195         // passed InReg - is surely an HVA
9196         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9197             isa<StructType>(FinalType)) {
9198           // The first value of a structure is marked
9199           if (0 == Value)
9200             Flags.setHvaStart();
9201           Flags.setHva();
9202         }
9203         // Set InReg Flag
9204         Flags.setInReg();
9205       }
9206       if (Args[i].IsSRet)
9207         Flags.setSRet();
9208       if (Args[i].IsSwiftSelf)
9209         Flags.setSwiftSelf();
9210       if (Args[i].IsSwiftError)
9211         Flags.setSwiftError();
9212       if (Args[i].IsCFGuardTarget)
9213         Flags.setCFGuardTarget();
9214       if (Args[i].IsByVal)
9215         Flags.setByVal();
9216       if (Args[i].IsByRef)
9217         Flags.setByRef();
9218       if (Args[i].IsPreallocated) {
9219         Flags.setPreallocated();
9220         // Set the byval flag for CCAssignFn callbacks that don't know about
9221         // preallocated.  This way we can know how many bytes we should've
9222         // allocated and how many bytes a callee cleanup function will pop.  If
9223         // we port preallocated to more targets, we'll have to add custom
9224         // preallocated handling in the various CC lowering callbacks.
9225         Flags.setByVal();
9226       }
9227       if (Args[i].IsInAlloca) {
9228         Flags.setInAlloca();
9229         // Set the byval flag for CCAssignFn callbacks that don't know about
9230         // inalloca.  This way we can know how many bytes we should've allocated
9231         // and how many bytes a callee cleanup function will pop.  If we port
9232         // inalloca to more targets, we'll have to add custom inalloca handling
9233         // in the various CC lowering callbacks.
9234         Flags.setByVal();
9235       }
9236       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9237         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9238         Type *ElementTy = Ty->getElementType();
9239 
9240         unsigned FrameSize = DL.getTypeAllocSize(
9241             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9242         Flags.setByValSize(FrameSize);
9243 
9244         // info is not there but there are cases it cannot get right.
9245         Align FrameAlign;
9246         if (auto MA = Args[i].Alignment)
9247           FrameAlign = *MA;
9248         else
9249           FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
9250         Flags.setByValAlign(FrameAlign);
9251       }
9252       if (Args[i].IsNest)
9253         Flags.setNest();
9254       if (NeedsRegBlock)
9255         Flags.setInConsecutiveRegs();
9256       Flags.setOrigAlign(OriginalAlignment);
9257 
9258       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9259                                                  CLI.CallConv, VT);
9260       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9261                                                         CLI.CallConv, VT);
9262       SmallVector<SDValue, 4> Parts(NumParts);
9263       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9264 
9265       if (Args[i].IsSExt)
9266         ExtendKind = ISD::SIGN_EXTEND;
9267       else if (Args[i].IsZExt)
9268         ExtendKind = ISD::ZERO_EXTEND;
9269 
9270       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9271       // for now.
9272       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9273           CanLowerReturn) {
9274         assert((CLI.RetTy == Args[i].Ty ||
9275                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9276                  CLI.RetTy->getPointerAddressSpace() ==
9277                      Args[i].Ty->getPointerAddressSpace())) &&
9278                RetTys.size() == NumValues && "unexpected use of 'returned'");
9279         // Before passing 'returned' to the target lowering code, ensure that
9280         // either the register MVT and the actual EVT are the same size or that
9281         // the return value and argument are extended in the same way; in these
9282         // cases it's safe to pass the argument register value unchanged as the
9283         // return register value (although it's at the target's option whether
9284         // to do so)
9285         // TODO: allow code generation to take advantage of partially preserved
9286         // registers rather than clobbering the entire register when the
9287         // parameter extension method is not compatible with the return
9288         // extension method
9289         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9290             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9291              CLI.RetZExt == Args[i].IsZExt))
9292           Flags.setReturned();
9293       }
9294 
9295       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9296                      CLI.CallConv, ExtendKind);
9297 
9298       for (unsigned j = 0; j != NumParts; ++j) {
9299         // if it isn't first piece, alignment must be 1
9300         // For scalable vectors the scalable part is currently handled
9301         // by individual targets, so we just use the known minimum size here.
9302         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9303                     i < CLI.NumFixedArgs, i,
9304                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9305         if (NumParts > 1 && j == 0)
9306           MyFlags.Flags.setSplit();
9307         else if (j != 0) {
9308           MyFlags.Flags.setOrigAlign(Align(1));
9309           if (j == NumParts - 1)
9310             MyFlags.Flags.setSplitEnd();
9311         }
9312 
9313         CLI.Outs.push_back(MyFlags);
9314         CLI.OutVals.push_back(Parts[j]);
9315       }
9316 
9317       if (NeedsRegBlock && Value == NumValues - 1)
9318         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9319     }
9320   }
9321 
9322   SmallVector<SDValue, 4> InVals;
9323   CLI.Chain = LowerCall(CLI, InVals);
9324 
9325   // Update CLI.InVals to use outside of this function.
9326   CLI.InVals = InVals;
9327 
9328   // Verify that the target's LowerCall behaved as expected.
9329   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9330          "LowerCall didn't return a valid chain!");
9331   assert((!CLI.IsTailCall || InVals.empty()) &&
9332          "LowerCall emitted a return value for a tail call!");
9333   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9334          "LowerCall didn't emit the correct number of values!");
9335 
9336   // For a tail call, the return value is merely live-out and there aren't
9337   // any nodes in the DAG representing it. Return a special value to
9338   // indicate that a tail call has been emitted and no more Instructions
9339   // should be processed in the current block.
9340   if (CLI.IsTailCall) {
9341     CLI.DAG.setRoot(CLI.Chain);
9342     return std::make_pair(SDValue(), SDValue());
9343   }
9344 
9345 #ifndef NDEBUG
9346   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9347     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9348     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9349            "LowerCall emitted a value with the wrong type!");
9350   }
9351 #endif
9352 
9353   SmallVector<SDValue, 4> ReturnValues;
9354   if (!CanLowerReturn) {
9355     // The instruction result is the result of loading from the
9356     // hidden sret parameter.
9357     SmallVector<EVT, 1> PVTs;
9358     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9359 
9360     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9361     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9362     EVT PtrVT = PVTs[0];
9363 
9364     unsigned NumValues = RetTys.size();
9365     ReturnValues.resize(NumValues);
9366     SmallVector<SDValue, 4> Chains(NumValues);
9367 
9368     // An aggregate return value cannot wrap around the address space, so
9369     // offsets to its parts don't wrap either.
9370     SDNodeFlags Flags;
9371     Flags.setNoUnsignedWrap(true);
9372 
9373     MachineFunction &MF = CLI.DAG.getMachineFunction();
9374     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9375     for (unsigned i = 0; i < NumValues; ++i) {
9376       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9377                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9378                                                         PtrVT), Flags);
9379       SDValue L = CLI.DAG.getLoad(
9380           RetTys[i], CLI.DL, CLI.Chain, Add,
9381           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9382                                             DemoteStackIdx, Offsets[i]),
9383           HiddenSRetAlign);
9384       ReturnValues[i] = L;
9385       Chains[i] = L.getValue(1);
9386     }
9387 
9388     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9389   } else {
9390     // Collect the legal value parts into potentially illegal values
9391     // that correspond to the original function's return values.
9392     Optional<ISD::NodeType> AssertOp;
9393     if (CLI.RetSExt)
9394       AssertOp = ISD::AssertSext;
9395     else if (CLI.RetZExt)
9396       AssertOp = ISD::AssertZext;
9397     unsigned CurReg = 0;
9398     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9399       EVT VT = RetTys[I];
9400       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9401                                                      CLI.CallConv, VT);
9402       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9403                                                        CLI.CallConv, VT);
9404 
9405       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9406                                               NumRegs, RegisterVT, VT, nullptr,
9407                                               CLI.CallConv, AssertOp));
9408       CurReg += NumRegs;
9409     }
9410 
9411     // For a function returning void, there is no return value. We can't create
9412     // such a node, so we just return a null return value in that case. In
9413     // that case, nothing will actually look at the value.
9414     if (ReturnValues.empty())
9415       return std::make_pair(SDValue(), CLI.Chain);
9416   }
9417 
9418   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9419                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9420   return std::make_pair(Res, CLI.Chain);
9421 }
9422 
9423 void TargetLowering::LowerOperationWrapper(SDNode *N,
9424                                            SmallVectorImpl<SDValue> &Results,
9425                                            SelectionDAG &DAG) const {
9426   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9427     Results.push_back(Res);
9428 }
9429 
9430 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9431   llvm_unreachable("LowerOperation not implemented for this target!");
9432 }
9433 
9434 void
9435 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9436   SDValue Op = getNonRegisterValue(V);
9437   assert((Op.getOpcode() != ISD::CopyFromReg ||
9438           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9439          "Copy from a reg to the same reg!");
9440   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9441 
9442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9443   // If this is an InlineAsm we have to match the registers required, not the
9444   // notional registers required by the type.
9445 
9446   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9447                    None); // This is not an ABI copy.
9448   SDValue Chain = DAG.getEntryNode();
9449 
9450   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9451                               FuncInfo.PreferredExtendType.end())
9452                                  ? ISD::ANY_EXTEND
9453                                  : FuncInfo.PreferredExtendType[V];
9454   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9455   PendingExports.push_back(Chain);
9456 }
9457 
9458 #include "llvm/CodeGen/SelectionDAGISel.h"
9459 
9460 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9461 /// entry block, return true.  This includes arguments used by switches, since
9462 /// the switch may expand into multiple basic blocks.
9463 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9464   // With FastISel active, we may be splitting blocks, so force creation
9465   // of virtual registers for all non-dead arguments.
9466   if (FastISel)
9467     return A->use_empty();
9468 
9469   const BasicBlock &Entry = A->getParent()->front();
9470   for (const User *U : A->users())
9471     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9472       return false;  // Use not in entry block.
9473 
9474   return true;
9475 }
9476 
9477 using ArgCopyElisionMapTy =
9478     DenseMap<const Argument *,
9479              std::pair<const AllocaInst *, const StoreInst *>>;
9480 
9481 /// Scan the entry block of the function in FuncInfo for arguments that look
9482 /// like copies into a local alloca. Record any copied arguments in
9483 /// ArgCopyElisionCandidates.
9484 static void
9485 findArgumentCopyElisionCandidates(const DataLayout &DL,
9486                                   FunctionLoweringInfo *FuncInfo,
9487                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9488   // Record the state of every static alloca used in the entry block. Argument
9489   // allocas are all used in the entry block, so we need approximately as many
9490   // entries as we have arguments.
9491   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9492   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9493   unsigned NumArgs = FuncInfo->Fn->arg_size();
9494   StaticAllocas.reserve(NumArgs * 2);
9495 
9496   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9497     if (!V)
9498       return nullptr;
9499     V = V->stripPointerCasts();
9500     const auto *AI = dyn_cast<AllocaInst>(V);
9501     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9502       return nullptr;
9503     auto Iter = StaticAllocas.insert({AI, Unknown});
9504     return &Iter.first->second;
9505   };
9506 
9507   // Look for stores of arguments to static allocas. Look through bitcasts and
9508   // GEPs to handle type coercions, as long as the alloca is fully initialized
9509   // by the store. Any non-store use of an alloca escapes it and any subsequent
9510   // unanalyzed store might write it.
9511   // FIXME: Handle structs initialized with multiple stores.
9512   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9513     // Look for stores, and handle non-store uses conservatively.
9514     const auto *SI = dyn_cast<StoreInst>(&I);
9515     if (!SI) {
9516       // We will look through cast uses, so ignore them completely.
9517       if (I.isCast())
9518         continue;
9519       // Ignore debug info intrinsics, they don't escape or store to allocas.
9520       if (isa<DbgInfoIntrinsic>(I))
9521         continue;
9522       // This is an unknown instruction. Assume it escapes or writes to all
9523       // static alloca operands.
9524       for (const Use &U : I.operands()) {
9525         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9526           *Info = StaticAllocaInfo::Clobbered;
9527       }
9528       continue;
9529     }
9530 
9531     // If the stored value is a static alloca, mark it as escaped.
9532     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9533       *Info = StaticAllocaInfo::Clobbered;
9534 
9535     // Check if the destination is a static alloca.
9536     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9537     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9538     if (!Info)
9539       continue;
9540     const AllocaInst *AI = cast<AllocaInst>(Dst);
9541 
9542     // Skip allocas that have been initialized or clobbered.
9543     if (*Info != StaticAllocaInfo::Unknown)
9544       continue;
9545 
9546     // Check if the stored value is an argument, and that this store fully
9547     // initializes the alloca. Don't elide copies from the same argument twice.
9548     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9549     const auto *Arg = dyn_cast<Argument>(Val);
9550     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
9551         Arg->getType()->isEmptyTy() ||
9552         DL.getTypeStoreSize(Arg->getType()) !=
9553             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9554         ArgCopyElisionCandidates.count(Arg)) {
9555       *Info = StaticAllocaInfo::Clobbered;
9556       continue;
9557     }
9558 
9559     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9560                       << '\n');
9561 
9562     // Mark this alloca and store for argument copy elision.
9563     *Info = StaticAllocaInfo::Elidable;
9564     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9565 
9566     // Stop scanning if we've seen all arguments. This will happen early in -O0
9567     // builds, which is useful, because -O0 builds have large entry blocks and
9568     // many allocas.
9569     if (ArgCopyElisionCandidates.size() == NumArgs)
9570       break;
9571   }
9572 }
9573 
9574 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9575 /// ArgVal is a load from a suitable fixed stack object.
9576 static void tryToElideArgumentCopy(
9577     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9578     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9579     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9580     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9581     SDValue ArgVal, bool &ArgHasUses) {
9582   // Check if this is a load from a fixed stack object.
9583   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9584   if (!LNode)
9585     return;
9586   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9587   if (!FINode)
9588     return;
9589 
9590   // Check that the fixed stack object is the right size and alignment.
9591   // Look at the alignment that the user wrote on the alloca instead of looking
9592   // at the stack object.
9593   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9594   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9595   const AllocaInst *AI = ArgCopyIter->second.first;
9596   int FixedIndex = FINode->getIndex();
9597   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9598   int OldIndex = AllocaIndex;
9599   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9600   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9601     LLVM_DEBUG(
9602         dbgs() << "  argument copy elision failed due to bad fixed stack "
9603                   "object size\n");
9604     return;
9605   }
9606   Align RequiredAlignment = AI->getAlign();
9607   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9608     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9609                          "greater than stack argument alignment ("
9610                       << DebugStr(RequiredAlignment) << " vs "
9611                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9612     return;
9613   }
9614 
9615   // Perform the elision. Delete the old stack object and replace its only use
9616   // in the variable info map. Mark the stack object as mutable.
9617   LLVM_DEBUG({
9618     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9619            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9620            << '\n';
9621   });
9622   MFI.RemoveStackObject(OldIndex);
9623   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9624   AllocaIndex = FixedIndex;
9625   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9626   Chains.push_back(ArgVal.getValue(1));
9627 
9628   // Avoid emitting code for the store implementing the copy.
9629   const StoreInst *SI = ArgCopyIter->second.second;
9630   ElidedArgCopyInstrs.insert(SI);
9631 
9632   // Check for uses of the argument again so that we can avoid exporting ArgVal
9633   // if it is't used by anything other than the store.
9634   for (const Value *U : Arg.users()) {
9635     if (U != SI) {
9636       ArgHasUses = true;
9637       break;
9638     }
9639   }
9640 }
9641 
9642 void SelectionDAGISel::LowerArguments(const Function &F) {
9643   SelectionDAG &DAG = SDB->DAG;
9644   SDLoc dl = SDB->getCurSDLoc();
9645   const DataLayout &DL = DAG.getDataLayout();
9646   SmallVector<ISD::InputArg, 16> Ins;
9647 
9648   // In Naked functions we aren't going to save any registers.
9649   if (F.hasFnAttribute(Attribute::Naked))
9650     return;
9651 
9652   if (!FuncInfo->CanLowerReturn) {
9653     // Put in an sret pointer parameter before all the other parameters.
9654     SmallVector<EVT, 1> ValueVTs;
9655     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9656                     F.getReturnType()->getPointerTo(
9657                         DAG.getDataLayout().getAllocaAddrSpace()),
9658                     ValueVTs);
9659 
9660     // NOTE: Assuming that a pointer will never break down to more than one VT
9661     // or one register.
9662     ISD::ArgFlagsTy Flags;
9663     Flags.setSRet();
9664     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9665     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9666                          ISD::InputArg::NoArgIndex, 0);
9667     Ins.push_back(RetArg);
9668   }
9669 
9670   // Look for stores of arguments to static allocas. Mark such arguments with a
9671   // flag to ask the target to give us the memory location of that argument if
9672   // available.
9673   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9674   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9675                                     ArgCopyElisionCandidates);
9676 
9677   // Set up the incoming argument description vector.
9678   for (const Argument &Arg : F.args()) {
9679     unsigned ArgNo = Arg.getArgNo();
9680     SmallVector<EVT, 4> ValueVTs;
9681     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9682     bool isArgValueUsed = !Arg.use_empty();
9683     unsigned PartBase = 0;
9684     Type *FinalType = Arg.getType();
9685     if (Arg.hasAttribute(Attribute::ByVal))
9686       FinalType = Arg.getParamByValType();
9687     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9688         FinalType, F.getCallingConv(), F.isVarArg());
9689     for (unsigned Value = 0, NumValues = ValueVTs.size();
9690          Value != NumValues; ++Value) {
9691       EVT VT = ValueVTs[Value];
9692       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9693       ISD::ArgFlagsTy Flags;
9694 
9695       // Certain targets (such as MIPS), may have a different ABI alignment
9696       // for a type depending on the context. Give the target a chance to
9697       // specify the alignment it wants.
9698       const Align OriginalAlignment(
9699           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9700 
9701       if (Arg.getType()->isPointerTy()) {
9702         Flags.setPointer();
9703         Flags.setPointerAddrSpace(
9704             cast<PointerType>(Arg.getType())->getAddressSpace());
9705       }
9706       if (Arg.hasAttribute(Attribute::ZExt))
9707         Flags.setZExt();
9708       if (Arg.hasAttribute(Attribute::SExt))
9709         Flags.setSExt();
9710       if (Arg.hasAttribute(Attribute::InReg)) {
9711         // If we are using vectorcall calling convention, a structure that is
9712         // passed InReg - is surely an HVA
9713         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9714             isa<StructType>(Arg.getType())) {
9715           // The first value of a structure is marked
9716           if (0 == Value)
9717             Flags.setHvaStart();
9718           Flags.setHva();
9719         }
9720         // Set InReg Flag
9721         Flags.setInReg();
9722       }
9723       if (Arg.hasAttribute(Attribute::StructRet))
9724         Flags.setSRet();
9725       if (Arg.hasAttribute(Attribute::SwiftSelf))
9726         Flags.setSwiftSelf();
9727       if (Arg.hasAttribute(Attribute::SwiftError))
9728         Flags.setSwiftError();
9729       if (Arg.hasAttribute(Attribute::ByVal))
9730         Flags.setByVal();
9731       if (Arg.hasAttribute(Attribute::ByRef))
9732         Flags.setByRef();
9733       if (Arg.hasAttribute(Attribute::InAlloca)) {
9734         Flags.setInAlloca();
9735         // Set the byval flag for CCAssignFn callbacks that don't know about
9736         // inalloca.  This way we can know how many bytes we should've allocated
9737         // and how many bytes a callee cleanup function will pop.  If we port
9738         // inalloca to more targets, we'll have to add custom inalloca handling
9739         // in the various CC lowering callbacks.
9740         Flags.setByVal();
9741       }
9742       if (Arg.hasAttribute(Attribute::Preallocated)) {
9743         Flags.setPreallocated();
9744         // Set the byval flag for CCAssignFn callbacks that don't know about
9745         // preallocated.  This way we can know how many bytes we should've
9746         // allocated and how many bytes a callee cleanup function will pop.  If
9747         // we port preallocated to more targets, we'll have to add custom
9748         // preallocated handling in the various CC lowering callbacks.
9749         Flags.setByVal();
9750       }
9751 
9752       Type *ArgMemTy = nullptr;
9753       if (F.getCallingConv() == CallingConv::X86_INTR) {
9754         // IA Interrupt passes frame (1st parameter) by value in the stack.
9755         if (ArgNo == 0) {
9756           Flags.setByVal();
9757           // FIXME: Dependence on pointee element type. See bug 46672.
9758           ArgMemTy = Arg.getType()->getPointerElementType();
9759         }
9760       }
9761       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
9762           Flags.isByRef()) {
9763         if (!ArgMemTy)
9764           ArgMemTy = Arg.getPointeeInMemoryValueType();
9765 
9766         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
9767 
9768         // For in-memory arguments, size and alignment should be passed from FE.
9769         // BE will guess if this info is not there but there are cases it cannot
9770         // get right.
9771         MaybeAlign MemAlign = Arg.getParamAlign();
9772         if (!MemAlign)
9773           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
9774 
9775         if (Flags.isByRef()) {
9776           Flags.setByRefSize(MemSize);
9777           Flags.setByRefAlign(*MemAlign);
9778         } else {
9779           Flags.setByValSize(MemSize);
9780           Flags.setByValAlign(*MemAlign);
9781         }
9782       }
9783 
9784       if (Arg.hasAttribute(Attribute::Nest))
9785         Flags.setNest();
9786       if (NeedsRegBlock)
9787         Flags.setInConsecutiveRegs();
9788       Flags.setOrigAlign(OriginalAlignment);
9789       if (ArgCopyElisionCandidates.count(&Arg))
9790         Flags.setCopyElisionCandidate();
9791       if (Arg.hasAttribute(Attribute::Returned))
9792         Flags.setReturned();
9793 
9794       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9795           *CurDAG->getContext(), F.getCallingConv(), VT);
9796       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9797           *CurDAG->getContext(), F.getCallingConv(), VT);
9798       for (unsigned i = 0; i != NumRegs; ++i) {
9799         // For scalable vectors, use the minimum size; individual targets
9800         // are responsible for handling scalable vector arguments and
9801         // return values.
9802         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9803                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9804         if (NumRegs > 1 && i == 0)
9805           MyFlags.Flags.setSplit();
9806         // if it isn't first piece, alignment must be 1
9807         else if (i > 0) {
9808           MyFlags.Flags.setOrigAlign(Align(1));
9809           if (i == NumRegs - 1)
9810             MyFlags.Flags.setSplitEnd();
9811         }
9812         Ins.push_back(MyFlags);
9813       }
9814       if (NeedsRegBlock && Value == NumValues - 1)
9815         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9816       PartBase += VT.getStoreSize().getKnownMinSize();
9817     }
9818   }
9819 
9820   // Call the target to set up the argument values.
9821   SmallVector<SDValue, 8> InVals;
9822   SDValue NewRoot = TLI->LowerFormalArguments(
9823       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9824 
9825   // Verify that the target's LowerFormalArguments behaved as expected.
9826   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9827          "LowerFormalArguments didn't return a valid chain!");
9828   assert(InVals.size() == Ins.size() &&
9829          "LowerFormalArguments didn't emit the correct number of values!");
9830   LLVM_DEBUG({
9831     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9832       assert(InVals[i].getNode() &&
9833              "LowerFormalArguments emitted a null value!");
9834       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9835              "LowerFormalArguments emitted a value with the wrong type!");
9836     }
9837   });
9838 
9839   // Update the DAG with the new chain value resulting from argument lowering.
9840   DAG.setRoot(NewRoot);
9841 
9842   // Set up the argument values.
9843   unsigned i = 0;
9844   if (!FuncInfo->CanLowerReturn) {
9845     // Create a virtual register for the sret pointer, and put in a copy
9846     // from the sret argument into it.
9847     SmallVector<EVT, 1> ValueVTs;
9848     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9849                     F.getReturnType()->getPointerTo(
9850                         DAG.getDataLayout().getAllocaAddrSpace()),
9851                     ValueVTs);
9852     MVT VT = ValueVTs[0].getSimpleVT();
9853     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9854     Optional<ISD::NodeType> AssertOp = None;
9855     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9856                                         nullptr, F.getCallingConv(), AssertOp);
9857 
9858     MachineFunction& MF = SDB->DAG.getMachineFunction();
9859     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9860     Register SRetReg =
9861         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9862     FuncInfo->DemoteRegister = SRetReg;
9863     NewRoot =
9864         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9865     DAG.setRoot(NewRoot);
9866 
9867     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9868     ++i;
9869   }
9870 
9871   SmallVector<SDValue, 4> Chains;
9872   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9873   for (const Argument &Arg : F.args()) {
9874     SmallVector<SDValue, 4> ArgValues;
9875     SmallVector<EVT, 4> ValueVTs;
9876     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9877     unsigned NumValues = ValueVTs.size();
9878     if (NumValues == 0)
9879       continue;
9880 
9881     bool ArgHasUses = !Arg.use_empty();
9882 
9883     // Elide the copying store if the target loaded this argument from a
9884     // suitable fixed stack object.
9885     if (Ins[i].Flags.isCopyElisionCandidate()) {
9886       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9887                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9888                              InVals[i], ArgHasUses);
9889     }
9890 
9891     // If this argument is unused then remember its value. It is used to generate
9892     // debugging information.
9893     bool isSwiftErrorArg =
9894         TLI->supportSwiftError() &&
9895         Arg.hasAttribute(Attribute::SwiftError);
9896     if (!ArgHasUses && !isSwiftErrorArg) {
9897       SDB->setUnusedArgValue(&Arg, InVals[i]);
9898 
9899       // Also remember any frame index for use in FastISel.
9900       if (FrameIndexSDNode *FI =
9901           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9902         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9903     }
9904 
9905     for (unsigned Val = 0; Val != NumValues; ++Val) {
9906       EVT VT = ValueVTs[Val];
9907       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9908                                                       F.getCallingConv(), VT);
9909       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9910           *CurDAG->getContext(), F.getCallingConv(), VT);
9911 
9912       // Even an apparent 'unused' swifterror argument needs to be returned. So
9913       // we do generate a copy for it that can be used on return from the
9914       // function.
9915       if (ArgHasUses || isSwiftErrorArg) {
9916         Optional<ISD::NodeType> AssertOp;
9917         if (Arg.hasAttribute(Attribute::SExt))
9918           AssertOp = ISD::AssertSext;
9919         else if (Arg.hasAttribute(Attribute::ZExt))
9920           AssertOp = ISD::AssertZext;
9921 
9922         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9923                                              PartVT, VT, nullptr,
9924                                              F.getCallingConv(), AssertOp));
9925       }
9926 
9927       i += NumParts;
9928     }
9929 
9930     // We don't need to do anything else for unused arguments.
9931     if (ArgValues.empty())
9932       continue;
9933 
9934     // Note down frame index.
9935     if (FrameIndexSDNode *FI =
9936         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9937       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9938 
9939     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9940                                      SDB->getCurSDLoc());
9941 
9942     SDB->setValue(&Arg, Res);
9943     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9944       // We want to associate the argument with the frame index, among
9945       // involved operands, that correspond to the lowest address. The
9946       // getCopyFromParts function, called earlier, is swapping the order of
9947       // the operands to BUILD_PAIR depending on endianness. The result of
9948       // that swapping is that the least significant bits of the argument will
9949       // be in the first operand of the BUILD_PAIR node, and the most
9950       // significant bits will be in the second operand.
9951       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9952       if (LoadSDNode *LNode =
9953           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9954         if (FrameIndexSDNode *FI =
9955             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9956           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9957     }
9958 
9959     // Analyses past this point are naive and don't expect an assertion.
9960     if (Res.getOpcode() == ISD::AssertZext)
9961       Res = Res.getOperand(0);
9962 
9963     // Update the SwiftErrorVRegDefMap.
9964     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9965       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9966       if (Register::isVirtualRegister(Reg))
9967         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9968                                    Reg);
9969     }
9970 
9971     // If this argument is live outside of the entry block, insert a copy from
9972     // wherever we got it to the vreg that other BB's will reference it as.
9973     if (Res.getOpcode() == ISD::CopyFromReg) {
9974       // If we can, though, try to skip creating an unnecessary vreg.
9975       // FIXME: This isn't very clean... it would be nice to make this more
9976       // general.
9977       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9978       if (Register::isVirtualRegister(Reg)) {
9979         FuncInfo->ValueMap[&Arg] = Reg;
9980         continue;
9981       }
9982     }
9983     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9984       FuncInfo->InitializeRegForValue(&Arg);
9985       SDB->CopyToExportRegsIfNeeded(&Arg);
9986     }
9987   }
9988 
9989   if (!Chains.empty()) {
9990     Chains.push_back(NewRoot);
9991     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9992   }
9993 
9994   DAG.setRoot(NewRoot);
9995 
9996   assert(i == InVals.size() && "Argument register count mismatch!");
9997 
9998   // If any argument copy elisions occurred and we have debug info, update the
9999   // stale frame indices used in the dbg.declare variable info table.
10000   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10001   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10002     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10003       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10004       if (I != ArgCopyElisionFrameIndexMap.end())
10005         VI.Slot = I->second;
10006     }
10007   }
10008 
10009   // Finally, if the target has anything special to do, allow it to do so.
10010   emitFunctionEntryCode();
10011 }
10012 
10013 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10014 /// ensure constants are generated when needed.  Remember the virtual registers
10015 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10016 /// directly add them, because expansion might result in multiple MBB's for one
10017 /// BB.  As such, the start of the BB might correspond to a different MBB than
10018 /// the end.
10019 void
10020 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10021   const Instruction *TI = LLVMBB->getTerminator();
10022 
10023   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10024 
10025   // Check PHI nodes in successors that expect a value to be available from this
10026   // block.
10027   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10028     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10029     if (!isa<PHINode>(SuccBB->begin())) continue;
10030     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10031 
10032     // If this terminator has multiple identical successors (common for
10033     // switches), only handle each succ once.
10034     if (!SuccsHandled.insert(SuccMBB).second)
10035       continue;
10036 
10037     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10038 
10039     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10040     // nodes and Machine PHI nodes, but the incoming operands have not been
10041     // emitted yet.
10042     for (const PHINode &PN : SuccBB->phis()) {
10043       // Ignore dead phi's.
10044       if (PN.use_empty())
10045         continue;
10046 
10047       // Skip empty types
10048       if (PN.getType()->isEmptyTy())
10049         continue;
10050 
10051       unsigned Reg;
10052       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10053 
10054       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10055         unsigned &RegOut = ConstantsOut[C];
10056         if (RegOut == 0) {
10057           RegOut = FuncInfo.CreateRegs(C);
10058           CopyValueToVirtualRegister(C, RegOut);
10059         }
10060         Reg = RegOut;
10061       } else {
10062         DenseMap<const Value *, Register>::iterator I =
10063           FuncInfo.ValueMap.find(PHIOp);
10064         if (I != FuncInfo.ValueMap.end())
10065           Reg = I->second;
10066         else {
10067           assert(isa<AllocaInst>(PHIOp) &&
10068                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10069                  "Didn't codegen value into a register!??");
10070           Reg = FuncInfo.CreateRegs(PHIOp);
10071           CopyValueToVirtualRegister(PHIOp, Reg);
10072         }
10073       }
10074 
10075       // Remember that this register needs to added to the machine PHI node as
10076       // the input for this MBB.
10077       SmallVector<EVT, 4> ValueVTs;
10078       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10079       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10080       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10081         EVT VT = ValueVTs[vti];
10082         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10083         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10084           FuncInfo.PHINodesToUpdate.push_back(
10085               std::make_pair(&*MBBI++, Reg + i));
10086         Reg += NumRegisters;
10087       }
10088     }
10089   }
10090 
10091   ConstantsOut.clear();
10092 }
10093 
10094 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10095 /// is 0.
10096 MachineBasicBlock *
10097 SelectionDAGBuilder::StackProtectorDescriptor::
10098 AddSuccessorMBB(const BasicBlock *BB,
10099                 MachineBasicBlock *ParentMBB,
10100                 bool IsLikely,
10101                 MachineBasicBlock *SuccMBB) {
10102   // If SuccBB has not been created yet, create it.
10103   if (!SuccMBB) {
10104     MachineFunction *MF = ParentMBB->getParent();
10105     MachineFunction::iterator BBI(ParentMBB);
10106     SuccMBB = MF->CreateMachineBasicBlock(BB);
10107     MF->insert(++BBI, SuccMBB);
10108   }
10109   // Add it as a successor of ParentMBB.
10110   ParentMBB->addSuccessor(
10111       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10112   return SuccMBB;
10113 }
10114 
10115 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10116   MachineFunction::iterator I(MBB);
10117   if (++I == FuncInfo.MF->end())
10118     return nullptr;
10119   return &*I;
10120 }
10121 
10122 /// During lowering new call nodes can be created (such as memset, etc.).
10123 /// Those will become new roots of the current DAG, but complications arise
10124 /// when they are tail calls. In such cases, the call lowering will update
10125 /// the root, but the builder still needs to know that a tail call has been
10126 /// lowered in order to avoid generating an additional return.
10127 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10128   // If the node is null, we do have a tail call.
10129   if (MaybeTC.getNode() != nullptr)
10130     DAG.setRoot(MaybeTC);
10131   else
10132     HasTailCall = true;
10133 }
10134 
10135 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10136                                         MachineBasicBlock *SwitchMBB,
10137                                         MachineBasicBlock *DefaultMBB) {
10138   MachineFunction *CurMF = FuncInfo.MF;
10139   MachineBasicBlock *NextMBB = nullptr;
10140   MachineFunction::iterator BBI(W.MBB);
10141   if (++BBI != FuncInfo.MF->end())
10142     NextMBB = &*BBI;
10143 
10144   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10145 
10146   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10147 
10148   if (Size == 2 && W.MBB == SwitchMBB) {
10149     // If any two of the cases has the same destination, and if one value
10150     // is the same as the other, but has one bit unset that the other has set,
10151     // use bit manipulation to do two compares at once.  For example:
10152     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10153     // TODO: This could be extended to merge any 2 cases in switches with 3
10154     // cases.
10155     // TODO: Handle cases where W.CaseBB != SwitchBB.
10156     CaseCluster &Small = *W.FirstCluster;
10157     CaseCluster &Big = *W.LastCluster;
10158 
10159     if (Small.Low == Small.High && Big.Low == Big.High &&
10160         Small.MBB == Big.MBB) {
10161       const APInt &SmallValue = Small.Low->getValue();
10162       const APInt &BigValue = Big.Low->getValue();
10163 
10164       // Check that there is only one bit different.
10165       APInt CommonBit = BigValue ^ SmallValue;
10166       if (CommonBit.isPowerOf2()) {
10167         SDValue CondLHS = getValue(Cond);
10168         EVT VT = CondLHS.getValueType();
10169         SDLoc DL = getCurSDLoc();
10170 
10171         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10172                                  DAG.getConstant(CommonBit, DL, VT));
10173         SDValue Cond = DAG.getSetCC(
10174             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10175             ISD::SETEQ);
10176 
10177         // Update successor info.
10178         // Both Small and Big will jump to Small.BB, so we sum up the
10179         // probabilities.
10180         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10181         if (BPI)
10182           addSuccessorWithProb(
10183               SwitchMBB, DefaultMBB,
10184               // The default destination is the first successor in IR.
10185               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10186         else
10187           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10188 
10189         // Insert the true branch.
10190         SDValue BrCond =
10191             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10192                         DAG.getBasicBlock(Small.MBB));
10193         // Insert the false branch.
10194         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10195                              DAG.getBasicBlock(DefaultMBB));
10196 
10197         DAG.setRoot(BrCond);
10198         return;
10199       }
10200     }
10201   }
10202 
10203   if (TM.getOptLevel() != CodeGenOpt::None) {
10204     // Here, we order cases by probability so the most likely case will be
10205     // checked first. However, two clusters can have the same probability in
10206     // which case their relative ordering is non-deterministic. So we use Low
10207     // as a tie-breaker as clusters are guaranteed to never overlap.
10208     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10209                [](const CaseCluster &a, const CaseCluster &b) {
10210       return a.Prob != b.Prob ?
10211              a.Prob > b.Prob :
10212              a.Low->getValue().slt(b.Low->getValue());
10213     });
10214 
10215     // Rearrange the case blocks so that the last one falls through if possible
10216     // without changing the order of probabilities.
10217     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10218       --I;
10219       if (I->Prob > W.LastCluster->Prob)
10220         break;
10221       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10222         std::swap(*I, *W.LastCluster);
10223         break;
10224       }
10225     }
10226   }
10227 
10228   // Compute total probability.
10229   BranchProbability DefaultProb = W.DefaultProb;
10230   BranchProbability UnhandledProbs = DefaultProb;
10231   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10232     UnhandledProbs += I->Prob;
10233 
10234   MachineBasicBlock *CurMBB = W.MBB;
10235   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10236     bool FallthroughUnreachable = false;
10237     MachineBasicBlock *Fallthrough;
10238     if (I == W.LastCluster) {
10239       // For the last cluster, fall through to the default destination.
10240       Fallthrough = DefaultMBB;
10241       FallthroughUnreachable = isa<UnreachableInst>(
10242           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10243     } else {
10244       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10245       CurMF->insert(BBI, Fallthrough);
10246       // Put Cond in a virtual register to make it available from the new blocks.
10247       ExportFromCurrentBlock(Cond);
10248     }
10249     UnhandledProbs -= I->Prob;
10250 
10251     switch (I->Kind) {
10252       case CC_JumpTable: {
10253         // FIXME: Optimize away range check based on pivot comparisons.
10254         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10255         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10256 
10257         // The jump block hasn't been inserted yet; insert it here.
10258         MachineBasicBlock *JumpMBB = JT->MBB;
10259         CurMF->insert(BBI, JumpMBB);
10260 
10261         auto JumpProb = I->Prob;
10262         auto FallthroughProb = UnhandledProbs;
10263 
10264         // If the default statement is a target of the jump table, we evenly
10265         // distribute the default probability to successors of CurMBB. Also
10266         // update the probability on the edge from JumpMBB to Fallthrough.
10267         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10268                                               SE = JumpMBB->succ_end();
10269              SI != SE; ++SI) {
10270           if (*SI == DefaultMBB) {
10271             JumpProb += DefaultProb / 2;
10272             FallthroughProb -= DefaultProb / 2;
10273             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10274             JumpMBB->normalizeSuccProbs();
10275             break;
10276           }
10277         }
10278 
10279         if (FallthroughUnreachable) {
10280           // Skip the range check if the fallthrough block is unreachable.
10281           JTH->OmitRangeCheck = true;
10282         }
10283 
10284         if (!JTH->OmitRangeCheck)
10285           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10286         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10287         CurMBB->normalizeSuccProbs();
10288 
10289         // The jump table header will be inserted in our current block, do the
10290         // range check, and fall through to our fallthrough block.
10291         JTH->HeaderBB = CurMBB;
10292         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10293 
10294         // If we're in the right place, emit the jump table header right now.
10295         if (CurMBB == SwitchMBB) {
10296           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10297           JTH->Emitted = true;
10298         }
10299         break;
10300       }
10301       case CC_BitTests: {
10302         // FIXME: Optimize away range check based on pivot comparisons.
10303         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10304 
10305         // The bit test blocks haven't been inserted yet; insert them here.
10306         for (BitTestCase &BTC : BTB->Cases)
10307           CurMF->insert(BBI, BTC.ThisBB);
10308 
10309         // Fill in fields of the BitTestBlock.
10310         BTB->Parent = CurMBB;
10311         BTB->Default = Fallthrough;
10312 
10313         BTB->DefaultProb = UnhandledProbs;
10314         // If the cases in bit test don't form a contiguous range, we evenly
10315         // distribute the probability on the edge to Fallthrough to two
10316         // successors of CurMBB.
10317         if (!BTB->ContiguousRange) {
10318           BTB->Prob += DefaultProb / 2;
10319           BTB->DefaultProb -= DefaultProb / 2;
10320         }
10321 
10322         if (FallthroughUnreachable) {
10323           // Skip the range check if the fallthrough block is unreachable.
10324           BTB->OmitRangeCheck = true;
10325         }
10326 
10327         // If we're in the right place, emit the bit test header right now.
10328         if (CurMBB == SwitchMBB) {
10329           visitBitTestHeader(*BTB, SwitchMBB);
10330           BTB->Emitted = true;
10331         }
10332         break;
10333       }
10334       case CC_Range: {
10335         const Value *RHS, *LHS, *MHS;
10336         ISD::CondCode CC;
10337         if (I->Low == I->High) {
10338           // Check Cond == I->Low.
10339           CC = ISD::SETEQ;
10340           LHS = Cond;
10341           RHS=I->Low;
10342           MHS = nullptr;
10343         } else {
10344           // Check I->Low <= Cond <= I->High.
10345           CC = ISD::SETLE;
10346           LHS = I->Low;
10347           MHS = Cond;
10348           RHS = I->High;
10349         }
10350 
10351         // If Fallthrough is unreachable, fold away the comparison.
10352         if (FallthroughUnreachable)
10353           CC = ISD::SETTRUE;
10354 
10355         // The false probability is the sum of all unhandled cases.
10356         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10357                      getCurSDLoc(), I->Prob, UnhandledProbs);
10358 
10359         if (CurMBB == SwitchMBB)
10360           visitSwitchCase(CB, SwitchMBB);
10361         else
10362           SL->SwitchCases.push_back(CB);
10363 
10364         break;
10365       }
10366     }
10367     CurMBB = Fallthrough;
10368   }
10369 }
10370 
10371 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10372                                               CaseClusterIt First,
10373                                               CaseClusterIt Last) {
10374   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10375     if (X.Prob != CC.Prob)
10376       return X.Prob > CC.Prob;
10377 
10378     // Ties are broken by comparing the case value.
10379     return X.Low->getValue().slt(CC.Low->getValue());
10380   });
10381 }
10382 
10383 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10384                                         const SwitchWorkListItem &W,
10385                                         Value *Cond,
10386                                         MachineBasicBlock *SwitchMBB) {
10387   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10388          "Clusters not sorted?");
10389 
10390   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10391 
10392   // Balance the tree based on branch probabilities to create a near-optimal (in
10393   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10394   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10395   CaseClusterIt LastLeft = W.FirstCluster;
10396   CaseClusterIt FirstRight = W.LastCluster;
10397   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10398   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10399 
10400   // Move LastLeft and FirstRight towards each other from opposite directions to
10401   // find a partitioning of the clusters which balances the probability on both
10402   // sides. If LeftProb and RightProb are equal, alternate which side is
10403   // taken to ensure 0-probability nodes are distributed evenly.
10404   unsigned I = 0;
10405   while (LastLeft + 1 < FirstRight) {
10406     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10407       LeftProb += (++LastLeft)->Prob;
10408     else
10409       RightProb += (--FirstRight)->Prob;
10410     I++;
10411   }
10412 
10413   while (true) {
10414     // Our binary search tree differs from a typical BST in that ours can have up
10415     // to three values in each leaf. The pivot selection above doesn't take that
10416     // into account, which means the tree might require more nodes and be less
10417     // efficient. We compensate for this here.
10418 
10419     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10420     unsigned NumRight = W.LastCluster - FirstRight + 1;
10421 
10422     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10423       // If one side has less than 3 clusters, and the other has more than 3,
10424       // consider taking a cluster from the other side.
10425 
10426       if (NumLeft < NumRight) {
10427         // Consider moving the first cluster on the right to the left side.
10428         CaseCluster &CC = *FirstRight;
10429         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10430         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10431         if (LeftSideRank <= RightSideRank) {
10432           // Moving the cluster to the left does not demote it.
10433           ++LastLeft;
10434           ++FirstRight;
10435           continue;
10436         }
10437       } else {
10438         assert(NumRight < NumLeft);
10439         // Consider moving the last element on the left to the right side.
10440         CaseCluster &CC = *LastLeft;
10441         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10442         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10443         if (RightSideRank <= LeftSideRank) {
10444           // Moving the cluster to the right does not demot it.
10445           --LastLeft;
10446           --FirstRight;
10447           continue;
10448         }
10449       }
10450     }
10451     break;
10452   }
10453 
10454   assert(LastLeft + 1 == FirstRight);
10455   assert(LastLeft >= W.FirstCluster);
10456   assert(FirstRight <= W.LastCluster);
10457 
10458   // Use the first element on the right as pivot since we will make less-than
10459   // comparisons against it.
10460   CaseClusterIt PivotCluster = FirstRight;
10461   assert(PivotCluster > W.FirstCluster);
10462   assert(PivotCluster <= W.LastCluster);
10463 
10464   CaseClusterIt FirstLeft = W.FirstCluster;
10465   CaseClusterIt LastRight = W.LastCluster;
10466 
10467   const ConstantInt *Pivot = PivotCluster->Low;
10468 
10469   // New blocks will be inserted immediately after the current one.
10470   MachineFunction::iterator BBI(W.MBB);
10471   ++BBI;
10472 
10473   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10474   // we can branch to its destination directly if it's squeezed exactly in
10475   // between the known lower bound and Pivot - 1.
10476   MachineBasicBlock *LeftMBB;
10477   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10478       FirstLeft->Low == W.GE &&
10479       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10480     LeftMBB = FirstLeft->MBB;
10481   } else {
10482     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10483     FuncInfo.MF->insert(BBI, LeftMBB);
10484     WorkList.push_back(
10485         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10486     // Put Cond in a virtual register to make it available from the new blocks.
10487     ExportFromCurrentBlock(Cond);
10488   }
10489 
10490   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10491   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10492   // directly if RHS.High equals the current upper bound.
10493   MachineBasicBlock *RightMBB;
10494   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10495       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10496     RightMBB = FirstRight->MBB;
10497   } else {
10498     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10499     FuncInfo.MF->insert(BBI, RightMBB);
10500     WorkList.push_back(
10501         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10502     // Put Cond in a virtual register to make it available from the new blocks.
10503     ExportFromCurrentBlock(Cond);
10504   }
10505 
10506   // Create the CaseBlock record that will be used to lower the branch.
10507   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10508                getCurSDLoc(), LeftProb, RightProb);
10509 
10510   if (W.MBB == SwitchMBB)
10511     visitSwitchCase(CB, SwitchMBB);
10512   else
10513     SL->SwitchCases.push_back(CB);
10514 }
10515 
10516 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10517 // from the swith statement.
10518 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10519                                             BranchProbability PeeledCaseProb) {
10520   if (PeeledCaseProb == BranchProbability::getOne())
10521     return BranchProbability::getZero();
10522   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10523 
10524   uint32_t Numerator = CaseProb.getNumerator();
10525   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10526   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10527 }
10528 
10529 // Try to peel the top probability case if it exceeds the threshold.
10530 // Return current MachineBasicBlock for the switch statement if the peeling
10531 // does not occur.
10532 // If the peeling is performed, return the newly created MachineBasicBlock
10533 // for the peeled switch statement. Also update Clusters to remove the peeled
10534 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10535 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10536     const SwitchInst &SI, CaseClusterVector &Clusters,
10537     BranchProbability &PeeledCaseProb) {
10538   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10539   // Don't perform if there is only one cluster or optimizing for size.
10540   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10541       TM.getOptLevel() == CodeGenOpt::None ||
10542       SwitchMBB->getParent()->getFunction().hasMinSize())
10543     return SwitchMBB;
10544 
10545   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10546   unsigned PeeledCaseIndex = 0;
10547   bool SwitchPeeled = false;
10548   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10549     CaseCluster &CC = Clusters[Index];
10550     if (CC.Prob < TopCaseProb)
10551       continue;
10552     TopCaseProb = CC.Prob;
10553     PeeledCaseIndex = Index;
10554     SwitchPeeled = true;
10555   }
10556   if (!SwitchPeeled)
10557     return SwitchMBB;
10558 
10559   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10560                     << TopCaseProb << "\n");
10561 
10562   // Record the MBB for the peeled switch statement.
10563   MachineFunction::iterator BBI(SwitchMBB);
10564   ++BBI;
10565   MachineBasicBlock *PeeledSwitchMBB =
10566       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10567   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10568 
10569   ExportFromCurrentBlock(SI.getCondition());
10570   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10571   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10572                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10573   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10574 
10575   Clusters.erase(PeeledCaseIt);
10576   for (CaseCluster &CC : Clusters) {
10577     LLVM_DEBUG(
10578         dbgs() << "Scale the probablity for one cluster, before scaling: "
10579                << CC.Prob << "\n");
10580     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10581     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10582   }
10583   PeeledCaseProb = TopCaseProb;
10584   return PeeledSwitchMBB;
10585 }
10586 
10587 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10588   // Extract cases from the switch.
10589   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10590   CaseClusterVector Clusters;
10591   Clusters.reserve(SI.getNumCases());
10592   for (auto I : SI.cases()) {
10593     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10594     const ConstantInt *CaseVal = I.getCaseValue();
10595     BranchProbability Prob =
10596         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10597             : BranchProbability(1, SI.getNumCases() + 1);
10598     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10599   }
10600 
10601   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10602 
10603   // Cluster adjacent cases with the same destination. We do this at all
10604   // optimization levels because it's cheap to do and will make codegen faster
10605   // if there are many clusters.
10606   sortAndRangeify(Clusters);
10607 
10608   // The branch probablity of the peeled case.
10609   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10610   MachineBasicBlock *PeeledSwitchMBB =
10611       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10612 
10613   // If there is only the default destination, jump there directly.
10614   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10615   if (Clusters.empty()) {
10616     assert(PeeledSwitchMBB == SwitchMBB);
10617     SwitchMBB->addSuccessor(DefaultMBB);
10618     if (DefaultMBB != NextBlock(SwitchMBB)) {
10619       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10620                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10621     }
10622     return;
10623   }
10624 
10625   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10626   SL->findBitTestClusters(Clusters, &SI);
10627 
10628   LLVM_DEBUG({
10629     dbgs() << "Case clusters: ";
10630     for (const CaseCluster &C : Clusters) {
10631       if (C.Kind == CC_JumpTable)
10632         dbgs() << "JT:";
10633       if (C.Kind == CC_BitTests)
10634         dbgs() << "BT:";
10635 
10636       C.Low->getValue().print(dbgs(), true);
10637       if (C.Low != C.High) {
10638         dbgs() << '-';
10639         C.High->getValue().print(dbgs(), true);
10640       }
10641       dbgs() << ' ';
10642     }
10643     dbgs() << '\n';
10644   });
10645 
10646   assert(!Clusters.empty());
10647   SwitchWorkList WorkList;
10648   CaseClusterIt First = Clusters.begin();
10649   CaseClusterIt Last = Clusters.end() - 1;
10650   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10651   // Scale the branchprobability for DefaultMBB if the peel occurs and
10652   // DefaultMBB is not replaced.
10653   if (PeeledCaseProb != BranchProbability::getZero() &&
10654       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10655     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10656   WorkList.push_back(
10657       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10658 
10659   while (!WorkList.empty()) {
10660     SwitchWorkListItem W = WorkList.back();
10661     WorkList.pop_back();
10662     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10663 
10664     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10665         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10666       // For optimized builds, lower large range as a balanced binary tree.
10667       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10668       continue;
10669     }
10670 
10671     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10672   }
10673 }
10674 
10675 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10676   SmallVector<EVT, 4> ValueVTs;
10677   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10678                   ValueVTs);
10679   unsigned NumValues = ValueVTs.size();
10680   if (NumValues == 0) return;
10681 
10682   SmallVector<SDValue, 4> Values(NumValues);
10683   SDValue Op = getValue(I.getOperand(0));
10684 
10685   for (unsigned i = 0; i != NumValues; ++i)
10686     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10687                             SDValue(Op.getNode(), Op.getResNo() + i));
10688 
10689   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10690                            DAG.getVTList(ValueVTs), Values));
10691 }
10692