xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 714ceefad9b96ab3ef20913f2110883a1ad34a13)
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 (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1124     // ConstrainedFPIntrinsics handle their own FMF.
1125     if (!isa<ConstrainedFPIntrinsic>(&I)) {
1126       // Propagate the fast-math-flags of this IR instruction to the DAG node that
1127       // maps to this instruction.
1128       // TODO: We could handle all flags (nsw, etc) here.
1129       // TODO: If an IR instruction maps to >1 node, only the final node will have
1130       //       flags set.
1131       // TODO: The handling of flags should be improved, see
1132       //       https://reviews.llvm.org/D86871
1133       if (SDNode *Node = getNodeForIRValue(&I)) {
1134         SDNodeFlags IncomingFlags;
1135         IncomingFlags.copyFMF(*FPMO);
1136         if (!Node->getFlags().isDefined())
1137           Node->setFlags(IncomingFlags);
1138         else
1139           Node->intersectFlagsWith(IncomingFlags);
1140       }
1141     }
1142   }
1143 
1144   if (!I.isTerminator() && !HasTailCall &&
1145       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1146     CopyToExportRegsIfNeeded(&I);
1147 
1148   CurInst = nullptr;
1149 }
1150 
1151 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1152   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1153 }
1154 
1155 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1156   // Note: this doesn't use InstVisitor, because it has to work with
1157   // ConstantExpr's in addition to instructions.
1158   switch (Opcode) {
1159   default: llvm_unreachable("Unknown instruction type encountered!");
1160     // Build the switch statement using the Instruction.def file.
1161 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1162     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1163 #include "llvm/IR/Instruction.def"
1164   }
1165 }
1166 
1167 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1168                                                 const DIExpression *Expr) {
1169   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1170     const DbgValueInst *DI = DDI.getDI();
1171     DIVariable *DanglingVariable = DI->getVariable();
1172     DIExpression *DanglingExpr = DI->getExpression();
1173     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1174       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1175       return true;
1176     }
1177     return false;
1178   };
1179 
1180   for (auto &DDIMI : DanglingDebugInfoMap) {
1181     DanglingDebugInfoVector &DDIV = DDIMI.second;
1182 
1183     // If debug info is to be dropped, run it through final checks to see
1184     // whether it can be salvaged.
1185     for (auto &DDI : DDIV)
1186       if (isMatchingDbgValue(DDI))
1187         salvageUnresolvedDbgValue(DDI);
1188 
1189     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1190   }
1191 }
1192 
1193 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1194 // generate the debug data structures now that we've seen its definition.
1195 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1196                                                    SDValue Val) {
1197   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1198   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1199     return;
1200 
1201   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1202   for (auto &DDI : DDIV) {
1203     const DbgValueInst *DI = DDI.getDI();
1204     assert(DI && "Ill-formed DanglingDebugInfo");
1205     DebugLoc dl = DDI.getdl();
1206     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1207     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1208     DILocalVariable *Variable = DI->getVariable();
1209     DIExpression *Expr = DI->getExpression();
1210     assert(Variable->isValidLocationForIntrinsic(dl) &&
1211            "Expected inlined-at fields to agree");
1212     SDDbgValue *SDV;
1213     if (Val.getNode()) {
1214       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1215       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1216       // we couldn't resolve it directly when examining the DbgValue intrinsic
1217       // in the first place we should not be more successful here). Unless we
1218       // have some test case that prove this to be correct we should avoid
1219       // calling EmitFuncArgumentDbgValue here.
1220       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1221         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1222                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1223         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1224         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1225         // inserted after the definition of Val when emitting the instructions
1226         // after ISel. An alternative could be to teach
1227         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1228         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1229                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1230                    << ValSDNodeOrder << "\n");
1231         SDV = getDbgValue(Val, Variable, Expr, dl,
1232                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1233         DAG.AddDbgValue(SDV, Val.getNode(), false);
1234       } else
1235         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1236                           << "in EmitFuncArgumentDbgValue\n");
1237     } else {
1238       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1239       auto Undef =
1240           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1241       auto SDV =
1242           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1243       DAG.AddDbgValue(SDV, nullptr, false);
1244     }
1245   }
1246   DDIV.clear();
1247 }
1248 
1249 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1250   Value *V = DDI.getDI()->getValue();
1251   DILocalVariable *Var = DDI.getDI()->getVariable();
1252   DIExpression *Expr = DDI.getDI()->getExpression();
1253   DebugLoc DL = DDI.getdl();
1254   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1255   unsigned SDOrder = DDI.getSDNodeOrder();
1256 
1257   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1258   // that DW_OP_stack_value is desired.
1259   assert(isa<DbgValueInst>(DDI.getDI()));
1260   bool StackValue = true;
1261 
1262   // Can this Value can be encoded without any further work?
1263   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1264     return;
1265 
1266   // Attempt to salvage back through as many instructions as possible. Bail if
1267   // a non-instruction is seen, such as a constant expression or global
1268   // variable. FIXME: Further work could recover those too.
1269   while (isa<Instruction>(V)) {
1270     Instruction &VAsInst = *cast<Instruction>(V);
1271     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1272 
1273     // If we cannot salvage any further, and haven't yet found a suitable debug
1274     // expression, bail out.
1275     if (!NewExpr)
1276       break;
1277 
1278     // New value and expr now represent this debuginfo.
1279     V = VAsInst.getOperand(0);
1280     Expr = NewExpr;
1281 
1282     // Some kind of simplification occurred: check whether the operand of the
1283     // salvaged debug expression can be encoded in this DAG.
1284     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1285       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1286                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1287       return;
1288     }
1289   }
1290 
1291   // This was the final opportunity to salvage this debug information, and it
1292   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1293   // any earlier variable location.
1294   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1295   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1296   DAG.AddDbgValue(SDV, nullptr, false);
1297 
1298   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1299                     << "\n");
1300   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1301                     << "\n");
1302 }
1303 
1304 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1305                                            DIExpression *Expr, DebugLoc dl,
1306                                            DebugLoc InstDL, unsigned Order) {
1307   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1308   SDDbgValue *SDV;
1309   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1310       isa<ConstantPointerNull>(V)) {
1311     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1312     DAG.AddDbgValue(SDV, nullptr, false);
1313     return true;
1314   }
1315 
1316   // If the Value is a frame index, we can create a FrameIndex debug value
1317   // without relying on the DAG at all.
1318   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1319     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1320     if (SI != FuncInfo.StaticAllocaMap.end()) {
1321       auto SDV =
1322           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1323                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1324       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1325       // is still available even if the SDNode gets optimized out.
1326       DAG.AddDbgValue(SDV, nullptr, false);
1327       return true;
1328     }
1329   }
1330 
1331   // Do not use getValue() in here; we don't want to generate code at
1332   // this point if it hasn't been done yet.
1333   SDValue N = NodeMap[V];
1334   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1335     N = UnusedArgNodeMap[V];
1336   if (N.getNode()) {
1337     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1338       return true;
1339     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1340     DAG.AddDbgValue(SDV, N.getNode(), false);
1341     return true;
1342   }
1343 
1344   // Special rules apply for the first dbg.values of parameter variables in a
1345   // function. Identify them by the fact they reference Argument Values, that
1346   // they're parameters, and they are parameters of the current function. We
1347   // need to let them dangle until they get an SDNode.
1348   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1349                        !InstDL.getInlinedAt();
1350   if (!IsParamOfFunc) {
1351     // The value is not used in this block yet (or it would have an SDNode).
1352     // We still want the value to appear for the user if possible -- if it has
1353     // an associated VReg, we can refer to that instead.
1354     auto VMI = FuncInfo.ValueMap.find(V);
1355     if (VMI != FuncInfo.ValueMap.end()) {
1356       unsigned Reg = VMI->second;
1357       // If this is a PHI node, it may be split up into several MI PHI nodes
1358       // (in FunctionLoweringInfo::set).
1359       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1360                        V->getType(), None);
1361       if (RFV.occupiesMultipleRegs()) {
1362         unsigned Offset = 0;
1363         unsigned BitsToDescribe = 0;
1364         if (auto VarSize = Var->getSizeInBits())
1365           BitsToDescribe = *VarSize;
1366         if (auto Fragment = Expr->getFragmentInfo())
1367           BitsToDescribe = Fragment->SizeInBits;
1368         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1369           unsigned RegisterSize = RegAndSize.second;
1370           // Bail out if all bits are described already.
1371           if (Offset >= BitsToDescribe)
1372             break;
1373           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1374               ? BitsToDescribe - Offset
1375               : RegisterSize;
1376           auto FragmentExpr = DIExpression::createFragmentExpression(
1377               Expr, Offset, FragmentSize);
1378           if (!FragmentExpr)
1379               continue;
1380           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1381                                     false, dl, SDNodeOrder);
1382           DAG.AddDbgValue(SDV, nullptr, false);
1383           Offset += RegisterSize;
1384         }
1385       } else {
1386         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1387         DAG.AddDbgValue(SDV, nullptr, false);
1388       }
1389       return true;
1390     }
1391   }
1392 
1393   return false;
1394 }
1395 
1396 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1397   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1398   for (auto &Pair : DanglingDebugInfoMap)
1399     for (auto &DDI : Pair.second)
1400       salvageUnresolvedDbgValue(DDI);
1401   clearDanglingDebugInfo();
1402 }
1403 
1404 /// getCopyFromRegs - If there was virtual register allocated for the value V
1405 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1406 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1407   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1408   SDValue Result;
1409 
1410   if (It != FuncInfo.ValueMap.end()) {
1411     Register InReg = It->second;
1412 
1413     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1414                      DAG.getDataLayout(), InReg, Ty,
1415                      None); // This is not an ABI copy.
1416     SDValue Chain = DAG.getEntryNode();
1417     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1418                                  V);
1419     resolveDanglingDebugInfo(V, Result);
1420   }
1421 
1422   return Result;
1423 }
1424 
1425 /// getValue - Return an SDValue for the given Value.
1426 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1427   // If we already have an SDValue for this value, use it. It's important
1428   // to do this first, so that we don't create a CopyFromReg if we already
1429   // have a regular SDValue.
1430   SDValue &N = NodeMap[V];
1431   if (N.getNode()) return N;
1432 
1433   // If there's a virtual register allocated and initialized for this
1434   // value, use it.
1435   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1436     return copyFromReg;
1437 
1438   // Otherwise create a new SDValue and remember it.
1439   SDValue Val = getValueImpl(V);
1440   NodeMap[V] = Val;
1441   resolveDanglingDebugInfo(V, Val);
1442   return Val;
1443 }
1444 
1445 /// getNonRegisterValue - Return an SDValue for the given Value, but
1446 /// don't look in FuncInfo.ValueMap for a virtual register.
1447 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1448   // If we already have an SDValue for this value, use it.
1449   SDValue &N = NodeMap[V];
1450   if (N.getNode()) {
1451     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1452       // Remove the debug location from the node as the node is about to be used
1453       // in a location which may differ from the original debug location.  This
1454       // is relevant to Constant and ConstantFP nodes because they can appear
1455       // as constant expressions inside PHI nodes.
1456       N->setDebugLoc(DebugLoc());
1457     }
1458     return N;
1459   }
1460 
1461   // Otherwise create a new SDValue and remember it.
1462   SDValue Val = getValueImpl(V);
1463   NodeMap[V] = Val;
1464   resolveDanglingDebugInfo(V, Val);
1465   return Val;
1466 }
1467 
1468 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1469 /// Create an SDValue for the given value.
1470 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1471   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1472 
1473   if (const Constant *C = dyn_cast<Constant>(V)) {
1474     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1475 
1476     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1477       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1478 
1479     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1480       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1481 
1482     if (isa<ConstantPointerNull>(C)) {
1483       unsigned AS = V->getType()->getPointerAddressSpace();
1484       return DAG.getConstant(0, getCurSDLoc(),
1485                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1486     }
1487 
1488     if (match(C, m_VScale(DAG.getDataLayout())))
1489       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1490 
1491     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1492       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1493 
1494     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1495       return DAG.getUNDEF(VT);
1496 
1497     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1498       visit(CE->getOpcode(), *CE);
1499       SDValue N1 = NodeMap[V];
1500       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1501       return N1;
1502     }
1503 
1504     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1505       SmallVector<SDValue, 4> Constants;
1506       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1507            OI != OE; ++OI) {
1508         SDNode *Val = getValue(*OI).getNode();
1509         // If the operand is an empty aggregate, there are no values.
1510         if (!Val) continue;
1511         // Add each leaf value from the operand to the Constants list
1512         // to form a flattened list of all the values.
1513         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1514           Constants.push_back(SDValue(Val, i));
1515       }
1516 
1517       return DAG.getMergeValues(Constants, getCurSDLoc());
1518     }
1519 
1520     if (const ConstantDataSequential *CDS =
1521           dyn_cast<ConstantDataSequential>(C)) {
1522       SmallVector<SDValue, 4> Ops;
1523       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1524         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1525         // Add each leaf value from the operand to the Constants list
1526         // to form a flattened list of all the values.
1527         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1528           Ops.push_back(SDValue(Val, i));
1529       }
1530 
1531       if (isa<ArrayType>(CDS->getType()))
1532         return DAG.getMergeValues(Ops, getCurSDLoc());
1533       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1534     }
1535 
1536     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1537       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1538              "Unknown struct or array constant!");
1539 
1540       SmallVector<EVT, 4> ValueVTs;
1541       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1542       unsigned NumElts = ValueVTs.size();
1543       if (NumElts == 0)
1544         return SDValue(); // empty struct
1545       SmallVector<SDValue, 4> Constants(NumElts);
1546       for (unsigned i = 0; i != NumElts; ++i) {
1547         EVT EltVT = ValueVTs[i];
1548         if (isa<UndefValue>(C))
1549           Constants[i] = DAG.getUNDEF(EltVT);
1550         else if (EltVT.isFloatingPoint())
1551           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1552         else
1553           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1554       }
1555 
1556       return DAG.getMergeValues(Constants, getCurSDLoc());
1557     }
1558 
1559     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1560       return DAG.getBlockAddress(BA, VT);
1561 
1562     VectorType *VecTy = cast<VectorType>(V->getType());
1563 
1564     // Now that we know the number and type of the elements, get that number of
1565     // elements into the Ops array based on what kind of constant it is.
1566     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1567       SmallVector<SDValue, 16> Ops;
1568       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1569       for (unsigned i = 0; i != NumElements; ++i)
1570         Ops.push_back(getValue(CV->getOperand(i)));
1571 
1572       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1573     } else if (isa<ConstantAggregateZero>(C)) {
1574       EVT EltVT =
1575           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1576 
1577       SDValue Op;
1578       if (EltVT.isFloatingPoint())
1579         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1580       else
1581         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1582 
1583       if (isa<ScalableVectorType>(VecTy))
1584         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1585       else {
1586         SmallVector<SDValue, 16> Ops;
1587         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1588         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1589       }
1590     }
1591     llvm_unreachable("Unknown vector constant");
1592   }
1593 
1594   // If this is a static alloca, generate it as the frameindex instead of
1595   // computation.
1596   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1597     DenseMap<const AllocaInst*, int>::iterator SI =
1598       FuncInfo.StaticAllocaMap.find(AI);
1599     if (SI != FuncInfo.StaticAllocaMap.end())
1600       return DAG.getFrameIndex(SI->second,
1601                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1602   }
1603 
1604   // If this is an instruction which fast-isel has deferred, select it now.
1605   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1606     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1607 
1608     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1609                      Inst->getType(), getABIRegCopyCC(V));
1610     SDValue Chain = DAG.getEntryNode();
1611     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1612   }
1613 
1614   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1615     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1616   }
1617   llvm_unreachable("Can't get register for value!");
1618 }
1619 
1620 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1621   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1622   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1623   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1624   bool IsSEH = isAsynchronousEHPersonality(Pers);
1625   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1626   if (!IsSEH)
1627     CatchPadMBB->setIsEHScopeEntry();
1628   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1629   if (IsMSVCCXX || IsCoreCLR)
1630     CatchPadMBB->setIsEHFuncletEntry();
1631 }
1632 
1633 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1634   // Update machine-CFG edge.
1635   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1636   FuncInfo.MBB->addSuccessor(TargetMBB);
1637 
1638   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1639   bool IsSEH = isAsynchronousEHPersonality(Pers);
1640   if (IsSEH) {
1641     // If this is not a fall-through branch or optimizations are switched off,
1642     // emit the branch.
1643     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1644         TM.getOptLevel() == CodeGenOpt::None)
1645       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1646                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1647     return;
1648   }
1649 
1650   // Figure out the funclet membership for the catchret's successor.
1651   // This will be used by the FuncletLayout pass to determine how to order the
1652   // BB's.
1653   // A 'catchret' returns to the outer scope's color.
1654   Value *ParentPad = I.getCatchSwitchParentPad();
1655   const BasicBlock *SuccessorColor;
1656   if (isa<ConstantTokenNone>(ParentPad))
1657     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1658   else
1659     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1660   assert(SuccessorColor && "No parent funclet for catchret!");
1661   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1662   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1663 
1664   // Create the terminator node.
1665   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1666                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1667                             DAG.getBasicBlock(SuccessorColorMBB));
1668   DAG.setRoot(Ret);
1669 }
1670 
1671 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1672   // Don't emit any special code for the cleanuppad instruction. It just marks
1673   // the start of an EH scope/funclet.
1674   FuncInfo.MBB->setIsEHScopeEntry();
1675   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1676   if (Pers != EHPersonality::Wasm_CXX) {
1677     FuncInfo.MBB->setIsEHFuncletEntry();
1678     FuncInfo.MBB->setIsCleanupFuncletEntry();
1679   }
1680 }
1681 
1682 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1683 // the control flow always stops at the single catch pad, as it does for a
1684 // cleanup pad. In case the exception caught is not of the types the catch pad
1685 // catches, it will be rethrown by a rethrow.
1686 static void findWasmUnwindDestinations(
1687     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1688     BranchProbability Prob,
1689     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1690         &UnwindDests) {
1691   while (EHPadBB) {
1692     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1693     if (isa<CleanupPadInst>(Pad)) {
1694       // Stop on cleanup pads.
1695       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1696       UnwindDests.back().first->setIsEHScopeEntry();
1697       break;
1698     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1699       // Add the catchpad handlers to the possible destinations. We don't
1700       // continue to the unwind destination of the catchswitch for wasm.
1701       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1702         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1703         UnwindDests.back().first->setIsEHScopeEntry();
1704       }
1705       break;
1706     } else {
1707       continue;
1708     }
1709   }
1710 }
1711 
1712 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1713 /// many places it could ultimately go. In the IR, we have a single unwind
1714 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1715 /// This function skips over imaginary basic blocks that hold catchswitch
1716 /// instructions, and finds all the "real" machine
1717 /// basic block destinations. As those destinations may not be successors of
1718 /// EHPadBB, here we also calculate the edge probability to those destinations.
1719 /// The passed-in Prob is the edge probability to EHPadBB.
1720 static void findUnwindDestinations(
1721     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1722     BranchProbability Prob,
1723     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1724         &UnwindDests) {
1725   EHPersonality Personality =
1726     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1727   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1728   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1729   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1730   bool IsSEH = isAsynchronousEHPersonality(Personality);
1731 
1732   if (IsWasmCXX) {
1733     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1734     assert(UnwindDests.size() <= 1 &&
1735            "There should be at most one unwind destination for wasm");
1736     return;
1737   }
1738 
1739   while (EHPadBB) {
1740     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1741     BasicBlock *NewEHPadBB = nullptr;
1742     if (isa<LandingPadInst>(Pad)) {
1743       // Stop on landingpads. They are not funclets.
1744       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1745       break;
1746     } else if (isa<CleanupPadInst>(Pad)) {
1747       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1748       // personalities.
1749       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1750       UnwindDests.back().first->setIsEHScopeEntry();
1751       UnwindDests.back().first->setIsEHFuncletEntry();
1752       break;
1753     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1754       // Add the catchpad handlers to the possible destinations.
1755       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1756         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1757         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1758         if (IsMSVCCXX || IsCoreCLR)
1759           UnwindDests.back().first->setIsEHFuncletEntry();
1760         if (!IsSEH)
1761           UnwindDests.back().first->setIsEHScopeEntry();
1762       }
1763       NewEHPadBB = CatchSwitch->getUnwindDest();
1764     } else {
1765       continue;
1766     }
1767 
1768     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1769     if (BPI && NewEHPadBB)
1770       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1771     EHPadBB = NewEHPadBB;
1772   }
1773 }
1774 
1775 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1776   // Update successor info.
1777   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1778   auto UnwindDest = I.getUnwindDest();
1779   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1780   BranchProbability UnwindDestProb =
1781       (BPI && UnwindDest)
1782           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1783           : BranchProbability::getZero();
1784   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1785   for (auto &UnwindDest : UnwindDests) {
1786     UnwindDest.first->setIsEHPad();
1787     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1788   }
1789   FuncInfo.MBB->normalizeSuccProbs();
1790 
1791   // Create the terminator node.
1792   SDValue Ret =
1793       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1794   DAG.setRoot(Ret);
1795 }
1796 
1797 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1798   report_fatal_error("visitCatchSwitch not yet implemented!");
1799 }
1800 
1801 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1802   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1803   auto &DL = DAG.getDataLayout();
1804   SDValue Chain = getControlRoot();
1805   SmallVector<ISD::OutputArg, 8> Outs;
1806   SmallVector<SDValue, 8> OutVals;
1807 
1808   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1809   // lower
1810   //
1811   //   %val = call <ty> @llvm.experimental.deoptimize()
1812   //   ret <ty> %val
1813   //
1814   // differently.
1815   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1816     LowerDeoptimizingReturn();
1817     return;
1818   }
1819 
1820   if (!FuncInfo.CanLowerReturn) {
1821     unsigned DemoteReg = FuncInfo.DemoteRegister;
1822     const Function *F = I.getParent()->getParent();
1823 
1824     // Emit a store of the return value through the virtual register.
1825     // Leave Outs empty so that LowerReturn won't try to load return
1826     // registers the usual way.
1827     SmallVector<EVT, 1> PtrValueVTs;
1828     ComputeValueVTs(TLI, DL,
1829                     F->getReturnType()->getPointerTo(
1830                         DAG.getDataLayout().getAllocaAddrSpace()),
1831                     PtrValueVTs);
1832 
1833     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1834                                         DemoteReg, PtrValueVTs[0]);
1835     SDValue RetOp = getValue(I.getOperand(0));
1836 
1837     SmallVector<EVT, 4> ValueVTs, MemVTs;
1838     SmallVector<uint64_t, 4> Offsets;
1839     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1840                     &Offsets);
1841     unsigned NumValues = ValueVTs.size();
1842 
1843     SmallVector<SDValue, 4> Chains(NumValues);
1844     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1845     for (unsigned i = 0; i != NumValues; ++i) {
1846       // An aggregate return value cannot wrap around the address space, so
1847       // offsets to its parts don't wrap either.
1848       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1849                                            TypeSize::Fixed(Offsets[i]));
1850 
1851       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1852       if (MemVTs[i] != ValueVTs[i])
1853         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1854       Chains[i] = DAG.getStore(
1855           Chain, getCurSDLoc(), Val,
1856           // FIXME: better loc info would be nice.
1857           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1858           commonAlignment(BaseAlign, Offsets[i]));
1859     }
1860 
1861     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1862                         MVT::Other, Chains);
1863   } else if (I.getNumOperands() != 0) {
1864     SmallVector<EVT, 4> ValueVTs;
1865     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1866     unsigned NumValues = ValueVTs.size();
1867     if (NumValues) {
1868       SDValue RetOp = getValue(I.getOperand(0));
1869 
1870       const Function *F = I.getParent()->getParent();
1871 
1872       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1873           I.getOperand(0)->getType(), F->getCallingConv(),
1874           /*IsVarArg*/ false);
1875 
1876       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1877       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1878                                           Attribute::SExt))
1879         ExtendKind = ISD::SIGN_EXTEND;
1880       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1881                                                Attribute::ZExt))
1882         ExtendKind = ISD::ZERO_EXTEND;
1883 
1884       LLVMContext &Context = F->getContext();
1885       bool RetInReg = F->getAttributes().hasAttribute(
1886           AttributeList::ReturnIndex, Attribute::InReg);
1887 
1888       for (unsigned j = 0; j != NumValues; ++j) {
1889         EVT VT = ValueVTs[j];
1890 
1891         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1892           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1893 
1894         CallingConv::ID CC = F->getCallingConv();
1895 
1896         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1897         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1898         SmallVector<SDValue, 4> Parts(NumParts);
1899         getCopyToParts(DAG, getCurSDLoc(),
1900                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1901                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1902 
1903         // 'inreg' on function refers to return value
1904         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1905         if (RetInReg)
1906           Flags.setInReg();
1907 
1908         if (I.getOperand(0)->getType()->isPointerTy()) {
1909           Flags.setPointer();
1910           Flags.setPointerAddrSpace(
1911               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1912         }
1913 
1914         if (NeedsRegBlock) {
1915           Flags.setInConsecutiveRegs();
1916           if (j == NumValues - 1)
1917             Flags.setInConsecutiveRegsLast();
1918         }
1919 
1920         // Propagate extension type if any
1921         if (ExtendKind == ISD::SIGN_EXTEND)
1922           Flags.setSExt();
1923         else if (ExtendKind == ISD::ZERO_EXTEND)
1924           Flags.setZExt();
1925 
1926         for (unsigned i = 0; i < NumParts; ++i) {
1927           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1928                                         VT, /*isfixed=*/true, 0, 0));
1929           OutVals.push_back(Parts[i]);
1930         }
1931       }
1932     }
1933   }
1934 
1935   // Push in swifterror virtual register as the last element of Outs. This makes
1936   // sure swifterror virtual register will be returned in the swifterror
1937   // physical register.
1938   const Function *F = I.getParent()->getParent();
1939   if (TLI.supportSwiftError() &&
1940       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1941     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1942     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1943     Flags.setSwiftError();
1944     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1945                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1946                                   true /*isfixed*/, 1 /*origidx*/,
1947                                   0 /*partOffs*/));
1948     // Create SDNode for the swifterror virtual register.
1949     OutVals.push_back(
1950         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1951                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1952                         EVT(TLI.getPointerTy(DL))));
1953   }
1954 
1955   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1956   CallingConv::ID CallConv =
1957     DAG.getMachineFunction().getFunction().getCallingConv();
1958   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1959       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1960 
1961   // Verify that the target's LowerReturn behaved as expected.
1962   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1963          "LowerReturn didn't return a valid chain!");
1964 
1965   // Update the DAG with the new chain value resulting from return lowering.
1966   DAG.setRoot(Chain);
1967 }
1968 
1969 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1970 /// created for it, emit nodes to copy the value into the virtual
1971 /// registers.
1972 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1973   // Skip empty types
1974   if (V->getType()->isEmptyTy())
1975     return;
1976 
1977   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
1978   if (VMI != FuncInfo.ValueMap.end()) {
1979     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1980     CopyValueToVirtualRegister(V, VMI->second);
1981   }
1982 }
1983 
1984 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1985 /// the current basic block, add it to ValueMap now so that we'll get a
1986 /// CopyTo/FromReg.
1987 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1988   // No need to export constants.
1989   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1990 
1991   // Already exported?
1992   if (FuncInfo.isExportedInst(V)) return;
1993 
1994   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1995   CopyValueToVirtualRegister(V, Reg);
1996 }
1997 
1998 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1999                                                      const BasicBlock *FromBB) {
2000   // The operands of the setcc have to be in this block.  We don't know
2001   // how to export them from some other block.
2002   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2003     // Can export from current BB.
2004     if (VI->getParent() == FromBB)
2005       return true;
2006 
2007     // Is already exported, noop.
2008     return FuncInfo.isExportedInst(V);
2009   }
2010 
2011   // If this is an argument, we can export it if the BB is the entry block or
2012   // if it is already exported.
2013   if (isa<Argument>(V)) {
2014     if (FromBB == &FromBB->getParent()->getEntryBlock())
2015       return true;
2016 
2017     // Otherwise, can only export this if it is already exported.
2018     return FuncInfo.isExportedInst(V);
2019   }
2020 
2021   // Otherwise, constants can always be exported.
2022   return true;
2023 }
2024 
2025 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2026 BranchProbability
2027 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2028                                         const MachineBasicBlock *Dst) const {
2029   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2030   const BasicBlock *SrcBB = Src->getBasicBlock();
2031   const BasicBlock *DstBB = Dst->getBasicBlock();
2032   if (!BPI) {
2033     // If BPI is not available, set the default probability as 1 / N, where N is
2034     // the number of successors.
2035     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2036     return BranchProbability(1, SuccSize);
2037   }
2038   return BPI->getEdgeProbability(SrcBB, DstBB);
2039 }
2040 
2041 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2042                                                MachineBasicBlock *Dst,
2043                                                BranchProbability Prob) {
2044   if (!FuncInfo.BPI)
2045     Src->addSuccessorWithoutProb(Dst);
2046   else {
2047     if (Prob.isUnknown())
2048       Prob = getEdgeProbability(Src, Dst);
2049     Src->addSuccessor(Dst, Prob);
2050   }
2051 }
2052 
2053 static bool InBlock(const Value *V, const BasicBlock *BB) {
2054   if (const Instruction *I = dyn_cast<Instruction>(V))
2055     return I->getParent() == BB;
2056   return true;
2057 }
2058 
2059 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2060 /// This function emits a branch and is used at the leaves of an OR or an
2061 /// AND operator tree.
2062 void
2063 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2064                                                   MachineBasicBlock *TBB,
2065                                                   MachineBasicBlock *FBB,
2066                                                   MachineBasicBlock *CurBB,
2067                                                   MachineBasicBlock *SwitchBB,
2068                                                   BranchProbability TProb,
2069                                                   BranchProbability FProb,
2070                                                   bool InvertCond) {
2071   const BasicBlock *BB = CurBB->getBasicBlock();
2072 
2073   // If the leaf of the tree is a comparison, merge the condition into
2074   // the caseblock.
2075   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2076     // The operands of the cmp have to be in this block.  We don't know
2077     // how to export them from some other block.  If this is the first block
2078     // of the sequence, no exporting is needed.
2079     if (CurBB == SwitchBB ||
2080         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2081          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2082       ISD::CondCode Condition;
2083       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2084         ICmpInst::Predicate Pred =
2085             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2086         Condition = getICmpCondCode(Pred);
2087       } else {
2088         const FCmpInst *FC = cast<FCmpInst>(Cond);
2089         FCmpInst::Predicate Pred =
2090             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2091         Condition = getFCmpCondCode(Pred);
2092         if (TM.Options.NoNaNsFPMath)
2093           Condition = getFCmpCodeWithoutNaN(Condition);
2094       }
2095 
2096       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2097                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2098       SL->SwitchCases.push_back(CB);
2099       return;
2100     }
2101   }
2102 
2103   // Create a CaseBlock record representing this branch.
2104   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2105   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2106                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2107   SL->SwitchCases.push_back(CB);
2108 }
2109 
2110 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2111                                                MachineBasicBlock *TBB,
2112                                                MachineBasicBlock *FBB,
2113                                                MachineBasicBlock *CurBB,
2114                                                MachineBasicBlock *SwitchBB,
2115                                                Instruction::BinaryOps Opc,
2116                                                BranchProbability TProb,
2117                                                BranchProbability FProb,
2118                                                bool InvertCond) {
2119   // Skip over not part of the tree and remember to invert op and operands at
2120   // next level.
2121   Value *NotCond;
2122   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2123       InBlock(NotCond, CurBB->getBasicBlock())) {
2124     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2125                          !InvertCond);
2126     return;
2127   }
2128 
2129   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2130   // Compute the effective opcode for Cond, taking into account whether it needs
2131   // to be inverted, e.g.
2132   //   and (not (or A, B)), C
2133   // gets lowered as
2134   //   and (and (not A, not B), C)
2135   unsigned BOpc = 0;
2136   if (BOp) {
2137     BOpc = BOp->getOpcode();
2138     if (InvertCond) {
2139       if (BOpc == Instruction::And)
2140         BOpc = Instruction::Or;
2141       else if (BOpc == Instruction::Or)
2142         BOpc = Instruction::And;
2143     }
2144   }
2145 
2146   // If this node is not part of the or/and tree, emit it as a branch.
2147   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2148       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2149       BOp->getParent() != CurBB->getBasicBlock() ||
2150       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2151       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2152     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2153                                  TProb, FProb, InvertCond);
2154     return;
2155   }
2156 
2157   //  Create TmpBB after CurBB.
2158   MachineFunction::iterator BBI(CurBB);
2159   MachineFunction &MF = DAG.getMachineFunction();
2160   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2161   CurBB->getParent()->insert(++BBI, TmpBB);
2162 
2163   if (Opc == Instruction::Or) {
2164     // Codegen X | Y as:
2165     // BB1:
2166     //   jmp_if_X TBB
2167     //   jmp TmpBB
2168     // TmpBB:
2169     //   jmp_if_Y TBB
2170     //   jmp FBB
2171     //
2172 
2173     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2174     // The requirement is that
2175     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2176     //     = TrueProb for original BB.
2177     // Assuming the original probabilities are A and B, one choice is to set
2178     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2179     // A/(1+B) and 2B/(1+B). This choice assumes that
2180     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2181     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2182     // TmpBB, but the math is more complicated.
2183 
2184     auto NewTrueProb = TProb / 2;
2185     auto NewFalseProb = TProb / 2 + FProb;
2186     // Emit the LHS condition.
2187     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2188                          NewTrueProb, NewFalseProb, InvertCond);
2189 
2190     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2191     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2192     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2193     // Emit the RHS condition into TmpBB.
2194     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2195                          Probs[0], Probs[1], InvertCond);
2196   } else {
2197     assert(Opc == Instruction::And && "Unknown merge op!");
2198     // Codegen X & Y as:
2199     // BB1:
2200     //   jmp_if_X TmpBB
2201     //   jmp FBB
2202     // TmpBB:
2203     //   jmp_if_Y TBB
2204     //   jmp FBB
2205     //
2206     //  This requires creation of TmpBB after CurBB.
2207 
2208     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2209     // The requirement is that
2210     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2211     //     = FalseProb for original BB.
2212     // Assuming the original probabilities are A and B, one choice is to set
2213     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2214     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2215     // TrueProb for BB1 * FalseProb for TmpBB.
2216 
2217     auto NewTrueProb = TProb + FProb / 2;
2218     auto NewFalseProb = FProb / 2;
2219     // Emit the LHS condition.
2220     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2221                          NewTrueProb, NewFalseProb, InvertCond);
2222 
2223     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2224     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2225     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2226     // Emit the RHS condition into TmpBB.
2227     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2228                          Probs[0], Probs[1], InvertCond);
2229   }
2230 }
2231 
2232 /// If the set of cases should be emitted as a series of branches, return true.
2233 /// If we should emit this as a bunch of and/or'd together conditions, return
2234 /// false.
2235 bool
2236 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2237   if (Cases.size() != 2) return true;
2238 
2239   // If this is two comparisons of the same values or'd or and'd together, they
2240   // will get folded into a single comparison, so don't emit two blocks.
2241   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2242        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2243       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2244        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2245     return false;
2246   }
2247 
2248   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2249   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2250   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2251       Cases[0].CC == Cases[1].CC &&
2252       isa<Constant>(Cases[0].CmpRHS) &&
2253       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2254     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2255       return false;
2256     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2257       return false;
2258   }
2259 
2260   return true;
2261 }
2262 
2263 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2264   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2265 
2266   // Update machine-CFG edges.
2267   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2268 
2269   if (I.isUnconditional()) {
2270     // Update machine-CFG edges.
2271     BrMBB->addSuccessor(Succ0MBB);
2272 
2273     // If this is not a fall-through branch or optimizations are switched off,
2274     // emit the branch.
2275     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2276       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2277                               MVT::Other, getControlRoot(),
2278                               DAG.getBasicBlock(Succ0MBB)));
2279 
2280     return;
2281   }
2282 
2283   // If this condition is one of the special cases we handle, do special stuff
2284   // now.
2285   const Value *CondVal = I.getCondition();
2286   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2287 
2288   // If this is a series of conditions that are or'd or and'd together, emit
2289   // this as a sequence of branches instead of setcc's with and/or operations.
2290   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2291   // unpredictable branches, and vector extracts because those jumps are likely
2292   // expensive for any target), this should improve performance.
2293   // For example, instead of something like:
2294   //     cmp A, B
2295   //     C = seteq
2296   //     cmp D, E
2297   //     F = setle
2298   //     or C, F
2299   //     jnz foo
2300   // Emit:
2301   //     cmp A, B
2302   //     je foo
2303   //     cmp D, E
2304   //     jle foo
2305   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2306     Instruction::BinaryOps Opcode = BOp->getOpcode();
2307     Value *Vec, *BOp0 = BOp->getOperand(0), *BOp1 = BOp->getOperand(1);
2308     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2309         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2310         (Opcode == Instruction::And || Opcode == Instruction::Or) &&
2311         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2312           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2313       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2314                            Opcode,
2315                            getEdgeProbability(BrMBB, Succ0MBB),
2316                            getEdgeProbability(BrMBB, Succ1MBB),
2317                            /*InvertCond=*/false);
2318       // If the compares in later blocks need to use values not currently
2319       // exported from this block, export them now.  This block should always
2320       // be the first entry.
2321       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2322 
2323       // Allow some cases to be rejected.
2324       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2325         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2326           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2327           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2328         }
2329 
2330         // Emit the branch for this block.
2331         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2332         SL->SwitchCases.erase(SL->SwitchCases.begin());
2333         return;
2334       }
2335 
2336       // Okay, we decided not to do this, remove any inserted MBB's and clear
2337       // SwitchCases.
2338       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2339         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2340 
2341       SL->SwitchCases.clear();
2342     }
2343   }
2344 
2345   // Create a CaseBlock record representing this branch.
2346   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2347                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2348 
2349   // Use visitSwitchCase to actually insert the fast branch sequence for this
2350   // cond branch.
2351   visitSwitchCase(CB, BrMBB);
2352 }
2353 
2354 /// visitSwitchCase - Emits the necessary code to represent a single node in
2355 /// the binary search tree resulting from lowering a switch instruction.
2356 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2357                                           MachineBasicBlock *SwitchBB) {
2358   SDValue Cond;
2359   SDValue CondLHS = getValue(CB.CmpLHS);
2360   SDLoc dl = CB.DL;
2361 
2362   if (CB.CC == ISD::SETTRUE) {
2363     // Branch or fall through to TrueBB.
2364     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2365     SwitchBB->normalizeSuccProbs();
2366     if (CB.TrueBB != NextBlock(SwitchBB)) {
2367       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2368                               DAG.getBasicBlock(CB.TrueBB)));
2369     }
2370     return;
2371   }
2372 
2373   auto &TLI = DAG.getTargetLoweringInfo();
2374   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2375 
2376   // Build the setcc now.
2377   if (!CB.CmpMHS) {
2378     // Fold "(X == true)" to X and "(X == false)" to !X to
2379     // handle common cases produced by branch lowering.
2380     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2381         CB.CC == ISD::SETEQ)
2382       Cond = CondLHS;
2383     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2384              CB.CC == ISD::SETEQ) {
2385       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2386       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2387     } else {
2388       SDValue CondRHS = getValue(CB.CmpRHS);
2389 
2390       // If a pointer's DAG type is larger than its memory type then the DAG
2391       // values are zero-extended. This breaks signed comparisons so truncate
2392       // back to the underlying type before doing the compare.
2393       if (CondLHS.getValueType() != MemVT) {
2394         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2395         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2396       }
2397       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2398     }
2399   } else {
2400     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2401 
2402     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2403     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2404 
2405     SDValue CmpOp = getValue(CB.CmpMHS);
2406     EVT VT = CmpOp.getValueType();
2407 
2408     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2409       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2410                           ISD::SETLE);
2411     } else {
2412       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2413                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2414       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2415                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2416     }
2417   }
2418 
2419   // Update successor info
2420   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2421   // TrueBB and FalseBB are always different unless the incoming IR is
2422   // degenerate. This only happens when running llc on weird IR.
2423   if (CB.TrueBB != CB.FalseBB)
2424     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2425   SwitchBB->normalizeSuccProbs();
2426 
2427   // If the lhs block is the next block, invert the condition so that we can
2428   // fall through to the lhs instead of the rhs block.
2429   if (CB.TrueBB == NextBlock(SwitchBB)) {
2430     std::swap(CB.TrueBB, CB.FalseBB);
2431     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2432     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2433   }
2434 
2435   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2436                                MVT::Other, getControlRoot(), Cond,
2437                                DAG.getBasicBlock(CB.TrueBB));
2438 
2439   // Insert the false branch. Do this even if it's a fall through branch,
2440   // this makes it easier to do DAG optimizations which require inverting
2441   // the branch condition.
2442   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2443                        DAG.getBasicBlock(CB.FalseBB));
2444 
2445   DAG.setRoot(BrCond);
2446 }
2447 
2448 /// visitJumpTable - Emit JumpTable node in the current MBB
2449 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2450   // Emit the code for the jump table
2451   assert(JT.Reg != -1U && "Should lower JT Header first!");
2452   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2453   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2454                                      JT.Reg, PTy);
2455   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2456   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2457                                     MVT::Other, Index.getValue(1),
2458                                     Table, Index);
2459   DAG.setRoot(BrJumpTable);
2460 }
2461 
2462 /// visitJumpTableHeader - This function emits necessary code to produce index
2463 /// in the JumpTable from switch case.
2464 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2465                                                JumpTableHeader &JTH,
2466                                                MachineBasicBlock *SwitchBB) {
2467   SDLoc dl = getCurSDLoc();
2468 
2469   // Subtract the lowest switch case value from the value being switched on.
2470   SDValue SwitchOp = getValue(JTH.SValue);
2471   EVT VT = SwitchOp.getValueType();
2472   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2473                             DAG.getConstant(JTH.First, dl, VT));
2474 
2475   // The SDNode we just created, which holds the value being switched on minus
2476   // the smallest case value, needs to be copied to a virtual register so it
2477   // can be used as an index into the jump table in a subsequent basic block.
2478   // This value may be smaller or larger than the target's pointer type, and
2479   // therefore require extension or truncating.
2480   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2481   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2482 
2483   unsigned JumpTableReg =
2484       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2485   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2486                                     JumpTableReg, SwitchOp);
2487   JT.Reg = JumpTableReg;
2488 
2489   if (!JTH.OmitRangeCheck) {
2490     // Emit the range check for the jump table, and branch to the default block
2491     // for the switch statement if the value being switched on exceeds the
2492     // largest case in the switch.
2493     SDValue CMP = DAG.getSetCC(
2494         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2495                                    Sub.getValueType()),
2496         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2497 
2498     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2499                                  MVT::Other, CopyTo, CMP,
2500                                  DAG.getBasicBlock(JT.Default));
2501 
2502     // Avoid emitting unnecessary branches to the next block.
2503     if (JT.MBB != NextBlock(SwitchBB))
2504       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2505                            DAG.getBasicBlock(JT.MBB));
2506 
2507     DAG.setRoot(BrCond);
2508   } else {
2509     // Avoid emitting unnecessary branches to the next block.
2510     if (JT.MBB != NextBlock(SwitchBB))
2511       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2512                               DAG.getBasicBlock(JT.MBB)));
2513     else
2514       DAG.setRoot(CopyTo);
2515   }
2516 }
2517 
2518 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2519 /// variable if there exists one.
2520 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2521                                  SDValue &Chain) {
2522   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2523   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2524   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2525   MachineFunction &MF = DAG.getMachineFunction();
2526   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2527   MachineSDNode *Node =
2528       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2529   if (Global) {
2530     MachinePointerInfo MPInfo(Global);
2531     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2532                  MachineMemOperand::MODereferenceable;
2533     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2534         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2535     DAG.setNodeMemRefs(Node, {MemRef});
2536   }
2537   if (PtrTy != PtrMemTy)
2538     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2539   return SDValue(Node, 0);
2540 }
2541 
2542 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2543 /// tail spliced into a stack protector check success bb.
2544 ///
2545 /// For a high level explanation of how this fits into the stack protector
2546 /// generation see the comment on the declaration of class
2547 /// StackProtectorDescriptor.
2548 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2549                                                   MachineBasicBlock *ParentBB) {
2550 
2551   // First create the loads to the guard/stack slot for the comparison.
2552   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2553   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2554   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2555 
2556   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2557   int FI = MFI.getStackProtectorIndex();
2558 
2559   SDValue Guard;
2560   SDLoc dl = getCurSDLoc();
2561   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2562   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2563   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2564 
2565   // Generate code to load the content of the guard slot.
2566   SDValue GuardVal = DAG.getLoad(
2567       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2568       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2569       MachineMemOperand::MOVolatile);
2570 
2571   if (TLI.useStackGuardXorFP())
2572     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2573 
2574   // Retrieve guard check function, nullptr if instrumentation is inlined.
2575   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2576     // The target provides a guard check function to validate the guard value.
2577     // Generate a call to that function with the content of the guard slot as
2578     // argument.
2579     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2580     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2581 
2582     TargetLowering::ArgListTy Args;
2583     TargetLowering::ArgListEntry Entry;
2584     Entry.Node = GuardVal;
2585     Entry.Ty = FnTy->getParamType(0);
2586     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2587       Entry.IsInReg = true;
2588     Args.push_back(Entry);
2589 
2590     TargetLowering::CallLoweringInfo CLI(DAG);
2591     CLI.setDebugLoc(getCurSDLoc())
2592         .setChain(DAG.getEntryNode())
2593         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2594                    getValue(GuardCheckFn), std::move(Args));
2595 
2596     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2597     DAG.setRoot(Result.second);
2598     return;
2599   }
2600 
2601   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2602   // Otherwise, emit a volatile load to retrieve the stack guard value.
2603   SDValue Chain = DAG.getEntryNode();
2604   if (TLI.useLoadStackGuardNode()) {
2605     Guard = getLoadStackGuard(DAG, dl, Chain);
2606   } else {
2607     const Value *IRGuard = TLI.getSDagStackGuard(M);
2608     SDValue GuardPtr = getValue(IRGuard);
2609 
2610     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2611                         MachinePointerInfo(IRGuard, 0), Align,
2612                         MachineMemOperand::MOVolatile);
2613   }
2614 
2615   // Perform the comparison via a getsetcc.
2616   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2617                                                         *DAG.getContext(),
2618                                                         Guard.getValueType()),
2619                              Guard, GuardVal, ISD::SETNE);
2620 
2621   // If the guard/stackslot do not equal, branch to failure MBB.
2622   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2623                                MVT::Other, GuardVal.getOperand(0),
2624                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2625   // Otherwise branch to success MBB.
2626   SDValue Br = DAG.getNode(ISD::BR, dl,
2627                            MVT::Other, BrCond,
2628                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2629 
2630   DAG.setRoot(Br);
2631 }
2632 
2633 /// Codegen the failure basic block for a stack protector check.
2634 ///
2635 /// A failure stack protector machine basic block consists simply of a call to
2636 /// __stack_chk_fail().
2637 ///
2638 /// For a high level explanation of how this fits into the stack protector
2639 /// generation see the comment on the declaration of class
2640 /// StackProtectorDescriptor.
2641 void
2642 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2643   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2644   TargetLowering::MakeLibCallOptions CallOptions;
2645   CallOptions.setDiscardResult(true);
2646   SDValue Chain =
2647       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2648                       None, CallOptions, getCurSDLoc()).second;
2649   // On PS4, the "return address" must still be within the calling function,
2650   // even if it's at the very end, so emit an explicit TRAP here.
2651   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2652   if (TM.getTargetTriple().isPS4CPU())
2653     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2654   // WebAssembly needs an unreachable instruction after a non-returning call,
2655   // because the function return type can be different from __stack_chk_fail's
2656   // return type (void).
2657   if (TM.getTargetTriple().isWasm())
2658     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2659 
2660   DAG.setRoot(Chain);
2661 }
2662 
2663 /// visitBitTestHeader - This function emits necessary code to produce value
2664 /// suitable for "bit tests"
2665 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2666                                              MachineBasicBlock *SwitchBB) {
2667   SDLoc dl = getCurSDLoc();
2668 
2669   // Subtract the minimum value.
2670   SDValue SwitchOp = getValue(B.SValue);
2671   EVT VT = SwitchOp.getValueType();
2672   SDValue RangeSub =
2673       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2674 
2675   // Determine the type of the test operands.
2676   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2677   bool UsePtrType = false;
2678   if (!TLI.isTypeLegal(VT)) {
2679     UsePtrType = true;
2680   } else {
2681     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2682       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2683         // Switch table case range are encoded into series of masks.
2684         // Just use pointer type, it's guaranteed to fit.
2685         UsePtrType = true;
2686         break;
2687       }
2688   }
2689   SDValue Sub = RangeSub;
2690   if (UsePtrType) {
2691     VT = TLI.getPointerTy(DAG.getDataLayout());
2692     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2693   }
2694 
2695   B.RegVT = VT.getSimpleVT();
2696   B.Reg = FuncInfo.CreateReg(B.RegVT);
2697   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2698 
2699   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2700 
2701   if (!B.OmitRangeCheck)
2702     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2703   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2704   SwitchBB->normalizeSuccProbs();
2705 
2706   SDValue Root = CopyTo;
2707   if (!B.OmitRangeCheck) {
2708     // Conditional branch to the default block.
2709     SDValue RangeCmp = DAG.getSetCC(dl,
2710         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2711                                RangeSub.getValueType()),
2712         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2713         ISD::SETUGT);
2714 
2715     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2716                        DAG.getBasicBlock(B.Default));
2717   }
2718 
2719   // Avoid emitting unnecessary branches to the next block.
2720   if (MBB != NextBlock(SwitchBB))
2721     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2722 
2723   DAG.setRoot(Root);
2724 }
2725 
2726 /// visitBitTestCase - this function produces one "bit test"
2727 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2728                                            MachineBasicBlock* NextMBB,
2729                                            BranchProbability BranchProbToNext,
2730                                            unsigned Reg,
2731                                            BitTestCase &B,
2732                                            MachineBasicBlock *SwitchBB) {
2733   SDLoc dl = getCurSDLoc();
2734   MVT VT = BB.RegVT;
2735   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2736   SDValue Cmp;
2737   unsigned PopCount = countPopulation(B.Mask);
2738   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2739   if (PopCount == 1) {
2740     // Testing for a single bit; just compare the shift count with what it
2741     // would need to be to shift a 1 bit in that position.
2742     Cmp = DAG.getSetCC(
2743         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2744         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2745         ISD::SETEQ);
2746   } else if (PopCount == BB.Range) {
2747     // There is only one zero bit in the range, test for it directly.
2748     Cmp = DAG.getSetCC(
2749         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2750         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2751         ISD::SETNE);
2752   } else {
2753     // Make desired shift
2754     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2755                                     DAG.getConstant(1, dl, VT), ShiftOp);
2756 
2757     // Emit bit tests and jumps
2758     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2759                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2760     Cmp = DAG.getSetCC(
2761         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2762         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2763   }
2764 
2765   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2766   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2767   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2768   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2769   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2770   // one as they are relative probabilities (and thus work more like weights),
2771   // and hence we need to normalize them to let the sum of them become one.
2772   SwitchBB->normalizeSuccProbs();
2773 
2774   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2775                               MVT::Other, getControlRoot(),
2776                               Cmp, DAG.getBasicBlock(B.TargetBB));
2777 
2778   // Avoid emitting unnecessary branches to the next block.
2779   if (NextMBB != NextBlock(SwitchBB))
2780     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2781                         DAG.getBasicBlock(NextMBB));
2782 
2783   DAG.setRoot(BrAnd);
2784 }
2785 
2786 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2787   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2788 
2789   // Retrieve successors. Look through artificial IR level blocks like
2790   // catchswitch for successors.
2791   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2792   const BasicBlock *EHPadBB = I.getSuccessor(1);
2793 
2794   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2795   // have to do anything here to lower funclet bundles.
2796   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2797                                         LLVMContext::OB_gc_transition,
2798                                         LLVMContext::OB_gc_live,
2799                                         LLVMContext::OB_funclet,
2800                                         LLVMContext::OB_cfguardtarget}) &&
2801          "Cannot lower invokes with arbitrary operand bundles yet!");
2802 
2803   const Value *Callee(I.getCalledOperand());
2804   const Function *Fn = dyn_cast<Function>(Callee);
2805   if (isa<InlineAsm>(Callee))
2806     visitInlineAsm(I);
2807   else if (Fn && Fn->isIntrinsic()) {
2808     switch (Fn->getIntrinsicID()) {
2809     default:
2810       llvm_unreachable("Cannot invoke this intrinsic");
2811     case Intrinsic::donothing:
2812       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2813       break;
2814     case Intrinsic::experimental_patchpoint_void:
2815     case Intrinsic::experimental_patchpoint_i64:
2816       visitPatchpoint(I, EHPadBB);
2817       break;
2818     case Intrinsic::experimental_gc_statepoint:
2819       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2820       break;
2821     case Intrinsic::wasm_rethrow_in_catch: {
2822       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2823       // special because it can be invoked, so we manually lower it to a DAG
2824       // node here.
2825       SmallVector<SDValue, 8> Ops;
2826       Ops.push_back(getRoot()); // inchain
2827       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2828       Ops.push_back(
2829           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2830                                 TLI.getPointerTy(DAG.getDataLayout())));
2831       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2832       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2833       break;
2834     }
2835     }
2836   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2837     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2838     // Eventually we will support lowering the @llvm.experimental.deoptimize
2839     // intrinsic, and right now there are no plans to support other intrinsics
2840     // with deopt state.
2841     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2842   } else {
2843     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2844   }
2845 
2846   // If the value of the invoke is used outside of its defining block, make it
2847   // available as a virtual register.
2848   // We already took care of the exported value for the statepoint instruction
2849   // during call to the LowerStatepoint.
2850   if (!isa<GCStatepointInst>(I)) {
2851     CopyToExportRegsIfNeeded(&I);
2852   }
2853 
2854   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2855   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2856   BranchProbability EHPadBBProb =
2857       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2858           : BranchProbability::getZero();
2859   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2860 
2861   // Update successor info.
2862   addSuccessorWithProb(InvokeMBB, Return);
2863   for (auto &UnwindDest : UnwindDests) {
2864     UnwindDest.first->setIsEHPad();
2865     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2866   }
2867   InvokeMBB->normalizeSuccProbs();
2868 
2869   // Drop into normal successor.
2870   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2871                           DAG.getBasicBlock(Return)));
2872 }
2873 
2874 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2875   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2876 
2877   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2878   // have to do anything here to lower funclet bundles.
2879   assert(!I.hasOperandBundlesOtherThan(
2880              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2881          "Cannot lower callbrs with arbitrary operand bundles yet!");
2882 
2883   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2884   visitInlineAsm(I);
2885   CopyToExportRegsIfNeeded(&I);
2886 
2887   // Retrieve successors.
2888   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2889 
2890   // Update successor info.
2891   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2892   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2893     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2894     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2895     Target->setIsInlineAsmBrIndirectTarget();
2896   }
2897   CallBrMBB->normalizeSuccProbs();
2898 
2899   // Drop into default successor.
2900   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2901                           MVT::Other, getControlRoot(),
2902                           DAG.getBasicBlock(Return)));
2903 }
2904 
2905 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2906   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2907 }
2908 
2909 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2910   assert(FuncInfo.MBB->isEHPad() &&
2911          "Call to landingpad not in landing pad!");
2912 
2913   // If there aren't registers to copy the values into (e.g., during SjLj
2914   // exceptions), then don't bother to create these DAG nodes.
2915   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2916   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2917   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2918       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2919     return;
2920 
2921   // If landingpad's return type is token type, we don't create DAG nodes
2922   // for its exception pointer and selector value. The extraction of exception
2923   // pointer or selector value from token type landingpads is not currently
2924   // supported.
2925   if (LP.getType()->isTokenTy())
2926     return;
2927 
2928   SmallVector<EVT, 2> ValueVTs;
2929   SDLoc dl = getCurSDLoc();
2930   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2931   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2932 
2933   // Get the two live-in registers as SDValues. The physregs have already been
2934   // copied into virtual registers.
2935   SDValue Ops[2];
2936   if (FuncInfo.ExceptionPointerVirtReg) {
2937     Ops[0] = DAG.getZExtOrTrunc(
2938         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2939                            FuncInfo.ExceptionPointerVirtReg,
2940                            TLI.getPointerTy(DAG.getDataLayout())),
2941         dl, ValueVTs[0]);
2942   } else {
2943     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2944   }
2945   Ops[1] = DAG.getZExtOrTrunc(
2946       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2947                          FuncInfo.ExceptionSelectorVirtReg,
2948                          TLI.getPointerTy(DAG.getDataLayout())),
2949       dl, ValueVTs[1]);
2950 
2951   // Merge into one.
2952   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2953                             DAG.getVTList(ValueVTs), Ops);
2954   setValue(&LP, Res);
2955 }
2956 
2957 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2958                                            MachineBasicBlock *Last) {
2959   // Update JTCases.
2960   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2961     if (SL->JTCases[i].first.HeaderBB == First)
2962       SL->JTCases[i].first.HeaderBB = Last;
2963 
2964   // Update BitTestCases.
2965   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2966     if (SL->BitTestCases[i].Parent == First)
2967       SL->BitTestCases[i].Parent = Last;
2968 }
2969 
2970 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2971   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2972 
2973   // Update machine-CFG edges with unique successors.
2974   SmallSet<BasicBlock*, 32> Done;
2975   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2976     BasicBlock *BB = I.getSuccessor(i);
2977     bool Inserted = Done.insert(BB).second;
2978     if (!Inserted)
2979         continue;
2980 
2981     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2982     addSuccessorWithProb(IndirectBrMBB, Succ);
2983   }
2984   IndirectBrMBB->normalizeSuccProbs();
2985 
2986   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2987                           MVT::Other, getControlRoot(),
2988                           getValue(I.getAddress())));
2989 }
2990 
2991 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2992   if (!DAG.getTarget().Options.TrapUnreachable)
2993     return;
2994 
2995   // We may be able to ignore unreachable behind a noreturn call.
2996   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2997     const BasicBlock &BB = *I.getParent();
2998     if (&I != &BB.front()) {
2999       BasicBlock::const_iterator PredI =
3000         std::prev(BasicBlock::const_iterator(&I));
3001       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3002         if (Call->doesNotReturn())
3003           return;
3004       }
3005     }
3006   }
3007 
3008   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3009 }
3010 
3011 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3012   SDNodeFlags Flags;
3013 
3014   SDValue Op = getValue(I.getOperand(0));
3015   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3016                                     Op, Flags);
3017   setValue(&I, UnNodeValue);
3018 }
3019 
3020 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3021   SDNodeFlags Flags;
3022   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3023     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3024     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3025   }
3026   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3027     Flags.setExact(ExactOp->isExact());
3028   }
3029 
3030   SDValue Op1 = getValue(I.getOperand(0));
3031   SDValue Op2 = getValue(I.getOperand(1));
3032   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3033                                      Op1, Op2, Flags);
3034   setValue(&I, BinNodeValue);
3035 }
3036 
3037 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3038   SDValue Op1 = getValue(I.getOperand(0));
3039   SDValue Op2 = getValue(I.getOperand(1));
3040 
3041   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3042       Op1.getValueType(), DAG.getDataLayout());
3043 
3044   // Coerce the shift amount to the right type if we can.
3045   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3046     unsigned ShiftSize = ShiftTy.getSizeInBits();
3047     unsigned Op2Size = Op2.getValueSizeInBits();
3048     SDLoc DL = getCurSDLoc();
3049 
3050     // If the operand is smaller than the shift count type, promote it.
3051     if (ShiftSize > Op2Size)
3052       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3053 
3054     // If the operand is larger than the shift count type but the shift
3055     // count type has enough bits to represent any shift value, truncate
3056     // it now. This is a common case and it exposes the truncate to
3057     // optimization early.
3058     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3059       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3060     // Otherwise we'll need to temporarily settle for some other convenient
3061     // type.  Type legalization will make adjustments once the shiftee is split.
3062     else
3063       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3064   }
3065 
3066   bool nuw = false;
3067   bool nsw = false;
3068   bool exact = false;
3069 
3070   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3071 
3072     if (const OverflowingBinaryOperator *OFBinOp =
3073             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3074       nuw = OFBinOp->hasNoUnsignedWrap();
3075       nsw = OFBinOp->hasNoSignedWrap();
3076     }
3077     if (const PossiblyExactOperator *ExactOp =
3078             dyn_cast<const PossiblyExactOperator>(&I))
3079       exact = ExactOp->isExact();
3080   }
3081   SDNodeFlags Flags;
3082   Flags.setExact(exact);
3083   Flags.setNoSignedWrap(nsw);
3084   Flags.setNoUnsignedWrap(nuw);
3085   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3086                             Flags);
3087   setValue(&I, Res);
3088 }
3089 
3090 void SelectionDAGBuilder::visitSDiv(const User &I) {
3091   SDValue Op1 = getValue(I.getOperand(0));
3092   SDValue Op2 = getValue(I.getOperand(1));
3093 
3094   SDNodeFlags Flags;
3095   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3096                  cast<PossiblyExactOperator>(&I)->isExact());
3097   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3098                            Op2, Flags));
3099 }
3100 
3101 void SelectionDAGBuilder::visitICmp(const User &I) {
3102   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3103   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3104     predicate = IC->getPredicate();
3105   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3106     predicate = ICmpInst::Predicate(IC->getPredicate());
3107   SDValue Op1 = getValue(I.getOperand(0));
3108   SDValue Op2 = getValue(I.getOperand(1));
3109   ISD::CondCode Opcode = getICmpCondCode(predicate);
3110 
3111   auto &TLI = DAG.getTargetLoweringInfo();
3112   EVT MemVT =
3113       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3114 
3115   // If a pointer's DAG type is larger than its memory type then the DAG values
3116   // are zero-extended. This breaks signed comparisons so truncate back to the
3117   // underlying type before doing the compare.
3118   if (Op1.getValueType() != MemVT) {
3119     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3120     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3121   }
3122 
3123   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3124                                                         I.getType());
3125   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3126 }
3127 
3128 void SelectionDAGBuilder::visitFCmp(const User &I) {
3129   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3130   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3131     predicate = FC->getPredicate();
3132   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3133     predicate = FCmpInst::Predicate(FC->getPredicate());
3134   SDValue Op1 = getValue(I.getOperand(0));
3135   SDValue Op2 = getValue(I.getOperand(1));
3136 
3137   ISD::CondCode Condition = getFCmpCondCode(predicate);
3138   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3139   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3140     Condition = getFCmpCodeWithoutNaN(Condition);
3141 
3142   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3143                                                         I.getType());
3144   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3145 }
3146 
3147 // Check if the condition of the select has one use or two users that are both
3148 // selects with the same condition.
3149 static bool hasOnlySelectUsers(const Value *Cond) {
3150   return llvm::all_of(Cond->users(), [](const Value *V) {
3151     return isa<SelectInst>(V);
3152   });
3153 }
3154 
3155 void SelectionDAGBuilder::visitSelect(const User &I) {
3156   SmallVector<EVT, 4> ValueVTs;
3157   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3158                   ValueVTs);
3159   unsigned NumValues = ValueVTs.size();
3160   if (NumValues == 0) return;
3161 
3162   SmallVector<SDValue, 4> Values(NumValues);
3163   SDValue Cond     = getValue(I.getOperand(0));
3164   SDValue LHSVal   = getValue(I.getOperand(1));
3165   SDValue RHSVal   = getValue(I.getOperand(2));
3166   SmallVector<SDValue, 1> BaseOps(1, Cond);
3167   ISD::NodeType OpCode =
3168       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3169 
3170   bool IsUnaryAbs = false;
3171 
3172   // Min/max matching is only viable if all output VTs are the same.
3173   if (is_splat(ValueVTs)) {
3174     EVT VT = ValueVTs[0];
3175     LLVMContext &Ctx = *DAG.getContext();
3176     auto &TLI = DAG.getTargetLoweringInfo();
3177 
3178     // We care about the legality of the operation after it has been type
3179     // legalized.
3180     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3181       VT = TLI.getTypeToTransformTo(Ctx, VT);
3182 
3183     // If the vselect is legal, assume we want to leave this as a vector setcc +
3184     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3185     // min/max is legal on the scalar type.
3186     bool UseScalarMinMax = VT.isVector() &&
3187       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3188 
3189     Value *LHS, *RHS;
3190     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3191     ISD::NodeType Opc = ISD::DELETED_NODE;
3192     switch (SPR.Flavor) {
3193     case SPF_UMAX:    Opc = ISD::UMAX; break;
3194     case SPF_UMIN:    Opc = ISD::UMIN; break;
3195     case SPF_SMAX:    Opc = ISD::SMAX; break;
3196     case SPF_SMIN:    Opc = ISD::SMIN; break;
3197     case SPF_FMINNUM:
3198       switch (SPR.NaNBehavior) {
3199       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3200       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3201       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3202       case SPNB_RETURNS_ANY: {
3203         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3204           Opc = ISD::FMINNUM;
3205         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3206           Opc = ISD::FMINIMUM;
3207         else if (UseScalarMinMax)
3208           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3209             ISD::FMINNUM : ISD::FMINIMUM;
3210         break;
3211       }
3212       }
3213       break;
3214     case SPF_FMAXNUM:
3215       switch (SPR.NaNBehavior) {
3216       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3217       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3218       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3219       case SPNB_RETURNS_ANY:
3220 
3221         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3222           Opc = ISD::FMAXNUM;
3223         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3224           Opc = ISD::FMAXIMUM;
3225         else if (UseScalarMinMax)
3226           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3227             ISD::FMAXNUM : ISD::FMAXIMUM;
3228         break;
3229       }
3230       break;
3231     case SPF_ABS:
3232       IsUnaryAbs = true;
3233       Opc = ISD::ABS;
3234       break;
3235     case SPF_NABS:
3236       // TODO: we need to produce sub(0, abs(X)).
3237     default: break;
3238     }
3239 
3240     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3241         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3242          (UseScalarMinMax &&
3243           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3244         // If the underlying comparison instruction is used by any other
3245         // instruction, the consumed instructions won't be destroyed, so it is
3246         // not profitable to convert to a min/max.
3247         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3248       OpCode = Opc;
3249       LHSVal = getValue(LHS);
3250       RHSVal = getValue(RHS);
3251       BaseOps.clear();
3252     }
3253 
3254     if (IsUnaryAbs) {
3255       OpCode = Opc;
3256       LHSVal = getValue(LHS);
3257       BaseOps.clear();
3258     }
3259   }
3260 
3261   if (IsUnaryAbs) {
3262     for (unsigned i = 0; i != NumValues; ++i) {
3263       Values[i] =
3264           DAG.getNode(OpCode, getCurSDLoc(),
3265                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3266                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3267     }
3268   } else {
3269     for (unsigned i = 0; i != NumValues; ++i) {
3270       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3271       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3272       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3273       Values[i] = DAG.getNode(
3274           OpCode, getCurSDLoc(),
3275           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3276     }
3277   }
3278 
3279   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3280                            DAG.getVTList(ValueVTs), Values));
3281 }
3282 
3283 void SelectionDAGBuilder::visitTrunc(const User &I) {
3284   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3285   SDValue N = getValue(I.getOperand(0));
3286   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3287                                                         I.getType());
3288   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3289 }
3290 
3291 void SelectionDAGBuilder::visitZExt(const User &I) {
3292   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3293   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3294   SDValue N = getValue(I.getOperand(0));
3295   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3296                                                         I.getType());
3297   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3298 }
3299 
3300 void SelectionDAGBuilder::visitSExt(const User &I) {
3301   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3302   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3303   SDValue N = getValue(I.getOperand(0));
3304   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3305                                                         I.getType());
3306   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3307 }
3308 
3309 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3310   // FPTrunc is never a no-op cast, no need to check
3311   SDValue N = getValue(I.getOperand(0));
3312   SDLoc dl = getCurSDLoc();
3313   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3314   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3315   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3316                            DAG.getTargetConstant(
3317                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3318 }
3319 
3320 void SelectionDAGBuilder::visitFPExt(const User &I) {
3321   // FPExt is never a no-op cast, no need to check
3322   SDValue N = getValue(I.getOperand(0));
3323   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3324                                                         I.getType());
3325   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3326 }
3327 
3328 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3329   // FPToUI is never a no-op cast, no need to check
3330   SDValue N = getValue(I.getOperand(0));
3331   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3332                                                         I.getType());
3333   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3334 }
3335 
3336 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3337   // FPToSI is never a no-op cast, no need to check
3338   SDValue N = getValue(I.getOperand(0));
3339   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3340                                                         I.getType());
3341   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3342 }
3343 
3344 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3345   // UIToFP is never a no-op cast, no need to check
3346   SDValue N = getValue(I.getOperand(0));
3347   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3348                                                         I.getType());
3349   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3350 }
3351 
3352 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3353   // SIToFP is never a no-op cast, no need to check
3354   SDValue N = getValue(I.getOperand(0));
3355   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3356                                                         I.getType());
3357   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3358 }
3359 
3360 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3361   // What to do depends on the size of the integer and the size of the pointer.
3362   // We can either truncate, zero extend, or no-op, accordingly.
3363   SDValue N = getValue(I.getOperand(0));
3364   auto &TLI = DAG.getTargetLoweringInfo();
3365   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3366                                                         I.getType());
3367   EVT PtrMemVT =
3368       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3369   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3370   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3371   setValue(&I, N);
3372 }
3373 
3374 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3375   // What to do depends on the size of the integer and the size of the pointer.
3376   // We can either truncate, zero extend, or no-op, accordingly.
3377   SDValue N = getValue(I.getOperand(0));
3378   auto &TLI = DAG.getTargetLoweringInfo();
3379   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3380   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3381   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3382   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3383   setValue(&I, N);
3384 }
3385 
3386 void SelectionDAGBuilder::visitBitCast(const User &I) {
3387   SDValue N = getValue(I.getOperand(0));
3388   SDLoc dl = getCurSDLoc();
3389   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3390                                                         I.getType());
3391 
3392   // BitCast assures us that source and destination are the same size so this is
3393   // either a BITCAST or a no-op.
3394   if (DestVT != N.getValueType())
3395     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3396                              DestVT, N)); // convert types.
3397   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3398   // might fold any kind of constant expression to an integer constant and that
3399   // is not what we are looking for. Only recognize a bitcast of a genuine
3400   // constant integer as an opaque constant.
3401   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3402     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3403                                  /*isOpaque*/true));
3404   else
3405     setValue(&I, N);            // noop cast.
3406 }
3407 
3408 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3409   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3410   const Value *SV = I.getOperand(0);
3411   SDValue N = getValue(SV);
3412   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3413 
3414   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3415   unsigned DestAS = I.getType()->getPointerAddressSpace();
3416 
3417   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3418     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3419 
3420   setValue(&I, N);
3421 }
3422 
3423 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3424   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3425   SDValue InVec = getValue(I.getOperand(0));
3426   SDValue InVal = getValue(I.getOperand(1));
3427   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3428                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3429   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3430                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3431                            InVec, InVal, InIdx));
3432 }
3433 
3434 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3435   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3436   SDValue InVec = getValue(I.getOperand(0));
3437   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3438                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3439   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3440                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3441                            InVec, InIdx));
3442 }
3443 
3444 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3445   SDValue Src1 = getValue(I.getOperand(0));
3446   SDValue Src2 = getValue(I.getOperand(1));
3447   ArrayRef<int> Mask;
3448   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3449     Mask = SVI->getShuffleMask();
3450   else
3451     Mask = cast<ConstantExpr>(I).getShuffleMask();
3452   SDLoc DL = getCurSDLoc();
3453   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3454   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3455   EVT SrcVT = Src1.getValueType();
3456 
3457   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3458       VT.isScalableVector()) {
3459     // Canonical splat form of first element of first input vector.
3460     SDValue FirstElt =
3461         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3462                     DAG.getVectorIdxConstant(0, DL));
3463     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3464     return;
3465   }
3466 
3467   // For now, we only handle splats for scalable vectors.
3468   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3469   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3470   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3471 
3472   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3473   unsigned MaskNumElts = Mask.size();
3474 
3475   if (SrcNumElts == MaskNumElts) {
3476     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3477     return;
3478   }
3479 
3480   // Normalize the shuffle vector since mask and vector length don't match.
3481   if (SrcNumElts < MaskNumElts) {
3482     // Mask is longer than the source vectors. We can use concatenate vector to
3483     // make the mask and vectors lengths match.
3484 
3485     if (MaskNumElts % SrcNumElts == 0) {
3486       // Mask length is a multiple of the source vector length.
3487       // Check if the shuffle is some kind of concatenation of the input
3488       // vectors.
3489       unsigned NumConcat = MaskNumElts / SrcNumElts;
3490       bool IsConcat = true;
3491       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3492       for (unsigned i = 0; i != MaskNumElts; ++i) {
3493         int Idx = Mask[i];
3494         if (Idx < 0)
3495           continue;
3496         // Ensure the indices in each SrcVT sized piece are sequential and that
3497         // the same source is used for the whole piece.
3498         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3499             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3500              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3501           IsConcat = false;
3502           break;
3503         }
3504         // Remember which source this index came from.
3505         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3506       }
3507 
3508       // The shuffle is concatenating multiple vectors together. Just emit
3509       // a CONCAT_VECTORS operation.
3510       if (IsConcat) {
3511         SmallVector<SDValue, 8> ConcatOps;
3512         for (auto Src : ConcatSrcs) {
3513           if (Src < 0)
3514             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3515           else if (Src == 0)
3516             ConcatOps.push_back(Src1);
3517           else
3518             ConcatOps.push_back(Src2);
3519         }
3520         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3521         return;
3522       }
3523     }
3524 
3525     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3526     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3527     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3528                                     PaddedMaskNumElts);
3529 
3530     // Pad both vectors with undefs to make them the same length as the mask.
3531     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3532 
3533     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3534     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3535     MOps1[0] = Src1;
3536     MOps2[0] = Src2;
3537 
3538     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3539     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3540 
3541     // Readjust mask for new input vector length.
3542     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3543     for (unsigned i = 0; i != MaskNumElts; ++i) {
3544       int Idx = Mask[i];
3545       if (Idx >= (int)SrcNumElts)
3546         Idx -= SrcNumElts - PaddedMaskNumElts;
3547       MappedOps[i] = Idx;
3548     }
3549 
3550     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3551 
3552     // If the concatenated vector was padded, extract a subvector with the
3553     // correct number of elements.
3554     if (MaskNumElts != PaddedMaskNumElts)
3555       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3556                            DAG.getVectorIdxConstant(0, DL));
3557 
3558     setValue(&I, Result);
3559     return;
3560   }
3561 
3562   if (SrcNumElts > MaskNumElts) {
3563     // Analyze the access pattern of the vector to see if we can extract
3564     // two subvectors and do the shuffle.
3565     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3566     bool CanExtract = true;
3567     for (int Idx : Mask) {
3568       unsigned Input = 0;
3569       if (Idx < 0)
3570         continue;
3571 
3572       if (Idx >= (int)SrcNumElts) {
3573         Input = 1;
3574         Idx -= SrcNumElts;
3575       }
3576 
3577       // If all the indices come from the same MaskNumElts sized portion of
3578       // the sources we can use extract. Also make sure the extract wouldn't
3579       // extract past the end of the source.
3580       int NewStartIdx = alignDown(Idx, MaskNumElts);
3581       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3582           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3583         CanExtract = false;
3584       // Make sure we always update StartIdx as we use it to track if all
3585       // elements are undef.
3586       StartIdx[Input] = NewStartIdx;
3587     }
3588 
3589     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3590       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3591       return;
3592     }
3593     if (CanExtract) {
3594       // Extract appropriate subvector and generate a vector shuffle
3595       for (unsigned Input = 0; Input < 2; ++Input) {
3596         SDValue &Src = Input == 0 ? Src1 : Src2;
3597         if (StartIdx[Input] < 0)
3598           Src = DAG.getUNDEF(VT);
3599         else {
3600           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3601                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3602         }
3603       }
3604 
3605       // Calculate new mask.
3606       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3607       for (int &Idx : MappedOps) {
3608         if (Idx >= (int)SrcNumElts)
3609           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3610         else if (Idx >= 0)
3611           Idx -= StartIdx[0];
3612       }
3613 
3614       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3615       return;
3616     }
3617   }
3618 
3619   // We can't use either concat vectors or extract subvectors so fall back to
3620   // replacing the shuffle with extract and build vector.
3621   // to insert and build vector.
3622   EVT EltVT = VT.getVectorElementType();
3623   SmallVector<SDValue,8> Ops;
3624   for (int Idx : Mask) {
3625     SDValue Res;
3626 
3627     if (Idx < 0) {
3628       Res = DAG.getUNDEF(EltVT);
3629     } else {
3630       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3631       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3632 
3633       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3634                         DAG.getVectorIdxConstant(Idx, DL));
3635     }
3636 
3637     Ops.push_back(Res);
3638   }
3639 
3640   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3641 }
3642 
3643 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3644   ArrayRef<unsigned> Indices;
3645   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3646     Indices = IV->getIndices();
3647   else
3648     Indices = cast<ConstantExpr>(&I)->getIndices();
3649 
3650   const Value *Op0 = I.getOperand(0);
3651   const Value *Op1 = I.getOperand(1);
3652   Type *AggTy = I.getType();
3653   Type *ValTy = Op1->getType();
3654   bool IntoUndef = isa<UndefValue>(Op0);
3655   bool FromUndef = isa<UndefValue>(Op1);
3656 
3657   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3658 
3659   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3660   SmallVector<EVT, 4> AggValueVTs;
3661   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3662   SmallVector<EVT, 4> ValValueVTs;
3663   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3664 
3665   unsigned NumAggValues = AggValueVTs.size();
3666   unsigned NumValValues = ValValueVTs.size();
3667   SmallVector<SDValue, 4> Values(NumAggValues);
3668 
3669   // Ignore an insertvalue that produces an empty object
3670   if (!NumAggValues) {
3671     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3672     return;
3673   }
3674 
3675   SDValue Agg = getValue(Op0);
3676   unsigned i = 0;
3677   // Copy the beginning value(s) from the original aggregate.
3678   for (; i != LinearIndex; ++i)
3679     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3680                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3681   // Copy values from the inserted value(s).
3682   if (NumValValues) {
3683     SDValue Val = getValue(Op1);
3684     for (; i != LinearIndex + NumValValues; ++i)
3685       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3686                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3687   }
3688   // Copy remaining value(s) from the original aggregate.
3689   for (; i != NumAggValues; ++i)
3690     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3691                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3692 
3693   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3694                            DAG.getVTList(AggValueVTs), Values));
3695 }
3696 
3697 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3698   ArrayRef<unsigned> Indices;
3699   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3700     Indices = EV->getIndices();
3701   else
3702     Indices = cast<ConstantExpr>(&I)->getIndices();
3703 
3704   const Value *Op0 = I.getOperand(0);
3705   Type *AggTy = Op0->getType();
3706   Type *ValTy = I.getType();
3707   bool OutOfUndef = isa<UndefValue>(Op0);
3708 
3709   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3710 
3711   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3712   SmallVector<EVT, 4> ValValueVTs;
3713   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3714 
3715   unsigned NumValValues = ValValueVTs.size();
3716 
3717   // Ignore a extractvalue that produces an empty object
3718   if (!NumValValues) {
3719     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3720     return;
3721   }
3722 
3723   SmallVector<SDValue, 4> Values(NumValValues);
3724 
3725   SDValue Agg = getValue(Op0);
3726   // Copy out the selected value(s).
3727   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3728     Values[i - LinearIndex] =
3729       OutOfUndef ?
3730         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3731         SDValue(Agg.getNode(), Agg.getResNo() + i);
3732 
3733   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3734                            DAG.getVTList(ValValueVTs), Values));
3735 }
3736 
3737 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3738   Value *Op0 = I.getOperand(0);
3739   // Note that the pointer operand may be a vector of pointers. Take the scalar
3740   // element which holds a pointer.
3741   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3742   SDValue N = getValue(Op0);
3743   SDLoc dl = getCurSDLoc();
3744   auto &TLI = DAG.getTargetLoweringInfo();
3745 
3746   // Normalize Vector GEP - all scalar operands should be converted to the
3747   // splat vector.
3748   bool IsVectorGEP = I.getType()->isVectorTy();
3749   ElementCount VectorElementCount =
3750       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3751                   : ElementCount::getFixed(0);
3752 
3753   if (IsVectorGEP && !N.getValueType().isVector()) {
3754     LLVMContext &Context = *DAG.getContext();
3755     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3756     if (VectorElementCount.isScalable())
3757       N = DAG.getSplatVector(VT, dl, N);
3758     else
3759       N = DAG.getSplatBuildVector(VT, dl, N);
3760   }
3761 
3762   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3763        GTI != E; ++GTI) {
3764     const Value *Idx = GTI.getOperand();
3765     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3766       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3767       if (Field) {
3768         // N = N + Offset
3769         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3770 
3771         // In an inbounds GEP with an offset that is nonnegative even when
3772         // interpreted as signed, assume there is no unsigned overflow.
3773         SDNodeFlags Flags;
3774         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3775           Flags.setNoUnsignedWrap(true);
3776 
3777         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3778                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3779       }
3780     } else {
3781       // IdxSize is the width of the arithmetic according to IR semantics.
3782       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3783       // (and fix up the result later).
3784       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3785       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3786       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3787       // We intentionally mask away the high bits here; ElementSize may not
3788       // fit in IdxTy.
3789       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3790       bool ElementScalable = ElementSize.isScalable();
3791 
3792       // If this is a scalar constant or a splat vector of constants,
3793       // handle it quickly.
3794       const auto *C = dyn_cast<Constant>(Idx);
3795       if (C && isa<VectorType>(C->getType()))
3796         C = C->getSplatValue();
3797 
3798       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3799       if (CI && CI->isZero())
3800         continue;
3801       if (CI && !ElementScalable) {
3802         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3803         LLVMContext &Context = *DAG.getContext();
3804         SDValue OffsVal;
3805         if (IsVectorGEP)
3806           OffsVal = DAG.getConstant(
3807               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3808         else
3809           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3810 
3811         // In an inbounds GEP with an offset that is nonnegative even when
3812         // interpreted as signed, assume there is no unsigned overflow.
3813         SDNodeFlags Flags;
3814         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3815           Flags.setNoUnsignedWrap(true);
3816 
3817         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3818 
3819         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3820         continue;
3821       }
3822 
3823       // N = N + Idx * ElementMul;
3824       SDValue IdxN = getValue(Idx);
3825 
3826       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3827         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3828                                   VectorElementCount);
3829         if (VectorElementCount.isScalable())
3830           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3831         else
3832           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3833       }
3834 
3835       // If the index is smaller or larger than intptr_t, truncate or extend
3836       // it.
3837       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3838 
3839       if (ElementScalable) {
3840         EVT VScaleTy = N.getValueType().getScalarType();
3841         SDValue VScale = DAG.getNode(
3842             ISD::VSCALE, dl, VScaleTy,
3843             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3844         if (IsVectorGEP)
3845           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3846         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3847       } else {
3848         // If this is a multiply by a power of two, turn it into a shl
3849         // immediately.  This is a very common case.
3850         if (ElementMul != 1) {
3851           if (ElementMul.isPowerOf2()) {
3852             unsigned Amt = ElementMul.logBase2();
3853             IdxN = DAG.getNode(ISD::SHL, dl,
3854                                N.getValueType(), IdxN,
3855                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3856           } else {
3857             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3858                                             IdxN.getValueType());
3859             IdxN = DAG.getNode(ISD::MUL, dl,
3860                                N.getValueType(), IdxN, Scale);
3861           }
3862         }
3863       }
3864 
3865       N = DAG.getNode(ISD::ADD, dl,
3866                       N.getValueType(), N, IdxN);
3867     }
3868   }
3869 
3870   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3871   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3872   if (IsVectorGEP) {
3873     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3874     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3875   }
3876 
3877   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3878     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3879 
3880   setValue(&I, N);
3881 }
3882 
3883 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3884   // If this is a fixed sized alloca in the entry block of the function,
3885   // allocate it statically on the stack.
3886   if (FuncInfo.StaticAllocaMap.count(&I))
3887     return;   // getValue will auto-populate this.
3888 
3889   SDLoc dl = getCurSDLoc();
3890   Type *Ty = I.getAllocatedType();
3891   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3892   auto &DL = DAG.getDataLayout();
3893   uint64_t TySize = DL.getTypeAllocSize(Ty);
3894   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3895 
3896   SDValue AllocSize = getValue(I.getArraySize());
3897 
3898   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3899   if (AllocSize.getValueType() != IntPtr)
3900     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3901 
3902   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3903                           AllocSize,
3904                           DAG.getConstant(TySize, dl, IntPtr));
3905 
3906   // Handle alignment.  If the requested alignment is less than or equal to
3907   // the stack alignment, ignore it.  If the size is greater than or equal to
3908   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3909   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3910   if (*Alignment <= StackAlign)
3911     Alignment = None;
3912 
3913   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3914   // Round the size of the allocation up to the stack alignment size
3915   // by add SA-1 to the size. This doesn't overflow because we're computing
3916   // an address inside an alloca.
3917   SDNodeFlags Flags;
3918   Flags.setNoUnsignedWrap(true);
3919   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3920                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3921 
3922   // Mask out the low bits for alignment purposes.
3923   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3924                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
3925 
3926   SDValue Ops[] = {
3927       getRoot(), AllocSize,
3928       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
3929   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3930   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3931   setValue(&I, DSA);
3932   DAG.setRoot(DSA.getValue(1));
3933 
3934   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3935 }
3936 
3937 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3938   if (I.isAtomic())
3939     return visitAtomicLoad(I);
3940 
3941   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3942   const Value *SV = I.getOperand(0);
3943   if (TLI.supportSwiftError()) {
3944     // Swifterror values can come from either a function parameter with
3945     // swifterror attribute or an alloca with swifterror attribute.
3946     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3947       if (Arg->hasSwiftErrorAttr())
3948         return visitLoadFromSwiftError(I);
3949     }
3950 
3951     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3952       if (Alloca->isSwiftError())
3953         return visitLoadFromSwiftError(I);
3954     }
3955   }
3956 
3957   SDValue Ptr = getValue(SV);
3958 
3959   Type *Ty = I.getType();
3960   Align Alignment = I.getAlign();
3961 
3962   AAMDNodes AAInfo;
3963   I.getAAMetadata(AAInfo);
3964   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3965 
3966   SmallVector<EVT, 4> ValueVTs, MemVTs;
3967   SmallVector<uint64_t, 4> Offsets;
3968   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
3969   unsigned NumValues = ValueVTs.size();
3970   if (NumValues == 0)
3971     return;
3972 
3973   bool isVolatile = I.isVolatile();
3974 
3975   SDValue Root;
3976   bool ConstantMemory = false;
3977   if (isVolatile)
3978     // Serialize volatile loads with other side effects.
3979     Root = getRoot();
3980   else if (NumValues > MaxParallelChains)
3981     Root = getMemoryRoot();
3982   else if (AA &&
3983            AA->pointsToConstantMemory(MemoryLocation(
3984                SV,
3985                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3986                AAInfo))) {
3987     // Do not serialize (non-volatile) loads of constant memory with anything.
3988     Root = DAG.getEntryNode();
3989     ConstantMemory = true;
3990   } else {
3991     // Do not serialize non-volatile loads against each other.
3992     Root = DAG.getRoot();
3993   }
3994 
3995   SDLoc dl = getCurSDLoc();
3996 
3997   if (isVolatile)
3998     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3999 
4000   // An aggregate load cannot wrap around the address space, so offsets to its
4001   // parts don't wrap either.
4002   SDNodeFlags Flags;
4003   Flags.setNoUnsignedWrap(true);
4004 
4005   SmallVector<SDValue, 4> Values(NumValues);
4006   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4007   EVT PtrVT = Ptr.getValueType();
4008 
4009   MachineMemOperand::Flags MMOFlags
4010     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4011 
4012   unsigned ChainI = 0;
4013   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4014     // Serializing loads here may result in excessive register pressure, and
4015     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4016     // could recover a bit by hoisting nodes upward in the chain by recognizing
4017     // they are side-effect free or do not alias. The optimizer should really
4018     // avoid this case by converting large object/array copies to llvm.memcpy
4019     // (MaxParallelChains should always remain as failsafe).
4020     if (ChainI == MaxParallelChains) {
4021       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4022       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4023                                   makeArrayRef(Chains.data(), ChainI));
4024       Root = Chain;
4025       ChainI = 0;
4026     }
4027     SDValue A = DAG.getNode(ISD::ADD, dl,
4028                             PtrVT, Ptr,
4029                             DAG.getConstant(Offsets[i], dl, PtrVT),
4030                             Flags);
4031 
4032     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4033                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4034                             MMOFlags, AAInfo, Ranges);
4035     Chains[ChainI] = L.getValue(1);
4036 
4037     if (MemVTs[i] != ValueVTs[i])
4038       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4039 
4040     Values[i] = L;
4041   }
4042 
4043   if (!ConstantMemory) {
4044     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4045                                 makeArrayRef(Chains.data(), ChainI));
4046     if (isVolatile)
4047       DAG.setRoot(Chain);
4048     else
4049       PendingLoads.push_back(Chain);
4050   }
4051 
4052   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4053                            DAG.getVTList(ValueVTs), Values));
4054 }
4055 
4056 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4057   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4058          "call visitStoreToSwiftError when backend supports swifterror");
4059 
4060   SmallVector<EVT, 4> ValueVTs;
4061   SmallVector<uint64_t, 4> Offsets;
4062   const Value *SrcV = I.getOperand(0);
4063   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4064                   SrcV->getType(), ValueVTs, &Offsets);
4065   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4066          "expect a single EVT for swifterror");
4067 
4068   SDValue Src = getValue(SrcV);
4069   // Create a virtual register, then update the virtual register.
4070   Register VReg =
4071       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4072   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4073   // Chain can be getRoot or getControlRoot.
4074   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4075                                       SDValue(Src.getNode(), Src.getResNo()));
4076   DAG.setRoot(CopyNode);
4077 }
4078 
4079 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4080   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4081          "call visitLoadFromSwiftError when backend supports swifterror");
4082 
4083   assert(!I.isVolatile() &&
4084          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4085          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4086          "Support volatile, non temporal, invariant for load_from_swift_error");
4087 
4088   const Value *SV = I.getOperand(0);
4089   Type *Ty = I.getType();
4090   AAMDNodes AAInfo;
4091   I.getAAMetadata(AAInfo);
4092   assert(
4093       (!AA ||
4094        !AA->pointsToConstantMemory(MemoryLocation(
4095            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4096            AAInfo))) &&
4097       "load_from_swift_error should not be constant memory");
4098 
4099   SmallVector<EVT, 4> ValueVTs;
4100   SmallVector<uint64_t, 4> Offsets;
4101   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4102                   ValueVTs, &Offsets);
4103   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4104          "expect a single EVT for swifterror");
4105 
4106   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4107   SDValue L = DAG.getCopyFromReg(
4108       getRoot(), getCurSDLoc(),
4109       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4110 
4111   setValue(&I, L);
4112 }
4113 
4114 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4115   if (I.isAtomic())
4116     return visitAtomicStore(I);
4117 
4118   const Value *SrcV = I.getOperand(0);
4119   const Value *PtrV = I.getOperand(1);
4120 
4121   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4122   if (TLI.supportSwiftError()) {
4123     // Swifterror values can come from either a function parameter with
4124     // swifterror attribute or an alloca with swifterror attribute.
4125     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4126       if (Arg->hasSwiftErrorAttr())
4127         return visitStoreToSwiftError(I);
4128     }
4129 
4130     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4131       if (Alloca->isSwiftError())
4132         return visitStoreToSwiftError(I);
4133     }
4134   }
4135 
4136   SmallVector<EVT, 4> ValueVTs, MemVTs;
4137   SmallVector<uint64_t, 4> Offsets;
4138   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4139                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4140   unsigned NumValues = ValueVTs.size();
4141   if (NumValues == 0)
4142     return;
4143 
4144   // Get the lowered operands. Note that we do this after
4145   // checking if NumResults is zero, because with zero results
4146   // the operands won't have values in the map.
4147   SDValue Src = getValue(SrcV);
4148   SDValue Ptr = getValue(PtrV);
4149 
4150   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4151   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4152   SDLoc dl = getCurSDLoc();
4153   Align Alignment = I.getAlign();
4154   AAMDNodes AAInfo;
4155   I.getAAMetadata(AAInfo);
4156 
4157   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4158 
4159   // An aggregate load cannot wrap around the address space, so offsets to its
4160   // parts don't wrap either.
4161   SDNodeFlags Flags;
4162   Flags.setNoUnsignedWrap(true);
4163 
4164   unsigned ChainI = 0;
4165   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4166     // See visitLoad comments.
4167     if (ChainI == MaxParallelChains) {
4168       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4169                                   makeArrayRef(Chains.data(), ChainI));
4170       Root = Chain;
4171       ChainI = 0;
4172     }
4173     SDValue Add =
4174         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4175     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4176     if (MemVTs[i] != ValueVTs[i])
4177       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4178     SDValue St =
4179         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4180                      Alignment, MMOFlags, AAInfo);
4181     Chains[ChainI] = St;
4182   }
4183 
4184   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4185                                   makeArrayRef(Chains.data(), ChainI));
4186   DAG.setRoot(StoreNode);
4187 }
4188 
4189 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4190                                            bool IsCompressing) {
4191   SDLoc sdl = getCurSDLoc();
4192 
4193   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4194                                MaybeAlign &Alignment) {
4195     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4196     Src0 = I.getArgOperand(0);
4197     Ptr = I.getArgOperand(1);
4198     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4199     Mask = I.getArgOperand(3);
4200   };
4201   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4202                                     MaybeAlign &Alignment) {
4203     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4204     Src0 = I.getArgOperand(0);
4205     Ptr = I.getArgOperand(1);
4206     Mask = I.getArgOperand(2);
4207     Alignment = None;
4208   };
4209 
4210   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4211   MaybeAlign Alignment;
4212   if (IsCompressing)
4213     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4214   else
4215     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4216 
4217   SDValue Ptr = getValue(PtrOperand);
4218   SDValue Src0 = getValue(Src0Operand);
4219   SDValue Mask = getValue(MaskOperand);
4220   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4221 
4222   EVT VT = Src0.getValueType();
4223   if (!Alignment)
4224     Alignment = DAG.getEVTAlign(VT);
4225 
4226   AAMDNodes AAInfo;
4227   I.getAAMetadata(AAInfo);
4228 
4229   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4230       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4231       // TODO: Make MachineMemOperands aware of scalable
4232       // vectors.
4233       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4234   SDValue StoreNode =
4235       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4236                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4237   DAG.setRoot(StoreNode);
4238   setValue(&I, StoreNode);
4239 }
4240 
4241 // Get a uniform base for the Gather/Scatter intrinsic.
4242 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4243 // We try to represent it as a base pointer + vector of indices.
4244 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4245 // The first operand of the GEP may be a single pointer or a vector of pointers
4246 // Example:
4247 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4248 //  or
4249 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4250 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4251 //
4252 // When the first GEP operand is a single pointer - it is the uniform base we
4253 // are looking for. If first operand of the GEP is a splat vector - we
4254 // extract the splat value and use it as a uniform base.
4255 // In all other cases the function returns 'false'.
4256 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4257                            ISD::MemIndexType &IndexType, SDValue &Scale,
4258                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4259   SelectionDAG& DAG = SDB->DAG;
4260   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4261   const DataLayout &DL = DAG.getDataLayout();
4262 
4263   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4264 
4265   // Handle splat constant pointer.
4266   if (auto *C = dyn_cast<Constant>(Ptr)) {
4267     C = C->getSplatValue();
4268     if (!C)
4269       return false;
4270 
4271     Base = SDB->getValue(C);
4272 
4273     unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements();
4274     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4275     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4276     IndexType = ISD::SIGNED_SCALED;
4277     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4278     return true;
4279   }
4280 
4281   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4282   if (!GEP || GEP->getParent() != CurBB)
4283     return false;
4284 
4285   if (GEP->getNumOperands() != 2)
4286     return false;
4287 
4288   const Value *BasePtr = GEP->getPointerOperand();
4289   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4290 
4291   // Make sure the base is scalar and the index is a vector.
4292   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4293     return false;
4294 
4295   Base = SDB->getValue(BasePtr);
4296   Index = SDB->getValue(IndexVal);
4297   IndexType = ISD::SIGNED_SCALED;
4298   Scale = DAG.getTargetConstant(
4299               DL.getTypeAllocSize(GEP->getResultElementType()),
4300               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4301   return true;
4302 }
4303 
4304 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4305   SDLoc sdl = getCurSDLoc();
4306 
4307   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4308   const Value *Ptr = I.getArgOperand(1);
4309   SDValue Src0 = getValue(I.getArgOperand(0));
4310   SDValue Mask = getValue(I.getArgOperand(3));
4311   EVT VT = Src0.getValueType();
4312   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4313                         ->getMaybeAlignValue()
4314                         .getValueOr(DAG.getEVTAlign(VT));
4315   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4316 
4317   AAMDNodes AAInfo;
4318   I.getAAMetadata(AAInfo);
4319 
4320   SDValue Base;
4321   SDValue Index;
4322   ISD::MemIndexType IndexType;
4323   SDValue Scale;
4324   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4325                                     I.getParent());
4326 
4327   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4328   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4329       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4330       // TODO: Make MachineMemOperands aware of scalable
4331       // vectors.
4332       MemoryLocation::UnknownSize, Alignment, AAInfo);
4333   if (!UniformBase) {
4334     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4335     Index = getValue(Ptr);
4336     IndexType = ISD::SIGNED_SCALED;
4337     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4338   }
4339   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4340   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4341                                          Ops, MMO, IndexType);
4342   DAG.setRoot(Scatter);
4343   setValue(&I, Scatter);
4344 }
4345 
4346 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4347   SDLoc sdl = getCurSDLoc();
4348 
4349   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4350                               MaybeAlign &Alignment) {
4351     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4352     Ptr = I.getArgOperand(0);
4353     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4354     Mask = I.getArgOperand(2);
4355     Src0 = I.getArgOperand(3);
4356   };
4357   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4358                                  MaybeAlign &Alignment) {
4359     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4360     Ptr = I.getArgOperand(0);
4361     Alignment = None;
4362     Mask = I.getArgOperand(1);
4363     Src0 = I.getArgOperand(2);
4364   };
4365 
4366   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4367   MaybeAlign Alignment;
4368   if (IsExpanding)
4369     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4370   else
4371     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4372 
4373   SDValue Ptr = getValue(PtrOperand);
4374   SDValue Src0 = getValue(Src0Operand);
4375   SDValue Mask = getValue(MaskOperand);
4376   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4377 
4378   EVT VT = Src0.getValueType();
4379   if (!Alignment)
4380     Alignment = DAG.getEVTAlign(VT);
4381 
4382   AAMDNodes AAInfo;
4383   I.getAAMetadata(AAInfo);
4384   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4385 
4386   // Do not serialize masked loads of constant memory with anything.
4387   MemoryLocation ML;
4388   if (VT.isScalableVector())
4389     ML = MemoryLocation(PtrOperand);
4390   else
4391     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4392                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4393                            AAInfo);
4394   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4395 
4396   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4397 
4398   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4399       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4400       // TODO: Make MachineMemOperands aware of scalable
4401       // vectors.
4402       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4403 
4404   SDValue Load =
4405       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4406                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4407   if (AddToChain)
4408     PendingLoads.push_back(Load.getValue(1));
4409   setValue(&I, Load);
4410 }
4411 
4412 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4413   SDLoc sdl = getCurSDLoc();
4414 
4415   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4416   const Value *Ptr = I.getArgOperand(0);
4417   SDValue Src0 = getValue(I.getArgOperand(3));
4418   SDValue Mask = getValue(I.getArgOperand(2));
4419 
4420   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4421   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4422   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4423                         ->getMaybeAlignValue()
4424                         .getValueOr(DAG.getEVTAlign(VT));
4425 
4426   AAMDNodes AAInfo;
4427   I.getAAMetadata(AAInfo);
4428   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4429 
4430   SDValue Root = DAG.getRoot();
4431   SDValue Base;
4432   SDValue Index;
4433   ISD::MemIndexType IndexType;
4434   SDValue Scale;
4435   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4436                                     I.getParent());
4437   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4438   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4439       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4440       // TODO: Make MachineMemOperands aware of scalable
4441       // vectors.
4442       MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges);
4443 
4444   if (!UniformBase) {
4445     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4446     Index = getValue(Ptr);
4447     IndexType = ISD::SIGNED_SCALED;
4448     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4449   }
4450   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4451   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4452                                        Ops, MMO, IndexType);
4453 
4454   PendingLoads.push_back(Gather.getValue(1));
4455   setValue(&I, Gather);
4456 }
4457 
4458 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4459   SDLoc dl = getCurSDLoc();
4460   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4461   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4462   SyncScope::ID SSID = I.getSyncScopeID();
4463 
4464   SDValue InChain = getRoot();
4465 
4466   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4467   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4468 
4469   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4470   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4471 
4472   MachineFunction &MF = DAG.getMachineFunction();
4473   MachineMemOperand *MMO = MF.getMachineMemOperand(
4474       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4475       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4476       FailureOrdering);
4477 
4478   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4479                                    dl, MemVT, VTs, InChain,
4480                                    getValue(I.getPointerOperand()),
4481                                    getValue(I.getCompareOperand()),
4482                                    getValue(I.getNewValOperand()), MMO);
4483 
4484   SDValue OutChain = L.getValue(2);
4485 
4486   setValue(&I, L);
4487   DAG.setRoot(OutChain);
4488 }
4489 
4490 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4491   SDLoc dl = getCurSDLoc();
4492   ISD::NodeType NT;
4493   switch (I.getOperation()) {
4494   default: llvm_unreachable("Unknown atomicrmw operation");
4495   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4496   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4497   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4498   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4499   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4500   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4501   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4502   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4503   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4504   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4505   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4506   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4507   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4508   }
4509   AtomicOrdering Ordering = I.getOrdering();
4510   SyncScope::ID SSID = I.getSyncScopeID();
4511 
4512   SDValue InChain = getRoot();
4513 
4514   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4516   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4517 
4518   MachineFunction &MF = DAG.getMachineFunction();
4519   MachineMemOperand *MMO = MF.getMachineMemOperand(
4520       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4521       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4522 
4523   SDValue L =
4524     DAG.getAtomic(NT, dl, MemVT, InChain,
4525                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4526                   MMO);
4527 
4528   SDValue OutChain = L.getValue(1);
4529 
4530   setValue(&I, L);
4531   DAG.setRoot(OutChain);
4532 }
4533 
4534 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4535   SDLoc dl = getCurSDLoc();
4536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4537   SDValue Ops[3];
4538   Ops[0] = getRoot();
4539   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4540                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4541   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4542                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4543   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4544 }
4545 
4546 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4547   SDLoc dl = getCurSDLoc();
4548   AtomicOrdering Order = I.getOrdering();
4549   SyncScope::ID SSID = I.getSyncScopeID();
4550 
4551   SDValue InChain = getRoot();
4552 
4553   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4554   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4555   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4556 
4557   if (!TLI.supportsUnalignedAtomics() &&
4558       I.getAlignment() < MemVT.getSizeInBits() / 8)
4559     report_fatal_error("Cannot generate unaligned atomic load");
4560 
4561   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4562 
4563   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4564       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4565       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4566 
4567   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4568 
4569   SDValue Ptr = getValue(I.getPointerOperand());
4570 
4571   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4572     // TODO: Once this is better exercised by tests, it should be merged with
4573     // the normal path for loads to prevent future divergence.
4574     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4575     if (MemVT != VT)
4576       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4577 
4578     setValue(&I, L);
4579     SDValue OutChain = L.getValue(1);
4580     if (!I.isUnordered())
4581       DAG.setRoot(OutChain);
4582     else
4583       PendingLoads.push_back(OutChain);
4584     return;
4585   }
4586 
4587   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4588                             Ptr, MMO);
4589 
4590   SDValue OutChain = L.getValue(1);
4591   if (MemVT != VT)
4592     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4593 
4594   setValue(&I, L);
4595   DAG.setRoot(OutChain);
4596 }
4597 
4598 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4599   SDLoc dl = getCurSDLoc();
4600 
4601   AtomicOrdering Ordering = I.getOrdering();
4602   SyncScope::ID SSID = I.getSyncScopeID();
4603 
4604   SDValue InChain = getRoot();
4605 
4606   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4607   EVT MemVT =
4608       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4609 
4610   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4611     report_fatal_error("Cannot generate unaligned atomic store");
4612 
4613   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4614 
4615   MachineFunction &MF = DAG.getMachineFunction();
4616   MachineMemOperand *MMO = MF.getMachineMemOperand(
4617       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4618       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4619 
4620   SDValue Val = getValue(I.getValueOperand());
4621   if (Val.getValueType() != MemVT)
4622     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4623   SDValue Ptr = getValue(I.getPointerOperand());
4624 
4625   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4626     // TODO: Once this is better exercised by tests, it should be merged with
4627     // the normal path for stores to prevent future divergence.
4628     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4629     DAG.setRoot(S);
4630     return;
4631   }
4632   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4633                                    Ptr, Val, MMO);
4634 
4635 
4636   DAG.setRoot(OutChain);
4637 }
4638 
4639 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4640 /// node.
4641 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4642                                                unsigned Intrinsic) {
4643   // Ignore the callsite's attributes. A specific call site may be marked with
4644   // readnone, but the lowering code will expect the chain based on the
4645   // definition.
4646   const Function *F = I.getCalledFunction();
4647   bool HasChain = !F->doesNotAccessMemory();
4648   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4649 
4650   // Build the operand list.
4651   SmallVector<SDValue, 8> Ops;
4652   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4653     if (OnlyLoad) {
4654       // We don't need to serialize loads against other loads.
4655       Ops.push_back(DAG.getRoot());
4656     } else {
4657       Ops.push_back(getRoot());
4658     }
4659   }
4660 
4661   // Info is set by getTgtMemInstrinsic
4662   TargetLowering::IntrinsicInfo Info;
4663   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4664   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4665                                                DAG.getMachineFunction(),
4666                                                Intrinsic);
4667 
4668   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4669   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4670       Info.opc == ISD::INTRINSIC_W_CHAIN)
4671     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4672                                         TLI.getPointerTy(DAG.getDataLayout())));
4673 
4674   // Add all operands of the call to the operand list.
4675   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4676     const Value *Arg = I.getArgOperand(i);
4677     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4678       Ops.push_back(getValue(Arg));
4679       continue;
4680     }
4681 
4682     // Use TargetConstant instead of a regular constant for immarg.
4683     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4684     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4685       assert(CI->getBitWidth() <= 64 &&
4686              "large intrinsic immediates not handled");
4687       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4688     } else {
4689       Ops.push_back(
4690           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4691     }
4692   }
4693 
4694   SmallVector<EVT, 4> ValueVTs;
4695   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4696 
4697   if (HasChain)
4698     ValueVTs.push_back(MVT::Other);
4699 
4700   SDVTList VTs = DAG.getVTList(ValueVTs);
4701 
4702   // Create the node.
4703   SDValue Result;
4704   if (IsTgtIntrinsic) {
4705     // This is target intrinsic that touches memory
4706     AAMDNodes AAInfo;
4707     I.getAAMetadata(AAInfo);
4708     Result =
4709         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4710                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4711                                 Info.align, Info.flags, Info.size, AAInfo);
4712   } else if (!HasChain) {
4713     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4714   } else if (!I.getType()->isVoidTy()) {
4715     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4716   } else {
4717     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4718   }
4719 
4720   if (HasChain) {
4721     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4722     if (OnlyLoad)
4723       PendingLoads.push_back(Chain);
4724     else
4725       DAG.setRoot(Chain);
4726   }
4727 
4728   if (!I.getType()->isVoidTy()) {
4729     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4730       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4731       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4732     } else
4733       Result = lowerRangeToAssertZExt(DAG, I, Result);
4734 
4735     MaybeAlign Alignment = I.getRetAlign();
4736     if (!Alignment)
4737       Alignment = F->getAttributes().getRetAlignment();
4738     // Insert `assertalign` node if there's an alignment.
4739     if (InsertAssertAlign && Alignment) {
4740       Result =
4741           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4742     }
4743 
4744     setValue(&I, Result);
4745   }
4746 }
4747 
4748 /// GetSignificand - Get the significand and build it into a floating-point
4749 /// number with exponent of 1:
4750 ///
4751 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4752 ///
4753 /// where Op is the hexadecimal representation of floating point value.
4754 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4755   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4756                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4757   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4758                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4759   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4760 }
4761 
4762 /// GetExponent - Get the exponent:
4763 ///
4764 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4765 ///
4766 /// where Op is the hexadecimal representation of floating point value.
4767 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4768                            const TargetLowering &TLI, const SDLoc &dl) {
4769   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4770                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4771   SDValue t1 = DAG.getNode(
4772       ISD::SRL, dl, MVT::i32, t0,
4773       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4774   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4775                            DAG.getConstant(127, dl, MVT::i32));
4776   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4777 }
4778 
4779 /// getF32Constant - Get 32-bit floating point constant.
4780 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4781                               const SDLoc &dl) {
4782   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4783                            MVT::f32);
4784 }
4785 
4786 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4787                                        SelectionDAG &DAG) {
4788   // TODO: What fast-math-flags should be set on the floating-point nodes?
4789 
4790   //   IntegerPartOfX = ((int32_t)(t0);
4791   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4792 
4793   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4794   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4795   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4796 
4797   //   IntegerPartOfX <<= 23;
4798   IntegerPartOfX = DAG.getNode(
4799       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4800       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4801                                   DAG.getDataLayout())));
4802 
4803   SDValue TwoToFractionalPartOfX;
4804   if (LimitFloatPrecision <= 6) {
4805     // For floating-point precision of 6:
4806     //
4807     //   TwoToFractionalPartOfX =
4808     //     0.997535578f +
4809     //       (0.735607626f + 0.252464424f * x) * x;
4810     //
4811     // error 0.0144103317, which is 6 bits
4812     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4813                              getF32Constant(DAG, 0x3e814304, dl));
4814     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4815                              getF32Constant(DAG, 0x3f3c50c8, dl));
4816     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4817     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4818                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4819   } else if (LimitFloatPrecision <= 12) {
4820     // For floating-point precision of 12:
4821     //
4822     //   TwoToFractionalPartOfX =
4823     //     0.999892986f +
4824     //       (0.696457318f +
4825     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4826     //
4827     // error 0.000107046256, which is 13 to 14 bits
4828     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4829                              getF32Constant(DAG, 0x3da235e3, dl));
4830     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4831                              getF32Constant(DAG, 0x3e65b8f3, dl));
4832     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4833     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4834                              getF32Constant(DAG, 0x3f324b07, dl));
4835     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4836     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4837                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4838   } else { // LimitFloatPrecision <= 18
4839     // For floating-point precision of 18:
4840     //
4841     //   TwoToFractionalPartOfX =
4842     //     0.999999982f +
4843     //       (0.693148872f +
4844     //         (0.240227044f +
4845     //           (0.554906021e-1f +
4846     //             (0.961591928e-2f +
4847     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4848     // error 2.47208000*10^(-7), which is better than 18 bits
4849     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4850                              getF32Constant(DAG, 0x3924b03e, dl));
4851     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4852                              getF32Constant(DAG, 0x3ab24b87, dl));
4853     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4854     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4855                              getF32Constant(DAG, 0x3c1d8c17, dl));
4856     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4857     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4858                              getF32Constant(DAG, 0x3d634a1d, dl));
4859     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4860     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4861                              getF32Constant(DAG, 0x3e75fe14, dl));
4862     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4863     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4864                               getF32Constant(DAG, 0x3f317234, dl));
4865     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4866     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4867                                          getF32Constant(DAG, 0x3f800000, dl));
4868   }
4869 
4870   // Add the exponent into the result in integer domain.
4871   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4872   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4873                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4874 }
4875 
4876 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4877 /// limited-precision mode.
4878 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4879                          const TargetLowering &TLI) {
4880   if (Op.getValueType() == MVT::f32 &&
4881       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4882 
4883     // Put the exponent in the right bit position for later addition to the
4884     // final result:
4885     //
4886     // t0 = Op * log2(e)
4887 
4888     // TODO: What fast-math-flags should be set here?
4889     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4890                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4891     return getLimitedPrecisionExp2(t0, dl, DAG);
4892   }
4893 
4894   // No special expansion.
4895   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4896 }
4897 
4898 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4899 /// limited-precision mode.
4900 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4901                          const TargetLowering &TLI) {
4902   // TODO: What fast-math-flags should be set on the floating-point nodes?
4903 
4904   if (Op.getValueType() == MVT::f32 &&
4905       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4906     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4907 
4908     // Scale the exponent by log(2).
4909     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4910     SDValue LogOfExponent =
4911         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4912                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
4913 
4914     // Get the significand and build it into a floating-point number with
4915     // exponent of 1.
4916     SDValue X = GetSignificand(DAG, Op1, dl);
4917 
4918     SDValue LogOfMantissa;
4919     if (LimitFloatPrecision <= 6) {
4920       // For floating-point precision of 6:
4921       //
4922       //   LogofMantissa =
4923       //     -1.1609546f +
4924       //       (1.4034025f - 0.23903021f * x) * x;
4925       //
4926       // error 0.0034276066, which is better than 8 bits
4927       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4928                                getF32Constant(DAG, 0xbe74c456, dl));
4929       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4930                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4931       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4932       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4933                                   getF32Constant(DAG, 0x3f949a29, dl));
4934     } else if (LimitFloatPrecision <= 12) {
4935       // For floating-point precision of 12:
4936       //
4937       //   LogOfMantissa =
4938       //     -1.7417939f +
4939       //       (2.8212026f +
4940       //         (-1.4699568f +
4941       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4942       //
4943       // error 0.000061011436, which is 14 bits
4944       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4945                                getF32Constant(DAG, 0xbd67b6d6, dl));
4946       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4947                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4948       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4949       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4950                                getF32Constant(DAG, 0x3fbc278b, dl));
4951       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4952       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4953                                getF32Constant(DAG, 0x40348e95, dl));
4954       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4955       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4956                                   getF32Constant(DAG, 0x3fdef31a, dl));
4957     } else { // LimitFloatPrecision <= 18
4958       // For floating-point precision of 18:
4959       //
4960       //   LogOfMantissa =
4961       //     -2.1072184f +
4962       //       (4.2372794f +
4963       //         (-3.7029485f +
4964       //           (2.2781945f +
4965       //             (-0.87823314f +
4966       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4967       //
4968       // error 0.0000023660568, which is better than 18 bits
4969       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4970                                getF32Constant(DAG, 0xbc91e5ac, dl));
4971       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4972                                getF32Constant(DAG, 0x3e4350aa, dl));
4973       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4974       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4975                                getF32Constant(DAG, 0x3f60d3e3, dl));
4976       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4977       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4978                                getF32Constant(DAG, 0x4011cdf0, dl));
4979       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4980       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4981                                getF32Constant(DAG, 0x406cfd1c, dl));
4982       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4983       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4984                                getF32Constant(DAG, 0x408797cb, dl));
4985       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4986       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4987                                   getF32Constant(DAG, 0x4006dcab, dl));
4988     }
4989 
4990     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4991   }
4992 
4993   // No special expansion.
4994   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4995 }
4996 
4997 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4998 /// limited-precision mode.
4999 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5000                           const TargetLowering &TLI) {
5001   // TODO: What fast-math-flags should be set on the floating-point nodes?
5002 
5003   if (Op.getValueType() == MVT::f32 &&
5004       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5005     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5006 
5007     // Get the exponent.
5008     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5009 
5010     // Get the significand and build it into a floating-point number with
5011     // exponent of 1.
5012     SDValue X = GetSignificand(DAG, Op1, dl);
5013 
5014     // Different possible minimax approximations of significand in
5015     // floating-point for various degrees of accuracy over [1,2].
5016     SDValue Log2ofMantissa;
5017     if (LimitFloatPrecision <= 6) {
5018       // For floating-point precision of 6:
5019       //
5020       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5021       //
5022       // error 0.0049451742, which is more than 7 bits
5023       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5024                                getF32Constant(DAG, 0xbeb08fe0, dl));
5025       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5026                                getF32Constant(DAG, 0x40019463, dl));
5027       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5028       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5029                                    getF32Constant(DAG, 0x3fd6633d, dl));
5030     } else if (LimitFloatPrecision <= 12) {
5031       // For floating-point precision of 12:
5032       //
5033       //   Log2ofMantissa =
5034       //     -2.51285454f +
5035       //       (4.07009056f +
5036       //         (-2.12067489f +
5037       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5038       //
5039       // error 0.0000876136000, which is better than 13 bits
5040       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5041                                getF32Constant(DAG, 0xbda7262e, dl));
5042       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5043                                getF32Constant(DAG, 0x3f25280b, dl));
5044       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5045       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5046                                getF32Constant(DAG, 0x4007b923, dl));
5047       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5048       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5049                                getF32Constant(DAG, 0x40823e2f, dl));
5050       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5051       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5052                                    getF32Constant(DAG, 0x4020d29c, dl));
5053     } else { // LimitFloatPrecision <= 18
5054       // For floating-point precision of 18:
5055       //
5056       //   Log2ofMantissa =
5057       //     -3.0400495f +
5058       //       (6.1129976f +
5059       //         (-5.3420409f +
5060       //           (3.2865683f +
5061       //             (-1.2669343f +
5062       //               (0.27515199f -
5063       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5064       //
5065       // error 0.0000018516, which is better than 18 bits
5066       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5067                                getF32Constant(DAG, 0xbcd2769e, dl));
5068       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5069                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5070       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5071       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5072                                getF32Constant(DAG, 0x3fa22ae7, dl));
5073       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5074       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5075                                getF32Constant(DAG, 0x40525723, dl));
5076       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5077       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5078                                getF32Constant(DAG, 0x40aaf200, dl));
5079       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5080       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5081                                getF32Constant(DAG, 0x40c39dad, dl));
5082       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5083       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5084                                    getF32Constant(DAG, 0x4042902c, dl));
5085     }
5086 
5087     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5088   }
5089 
5090   // No special expansion.
5091   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5092 }
5093 
5094 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5095 /// limited-precision mode.
5096 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5097                            const TargetLowering &TLI) {
5098   // TODO: What fast-math-flags should be set on the floating-point nodes?
5099 
5100   if (Op.getValueType() == MVT::f32 &&
5101       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5102     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5103 
5104     // Scale the exponent by log10(2) [0.30102999f].
5105     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5106     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5107                                         getF32Constant(DAG, 0x3e9a209a, dl));
5108 
5109     // Get the significand and build it into a floating-point number with
5110     // exponent of 1.
5111     SDValue X = GetSignificand(DAG, Op1, dl);
5112 
5113     SDValue Log10ofMantissa;
5114     if (LimitFloatPrecision <= 6) {
5115       // For floating-point precision of 6:
5116       //
5117       //   Log10ofMantissa =
5118       //     -0.50419619f +
5119       //       (0.60948995f - 0.10380950f * x) * x;
5120       //
5121       // error 0.0014886165, which is 6 bits
5122       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5123                                getF32Constant(DAG, 0xbdd49a13, dl));
5124       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5125                                getF32Constant(DAG, 0x3f1c0789, dl));
5126       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5127       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5128                                     getF32Constant(DAG, 0x3f011300, dl));
5129     } else if (LimitFloatPrecision <= 12) {
5130       // For floating-point precision of 12:
5131       //
5132       //   Log10ofMantissa =
5133       //     -0.64831180f +
5134       //       (0.91751397f +
5135       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5136       //
5137       // error 0.00019228036, which is better than 12 bits
5138       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5139                                getF32Constant(DAG, 0x3d431f31, dl));
5140       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5141                                getF32Constant(DAG, 0x3ea21fb2, dl));
5142       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5143       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5144                                getF32Constant(DAG, 0x3f6ae232, dl));
5145       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5146       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5147                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5148     } else { // LimitFloatPrecision <= 18
5149       // For floating-point precision of 18:
5150       //
5151       //   Log10ofMantissa =
5152       //     -0.84299375f +
5153       //       (1.5327582f +
5154       //         (-1.0688956f +
5155       //           (0.49102474f +
5156       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5157       //
5158       // error 0.0000037995730, which is better than 18 bits
5159       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5160                                getF32Constant(DAG, 0x3c5d51ce, dl));
5161       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5162                                getF32Constant(DAG, 0x3e00685a, dl));
5163       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5164       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5165                                getF32Constant(DAG, 0x3efb6798, dl));
5166       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5167       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5168                                getF32Constant(DAG, 0x3f88d192, dl));
5169       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5170       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5171                                getF32Constant(DAG, 0x3fc4316c, dl));
5172       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5173       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5174                                     getF32Constant(DAG, 0x3f57ce70, dl));
5175     }
5176 
5177     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5178   }
5179 
5180   // No special expansion.
5181   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5182 }
5183 
5184 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5185 /// limited-precision mode.
5186 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5187                           const TargetLowering &TLI) {
5188   if (Op.getValueType() == MVT::f32 &&
5189       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5190     return getLimitedPrecisionExp2(Op, dl, DAG);
5191 
5192   // No special expansion.
5193   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5194 }
5195 
5196 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5197 /// limited-precision mode with x == 10.0f.
5198 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5199                          SelectionDAG &DAG, const TargetLowering &TLI) {
5200   bool IsExp10 = false;
5201   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5202       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5203     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5204       APFloat Ten(10.0f);
5205       IsExp10 = LHSC->isExactlyValue(Ten);
5206     }
5207   }
5208 
5209   // TODO: What fast-math-flags should be set on the FMUL node?
5210   if (IsExp10) {
5211     // Put the exponent in the right bit position for later addition to the
5212     // final result:
5213     //
5214     //   #define LOG2OF10 3.3219281f
5215     //   t0 = Op * LOG2OF10;
5216     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5217                              getF32Constant(DAG, 0x40549a78, dl));
5218     return getLimitedPrecisionExp2(t0, dl, DAG);
5219   }
5220 
5221   // No special expansion.
5222   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5223 }
5224 
5225 /// ExpandPowI - Expand a llvm.powi intrinsic.
5226 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5227                           SelectionDAG &DAG) {
5228   // If RHS is a constant, we can expand this out to a multiplication tree,
5229   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5230   // optimizing for size, we only want to do this if the expansion would produce
5231   // a small number of multiplies, otherwise we do the full expansion.
5232   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5233     // Get the exponent as a positive value.
5234     unsigned Val = RHSC->getSExtValue();
5235     if ((int)Val < 0) Val = -Val;
5236 
5237     // powi(x, 0) -> 1.0
5238     if (Val == 0)
5239       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5240 
5241     bool OptForSize = DAG.shouldOptForSize();
5242     if (!OptForSize ||
5243         // If optimizing for size, don't insert too many multiplies.
5244         // This inserts up to 5 multiplies.
5245         countPopulation(Val) + Log2_32(Val) < 7) {
5246       // We use the simple binary decomposition method to generate the multiply
5247       // sequence.  There are more optimal ways to do this (for example,
5248       // powi(x,15) generates one more multiply than it should), but this has
5249       // the benefit of being both really simple and much better than a libcall.
5250       SDValue Res;  // Logically starts equal to 1.0
5251       SDValue CurSquare = LHS;
5252       // TODO: Intrinsics should have fast-math-flags that propagate to these
5253       // nodes.
5254       while (Val) {
5255         if (Val & 1) {
5256           if (Res.getNode())
5257             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5258           else
5259             Res = CurSquare;  // 1.0*CurSquare.
5260         }
5261 
5262         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5263                                 CurSquare, CurSquare);
5264         Val >>= 1;
5265       }
5266 
5267       // If the original was negative, invert the result, producing 1/(x*x*x).
5268       if (RHSC->getSExtValue() < 0)
5269         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5270                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5271       return Res;
5272     }
5273   }
5274 
5275   // Otherwise, expand to a libcall.
5276   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5277 }
5278 
5279 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5280                             SDValue LHS, SDValue RHS, SDValue Scale,
5281                             SelectionDAG &DAG, const TargetLowering &TLI) {
5282   EVT VT = LHS.getValueType();
5283   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5284   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5285   LLVMContext &Ctx = *DAG.getContext();
5286 
5287   // If the type is legal but the operation isn't, this node might survive all
5288   // the way to operation legalization. If we end up there and we do not have
5289   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5290   // node.
5291 
5292   // Coax the legalizer into expanding the node during type legalization instead
5293   // by bumping the size by one bit. This will force it to Promote, enabling the
5294   // early expansion and avoiding the need to expand later.
5295 
5296   // We don't have to do this if Scale is 0; that can always be expanded, unless
5297   // it's a saturating signed operation. Those can experience true integer
5298   // division overflow, a case which we must avoid.
5299 
5300   // FIXME: We wouldn't have to do this (or any of the early
5301   // expansion/promotion) if it was possible to expand a libcall of an
5302   // illegal type during operation legalization. But it's not, so things
5303   // get a bit hacky.
5304   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5305   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5306       (TLI.isTypeLegal(VT) ||
5307        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5308     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5309         Opcode, VT, ScaleInt);
5310     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5311       EVT PromVT;
5312       if (VT.isScalarInteger())
5313         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5314       else if (VT.isVector()) {
5315         PromVT = VT.getVectorElementType();
5316         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5317         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5318       } else
5319         llvm_unreachable("Wrong VT for DIVFIX?");
5320       if (Signed) {
5321         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5322         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5323       } else {
5324         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5325         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5326       }
5327       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5328       // For saturating operations, we need to shift up the LHS to get the
5329       // proper saturation width, and then shift down again afterwards.
5330       if (Saturating)
5331         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5332                           DAG.getConstant(1, DL, ShiftTy));
5333       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5334       if (Saturating)
5335         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5336                           DAG.getConstant(1, DL, ShiftTy));
5337       return DAG.getZExtOrTrunc(Res, DL, VT);
5338     }
5339   }
5340 
5341   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5342 }
5343 
5344 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5345 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5346 static void
5347 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5348                      const SDValue &N) {
5349   switch (N.getOpcode()) {
5350   case ISD::CopyFromReg: {
5351     SDValue Op = N.getOperand(1);
5352     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5353                       Op.getValueType().getSizeInBits());
5354     return;
5355   }
5356   case ISD::BITCAST:
5357   case ISD::AssertZext:
5358   case ISD::AssertSext:
5359   case ISD::TRUNCATE:
5360     getUnderlyingArgRegs(Regs, N.getOperand(0));
5361     return;
5362   case ISD::BUILD_PAIR:
5363   case ISD::BUILD_VECTOR:
5364   case ISD::CONCAT_VECTORS:
5365     for (SDValue Op : N->op_values())
5366       getUnderlyingArgRegs(Regs, Op);
5367     return;
5368   default:
5369     return;
5370   }
5371 }
5372 
5373 /// If the DbgValueInst is a dbg_value of a function argument, create the
5374 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5375 /// instruction selection, they will be inserted to the entry BB.
5376 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5377     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5378     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5379   const Argument *Arg = dyn_cast<Argument>(V);
5380   if (!Arg)
5381     return false;
5382 
5383   if (!IsDbgDeclare) {
5384     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5385     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5386     // the entry block.
5387     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5388     if (!IsInEntryBlock)
5389       return false;
5390 
5391     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5392     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5393     // variable that also is a param.
5394     //
5395     // Although, if we are at the top of the entry block already, we can still
5396     // emit using ArgDbgValue. This might catch some situations when the
5397     // dbg.value refers to an argument that isn't used in the entry block, so
5398     // any CopyToReg node would be optimized out and the only way to express
5399     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5400     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5401     // we should only emit as ArgDbgValue if the Variable is an argument to the
5402     // current function, and the dbg.value intrinsic is found in the entry
5403     // block.
5404     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5405         !DL->getInlinedAt();
5406     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5407     if (!IsInPrologue && !VariableIsFunctionInputArg)
5408       return false;
5409 
5410     // Here we assume that a function argument on IR level only can be used to
5411     // describe one input parameter on source level. If we for example have
5412     // source code like this
5413     //
5414     //    struct A { long x, y; };
5415     //    void foo(struct A a, long b) {
5416     //      ...
5417     //      b = a.x;
5418     //      ...
5419     //    }
5420     //
5421     // and IR like this
5422     //
5423     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5424     //  entry:
5425     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5426     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5427     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5428     //    ...
5429     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5430     //    ...
5431     //
5432     // then the last dbg.value is describing a parameter "b" using a value that
5433     // is an argument. But since we already has used %a1 to describe a parameter
5434     // we should not handle that last dbg.value here (that would result in an
5435     // incorrect hoisting of the DBG_VALUE to the function entry).
5436     // Notice that we allow one dbg.value per IR level argument, to accommodate
5437     // for the situation with fragments above.
5438     if (VariableIsFunctionInputArg) {
5439       unsigned ArgNo = Arg->getArgNo();
5440       if (ArgNo >= FuncInfo.DescribedArgs.size())
5441         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5442       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5443         return false;
5444       FuncInfo.DescribedArgs.set(ArgNo);
5445     }
5446   }
5447 
5448   MachineFunction &MF = DAG.getMachineFunction();
5449   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5450 
5451   bool IsIndirect = false;
5452   Optional<MachineOperand> Op;
5453   // Some arguments' frame index is recorded during argument lowering.
5454   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5455   if (FI != std::numeric_limits<int>::max())
5456     Op = MachineOperand::CreateFI(FI);
5457 
5458   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5459   if (!Op && N.getNode()) {
5460     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5461     Register Reg;
5462     if (ArgRegsAndSizes.size() == 1)
5463       Reg = ArgRegsAndSizes.front().first;
5464 
5465     if (Reg && Reg.isVirtual()) {
5466       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5467       Register PR = RegInfo.getLiveInPhysReg(Reg);
5468       if (PR)
5469         Reg = PR;
5470     }
5471     if (Reg) {
5472       Op = MachineOperand::CreateReg(Reg, false);
5473       IsIndirect = IsDbgDeclare;
5474     }
5475   }
5476 
5477   if (!Op && N.getNode()) {
5478     // Check if frame index is available.
5479     SDValue LCandidate = peekThroughBitcasts(N);
5480     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5481       if (FrameIndexSDNode *FINode =
5482           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5483         Op = MachineOperand::CreateFI(FINode->getIndex());
5484   }
5485 
5486   if (!Op) {
5487     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5488     auto splitMultiRegDbgValue
5489       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5490       unsigned Offset = 0;
5491       for (auto RegAndSize : SplitRegs) {
5492         // If the expression is already a fragment, the current register
5493         // offset+size might extend beyond the fragment. In this case, only
5494         // the register bits that are inside the fragment are relevant.
5495         int RegFragmentSizeInBits = RegAndSize.second;
5496         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5497           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5498           // The register is entirely outside the expression fragment,
5499           // so is irrelevant for debug info.
5500           if (Offset >= ExprFragmentSizeInBits)
5501             break;
5502           // The register is partially outside the expression fragment, only
5503           // the low bits within the fragment are relevant for debug info.
5504           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5505             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5506           }
5507         }
5508 
5509         auto FragmentExpr = DIExpression::createFragmentExpression(
5510             Expr, Offset, RegFragmentSizeInBits);
5511         Offset += RegAndSize.second;
5512         // If a valid fragment expression cannot be created, the variable's
5513         // correct value cannot be determined and so it is set as Undef.
5514         if (!FragmentExpr) {
5515           SDDbgValue *SDV = DAG.getConstantDbgValue(
5516               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5517           DAG.AddDbgValue(SDV, nullptr, false);
5518           continue;
5519         }
5520         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5521         FuncInfo.ArgDbgValues.push_back(
5522           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5523                   RegAndSize.first, Variable, *FragmentExpr));
5524       }
5525     };
5526 
5527     // Check if ValueMap has reg number.
5528     DenseMap<const Value *, Register>::const_iterator
5529       VMI = FuncInfo.ValueMap.find(V);
5530     if (VMI != FuncInfo.ValueMap.end()) {
5531       const auto &TLI = DAG.getTargetLoweringInfo();
5532       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5533                        V->getType(), getABIRegCopyCC(V));
5534       if (RFV.occupiesMultipleRegs()) {
5535         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5536         return true;
5537       }
5538 
5539       Op = MachineOperand::CreateReg(VMI->second, false);
5540       IsIndirect = IsDbgDeclare;
5541     } else if (ArgRegsAndSizes.size() > 1) {
5542       // This was split due to the calling convention, and no virtual register
5543       // mapping exists for the value.
5544       splitMultiRegDbgValue(ArgRegsAndSizes);
5545       return true;
5546     }
5547   }
5548 
5549   if (!Op)
5550     return false;
5551 
5552   assert(Variable->isValidLocationForIntrinsic(DL) &&
5553          "Expected inlined-at fields to agree");
5554   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5555   FuncInfo.ArgDbgValues.push_back(
5556       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5557               *Op, Variable, Expr));
5558 
5559   return true;
5560 }
5561 
5562 /// Return the appropriate SDDbgValue based on N.
5563 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5564                                              DILocalVariable *Variable,
5565                                              DIExpression *Expr,
5566                                              const DebugLoc &dl,
5567                                              unsigned DbgSDNodeOrder) {
5568   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5569     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5570     // stack slot locations.
5571     //
5572     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5573     // debug values here after optimization:
5574     //
5575     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5576     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5577     //
5578     // Both describe the direct values of their associated variables.
5579     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5580                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5581   }
5582   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5583                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5584 }
5585 
5586 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5587   switch (Intrinsic) {
5588   case Intrinsic::smul_fix:
5589     return ISD::SMULFIX;
5590   case Intrinsic::umul_fix:
5591     return ISD::UMULFIX;
5592   case Intrinsic::smul_fix_sat:
5593     return ISD::SMULFIXSAT;
5594   case Intrinsic::umul_fix_sat:
5595     return ISD::UMULFIXSAT;
5596   case Intrinsic::sdiv_fix:
5597     return ISD::SDIVFIX;
5598   case Intrinsic::udiv_fix:
5599     return ISD::UDIVFIX;
5600   case Intrinsic::sdiv_fix_sat:
5601     return ISD::SDIVFIXSAT;
5602   case Intrinsic::udiv_fix_sat:
5603     return ISD::UDIVFIXSAT;
5604   default:
5605     llvm_unreachable("Unhandled fixed point intrinsic");
5606   }
5607 }
5608 
5609 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5610                                            const char *FunctionName) {
5611   assert(FunctionName && "FunctionName must not be nullptr");
5612   SDValue Callee = DAG.getExternalSymbol(
5613       FunctionName,
5614       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5615   LowerCallTo(I, Callee, I.isTailCall());
5616 }
5617 
5618 /// Given a @llvm.call.preallocated.setup, return the corresponding
5619 /// preallocated call.
5620 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5621   assert(cast<CallBase>(PreallocatedSetup)
5622                  ->getCalledFunction()
5623                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5624          "expected call_preallocated_setup Value");
5625   for (auto *U : PreallocatedSetup->users()) {
5626     auto *UseCall = cast<CallBase>(U);
5627     const Function *Fn = UseCall->getCalledFunction();
5628     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5629       return UseCall;
5630     }
5631   }
5632   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5633 }
5634 
5635 /// Lower the call to the specified intrinsic function.
5636 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5637                                              unsigned Intrinsic) {
5638   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5639   SDLoc sdl = getCurSDLoc();
5640   DebugLoc dl = getCurDebugLoc();
5641   SDValue Res;
5642 
5643   switch (Intrinsic) {
5644   default:
5645     // By default, turn this into a target intrinsic node.
5646     visitTargetIntrinsic(I, Intrinsic);
5647     return;
5648   case Intrinsic::vscale: {
5649     match(&I, m_VScale(DAG.getDataLayout()));
5650     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5651     setValue(&I,
5652              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5653     return;
5654   }
5655   case Intrinsic::vastart:  visitVAStart(I); return;
5656   case Intrinsic::vaend:    visitVAEnd(I); return;
5657   case Intrinsic::vacopy:   visitVACopy(I); return;
5658   case Intrinsic::returnaddress:
5659     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5660                              TLI.getPointerTy(DAG.getDataLayout()),
5661                              getValue(I.getArgOperand(0))));
5662     return;
5663   case Intrinsic::addressofreturnaddress:
5664     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5665                              TLI.getPointerTy(DAG.getDataLayout())));
5666     return;
5667   case Intrinsic::sponentry:
5668     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5669                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5670     return;
5671   case Intrinsic::frameaddress:
5672     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5673                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5674                              getValue(I.getArgOperand(0))));
5675     return;
5676   case Intrinsic::read_volatile_register:
5677   case Intrinsic::read_register: {
5678     Value *Reg = I.getArgOperand(0);
5679     SDValue Chain = getRoot();
5680     SDValue RegName =
5681         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5682     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5683     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5684       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5685     setValue(&I, Res);
5686     DAG.setRoot(Res.getValue(1));
5687     return;
5688   }
5689   case Intrinsic::write_register: {
5690     Value *Reg = I.getArgOperand(0);
5691     Value *RegValue = I.getArgOperand(1);
5692     SDValue Chain = getRoot();
5693     SDValue RegName =
5694         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5695     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5696                             RegName, getValue(RegValue)));
5697     return;
5698   }
5699   case Intrinsic::memcpy: {
5700     const auto &MCI = cast<MemCpyInst>(I);
5701     SDValue Op1 = getValue(I.getArgOperand(0));
5702     SDValue Op2 = getValue(I.getArgOperand(1));
5703     SDValue Op3 = getValue(I.getArgOperand(2));
5704     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5705     Align DstAlign = MCI.getDestAlign().valueOrOne();
5706     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5707     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5708     bool isVol = MCI.isVolatile();
5709     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5710     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5711     // node.
5712     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5713     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5714                                /* AlwaysInline */ false, isTC,
5715                                MachinePointerInfo(I.getArgOperand(0)),
5716                                MachinePointerInfo(I.getArgOperand(1)));
5717     updateDAGForMaybeTailCall(MC);
5718     return;
5719   }
5720   case Intrinsic::memcpy_inline: {
5721     const auto &MCI = cast<MemCpyInlineInst>(I);
5722     SDValue Dst = getValue(I.getArgOperand(0));
5723     SDValue Src = getValue(I.getArgOperand(1));
5724     SDValue Size = getValue(I.getArgOperand(2));
5725     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5726     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5727     Align DstAlign = MCI.getDestAlign().valueOrOne();
5728     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5729     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5730     bool isVol = MCI.isVolatile();
5731     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5732     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5733     // node.
5734     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5735                                /* AlwaysInline */ true, isTC,
5736                                MachinePointerInfo(I.getArgOperand(0)),
5737                                MachinePointerInfo(I.getArgOperand(1)));
5738     updateDAGForMaybeTailCall(MC);
5739     return;
5740   }
5741   case Intrinsic::memset: {
5742     const auto &MSI = cast<MemSetInst>(I);
5743     SDValue Op1 = getValue(I.getArgOperand(0));
5744     SDValue Op2 = getValue(I.getArgOperand(1));
5745     SDValue Op3 = getValue(I.getArgOperand(2));
5746     // @llvm.memset defines 0 and 1 to both mean no alignment.
5747     Align Alignment = MSI.getDestAlign().valueOrOne();
5748     bool isVol = MSI.isVolatile();
5749     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5750     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5751     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5752                                MachinePointerInfo(I.getArgOperand(0)));
5753     updateDAGForMaybeTailCall(MS);
5754     return;
5755   }
5756   case Intrinsic::memmove: {
5757     const auto &MMI = cast<MemMoveInst>(I);
5758     SDValue Op1 = getValue(I.getArgOperand(0));
5759     SDValue Op2 = getValue(I.getArgOperand(1));
5760     SDValue Op3 = getValue(I.getArgOperand(2));
5761     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5762     Align DstAlign = MMI.getDestAlign().valueOrOne();
5763     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5764     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5765     bool isVol = MMI.isVolatile();
5766     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5767     // FIXME: Support passing different dest/src alignments to the memmove DAG
5768     // node.
5769     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5770     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5771                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5772                                 MachinePointerInfo(I.getArgOperand(1)));
5773     updateDAGForMaybeTailCall(MM);
5774     return;
5775   }
5776   case Intrinsic::memcpy_element_unordered_atomic: {
5777     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5778     SDValue Dst = getValue(MI.getRawDest());
5779     SDValue Src = getValue(MI.getRawSource());
5780     SDValue Length = getValue(MI.getLength());
5781 
5782     unsigned DstAlign = MI.getDestAlignment();
5783     unsigned SrcAlign = MI.getSourceAlignment();
5784     Type *LengthTy = MI.getLength()->getType();
5785     unsigned ElemSz = MI.getElementSizeInBytes();
5786     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5787     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5788                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5789                                      MachinePointerInfo(MI.getRawDest()),
5790                                      MachinePointerInfo(MI.getRawSource()));
5791     updateDAGForMaybeTailCall(MC);
5792     return;
5793   }
5794   case Intrinsic::memmove_element_unordered_atomic: {
5795     auto &MI = cast<AtomicMemMoveInst>(I);
5796     SDValue Dst = getValue(MI.getRawDest());
5797     SDValue Src = getValue(MI.getRawSource());
5798     SDValue Length = getValue(MI.getLength());
5799 
5800     unsigned DstAlign = MI.getDestAlignment();
5801     unsigned SrcAlign = MI.getSourceAlignment();
5802     Type *LengthTy = MI.getLength()->getType();
5803     unsigned ElemSz = MI.getElementSizeInBytes();
5804     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5805     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5806                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5807                                       MachinePointerInfo(MI.getRawDest()),
5808                                       MachinePointerInfo(MI.getRawSource()));
5809     updateDAGForMaybeTailCall(MC);
5810     return;
5811   }
5812   case Intrinsic::memset_element_unordered_atomic: {
5813     auto &MI = cast<AtomicMemSetInst>(I);
5814     SDValue Dst = getValue(MI.getRawDest());
5815     SDValue Val = getValue(MI.getValue());
5816     SDValue Length = getValue(MI.getLength());
5817 
5818     unsigned DstAlign = MI.getDestAlignment();
5819     Type *LengthTy = MI.getLength()->getType();
5820     unsigned ElemSz = MI.getElementSizeInBytes();
5821     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5822     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5823                                      LengthTy, ElemSz, isTC,
5824                                      MachinePointerInfo(MI.getRawDest()));
5825     updateDAGForMaybeTailCall(MC);
5826     return;
5827   }
5828   case Intrinsic::call_preallocated_setup: {
5829     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5830     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5831     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5832                               getRoot(), SrcValue);
5833     setValue(&I, Res);
5834     DAG.setRoot(Res);
5835     return;
5836   }
5837   case Intrinsic::call_preallocated_arg: {
5838     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5839     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5840     SDValue Ops[3];
5841     Ops[0] = getRoot();
5842     Ops[1] = SrcValue;
5843     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5844                                    MVT::i32); // arg index
5845     SDValue Res = DAG.getNode(
5846         ISD::PREALLOCATED_ARG, sdl,
5847         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5848     setValue(&I, Res);
5849     DAG.setRoot(Res.getValue(1));
5850     return;
5851   }
5852   case Intrinsic::dbg_addr:
5853   case Intrinsic::dbg_declare: {
5854     const auto &DI = cast<DbgVariableIntrinsic>(I);
5855     DILocalVariable *Variable = DI.getVariable();
5856     DIExpression *Expression = DI.getExpression();
5857     dropDanglingDebugInfo(Variable, Expression);
5858     assert(Variable && "Missing variable");
5859     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5860                       << "\n");
5861     // Check if address has undef value.
5862     const Value *Address = DI.getVariableLocation();
5863     if (!Address || isa<UndefValue>(Address) ||
5864         (Address->use_empty() && !isa<Argument>(Address))) {
5865       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5866                         << " (bad/undef/unused-arg address)\n");
5867       return;
5868     }
5869 
5870     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5871 
5872     // Check if this variable can be described by a frame index, typically
5873     // either as a static alloca or a byval parameter.
5874     int FI = std::numeric_limits<int>::max();
5875     if (const auto *AI =
5876             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5877       if (AI->isStaticAlloca()) {
5878         auto I = FuncInfo.StaticAllocaMap.find(AI);
5879         if (I != FuncInfo.StaticAllocaMap.end())
5880           FI = I->second;
5881       }
5882     } else if (const auto *Arg = dyn_cast<Argument>(
5883                    Address->stripInBoundsConstantOffsets())) {
5884       FI = FuncInfo.getArgumentFrameIndex(Arg);
5885     }
5886 
5887     // llvm.dbg.addr is control dependent and always generates indirect
5888     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5889     // the MachineFunction variable table.
5890     if (FI != std::numeric_limits<int>::max()) {
5891       if (Intrinsic == Intrinsic::dbg_addr) {
5892         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5893             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5894         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5895       } else {
5896         LLVM_DEBUG(dbgs() << "Skipping " << DI
5897                           << " (variable info stashed in MF side table)\n");
5898       }
5899       return;
5900     }
5901 
5902     SDValue &N = NodeMap[Address];
5903     if (!N.getNode() && isa<Argument>(Address))
5904       // Check unused arguments map.
5905       N = UnusedArgNodeMap[Address];
5906     SDDbgValue *SDV;
5907     if (N.getNode()) {
5908       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5909         Address = BCI->getOperand(0);
5910       // Parameters are handled specially.
5911       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5912       if (isParameter && FINode) {
5913         // Byval parameter. We have a frame index at this point.
5914         SDV =
5915             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5916                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5917       } else if (isa<Argument>(Address)) {
5918         // Address is an argument, so try to emit its dbg value using
5919         // virtual register info from the FuncInfo.ValueMap.
5920         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5921         return;
5922       } else {
5923         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5924                               true, dl, SDNodeOrder);
5925       }
5926       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5927     } else {
5928       // If Address is an argument then try to emit its dbg value using
5929       // virtual register info from the FuncInfo.ValueMap.
5930       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5931                                     N)) {
5932         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5933                           << " (could not emit func-arg dbg_value)\n");
5934       }
5935     }
5936     return;
5937   }
5938   case Intrinsic::dbg_label: {
5939     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5940     DILabel *Label = DI.getLabel();
5941     assert(Label && "Missing label");
5942 
5943     SDDbgLabel *SDV;
5944     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5945     DAG.AddDbgLabel(SDV);
5946     return;
5947   }
5948   case Intrinsic::dbg_value: {
5949     const DbgValueInst &DI = cast<DbgValueInst>(I);
5950     assert(DI.getVariable() && "Missing variable");
5951 
5952     DILocalVariable *Variable = DI.getVariable();
5953     DIExpression *Expression = DI.getExpression();
5954     dropDanglingDebugInfo(Variable, Expression);
5955     const Value *V = DI.getValue();
5956     if (!V)
5957       return;
5958 
5959     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5960         SDNodeOrder))
5961       return;
5962 
5963     // TODO: Dangling debug info will eventually either be resolved or produce
5964     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5965     // between the original dbg.value location and its resolved DBG_VALUE, which
5966     // we should ideally fill with an extra Undef DBG_VALUE.
5967 
5968     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5969     return;
5970   }
5971 
5972   case Intrinsic::eh_typeid_for: {
5973     // Find the type id for the given typeinfo.
5974     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5975     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5976     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5977     setValue(&I, Res);
5978     return;
5979   }
5980 
5981   case Intrinsic::eh_return_i32:
5982   case Intrinsic::eh_return_i64:
5983     DAG.getMachineFunction().setCallsEHReturn(true);
5984     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5985                             MVT::Other,
5986                             getControlRoot(),
5987                             getValue(I.getArgOperand(0)),
5988                             getValue(I.getArgOperand(1))));
5989     return;
5990   case Intrinsic::eh_unwind_init:
5991     DAG.getMachineFunction().setCallsUnwindInit(true);
5992     return;
5993   case Intrinsic::eh_dwarf_cfa:
5994     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5995                              TLI.getPointerTy(DAG.getDataLayout()),
5996                              getValue(I.getArgOperand(0))));
5997     return;
5998   case Intrinsic::eh_sjlj_callsite: {
5999     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6000     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6001     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6002     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6003 
6004     MMI.setCurrentCallSite(CI->getZExtValue());
6005     return;
6006   }
6007   case Intrinsic::eh_sjlj_functioncontext: {
6008     // Get and store the index of the function context.
6009     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6010     AllocaInst *FnCtx =
6011       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6012     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6013     MFI.setFunctionContextIndex(FI);
6014     return;
6015   }
6016   case Intrinsic::eh_sjlj_setjmp: {
6017     SDValue Ops[2];
6018     Ops[0] = getRoot();
6019     Ops[1] = getValue(I.getArgOperand(0));
6020     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6021                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6022     setValue(&I, Op.getValue(0));
6023     DAG.setRoot(Op.getValue(1));
6024     return;
6025   }
6026   case Intrinsic::eh_sjlj_longjmp:
6027     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6028                             getRoot(), getValue(I.getArgOperand(0))));
6029     return;
6030   case Intrinsic::eh_sjlj_setup_dispatch:
6031     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6032                             getRoot()));
6033     return;
6034   case Intrinsic::masked_gather:
6035     visitMaskedGather(I);
6036     return;
6037   case Intrinsic::masked_load:
6038     visitMaskedLoad(I);
6039     return;
6040   case Intrinsic::masked_scatter:
6041     visitMaskedScatter(I);
6042     return;
6043   case Intrinsic::masked_store:
6044     visitMaskedStore(I);
6045     return;
6046   case Intrinsic::masked_expandload:
6047     visitMaskedLoad(I, true /* IsExpanding */);
6048     return;
6049   case Intrinsic::masked_compressstore:
6050     visitMaskedStore(I, true /* IsCompressing */);
6051     return;
6052   case Intrinsic::powi:
6053     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6054                             getValue(I.getArgOperand(1)), DAG));
6055     return;
6056   case Intrinsic::log:
6057     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6058     return;
6059   case Intrinsic::log2:
6060     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6061     return;
6062   case Intrinsic::log10:
6063     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6064     return;
6065   case Intrinsic::exp:
6066     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6067     return;
6068   case Intrinsic::exp2:
6069     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6070     return;
6071   case Intrinsic::pow:
6072     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6073                            getValue(I.getArgOperand(1)), DAG, TLI));
6074     return;
6075   case Intrinsic::sqrt:
6076   case Intrinsic::fabs:
6077   case Intrinsic::sin:
6078   case Intrinsic::cos:
6079   case Intrinsic::floor:
6080   case Intrinsic::ceil:
6081   case Intrinsic::trunc:
6082   case Intrinsic::rint:
6083   case Intrinsic::nearbyint:
6084   case Intrinsic::round:
6085   case Intrinsic::roundeven:
6086   case Intrinsic::canonicalize: {
6087     unsigned Opcode;
6088     switch (Intrinsic) {
6089     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6090     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6091     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6092     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6093     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6094     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6095     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6096     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6097     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6098     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6099     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6100     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6101     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6102     }
6103 
6104     setValue(&I, DAG.getNode(Opcode, sdl,
6105                              getValue(I.getArgOperand(0)).getValueType(),
6106                              getValue(I.getArgOperand(0))));
6107     return;
6108   }
6109   case Intrinsic::lround:
6110   case Intrinsic::llround:
6111   case Intrinsic::lrint:
6112   case Intrinsic::llrint: {
6113     unsigned Opcode;
6114     switch (Intrinsic) {
6115     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6116     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6117     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6118     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6119     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6120     }
6121 
6122     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6123     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6124                              getValue(I.getArgOperand(0))));
6125     return;
6126   }
6127   case Intrinsic::minnum:
6128     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6129                              getValue(I.getArgOperand(0)).getValueType(),
6130                              getValue(I.getArgOperand(0)),
6131                              getValue(I.getArgOperand(1))));
6132     return;
6133   case Intrinsic::maxnum:
6134     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6135                              getValue(I.getArgOperand(0)).getValueType(),
6136                              getValue(I.getArgOperand(0)),
6137                              getValue(I.getArgOperand(1))));
6138     return;
6139   case Intrinsic::minimum:
6140     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6141                              getValue(I.getArgOperand(0)).getValueType(),
6142                              getValue(I.getArgOperand(0)),
6143                              getValue(I.getArgOperand(1))));
6144     return;
6145   case Intrinsic::maximum:
6146     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6147                              getValue(I.getArgOperand(0)).getValueType(),
6148                              getValue(I.getArgOperand(0)),
6149                              getValue(I.getArgOperand(1))));
6150     return;
6151   case Intrinsic::copysign:
6152     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6153                              getValue(I.getArgOperand(0)).getValueType(),
6154                              getValue(I.getArgOperand(0)),
6155                              getValue(I.getArgOperand(1))));
6156     return;
6157   case Intrinsic::fma:
6158     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6159                              getValue(I.getArgOperand(0)).getValueType(),
6160                              getValue(I.getArgOperand(0)),
6161                              getValue(I.getArgOperand(1)),
6162                              getValue(I.getArgOperand(2))));
6163     return;
6164 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6165   case Intrinsic::INTRINSIC:
6166 #include "llvm/IR/ConstrainedOps.def"
6167     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6168     return;
6169   case Intrinsic::fmuladd: {
6170     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6171     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6172         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6173       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6174                                getValue(I.getArgOperand(0)).getValueType(),
6175                                getValue(I.getArgOperand(0)),
6176                                getValue(I.getArgOperand(1)),
6177                                getValue(I.getArgOperand(2))));
6178     } else {
6179       // TODO: Intrinsic calls should have fast-math-flags.
6180       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6181                                 getValue(I.getArgOperand(0)).getValueType(),
6182                                 getValue(I.getArgOperand(0)),
6183                                 getValue(I.getArgOperand(1)));
6184       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6185                                 getValue(I.getArgOperand(0)).getValueType(),
6186                                 Mul,
6187                                 getValue(I.getArgOperand(2)));
6188       setValue(&I, Add);
6189     }
6190     return;
6191   }
6192   case Intrinsic::convert_to_fp16:
6193     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6194                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6195                                          getValue(I.getArgOperand(0)),
6196                                          DAG.getTargetConstant(0, sdl,
6197                                                                MVT::i32))));
6198     return;
6199   case Intrinsic::convert_from_fp16:
6200     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6201                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6202                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6203                                          getValue(I.getArgOperand(0)))));
6204     return;
6205   case Intrinsic::pcmarker: {
6206     SDValue Tmp = getValue(I.getArgOperand(0));
6207     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6208     return;
6209   }
6210   case Intrinsic::readcyclecounter: {
6211     SDValue Op = getRoot();
6212     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6213                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6214     setValue(&I, Res);
6215     DAG.setRoot(Res.getValue(1));
6216     return;
6217   }
6218   case Intrinsic::bitreverse:
6219     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6220                              getValue(I.getArgOperand(0)).getValueType(),
6221                              getValue(I.getArgOperand(0))));
6222     return;
6223   case Intrinsic::bswap:
6224     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6225                              getValue(I.getArgOperand(0)).getValueType(),
6226                              getValue(I.getArgOperand(0))));
6227     return;
6228   case Intrinsic::cttz: {
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::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6233                              sdl, Ty, Arg));
6234     return;
6235   }
6236   case Intrinsic::ctlz: {
6237     SDValue Arg = getValue(I.getArgOperand(0));
6238     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6239     EVT Ty = Arg.getValueType();
6240     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6241                              sdl, Ty, Arg));
6242     return;
6243   }
6244   case Intrinsic::ctpop: {
6245     SDValue Arg = getValue(I.getArgOperand(0));
6246     EVT Ty = Arg.getValueType();
6247     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6248     return;
6249   }
6250   case Intrinsic::fshl:
6251   case Intrinsic::fshr: {
6252     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6253     SDValue X = getValue(I.getArgOperand(0));
6254     SDValue Y = getValue(I.getArgOperand(1));
6255     SDValue Z = getValue(I.getArgOperand(2));
6256     EVT VT = X.getValueType();
6257 
6258     if (X == Y) {
6259       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6260       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6261     } else {
6262       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6263       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6264     }
6265     return;
6266   }
6267   case Intrinsic::sadd_sat: {
6268     SDValue Op1 = getValue(I.getArgOperand(0));
6269     SDValue Op2 = getValue(I.getArgOperand(1));
6270     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6271     return;
6272   }
6273   case Intrinsic::uadd_sat: {
6274     SDValue Op1 = getValue(I.getArgOperand(0));
6275     SDValue Op2 = getValue(I.getArgOperand(1));
6276     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6277     return;
6278   }
6279   case Intrinsic::ssub_sat: {
6280     SDValue Op1 = getValue(I.getArgOperand(0));
6281     SDValue Op2 = getValue(I.getArgOperand(1));
6282     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6283     return;
6284   }
6285   case Intrinsic::usub_sat: {
6286     SDValue Op1 = getValue(I.getArgOperand(0));
6287     SDValue Op2 = getValue(I.getArgOperand(1));
6288     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6289     return;
6290   }
6291   case Intrinsic::sshl_sat: {
6292     SDValue Op1 = getValue(I.getArgOperand(0));
6293     SDValue Op2 = getValue(I.getArgOperand(1));
6294     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6295     return;
6296   }
6297   case Intrinsic::ushl_sat: {
6298     SDValue Op1 = getValue(I.getArgOperand(0));
6299     SDValue Op2 = getValue(I.getArgOperand(1));
6300     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6301     return;
6302   }
6303   case Intrinsic::smul_fix:
6304   case Intrinsic::umul_fix:
6305   case Intrinsic::smul_fix_sat:
6306   case Intrinsic::umul_fix_sat: {
6307     SDValue Op1 = getValue(I.getArgOperand(0));
6308     SDValue Op2 = getValue(I.getArgOperand(1));
6309     SDValue Op3 = getValue(I.getArgOperand(2));
6310     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6311                              Op1.getValueType(), Op1, Op2, Op3));
6312     return;
6313   }
6314   case Intrinsic::sdiv_fix:
6315   case Intrinsic::udiv_fix:
6316   case Intrinsic::sdiv_fix_sat:
6317   case Intrinsic::udiv_fix_sat: {
6318     SDValue Op1 = getValue(I.getArgOperand(0));
6319     SDValue Op2 = getValue(I.getArgOperand(1));
6320     SDValue Op3 = getValue(I.getArgOperand(2));
6321     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6322                               Op1, Op2, Op3, DAG, TLI));
6323     return;
6324   }
6325   case Intrinsic::smax: {
6326     SDValue Op1 = getValue(I.getArgOperand(0));
6327     SDValue Op2 = getValue(I.getArgOperand(1));
6328     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6329     return;
6330   }
6331   case Intrinsic::smin: {
6332     SDValue Op1 = getValue(I.getArgOperand(0));
6333     SDValue Op2 = getValue(I.getArgOperand(1));
6334     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6335     return;
6336   }
6337   case Intrinsic::umax: {
6338     SDValue Op1 = getValue(I.getArgOperand(0));
6339     SDValue Op2 = getValue(I.getArgOperand(1));
6340     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6341     return;
6342   }
6343   case Intrinsic::umin: {
6344     SDValue Op1 = getValue(I.getArgOperand(0));
6345     SDValue Op2 = getValue(I.getArgOperand(1));
6346     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6347     return;
6348   }
6349   case Intrinsic::abs: {
6350     // TODO: Preserve "int min is poison" arg in SDAG?
6351     SDValue Op1 = getValue(I.getArgOperand(0));
6352     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6353     return;
6354   }
6355   case Intrinsic::stacksave: {
6356     SDValue Op = getRoot();
6357     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6358     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6359     setValue(&I, Res);
6360     DAG.setRoot(Res.getValue(1));
6361     return;
6362   }
6363   case Intrinsic::stackrestore:
6364     Res = getValue(I.getArgOperand(0));
6365     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6366     return;
6367   case Intrinsic::get_dynamic_area_offset: {
6368     SDValue Op = getRoot();
6369     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6370     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6371     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6372     // target.
6373     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6374       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6375                          " intrinsic!");
6376     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6377                       Op);
6378     DAG.setRoot(Op);
6379     setValue(&I, Res);
6380     return;
6381   }
6382   case Intrinsic::stackguard: {
6383     MachineFunction &MF = DAG.getMachineFunction();
6384     const Module &M = *MF.getFunction().getParent();
6385     SDValue Chain = getRoot();
6386     if (TLI.useLoadStackGuardNode()) {
6387       Res = getLoadStackGuard(DAG, sdl, Chain);
6388     } else {
6389       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6390       const Value *Global = TLI.getSDagStackGuard(M);
6391       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6392       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6393                         MachinePointerInfo(Global, 0), Align,
6394                         MachineMemOperand::MOVolatile);
6395     }
6396     if (TLI.useStackGuardXorFP())
6397       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6398     DAG.setRoot(Chain);
6399     setValue(&I, Res);
6400     return;
6401   }
6402   case Intrinsic::stackprotector: {
6403     // Emit code into the DAG to store the stack guard onto the stack.
6404     MachineFunction &MF = DAG.getMachineFunction();
6405     MachineFrameInfo &MFI = MF.getFrameInfo();
6406     SDValue Src, Chain = getRoot();
6407 
6408     if (TLI.useLoadStackGuardNode())
6409       Src = getLoadStackGuard(DAG, sdl, Chain);
6410     else
6411       Src = getValue(I.getArgOperand(0));   // The guard's value.
6412 
6413     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6414 
6415     int FI = FuncInfo.StaticAllocaMap[Slot];
6416     MFI.setStackProtectorIndex(FI);
6417     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6418 
6419     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6420 
6421     // Store the stack protector onto the stack.
6422     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6423                                                  DAG.getMachineFunction(), FI),
6424                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6425     setValue(&I, Res);
6426     DAG.setRoot(Res);
6427     return;
6428   }
6429   case Intrinsic::objectsize:
6430     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6431 
6432   case Intrinsic::is_constant:
6433     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6434 
6435   case Intrinsic::annotation:
6436   case Intrinsic::ptr_annotation:
6437   case Intrinsic::launder_invariant_group:
6438   case Intrinsic::strip_invariant_group:
6439     // Drop the intrinsic, but forward the value
6440     setValue(&I, getValue(I.getOperand(0)));
6441     return;
6442   case Intrinsic::assume:
6443   case Intrinsic::var_annotation:
6444   case Intrinsic::sideeffect:
6445     // Discard annotate attributes, assumptions, and artificial side-effects.
6446     return;
6447 
6448   case Intrinsic::codeview_annotation: {
6449     // Emit a label associated with this metadata.
6450     MachineFunction &MF = DAG.getMachineFunction();
6451     MCSymbol *Label =
6452         MF.getMMI().getContext().createTempSymbol("annotation", true);
6453     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6454     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6455     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6456     DAG.setRoot(Res);
6457     return;
6458   }
6459 
6460   case Intrinsic::init_trampoline: {
6461     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6462 
6463     SDValue Ops[6];
6464     Ops[0] = getRoot();
6465     Ops[1] = getValue(I.getArgOperand(0));
6466     Ops[2] = getValue(I.getArgOperand(1));
6467     Ops[3] = getValue(I.getArgOperand(2));
6468     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6469     Ops[5] = DAG.getSrcValue(F);
6470 
6471     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6472 
6473     DAG.setRoot(Res);
6474     return;
6475   }
6476   case Intrinsic::adjust_trampoline:
6477     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6478                              TLI.getPointerTy(DAG.getDataLayout()),
6479                              getValue(I.getArgOperand(0))));
6480     return;
6481   case Intrinsic::gcroot: {
6482     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6483            "only valid in functions with gc specified, enforced by Verifier");
6484     assert(GFI && "implied by previous");
6485     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6486     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6487 
6488     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6489     GFI->addStackRoot(FI->getIndex(), TypeMap);
6490     return;
6491   }
6492   case Intrinsic::gcread:
6493   case Intrinsic::gcwrite:
6494     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6495   case Intrinsic::flt_rounds:
6496     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6497     setValue(&I, Res);
6498     DAG.setRoot(Res.getValue(1));
6499     return;
6500 
6501   case Intrinsic::expect:
6502     // Just replace __builtin_expect(exp, c) with EXP.
6503     setValue(&I, getValue(I.getArgOperand(0)));
6504     return;
6505 
6506   case Intrinsic::debugtrap:
6507   case Intrinsic::trap: {
6508     StringRef TrapFuncName =
6509         I.getAttributes()
6510             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6511             .getValueAsString();
6512     if (TrapFuncName.empty()) {
6513       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6514         ISD::TRAP : ISD::DEBUGTRAP;
6515       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6516       return;
6517     }
6518     TargetLowering::ArgListTy Args;
6519 
6520     TargetLowering::CallLoweringInfo CLI(DAG);
6521     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6522         CallingConv::C, I.getType(),
6523         DAG.getExternalSymbol(TrapFuncName.data(),
6524                               TLI.getPointerTy(DAG.getDataLayout())),
6525         std::move(Args));
6526 
6527     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6528     DAG.setRoot(Result.second);
6529     return;
6530   }
6531 
6532   case Intrinsic::uadd_with_overflow:
6533   case Intrinsic::sadd_with_overflow:
6534   case Intrinsic::usub_with_overflow:
6535   case Intrinsic::ssub_with_overflow:
6536   case Intrinsic::umul_with_overflow:
6537   case Intrinsic::smul_with_overflow: {
6538     ISD::NodeType Op;
6539     switch (Intrinsic) {
6540     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6541     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6542     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6543     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6544     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6545     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6546     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6547     }
6548     SDValue Op1 = getValue(I.getArgOperand(0));
6549     SDValue Op2 = getValue(I.getArgOperand(1));
6550 
6551     EVT ResultVT = Op1.getValueType();
6552     EVT OverflowVT = MVT::i1;
6553     if (ResultVT.isVector())
6554       OverflowVT = EVT::getVectorVT(
6555           *Context, OverflowVT, ResultVT.getVectorNumElements());
6556 
6557     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6558     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6559     return;
6560   }
6561   case Intrinsic::prefetch: {
6562     SDValue Ops[5];
6563     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6564     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6565     Ops[0] = DAG.getRoot();
6566     Ops[1] = getValue(I.getArgOperand(0));
6567     Ops[2] = getValue(I.getArgOperand(1));
6568     Ops[3] = getValue(I.getArgOperand(2));
6569     Ops[4] = getValue(I.getArgOperand(3));
6570     SDValue Result = DAG.getMemIntrinsicNode(
6571         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6572         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6573         /* align */ None, Flags);
6574 
6575     // Chain the prefetch in parallell with any pending loads, to stay out of
6576     // the way of later optimizations.
6577     PendingLoads.push_back(Result);
6578     Result = getRoot();
6579     DAG.setRoot(Result);
6580     return;
6581   }
6582   case Intrinsic::lifetime_start:
6583   case Intrinsic::lifetime_end: {
6584     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6585     // Stack coloring is not enabled in O0, discard region information.
6586     if (TM.getOptLevel() == CodeGenOpt::None)
6587       return;
6588 
6589     const int64_t ObjectSize =
6590         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6591     Value *const ObjectPtr = I.getArgOperand(1);
6592     SmallVector<const Value *, 4> Allocas;
6593     getUnderlyingObjects(ObjectPtr, Allocas);
6594 
6595     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6596            E = Allocas.end(); Object != E; ++Object) {
6597       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6598 
6599       // Could not find an Alloca.
6600       if (!LifetimeObject)
6601         continue;
6602 
6603       // First check that the Alloca is static, otherwise it won't have a
6604       // valid frame index.
6605       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6606       if (SI == FuncInfo.StaticAllocaMap.end())
6607         return;
6608 
6609       const int FrameIndex = SI->second;
6610       int64_t Offset;
6611       if (GetPointerBaseWithConstantOffset(
6612               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6613         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6614       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6615                                 Offset);
6616       DAG.setRoot(Res);
6617     }
6618     return;
6619   }
6620   case Intrinsic::invariant_start:
6621     // Discard region information.
6622     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6623     return;
6624   case Intrinsic::invariant_end:
6625     // Discard region information.
6626     return;
6627   case Intrinsic::clear_cache:
6628     /// FunctionName may be null.
6629     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6630       lowerCallToExternalSymbol(I, FunctionName);
6631     return;
6632   case Intrinsic::donothing:
6633     // ignore
6634     return;
6635   case Intrinsic::experimental_stackmap:
6636     visitStackmap(I);
6637     return;
6638   case Intrinsic::experimental_patchpoint_void:
6639   case Intrinsic::experimental_patchpoint_i64:
6640     visitPatchpoint(I);
6641     return;
6642   case Intrinsic::experimental_gc_statepoint:
6643     LowerStatepoint(cast<GCStatepointInst>(I));
6644     return;
6645   case Intrinsic::experimental_gc_result:
6646     visitGCResult(cast<GCResultInst>(I));
6647     return;
6648   case Intrinsic::experimental_gc_relocate:
6649     visitGCRelocate(cast<GCRelocateInst>(I));
6650     return;
6651   case Intrinsic::instrprof_increment:
6652     llvm_unreachable("instrprof failed to lower an increment");
6653   case Intrinsic::instrprof_value_profile:
6654     llvm_unreachable("instrprof failed to lower a value profiling call");
6655   case Intrinsic::localescape: {
6656     MachineFunction &MF = DAG.getMachineFunction();
6657     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6658 
6659     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6660     // is the same on all targets.
6661     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6662       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6663       if (isa<ConstantPointerNull>(Arg))
6664         continue; // Skip null pointers. They represent a hole in index space.
6665       AllocaInst *Slot = cast<AllocaInst>(Arg);
6666       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6667              "can only escape static allocas");
6668       int FI = FuncInfo.StaticAllocaMap[Slot];
6669       MCSymbol *FrameAllocSym =
6670           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6671               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6672       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6673               TII->get(TargetOpcode::LOCAL_ESCAPE))
6674           .addSym(FrameAllocSym)
6675           .addFrameIndex(FI);
6676     }
6677 
6678     return;
6679   }
6680 
6681   case Intrinsic::localrecover: {
6682     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6683     MachineFunction &MF = DAG.getMachineFunction();
6684 
6685     // Get the symbol that defines the frame offset.
6686     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6687     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6688     unsigned IdxVal =
6689         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6690     MCSymbol *FrameAllocSym =
6691         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6692             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6693 
6694     Value *FP = I.getArgOperand(1);
6695     SDValue FPVal = getValue(FP);
6696     EVT PtrVT = FPVal.getValueType();
6697 
6698     // Create a MCSymbol for the label to avoid any target lowering
6699     // that would make this PC relative.
6700     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6701     SDValue OffsetVal =
6702         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6703 
6704     // Add the offset to the FP.
6705     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6706     setValue(&I, Add);
6707 
6708     return;
6709   }
6710 
6711   case Intrinsic::eh_exceptionpointer:
6712   case Intrinsic::eh_exceptioncode: {
6713     // Get the exception pointer vreg, copy from it, and resize it to fit.
6714     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6715     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6716     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6717     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6718     SDValue N =
6719         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6720     if (Intrinsic == Intrinsic::eh_exceptioncode)
6721       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6722     setValue(&I, N);
6723     return;
6724   }
6725   case Intrinsic::xray_customevent: {
6726     // Here we want to make sure that the intrinsic behaves as if it has a
6727     // specific calling convention, and only for x86_64.
6728     // FIXME: Support other platforms later.
6729     const auto &Triple = DAG.getTarget().getTargetTriple();
6730     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6731       return;
6732 
6733     SDLoc DL = getCurSDLoc();
6734     SmallVector<SDValue, 8> Ops;
6735 
6736     // We want to say that we always want the arguments in registers.
6737     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6738     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6739     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6740     SDValue Chain = getRoot();
6741     Ops.push_back(LogEntryVal);
6742     Ops.push_back(StrSizeVal);
6743     Ops.push_back(Chain);
6744 
6745     // We need to enforce the calling convention for the callsite, so that
6746     // argument ordering is enforced correctly, and that register allocation can
6747     // see that some registers may be assumed clobbered and have to preserve
6748     // them across calls to the intrinsic.
6749     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6750                                            DL, NodeTys, Ops);
6751     SDValue patchableNode = SDValue(MN, 0);
6752     DAG.setRoot(patchableNode);
6753     setValue(&I, patchableNode);
6754     return;
6755   }
6756   case Intrinsic::xray_typedevent: {
6757     // Here we want to make sure that the intrinsic behaves as if it has a
6758     // specific calling convention, and only for x86_64.
6759     // FIXME: Support other platforms later.
6760     const auto &Triple = DAG.getTarget().getTargetTriple();
6761     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6762       return;
6763 
6764     SDLoc DL = getCurSDLoc();
6765     SmallVector<SDValue, 8> Ops;
6766 
6767     // We want to say that we always want the arguments in registers.
6768     // It's unclear to me how manipulating the selection DAG here forces callers
6769     // to provide arguments in registers instead of on the stack.
6770     SDValue LogTypeId = getValue(I.getArgOperand(0));
6771     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6772     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6773     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6774     SDValue Chain = getRoot();
6775     Ops.push_back(LogTypeId);
6776     Ops.push_back(LogEntryVal);
6777     Ops.push_back(StrSizeVal);
6778     Ops.push_back(Chain);
6779 
6780     // We need to enforce the calling convention for the callsite, so that
6781     // argument ordering is enforced correctly, and that register allocation can
6782     // see that some registers may be assumed clobbered and have to preserve
6783     // them across calls to the intrinsic.
6784     MachineSDNode *MN = DAG.getMachineNode(
6785         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6786     SDValue patchableNode = SDValue(MN, 0);
6787     DAG.setRoot(patchableNode);
6788     setValue(&I, patchableNode);
6789     return;
6790   }
6791   case Intrinsic::experimental_deoptimize:
6792     LowerDeoptimizeCall(&I);
6793     return;
6794 
6795   case Intrinsic::experimental_vector_reduce_v2_fadd:
6796   case Intrinsic::experimental_vector_reduce_v2_fmul:
6797   case Intrinsic::experimental_vector_reduce_add:
6798   case Intrinsic::experimental_vector_reduce_mul:
6799   case Intrinsic::experimental_vector_reduce_and:
6800   case Intrinsic::experimental_vector_reduce_or:
6801   case Intrinsic::experimental_vector_reduce_xor:
6802   case Intrinsic::experimental_vector_reduce_smax:
6803   case Intrinsic::experimental_vector_reduce_smin:
6804   case Intrinsic::experimental_vector_reduce_umax:
6805   case Intrinsic::experimental_vector_reduce_umin:
6806   case Intrinsic::experimental_vector_reduce_fmax:
6807   case Intrinsic::experimental_vector_reduce_fmin:
6808     visitVectorReduce(I, Intrinsic);
6809     return;
6810 
6811   case Intrinsic::icall_branch_funnel: {
6812     SmallVector<SDValue, 16> Ops;
6813     Ops.push_back(getValue(I.getArgOperand(0)));
6814 
6815     int64_t Offset;
6816     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6817         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6818     if (!Base)
6819       report_fatal_error(
6820           "llvm.icall.branch.funnel operand must be a GlobalValue");
6821     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6822 
6823     struct BranchFunnelTarget {
6824       int64_t Offset;
6825       SDValue Target;
6826     };
6827     SmallVector<BranchFunnelTarget, 8> Targets;
6828 
6829     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6830       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6831           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6832       if (ElemBase != Base)
6833         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6834                            "to the same GlobalValue");
6835 
6836       SDValue Val = getValue(I.getArgOperand(Op + 1));
6837       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6838       if (!GA)
6839         report_fatal_error(
6840             "llvm.icall.branch.funnel operand must be a GlobalValue");
6841       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6842                                      GA->getGlobal(), getCurSDLoc(),
6843                                      Val.getValueType(), GA->getOffset())});
6844     }
6845     llvm::sort(Targets,
6846                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6847                  return T1.Offset < T2.Offset;
6848                });
6849 
6850     for (auto &T : Targets) {
6851       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6852       Ops.push_back(T.Target);
6853     }
6854 
6855     Ops.push_back(DAG.getRoot()); // Chain
6856     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6857                                  getCurSDLoc(), MVT::Other, Ops),
6858               0);
6859     DAG.setRoot(N);
6860     setValue(&I, N);
6861     HasTailCall = true;
6862     return;
6863   }
6864 
6865   case Intrinsic::wasm_landingpad_index:
6866     // Information this intrinsic contained has been transferred to
6867     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6868     // delete it now.
6869     return;
6870 
6871   case Intrinsic::aarch64_settag:
6872   case Intrinsic::aarch64_settag_zero: {
6873     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6874     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6875     SDValue Val = TSI.EmitTargetCodeForSetTag(
6876         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6877         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6878         ZeroMemory);
6879     DAG.setRoot(Val);
6880     setValue(&I, Val);
6881     return;
6882   }
6883   case Intrinsic::ptrmask: {
6884     SDValue Ptr = getValue(I.getOperand(0));
6885     SDValue Const = getValue(I.getOperand(1));
6886 
6887     EVT PtrVT = Ptr.getValueType();
6888     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
6889                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
6890     return;
6891   }
6892   case Intrinsic::get_active_lane_mask: {
6893     auto DL = getCurSDLoc();
6894     SDValue Index = getValue(I.getOperand(0));
6895     SDValue TripCount = getValue(I.getOperand(1));
6896     Type *ElementTy = I.getOperand(0)->getType();
6897     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6898     unsigned VecWidth = VT.getVectorNumElements();
6899 
6900     SmallVector<SDValue, 16> OpsTripCount;
6901     SmallVector<SDValue, 16> OpsIndex;
6902     SmallVector<SDValue, 16> OpsStepConstants;
6903     for (unsigned i = 0; i < VecWidth; i++) {
6904       OpsTripCount.push_back(TripCount);
6905       OpsIndex.push_back(Index);
6906       OpsStepConstants.push_back(
6907           DAG.getConstant(i, DL, EVT::getEVT(ElementTy)));
6908     }
6909 
6910     EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth);
6911 
6912     auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth));
6913     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
6914     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
6915     SDValue VectorInduction = DAG.getNode(
6916        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
6917     SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount);
6918     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
6919                                  VectorTripCount, ISD::CondCode::SETULT);
6920     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
6921                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
6922                              SetCC));
6923     return;
6924   }
6925   }
6926 }
6927 
6928 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6929     const ConstrainedFPIntrinsic &FPI) {
6930   SDLoc sdl = getCurSDLoc();
6931 
6932   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6933   SmallVector<EVT, 4> ValueVTs;
6934   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6935   ValueVTs.push_back(MVT::Other); // Out chain
6936 
6937   // We do not need to serialize constrained FP intrinsics against
6938   // each other or against (nonvolatile) loads, so they can be
6939   // chained like loads.
6940   SDValue Chain = DAG.getRoot();
6941   SmallVector<SDValue, 4> Opers;
6942   Opers.push_back(Chain);
6943   if (FPI.isUnaryOp()) {
6944     Opers.push_back(getValue(FPI.getArgOperand(0)));
6945   } else if (FPI.isTernaryOp()) {
6946     Opers.push_back(getValue(FPI.getArgOperand(0)));
6947     Opers.push_back(getValue(FPI.getArgOperand(1)));
6948     Opers.push_back(getValue(FPI.getArgOperand(2)));
6949   } else {
6950     Opers.push_back(getValue(FPI.getArgOperand(0)));
6951     Opers.push_back(getValue(FPI.getArgOperand(1)));
6952   }
6953 
6954   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
6955     assert(Result.getNode()->getNumValues() == 2);
6956 
6957     // Push node to the appropriate list so that future instructions can be
6958     // chained up correctly.
6959     SDValue OutChain = Result.getValue(1);
6960     switch (EB) {
6961     case fp::ExceptionBehavior::ebIgnore:
6962       // The only reason why ebIgnore nodes still need to be chained is that
6963       // they might depend on the current rounding mode, and therefore must
6964       // not be moved across instruction that may change that mode.
6965       LLVM_FALLTHROUGH;
6966     case fp::ExceptionBehavior::ebMayTrap:
6967       // These must not be moved across calls or instructions that may change
6968       // floating-point exception masks.
6969       PendingConstrainedFP.push_back(OutChain);
6970       break;
6971     case fp::ExceptionBehavior::ebStrict:
6972       // These must not be moved across calls or instructions that may change
6973       // floating-point exception masks or read floating-point exception flags.
6974       // In addition, they cannot be optimized out even if unused.
6975       PendingConstrainedFPStrict.push_back(OutChain);
6976       break;
6977     }
6978   };
6979 
6980   SDVTList VTs = DAG.getVTList(ValueVTs);
6981   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
6982 
6983   SDNodeFlags Flags;
6984   if (EB == fp::ExceptionBehavior::ebIgnore)
6985     Flags.setNoFPExcept(true);
6986 
6987   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
6988     Flags.copyFMF(*FPOp);
6989 
6990   unsigned Opcode;
6991   switch (FPI.getIntrinsicID()) {
6992   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6993 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
6994   case Intrinsic::INTRINSIC:                                                   \
6995     Opcode = ISD::STRICT_##DAGN;                                               \
6996     break;
6997 #include "llvm/IR/ConstrainedOps.def"
6998   case Intrinsic::experimental_constrained_fmuladd: {
6999     Opcode = ISD::STRICT_FMA;
7000     // Break fmuladd into fmul and fadd.
7001     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7002         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7003                                         ValueVTs[0])) {
7004       Opers.pop_back();
7005       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7006       pushOutChain(Mul, EB);
7007       Opcode = ISD::STRICT_FADD;
7008       Opers.clear();
7009       Opers.push_back(Mul.getValue(1));
7010       Opers.push_back(Mul.getValue(0));
7011       Opers.push_back(getValue(FPI.getArgOperand(2)));
7012     }
7013     break;
7014   }
7015   }
7016 
7017   // A few strict DAG nodes carry additional operands that are not
7018   // set up by the default code above.
7019   switch (Opcode) {
7020   default: break;
7021   case ISD::STRICT_FP_ROUND:
7022     Opers.push_back(
7023         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7024     break;
7025   case ISD::STRICT_FSETCC:
7026   case ISD::STRICT_FSETCCS: {
7027     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7028     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
7029     break;
7030   }
7031   }
7032 
7033   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7034   pushOutChain(Result, EB);
7035 
7036   SDValue FPResult = Result.getValue(0);
7037   setValue(&FPI, FPResult);
7038 }
7039 
7040 std::pair<SDValue, SDValue>
7041 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7042                                     const BasicBlock *EHPadBB) {
7043   MachineFunction &MF = DAG.getMachineFunction();
7044   MachineModuleInfo &MMI = MF.getMMI();
7045   MCSymbol *BeginLabel = nullptr;
7046 
7047   if (EHPadBB) {
7048     // Insert a label before the invoke call to mark the try range.  This can be
7049     // used to detect deletion of the invoke via the MachineModuleInfo.
7050     BeginLabel = MMI.getContext().createTempSymbol();
7051 
7052     // For SjLj, keep track of which landing pads go with which invokes
7053     // so as to maintain the ordering of pads in the LSDA.
7054     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7055     if (CallSiteIndex) {
7056       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7057       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7058 
7059       // Now that the call site is handled, stop tracking it.
7060       MMI.setCurrentCallSite(0);
7061     }
7062 
7063     // Both PendingLoads and PendingExports must be flushed here;
7064     // this call might not return.
7065     (void)getRoot();
7066     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7067 
7068     CLI.setChain(getRoot());
7069   }
7070   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7071   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7072 
7073   assert((CLI.IsTailCall || Result.second.getNode()) &&
7074          "Non-null chain expected with non-tail call!");
7075   assert((Result.second.getNode() || !Result.first.getNode()) &&
7076          "Null value expected with tail call!");
7077 
7078   if (!Result.second.getNode()) {
7079     // As a special case, a null chain means that a tail call has been emitted
7080     // and the DAG root is already updated.
7081     HasTailCall = true;
7082 
7083     // Since there's no actual continuation from this block, nothing can be
7084     // relying on us setting vregs for them.
7085     PendingExports.clear();
7086   } else {
7087     DAG.setRoot(Result.second);
7088   }
7089 
7090   if (EHPadBB) {
7091     // Insert a label at the end of the invoke call to mark the try range.  This
7092     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7093     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7094     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7095 
7096     // Inform MachineModuleInfo of range.
7097     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7098     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7099     // actually use outlined funclets and their LSDA info style.
7100     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7101       assert(CLI.CB);
7102       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7103       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7104     } else if (!isScopedEHPersonality(Pers)) {
7105       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7106     }
7107   }
7108 
7109   return Result;
7110 }
7111 
7112 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7113                                       bool isTailCall,
7114                                       const BasicBlock *EHPadBB) {
7115   auto &DL = DAG.getDataLayout();
7116   FunctionType *FTy = CB.getFunctionType();
7117   Type *RetTy = CB.getType();
7118 
7119   TargetLowering::ArgListTy Args;
7120   Args.reserve(CB.arg_size());
7121 
7122   const Value *SwiftErrorVal = nullptr;
7123   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7124 
7125   if (isTailCall) {
7126     // Avoid emitting tail calls in functions with the disable-tail-calls
7127     // attribute.
7128     auto *Caller = CB.getParent()->getParent();
7129     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7130         "true")
7131       isTailCall = false;
7132 
7133     // We can't tail call inside a function with a swifterror argument. Lowering
7134     // does not support this yet. It would have to move into the swifterror
7135     // register before the call.
7136     if (TLI.supportSwiftError() &&
7137         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7138       isTailCall = false;
7139   }
7140 
7141   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7142     TargetLowering::ArgListEntry Entry;
7143     const Value *V = *I;
7144 
7145     // Skip empty types
7146     if (V->getType()->isEmptyTy())
7147       continue;
7148 
7149     SDValue ArgNode = getValue(V);
7150     Entry.Node = ArgNode; Entry.Ty = V->getType();
7151 
7152     Entry.setAttributes(&CB, I - CB.arg_begin());
7153 
7154     // Use swifterror virtual register as input to the call.
7155     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7156       SwiftErrorVal = V;
7157       // We find the virtual register for the actual swifterror argument.
7158       // Instead of using the Value, we use the virtual register instead.
7159       Entry.Node =
7160           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7161                           EVT(TLI.getPointerTy(DL)));
7162     }
7163 
7164     Args.push_back(Entry);
7165 
7166     // If we have an explicit sret argument that is an Instruction, (i.e., it
7167     // might point to function-local memory), we can't meaningfully tail-call.
7168     if (Entry.IsSRet && isa<Instruction>(V))
7169       isTailCall = false;
7170   }
7171 
7172   // If call site has a cfguardtarget operand bundle, create and add an
7173   // additional ArgListEntry.
7174   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7175     TargetLowering::ArgListEntry Entry;
7176     Value *V = Bundle->Inputs[0];
7177     SDValue ArgNode = getValue(V);
7178     Entry.Node = ArgNode;
7179     Entry.Ty = V->getType();
7180     Entry.IsCFGuardTarget = true;
7181     Args.push_back(Entry);
7182   }
7183 
7184   // Check if target-independent constraints permit a tail call here.
7185   // Target-dependent constraints are checked within TLI->LowerCallTo.
7186   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7187     isTailCall = false;
7188 
7189   // Disable tail calls if there is an swifterror argument. Targets have not
7190   // been updated to support tail calls.
7191   if (TLI.supportSwiftError() && SwiftErrorVal)
7192     isTailCall = false;
7193 
7194   TargetLowering::CallLoweringInfo CLI(DAG);
7195   CLI.setDebugLoc(getCurSDLoc())
7196       .setChain(getRoot())
7197       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7198       .setTailCall(isTailCall)
7199       .setConvergent(CB.isConvergent())
7200       .setIsPreallocated(
7201           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7202   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7203 
7204   if (Result.first.getNode()) {
7205     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7206     setValue(&CB, Result.first);
7207   }
7208 
7209   // The last element of CLI.InVals has the SDValue for swifterror return.
7210   // Here we copy it to a virtual register and update SwiftErrorMap for
7211   // book-keeping.
7212   if (SwiftErrorVal && TLI.supportSwiftError()) {
7213     // Get the last element of InVals.
7214     SDValue Src = CLI.InVals.back();
7215     Register VReg =
7216         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7217     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7218     DAG.setRoot(CopyNode);
7219   }
7220 }
7221 
7222 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7223                              SelectionDAGBuilder &Builder) {
7224   // Check to see if this load can be trivially constant folded, e.g. if the
7225   // input is from a string literal.
7226   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7227     // Cast pointer to the type we really want to load.
7228     Type *LoadTy =
7229         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7230     if (LoadVT.isVector())
7231       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7232 
7233     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7234                                          PointerType::getUnqual(LoadTy));
7235 
7236     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7237             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7238       return Builder.getValue(LoadCst);
7239   }
7240 
7241   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7242   // still constant memory, the input chain can be the entry node.
7243   SDValue Root;
7244   bool ConstantMemory = false;
7245 
7246   // Do not serialize (non-volatile) loads of constant memory with anything.
7247   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7248     Root = Builder.DAG.getEntryNode();
7249     ConstantMemory = true;
7250   } else {
7251     // Do not serialize non-volatile loads against each other.
7252     Root = Builder.DAG.getRoot();
7253   }
7254 
7255   SDValue Ptr = Builder.getValue(PtrVal);
7256   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7257                                         Ptr, MachinePointerInfo(PtrVal),
7258                                         /* Alignment = */ 1);
7259 
7260   if (!ConstantMemory)
7261     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7262   return LoadVal;
7263 }
7264 
7265 /// Record the value for an instruction that produces an integer result,
7266 /// converting the type where necessary.
7267 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7268                                                   SDValue Value,
7269                                                   bool IsSigned) {
7270   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7271                                                     I.getType(), true);
7272   if (IsSigned)
7273     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7274   else
7275     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7276   setValue(&I, Value);
7277 }
7278 
7279 /// See if we can lower a memcmp call into an optimized form. If so, return
7280 /// true and lower it. Otherwise return false, and it will be lowered like a
7281 /// normal call.
7282 /// The caller already checked that \p I calls the appropriate LibFunc with a
7283 /// correct prototype.
7284 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7285   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7286   const Value *Size = I.getArgOperand(2);
7287   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7288   if (CSize && CSize->getZExtValue() == 0) {
7289     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7290                                                           I.getType(), true);
7291     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7292     return true;
7293   }
7294 
7295   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7296   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7297       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7298       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7299   if (Res.first.getNode()) {
7300     processIntegerCallValue(I, Res.first, true);
7301     PendingLoads.push_back(Res.second);
7302     return true;
7303   }
7304 
7305   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7306   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7307   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7308     return false;
7309 
7310   // If the target has a fast compare for the given size, it will return a
7311   // preferred load type for that size. Require that the load VT is legal and
7312   // that the target supports unaligned loads of that type. Otherwise, return
7313   // INVALID.
7314   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7315     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7316     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7317     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7318       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7319       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7320       // TODO: Check alignment of src and dest ptrs.
7321       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7322       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7323       if (!TLI.isTypeLegal(LVT) ||
7324           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7325           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7326         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7327     }
7328 
7329     return LVT;
7330   };
7331 
7332   // This turns into unaligned loads. We only do this if the target natively
7333   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7334   // we'll only produce a small number of byte loads.
7335   MVT LoadVT;
7336   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7337   switch (NumBitsToCompare) {
7338   default:
7339     return false;
7340   case 16:
7341     LoadVT = MVT::i16;
7342     break;
7343   case 32:
7344     LoadVT = MVT::i32;
7345     break;
7346   case 64:
7347   case 128:
7348   case 256:
7349     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7350     break;
7351   }
7352 
7353   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7354     return false;
7355 
7356   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7357   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7358 
7359   // Bitcast to a wide integer type if the loads are vectors.
7360   if (LoadVT.isVector()) {
7361     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7362     LoadL = DAG.getBitcast(CmpVT, LoadL);
7363     LoadR = DAG.getBitcast(CmpVT, LoadR);
7364   }
7365 
7366   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7367   processIntegerCallValue(I, Cmp, false);
7368   return true;
7369 }
7370 
7371 /// See if we can lower a memchr call into an optimized form. If so, return
7372 /// true and lower it. Otherwise return false, and it will be lowered like a
7373 /// normal call.
7374 /// The caller already checked that \p I calls the appropriate LibFunc with a
7375 /// correct prototype.
7376 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7377   const Value *Src = I.getArgOperand(0);
7378   const Value *Char = I.getArgOperand(1);
7379   const Value *Length = I.getArgOperand(2);
7380 
7381   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7382   std::pair<SDValue, SDValue> Res =
7383     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7384                                 getValue(Src), getValue(Char), getValue(Length),
7385                                 MachinePointerInfo(Src));
7386   if (Res.first.getNode()) {
7387     setValue(&I, Res.first);
7388     PendingLoads.push_back(Res.second);
7389     return true;
7390   }
7391 
7392   return false;
7393 }
7394 
7395 /// See if we can lower a mempcpy call into an optimized form. If so, return
7396 /// true and lower it. Otherwise return false, and it will be lowered like a
7397 /// normal call.
7398 /// The caller already checked that \p I calls the appropriate LibFunc with a
7399 /// correct prototype.
7400 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7401   SDValue Dst = getValue(I.getArgOperand(0));
7402   SDValue Src = getValue(I.getArgOperand(1));
7403   SDValue Size = getValue(I.getArgOperand(2));
7404 
7405   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7406   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7407   // DAG::getMemcpy needs Alignment to be defined.
7408   Align Alignment = std::min(DstAlign, SrcAlign);
7409 
7410   bool isVol = false;
7411   SDLoc sdl = getCurSDLoc();
7412 
7413   // In the mempcpy context we need to pass in a false value for isTailCall
7414   // because the return pointer needs to be adjusted by the size of
7415   // the copied memory.
7416   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7417   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7418                              /*isTailCall=*/false,
7419                              MachinePointerInfo(I.getArgOperand(0)),
7420                              MachinePointerInfo(I.getArgOperand(1)));
7421   assert(MC.getNode() != nullptr &&
7422          "** memcpy should not be lowered as TailCall in mempcpy context **");
7423   DAG.setRoot(MC);
7424 
7425   // Check if Size needs to be truncated or extended.
7426   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7427 
7428   // Adjust return pointer to point just past the last dst byte.
7429   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7430                                     Dst, Size);
7431   setValue(&I, DstPlusSize);
7432   return true;
7433 }
7434 
7435 /// See if we can lower a strcpy call into an optimized form.  If so, return
7436 /// true and lower it, otherwise return false and it will be lowered like a
7437 /// normal call.
7438 /// The caller already checked that \p I calls the appropriate LibFunc with a
7439 /// correct prototype.
7440 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7441   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7442 
7443   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7444   std::pair<SDValue, SDValue> Res =
7445     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7446                                 getValue(Arg0), getValue(Arg1),
7447                                 MachinePointerInfo(Arg0),
7448                                 MachinePointerInfo(Arg1), isStpcpy);
7449   if (Res.first.getNode()) {
7450     setValue(&I, Res.first);
7451     DAG.setRoot(Res.second);
7452     return true;
7453   }
7454 
7455   return false;
7456 }
7457 
7458 /// See if we can lower a strcmp call into an optimized form.  If so, return
7459 /// true and lower it, otherwise return false and it will be lowered like a
7460 /// normal call.
7461 /// The caller already checked that \p I calls the appropriate LibFunc with a
7462 /// correct prototype.
7463 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7464   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7465 
7466   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7467   std::pair<SDValue, SDValue> Res =
7468     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7469                                 getValue(Arg0), getValue(Arg1),
7470                                 MachinePointerInfo(Arg0),
7471                                 MachinePointerInfo(Arg1));
7472   if (Res.first.getNode()) {
7473     processIntegerCallValue(I, Res.first, true);
7474     PendingLoads.push_back(Res.second);
7475     return true;
7476   }
7477 
7478   return false;
7479 }
7480 
7481 /// See if we can lower a strlen call into an optimized form.  If so, return
7482 /// true and lower it, otherwise return false and it will be lowered like a
7483 /// normal call.
7484 /// The caller already checked that \p I calls the appropriate LibFunc with a
7485 /// correct prototype.
7486 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7487   const Value *Arg0 = I.getArgOperand(0);
7488 
7489   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7490   std::pair<SDValue, SDValue> Res =
7491     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7492                                 getValue(Arg0), MachinePointerInfo(Arg0));
7493   if (Res.first.getNode()) {
7494     processIntegerCallValue(I, Res.first, false);
7495     PendingLoads.push_back(Res.second);
7496     return true;
7497   }
7498 
7499   return false;
7500 }
7501 
7502 /// See if we can lower a strnlen call into an optimized form.  If so, return
7503 /// true and lower it, otherwise return false and it will be lowered like a
7504 /// normal call.
7505 /// The caller already checked that \p I calls the appropriate LibFunc with a
7506 /// correct prototype.
7507 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7508   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7509 
7510   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7511   std::pair<SDValue, SDValue> Res =
7512     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7513                                  getValue(Arg0), getValue(Arg1),
7514                                  MachinePointerInfo(Arg0));
7515   if (Res.first.getNode()) {
7516     processIntegerCallValue(I, Res.first, false);
7517     PendingLoads.push_back(Res.second);
7518     return true;
7519   }
7520 
7521   return false;
7522 }
7523 
7524 /// See if we can lower a unary floating-point operation into an SDNode with
7525 /// the specified Opcode.  If so, return true and lower it, otherwise return
7526 /// false and it will be lowered like a normal call.
7527 /// The caller already checked that \p I calls the appropriate LibFunc with a
7528 /// correct prototype.
7529 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7530                                               unsigned Opcode) {
7531   // We already checked this call's prototype; verify it doesn't modify errno.
7532   if (!I.onlyReadsMemory())
7533     return false;
7534 
7535   SDValue Tmp = getValue(I.getArgOperand(0));
7536   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7537   return true;
7538 }
7539 
7540 /// See if we can lower a binary floating-point operation into an SDNode with
7541 /// the specified Opcode. If so, return true and lower it. Otherwise return
7542 /// false, and it will be lowered like a normal call.
7543 /// The caller already checked that \p I calls the appropriate LibFunc with a
7544 /// correct prototype.
7545 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7546                                                unsigned Opcode) {
7547   // We already checked this call's prototype; verify it doesn't modify errno.
7548   if (!I.onlyReadsMemory())
7549     return false;
7550 
7551   SDValue Tmp0 = getValue(I.getArgOperand(0));
7552   SDValue Tmp1 = getValue(I.getArgOperand(1));
7553   EVT VT = Tmp0.getValueType();
7554   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7555   return true;
7556 }
7557 
7558 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7559   // Handle inline assembly differently.
7560   if (I.isInlineAsm()) {
7561     visitInlineAsm(I);
7562     return;
7563   }
7564 
7565   if (Function *F = I.getCalledFunction()) {
7566     if (F->isDeclaration()) {
7567       // Is this an LLVM intrinsic or a target-specific intrinsic?
7568       unsigned IID = F->getIntrinsicID();
7569       if (!IID)
7570         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7571           IID = II->getIntrinsicID(F);
7572 
7573       if (IID) {
7574         visitIntrinsicCall(I, IID);
7575         return;
7576       }
7577     }
7578 
7579     // Check for well-known libc/libm calls.  If the function is internal, it
7580     // can't be a library call.  Don't do the check if marked as nobuiltin for
7581     // some reason or the call site requires strict floating point semantics.
7582     LibFunc Func;
7583     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7584         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7585         LibInfo->hasOptimizedCodeGen(Func)) {
7586       switch (Func) {
7587       default: break;
7588       case LibFunc_copysign:
7589       case LibFunc_copysignf:
7590       case LibFunc_copysignl:
7591         // We already checked this call's prototype; verify it doesn't modify
7592         // errno.
7593         if (I.onlyReadsMemory()) {
7594           SDValue LHS = getValue(I.getArgOperand(0));
7595           SDValue RHS = getValue(I.getArgOperand(1));
7596           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7597                                    LHS.getValueType(), LHS, RHS));
7598           return;
7599         }
7600         break;
7601       case LibFunc_fabs:
7602       case LibFunc_fabsf:
7603       case LibFunc_fabsl:
7604         if (visitUnaryFloatCall(I, ISD::FABS))
7605           return;
7606         break;
7607       case LibFunc_fmin:
7608       case LibFunc_fminf:
7609       case LibFunc_fminl:
7610         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7611           return;
7612         break;
7613       case LibFunc_fmax:
7614       case LibFunc_fmaxf:
7615       case LibFunc_fmaxl:
7616         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7617           return;
7618         break;
7619       case LibFunc_sin:
7620       case LibFunc_sinf:
7621       case LibFunc_sinl:
7622         if (visitUnaryFloatCall(I, ISD::FSIN))
7623           return;
7624         break;
7625       case LibFunc_cos:
7626       case LibFunc_cosf:
7627       case LibFunc_cosl:
7628         if (visitUnaryFloatCall(I, ISD::FCOS))
7629           return;
7630         break;
7631       case LibFunc_sqrt:
7632       case LibFunc_sqrtf:
7633       case LibFunc_sqrtl:
7634       case LibFunc_sqrt_finite:
7635       case LibFunc_sqrtf_finite:
7636       case LibFunc_sqrtl_finite:
7637         if (visitUnaryFloatCall(I, ISD::FSQRT))
7638           return;
7639         break;
7640       case LibFunc_floor:
7641       case LibFunc_floorf:
7642       case LibFunc_floorl:
7643         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7644           return;
7645         break;
7646       case LibFunc_nearbyint:
7647       case LibFunc_nearbyintf:
7648       case LibFunc_nearbyintl:
7649         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7650           return;
7651         break;
7652       case LibFunc_ceil:
7653       case LibFunc_ceilf:
7654       case LibFunc_ceill:
7655         if (visitUnaryFloatCall(I, ISD::FCEIL))
7656           return;
7657         break;
7658       case LibFunc_rint:
7659       case LibFunc_rintf:
7660       case LibFunc_rintl:
7661         if (visitUnaryFloatCall(I, ISD::FRINT))
7662           return;
7663         break;
7664       case LibFunc_round:
7665       case LibFunc_roundf:
7666       case LibFunc_roundl:
7667         if (visitUnaryFloatCall(I, ISD::FROUND))
7668           return;
7669         break;
7670       case LibFunc_trunc:
7671       case LibFunc_truncf:
7672       case LibFunc_truncl:
7673         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7674           return;
7675         break;
7676       case LibFunc_log2:
7677       case LibFunc_log2f:
7678       case LibFunc_log2l:
7679         if (visitUnaryFloatCall(I, ISD::FLOG2))
7680           return;
7681         break;
7682       case LibFunc_exp2:
7683       case LibFunc_exp2f:
7684       case LibFunc_exp2l:
7685         if (visitUnaryFloatCall(I, ISD::FEXP2))
7686           return;
7687         break;
7688       case LibFunc_memcmp:
7689         if (visitMemCmpCall(I))
7690           return;
7691         break;
7692       case LibFunc_mempcpy:
7693         if (visitMemPCpyCall(I))
7694           return;
7695         break;
7696       case LibFunc_memchr:
7697         if (visitMemChrCall(I))
7698           return;
7699         break;
7700       case LibFunc_strcpy:
7701         if (visitStrCpyCall(I, false))
7702           return;
7703         break;
7704       case LibFunc_stpcpy:
7705         if (visitStrCpyCall(I, true))
7706           return;
7707         break;
7708       case LibFunc_strcmp:
7709         if (visitStrCmpCall(I))
7710           return;
7711         break;
7712       case LibFunc_strlen:
7713         if (visitStrLenCall(I))
7714           return;
7715         break;
7716       case LibFunc_strnlen:
7717         if (visitStrNLenCall(I))
7718           return;
7719         break;
7720       }
7721     }
7722   }
7723 
7724   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7725   // have to do anything here to lower funclet bundles.
7726   // CFGuardTarget bundles are lowered in LowerCallTo.
7727   assert(!I.hasOperandBundlesOtherThan(
7728              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
7729               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) &&
7730          "Cannot lower calls with arbitrary operand bundles!");
7731 
7732   SDValue Callee = getValue(I.getCalledOperand());
7733 
7734   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7735     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7736   else
7737     // Check if we can potentially perform a tail call. More detailed checking
7738     // is be done within LowerCallTo, after more information about the call is
7739     // known.
7740     LowerCallTo(I, Callee, I.isTailCall());
7741 }
7742 
7743 namespace {
7744 
7745 /// AsmOperandInfo - This contains information for each constraint that we are
7746 /// lowering.
7747 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7748 public:
7749   /// CallOperand - If this is the result output operand or a clobber
7750   /// this is null, otherwise it is the incoming operand to the CallInst.
7751   /// This gets modified as the asm is processed.
7752   SDValue CallOperand;
7753 
7754   /// AssignedRegs - If this is a register or register class operand, this
7755   /// contains the set of register corresponding to the operand.
7756   RegsForValue AssignedRegs;
7757 
7758   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7759     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7760   }
7761 
7762   /// Whether or not this operand accesses memory
7763   bool hasMemory(const TargetLowering &TLI) const {
7764     // Indirect operand accesses access memory.
7765     if (isIndirect)
7766       return true;
7767 
7768     for (const auto &Code : Codes)
7769       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7770         return true;
7771 
7772     return false;
7773   }
7774 
7775   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7776   /// corresponds to.  If there is no Value* for this operand, it returns
7777   /// MVT::Other.
7778   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7779                            const DataLayout &DL) const {
7780     if (!CallOperandVal) return MVT::Other;
7781 
7782     if (isa<BasicBlock>(CallOperandVal))
7783       return TLI.getProgramPointerTy(DL);
7784 
7785     llvm::Type *OpTy = CallOperandVal->getType();
7786 
7787     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7788     // If this is an indirect operand, the operand is a pointer to the
7789     // accessed type.
7790     if (isIndirect) {
7791       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7792       if (!PtrTy)
7793         report_fatal_error("Indirect operand for inline asm not a pointer!");
7794       OpTy = PtrTy->getElementType();
7795     }
7796 
7797     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7798     if (StructType *STy = dyn_cast<StructType>(OpTy))
7799       if (STy->getNumElements() == 1)
7800         OpTy = STy->getElementType(0);
7801 
7802     // If OpTy is not a single value, it may be a struct/union that we
7803     // can tile with integers.
7804     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7805       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7806       switch (BitSize) {
7807       default: break;
7808       case 1:
7809       case 8:
7810       case 16:
7811       case 32:
7812       case 64:
7813       case 128:
7814         OpTy = IntegerType::get(Context, BitSize);
7815         break;
7816       }
7817     }
7818 
7819     return TLI.getValueType(DL, OpTy, true);
7820   }
7821 };
7822 
7823 
7824 } // end anonymous namespace
7825 
7826 /// Make sure that the output operand \p OpInfo and its corresponding input
7827 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7828 /// out).
7829 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7830                                SDISelAsmOperandInfo &MatchingOpInfo,
7831                                SelectionDAG &DAG) {
7832   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7833     return;
7834 
7835   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7836   const auto &TLI = DAG.getTargetLoweringInfo();
7837 
7838   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7839       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7840                                        OpInfo.ConstraintVT);
7841   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7842       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7843                                        MatchingOpInfo.ConstraintVT);
7844   if ((OpInfo.ConstraintVT.isInteger() !=
7845        MatchingOpInfo.ConstraintVT.isInteger()) ||
7846       (MatchRC.second != InputRC.second)) {
7847     // FIXME: error out in a more elegant fashion
7848     report_fatal_error("Unsupported asm: input constraint"
7849                        " with a matching output constraint of"
7850                        " incompatible type!");
7851   }
7852   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7853 }
7854 
7855 /// Get a direct memory input to behave well as an indirect operand.
7856 /// This may introduce stores, hence the need for a \p Chain.
7857 /// \return The (possibly updated) chain.
7858 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7859                                         SDISelAsmOperandInfo &OpInfo,
7860                                         SelectionDAG &DAG) {
7861   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7862 
7863   // If we don't have an indirect input, put it in the constpool if we can,
7864   // otherwise spill it to a stack slot.
7865   // TODO: This isn't quite right. We need to handle these according to
7866   // the addressing mode that the constraint wants. Also, this may take
7867   // an additional register for the computation and we don't want that
7868   // either.
7869 
7870   // If the operand is a float, integer, or vector constant, spill to a
7871   // constant pool entry to get its address.
7872   const Value *OpVal = OpInfo.CallOperandVal;
7873   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7874       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7875     OpInfo.CallOperand = DAG.getConstantPool(
7876         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7877     return Chain;
7878   }
7879 
7880   // Otherwise, create a stack slot and emit a store to it before the asm.
7881   Type *Ty = OpVal->getType();
7882   auto &DL = DAG.getDataLayout();
7883   uint64_t TySize = DL.getTypeAllocSize(Ty);
7884   MachineFunction &MF = DAG.getMachineFunction();
7885   int SSFI = MF.getFrameInfo().CreateStackObject(
7886       TySize, DL.getPrefTypeAlign(Ty), false);
7887   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7888   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7889                             MachinePointerInfo::getFixedStack(MF, SSFI),
7890                             TLI.getMemValueType(DL, Ty));
7891   OpInfo.CallOperand = StackSlot;
7892 
7893   return Chain;
7894 }
7895 
7896 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7897 /// specified operand.  We prefer to assign virtual registers, to allow the
7898 /// register allocator to handle the assignment process.  However, if the asm
7899 /// uses features that we can't model on machineinstrs, we have SDISel do the
7900 /// allocation.  This produces generally horrible, but correct, code.
7901 ///
7902 ///   OpInfo describes the operand
7903 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7904 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7905                                  SDISelAsmOperandInfo &OpInfo,
7906                                  SDISelAsmOperandInfo &RefOpInfo) {
7907   LLVMContext &Context = *DAG.getContext();
7908   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7909 
7910   MachineFunction &MF = DAG.getMachineFunction();
7911   SmallVector<unsigned, 4> Regs;
7912   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7913 
7914   // No work to do for memory operations.
7915   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7916     return;
7917 
7918   // If this is a constraint for a single physreg, or a constraint for a
7919   // register class, find it.
7920   unsigned AssignedReg;
7921   const TargetRegisterClass *RC;
7922   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7923       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7924   // RC is unset only on failure. Return immediately.
7925   if (!RC)
7926     return;
7927 
7928   // Get the actual register value type.  This is important, because the user
7929   // may have asked for (e.g.) the AX register in i32 type.  We need to
7930   // remember that AX is actually i16 to get the right extension.
7931   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7932 
7933   if (OpInfo.ConstraintVT != MVT::Other) {
7934     // If this is an FP operand in an integer register (or visa versa), or more
7935     // generally if the operand value disagrees with the register class we plan
7936     // to stick it in, fix the operand type.
7937     //
7938     // If this is an input value, the bitcast to the new type is done now.
7939     // Bitcast for output value is done at the end of visitInlineAsm().
7940     if ((OpInfo.Type == InlineAsm::isOutput ||
7941          OpInfo.Type == InlineAsm::isInput) &&
7942         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7943       // Try to convert to the first EVT that the reg class contains.  If the
7944       // types are identical size, use a bitcast to convert (e.g. two differing
7945       // vector types).  Note: output bitcast is done at the end of
7946       // visitInlineAsm().
7947       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7948         // Exclude indirect inputs while they are unsupported because the code
7949         // to perform the load is missing and thus OpInfo.CallOperand still
7950         // refers to the input address rather than the pointed-to value.
7951         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7952           OpInfo.CallOperand =
7953               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7954         OpInfo.ConstraintVT = RegVT;
7955         // If the operand is an FP value and we want it in integer registers,
7956         // use the corresponding integer type. This turns an f64 value into
7957         // i64, which can be passed with two i32 values on a 32-bit machine.
7958       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7959         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7960         if (OpInfo.Type == InlineAsm::isInput)
7961           OpInfo.CallOperand =
7962               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7963         OpInfo.ConstraintVT = VT;
7964       }
7965     }
7966   }
7967 
7968   // No need to allocate a matching input constraint since the constraint it's
7969   // matching to has already been allocated.
7970   if (OpInfo.isMatchingInputConstraint())
7971     return;
7972 
7973   EVT ValueVT = OpInfo.ConstraintVT;
7974   if (OpInfo.ConstraintVT == MVT::Other)
7975     ValueVT = RegVT;
7976 
7977   // Initialize NumRegs.
7978   unsigned NumRegs = 1;
7979   if (OpInfo.ConstraintVT != MVT::Other)
7980     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7981 
7982   // If this is a constraint for a specific physical register, like {r17},
7983   // assign it now.
7984 
7985   // If this associated to a specific register, initialize iterator to correct
7986   // place. If virtual, make sure we have enough registers
7987 
7988   // Initialize iterator if necessary
7989   TargetRegisterClass::iterator I = RC->begin();
7990   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7991 
7992   // Do not check for single registers.
7993   if (AssignedReg) {
7994       for (; *I != AssignedReg; ++I)
7995         assert(I != RC->end() && "AssignedReg should be member of RC");
7996   }
7997 
7998   for (; NumRegs; --NumRegs, ++I) {
7999     assert(I != RC->end() && "Ran out of registers to allocate!");
8000     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8001     Regs.push_back(R);
8002   }
8003 
8004   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8005 }
8006 
8007 static unsigned
8008 findMatchingInlineAsmOperand(unsigned OperandNo,
8009                              const std::vector<SDValue> &AsmNodeOperands) {
8010   // Scan until we find the definition we already emitted of this operand.
8011   unsigned CurOp = InlineAsm::Op_FirstOperand;
8012   for (; OperandNo; --OperandNo) {
8013     // Advance to the next operand.
8014     unsigned OpFlag =
8015         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8016     assert((InlineAsm::isRegDefKind(OpFlag) ||
8017             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8018             InlineAsm::isMemKind(OpFlag)) &&
8019            "Skipped past definitions?");
8020     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8021   }
8022   return CurOp;
8023 }
8024 
8025 namespace {
8026 
8027 class ExtraFlags {
8028   unsigned Flags = 0;
8029 
8030 public:
8031   explicit ExtraFlags(const CallBase &Call) {
8032     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8033     if (IA->hasSideEffects())
8034       Flags |= InlineAsm::Extra_HasSideEffects;
8035     if (IA->isAlignStack())
8036       Flags |= InlineAsm::Extra_IsAlignStack;
8037     if (Call.isConvergent())
8038       Flags |= InlineAsm::Extra_IsConvergent;
8039     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8040   }
8041 
8042   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8043     // Ideally, we would only check against memory constraints.  However, the
8044     // meaning of an Other constraint can be target-specific and we can't easily
8045     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8046     // for Other constraints as well.
8047     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8048         OpInfo.ConstraintType == TargetLowering::C_Other) {
8049       if (OpInfo.Type == InlineAsm::isInput)
8050         Flags |= InlineAsm::Extra_MayLoad;
8051       else if (OpInfo.Type == InlineAsm::isOutput)
8052         Flags |= InlineAsm::Extra_MayStore;
8053       else if (OpInfo.Type == InlineAsm::isClobber)
8054         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8055     }
8056   }
8057 
8058   unsigned get() const { return Flags; }
8059 };
8060 
8061 } // end anonymous namespace
8062 
8063 /// visitInlineAsm - Handle a call to an InlineAsm object.
8064 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
8065   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8066 
8067   /// ConstraintOperands - Information about all of the constraints.
8068   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8069 
8070   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8071   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8072       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8073 
8074   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8075   // AsmDialect, MayLoad, MayStore).
8076   bool HasSideEffect = IA->hasSideEffects();
8077   ExtraFlags ExtraInfo(Call);
8078 
8079   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8080   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8081   unsigned NumMatchingOps = 0;
8082   for (auto &T : TargetConstraints) {
8083     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8084     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8085 
8086     // Compute the value type for each operand.
8087     if (OpInfo.Type == InlineAsm::isInput ||
8088         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8089       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8090 
8091       // Process the call argument. BasicBlocks are labels, currently appearing
8092       // only in asm's.
8093       if (isa<CallBrInst>(Call) &&
8094           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8095                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8096                         NumMatchingOps) &&
8097           (NumMatchingOps == 0 ||
8098            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8099                         NumMatchingOps))) {
8100         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8101         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8102         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8103       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8104         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8105       } else {
8106         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8107       }
8108 
8109       OpInfo.ConstraintVT =
8110           OpInfo
8111               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8112               .getSimpleVT();
8113     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8114       // The return value of the call is this value.  As such, there is no
8115       // corresponding argument.
8116       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8117       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8118         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8119             DAG.getDataLayout(), STy->getElementType(ResNo));
8120       } else {
8121         assert(ResNo == 0 && "Asm only has one result!");
8122         OpInfo.ConstraintVT =
8123             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8124       }
8125       ++ResNo;
8126     } else {
8127       OpInfo.ConstraintVT = MVT::Other;
8128     }
8129 
8130     if (OpInfo.hasMatchingInput())
8131       ++NumMatchingOps;
8132 
8133     if (!HasSideEffect)
8134       HasSideEffect = OpInfo.hasMemory(TLI);
8135 
8136     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8137     // FIXME: Could we compute this on OpInfo rather than T?
8138 
8139     // Compute the constraint code and ConstraintType to use.
8140     TLI.ComputeConstraintToUse(T, SDValue());
8141 
8142     if (T.ConstraintType == TargetLowering::C_Immediate &&
8143         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8144       // We've delayed emitting a diagnostic like the "n" constraint because
8145       // inlining could cause an integer showing up.
8146       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8147                                           "' expects an integer constant "
8148                                           "expression");
8149 
8150     ExtraInfo.update(T);
8151   }
8152 
8153 
8154   // We won't need to flush pending loads if this asm doesn't touch
8155   // memory and is nonvolatile.
8156   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8157 
8158   bool IsCallBr = isa<CallBrInst>(Call);
8159   if (IsCallBr) {
8160     // If this is a callbr we need to flush pending exports since inlineasm_br
8161     // is a terminator. We need to do this before nodes are glued to
8162     // the inlineasm_br node.
8163     Chain = getControlRoot();
8164   }
8165 
8166   // Second pass over the constraints: compute which constraint option to use.
8167   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8168     // If this is an output operand with a matching input operand, look up the
8169     // matching input. If their types mismatch, e.g. one is an integer, the
8170     // other is floating point, or their sizes are different, flag it as an
8171     // error.
8172     if (OpInfo.hasMatchingInput()) {
8173       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8174       patchMatchingInput(OpInfo, Input, DAG);
8175     }
8176 
8177     // Compute the constraint code and ConstraintType to use.
8178     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8179 
8180     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8181         OpInfo.Type == InlineAsm::isClobber)
8182       continue;
8183 
8184     // If this is a memory input, and if the operand is not indirect, do what we
8185     // need to provide an address for the memory input.
8186     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8187         !OpInfo.isIndirect) {
8188       assert((OpInfo.isMultipleAlternative ||
8189               (OpInfo.Type == InlineAsm::isInput)) &&
8190              "Can only indirectify direct input operands!");
8191 
8192       // Memory operands really want the address of the value.
8193       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8194 
8195       // There is no longer a Value* corresponding to this operand.
8196       OpInfo.CallOperandVal = nullptr;
8197 
8198       // It is now an indirect operand.
8199       OpInfo.isIndirect = true;
8200     }
8201 
8202   }
8203 
8204   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8205   std::vector<SDValue> AsmNodeOperands;
8206   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8207   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8208       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8209 
8210   // If we have a !srcloc metadata node associated with it, we want to attach
8211   // this to the ultimately generated inline asm machineinstr.  To do this, we
8212   // pass in the third operand as this (potentially null) inline asm MDNode.
8213   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8214   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8215 
8216   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8217   // bits as operand 3.
8218   AsmNodeOperands.push_back(DAG.getTargetConstant(
8219       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8220 
8221   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8222   // this, assign virtual and physical registers for inputs and otput.
8223   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8224     // Assign Registers.
8225     SDISelAsmOperandInfo &RefOpInfo =
8226         OpInfo.isMatchingInputConstraint()
8227             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8228             : OpInfo;
8229     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8230 
8231     auto DetectWriteToReservedRegister = [&]() {
8232       const MachineFunction &MF = DAG.getMachineFunction();
8233       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8234       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8235         if (Register::isPhysicalRegister(Reg) &&
8236             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8237           const char *RegName = TRI.getName(Reg);
8238           emitInlineAsmError(Call, "write to reserved register '" +
8239                                        Twine(RegName) + "'");
8240           return true;
8241         }
8242       }
8243       return false;
8244     };
8245 
8246     switch (OpInfo.Type) {
8247     case InlineAsm::isOutput:
8248       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8249         unsigned ConstraintID =
8250             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8251         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8252                "Failed to convert memory constraint code to constraint id.");
8253 
8254         // Add information to the INLINEASM node to know about this output.
8255         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8256         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8257         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8258                                                         MVT::i32));
8259         AsmNodeOperands.push_back(OpInfo.CallOperand);
8260       } else {
8261         // Otherwise, this outputs to a register (directly for C_Register /
8262         // C_RegisterClass, and a target-defined fashion for
8263         // C_Immediate/C_Other). Find a register that we can use.
8264         if (OpInfo.AssignedRegs.Regs.empty()) {
8265           emitInlineAsmError(
8266               Call, "couldn't allocate output register for constraint '" +
8267                         Twine(OpInfo.ConstraintCode) + "'");
8268           return;
8269         }
8270 
8271         if (DetectWriteToReservedRegister())
8272           return;
8273 
8274         // Add information to the INLINEASM node to know that this register is
8275         // set.
8276         OpInfo.AssignedRegs.AddInlineAsmOperands(
8277             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8278                                   : InlineAsm::Kind_RegDef,
8279             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8280       }
8281       break;
8282 
8283     case InlineAsm::isInput: {
8284       SDValue InOperandVal = OpInfo.CallOperand;
8285 
8286       if (OpInfo.isMatchingInputConstraint()) {
8287         // If this is required to match an output register we have already set,
8288         // just use its register.
8289         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8290                                                   AsmNodeOperands);
8291         unsigned OpFlag =
8292           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8293         if (InlineAsm::isRegDefKind(OpFlag) ||
8294             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8295           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8296           if (OpInfo.isIndirect) {
8297             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8298             emitInlineAsmError(Call, "inline asm not supported yet: "
8299                                      "don't know how to handle tied "
8300                                      "indirect register inputs");
8301             return;
8302           }
8303 
8304           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8305           SmallVector<unsigned, 4> Regs;
8306 
8307           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8308             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8309             MachineRegisterInfo &RegInfo =
8310                 DAG.getMachineFunction().getRegInfo();
8311             for (unsigned i = 0; i != NumRegs; ++i)
8312               Regs.push_back(RegInfo.createVirtualRegister(RC));
8313           } else {
8314             emitInlineAsmError(Call,
8315                                "inline asm error: This value type register "
8316                                "class is not natively supported!");
8317             return;
8318           }
8319 
8320           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8321 
8322           SDLoc dl = getCurSDLoc();
8323           // Use the produced MatchedRegs object to
8324           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8325           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8326                                            true, OpInfo.getMatchedOperand(), dl,
8327                                            DAG, AsmNodeOperands);
8328           break;
8329         }
8330 
8331         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8332         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8333                "Unexpected number of operands");
8334         // Add information to the INLINEASM node to know about this input.
8335         // See InlineAsm.h isUseOperandTiedToDef.
8336         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8337         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8338                                                     OpInfo.getMatchedOperand());
8339         AsmNodeOperands.push_back(DAG.getTargetConstant(
8340             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8341         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8342         break;
8343       }
8344 
8345       // Treat indirect 'X' constraint as memory.
8346       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8347           OpInfo.isIndirect)
8348         OpInfo.ConstraintType = TargetLowering::C_Memory;
8349 
8350       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8351           OpInfo.ConstraintType == TargetLowering::C_Other) {
8352         std::vector<SDValue> Ops;
8353         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8354                                           Ops, DAG);
8355         if (Ops.empty()) {
8356           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8357             if (isa<ConstantSDNode>(InOperandVal)) {
8358               emitInlineAsmError(Call, "value out of range for constraint '" +
8359                                            Twine(OpInfo.ConstraintCode) + "'");
8360               return;
8361             }
8362 
8363           emitInlineAsmError(Call,
8364                              "invalid operand for inline asm constraint '" +
8365                                  Twine(OpInfo.ConstraintCode) + "'");
8366           return;
8367         }
8368 
8369         // Add information to the INLINEASM node to know about this input.
8370         unsigned ResOpType =
8371           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8372         AsmNodeOperands.push_back(DAG.getTargetConstant(
8373             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8374         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8375         break;
8376       }
8377 
8378       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8379         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8380         assert(InOperandVal.getValueType() ==
8381                    TLI.getPointerTy(DAG.getDataLayout()) &&
8382                "Memory operands expect pointer values");
8383 
8384         unsigned ConstraintID =
8385             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8386         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8387                "Failed to convert memory constraint code to constraint id.");
8388 
8389         // Add information to the INLINEASM node to know about this input.
8390         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8391         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8392         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8393                                                         getCurSDLoc(),
8394                                                         MVT::i32));
8395         AsmNodeOperands.push_back(InOperandVal);
8396         break;
8397       }
8398 
8399       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8400               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8401              "Unknown constraint type!");
8402 
8403       // TODO: Support this.
8404       if (OpInfo.isIndirect) {
8405         emitInlineAsmError(
8406             Call, "Don't know how to handle indirect register inputs yet "
8407                   "for constraint '" +
8408                       Twine(OpInfo.ConstraintCode) + "'");
8409         return;
8410       }
8411 
8412       // Copy the input into the appropriate registers.
8413       if (OpInfo.AssignedRegs.Regs.empty()) {
8414         emitInlineAsmError(Call,
8415                            "couldn't allocate input reg for constraint '" +
8416                                Twine(OpInfo.ConstraintCode) + "'");
8417         return;
8418       }
8419 
8420       if (DetectWriteToReservedRegister())
8421         return;
8422 
8423       SDLoc dl = getCurSDLoc();
8424 
8425       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8426                                         &Call);
8427 
8428       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8429                                                dl, DAG, AsmNodeOperands);
8430       break;
8431     }
8432     case InlineAsm::isClobber:
8433       // Add the clobbered value to the operand list, so that the register
8434       // allocator is aware that the physreg got clobbered.
8435       if (!OpInfo.AssignedRegs.Regs.empty())
8436         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8437                                                  false, 0, getCurSDLoc(), DAG,
8438                                                  AsmNodeOperands);
8439       break;
8440     }
8441   }
8442 
8443   // Finish up input operands.  Set the input chain and add the flag last.
8444   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8445   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8446 
8447   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8448   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8449                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8450   Flag = Chain.getValue(1);
8451 
8452   // Do additional work to generate outputs.
8453 
8454   SmallVector<EVT, 1> ResultVTs;
8455   SmallVector<SDValue, 1> ResultValues;
8456   SmallVector<SDValue, 8> OutChains;
8457 
8458   llvm::Type *CallResultType = Call.getType();
8459   ArrayRef<Type *> ResultTypes;
8460   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8461     ResultTypes = StructResult->elements();
8462   else if (!CallResultType->isVoidTy())
8463     ResultTypes = makeArrayRef(CallResultType);
8464 
8465   auto CurResultType = ResultTypes.begin();
8466   auto handleRegAssign = [&](SDValue V) {
8467     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8468     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8469     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8470     ++CurResultType;
8471     // If the type of the inline asm call site return value is different but has
8472     // same size as the type of the asm output bitcast it.  One example of this
8473     // is for vectors with different width / number of elements.  This can
8474     // happen for register classes that can contain multiple different value
8475     // types.  The preg or vreg allocated may not have the same VT as was
8476     // expected.
8477     //
8478     // This can also happen for a return value that disagrees with the register
8479     // class it is put in, eg. a double in a general-purpose register on a
8480     // 32-bit machine.
8481     if (ResultVT != V.getValueType() &&
8482         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8483       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8484     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8485              V.getValueType().isInteger()) {
8486       // If a result value was tied to an input value, the computed result
8487       // may have a wider width than the expected result.  Extract the
8488       // relevant portion.
8489       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8490     }
8491     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8492     ResultVTs.push_back(ResultVT);
8493     ResultValues.push_back(V);
8494   };
8495 
8496   // Deal with output operands.
8497   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8498     if (OpInfo.Type == InlineAsm::isOutput) {
8499       SDValue Val;
8500       // Skip trivial output operands.
8501       if (OpInfo.AssignedRegs.Regs.empty())
8502         continue;
8503 
8504       switch (OpInfo.ConstraintType) {
8505       case TargetLowering::C_Register:
8506       case TargetLowering::C_RegisterClass:
8507         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8508                                                   Chain, &Flag, &Call);
8509         break;
8510       case TargetLowering::C_Immediate:
8511       case TargetLowering::C_Other:
8512         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8513                                               OpInfo, DAG);
8514         break;
8515       case TargetLowering::C_Memory:
8516         break; // Already handled.
8517       case TargetLowering::C_Unknown:
8518         assert(false && "Unexpected unknown constraint");
8519       }
8520 
8521       // Indirect output manifest as stores. Record output chains.
8522       if (OpInfo.isIndirect) {
8523         const Value *Ptr = OpInfo.CallOperandVal;
8524         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8525         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8526                                      MachinePointerInfo(Ptr));
8527         OutChains.push_back(Store);
8528       } else {
8529         // generate CopyFromRegs to associated registers.
8530         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8531         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8532           for (const SDValue &V : Val->op_values())
8533             handleRegAssign(V);
8534         } else
8535           handleRegAssign(Val);
8536       }
8537     }
8538   }
8539 
8540   // Set results.
8541   if (!ResultValues.empty()) {
8542     assert(CurResultType == ResultTypes.end() &&
8543            "Mismatch in number of ResultTypes");
8544     assert(ResultValues.size() == ResultTypes.size() &&
8545            "Mismatch in number of output operands in asm result");
8546 
8547     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8548                             DAG.getVTList(ResultVTs), ResultValues);
8549     setValue(&Call, V);
8550   }
8551 
8552   // Collect store chains.
8553   if (!OutChains.empty())
8554     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8555 
8556   // Only Update Root if inline assembly has a memory effect.
8557   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8558     DAG.setRoot(Chain);
8559 }
8560 
8561 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8562                                              const Twine &Message) {
8563   LLVMContext &Ctx = *DAG.getContext();
8564   Ctx.emitError(&Call, Message);
8565 
8566   // Make sure we leave the DAG in a valid state
8567   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8568   SmallVector<EVT, 1> ValueVTs;
8569   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8570 
8571   if (ValueVTs.empty())
8572     return;
8573 
8574   SmallVector<SDValue, 1> Ops;
8575   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8576     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8577 
8578   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8579 }
8580 
8581 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8582   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8583                           MVT::Other, getRoot(),
8584                           getValue(I.getArgOperand(0)),
8585                           DAG.getSrcValue(I.getArgOperand(0))));
8586 }
8587 
8588 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8589   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8590   const DataLayout &DL = DAG.getDataLayout();
8591   SDValue V = DAG.getVAArg(
8592       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8593       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8594       DL.getABITypeAlign(I.getType()).value());
8595   DAG.setRoot(V.getValue(1));
8596 
8597   if (I.getType()->isPointerTy())
8598     V = DAG.getPtrExtOrTrunc(
8599         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8600   setValue(&I, V);
8601 }
8602 
8603 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8604   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8605                           MVT::Other, getRoot(),
8606                           getValue(I.getArgOperand(0)),
8607                           DAG.getSrcValue(I.getArgOperand(0))));
8608 }
8609 
8610 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8611   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8612                           MVT::Other, getRoot(),
8613                           getValue(I.getArgOperand(0)),
8614                           getValue(I.getArgOperand(1)),
8615                           DAG.getSrcValue(I.getArgOperand(0)),
8616                           DAG.getSrcValue(I.getArgOperand(1))));
8617 }
8618 
8619 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8620                                                     const Instruction &I,
8621                                                     SDValue Op) {
8622   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8623   if (!Range)
8624     return Op;
8625 
8626   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8627   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8628     return Op;
8629 
8630   APInt Lo = CR.getUnsignedMin();
8631   if (!Lo.isMinValue())
8632     return Op;
8633 
8634   APInt Hi = CR.getUnsignedMax();
8635   unsigned Bits = std::max(Hi.getActiveBits(),
8636                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8637 
8638   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8639 
8640   SDLoc SL = getCurSDLoc();
8641 
8642   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8643                              DAG.getValueType(SmallVT));
8644   unsigned NumVals = Op.getNode()->getNumValues();
8645   if (NumVals == 1)
8646     return ZExt;
8647 
8648   SmallVector<SDValue, 4> Ops;
8649 
8650   Ops.push_back(ZExt);
8651   for (unsigned I = 1; I != NumVals; ++I)
8652     Ops.push_back(Op.getValue(I));
8653 
8654   return DAG.getMergeValues(Ops, SL);
8655 }
8656 
8657 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8658 /// the call being lowered.
8659 ///
8660 /// This is a helper for lowering intrinsics that follow a target calling
8661 /// convention or require stack pointer adjustment. Only a subset of the
8662 /// intrinsic's operands need to participate in the calling convention.
8663 void SelectionDAGBuilder::populateCallLoweringInfo(
8664     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8665     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8666     bool IsPatchPoint) {
8667   TargetLowering::ArgListTy Args;
8668   Args.reserve(NumArgs);
8669 
8670   // Populate the argument list.
8671   // Attributes for args start at offset 1, after the return attribute.
8672   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8673        ArgI != ArgE; ++ArgI) {
8674     const Value *V = Call->getOperand(ArgI);
8675 
8676     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8677 
8678     TargetLowering::ArgListEntry Entry;
8679     Entry.Node = getValue(V);
8680     Entry.Ty = V->getType();
8681     Entry.setAttributes(Call, ArgI);
8682     Args.push_back(Entry);
8683   }
8684 
8685   CLI.setDebugLoc(getCurSDLoc())
8686       .setChain(getRoot())
8687       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8688       .setDiscardResult(Call->use_empty())
8689       .setIsPatchPoint(IsPatchPoint)
8690       .setIsPreallocated(
8691           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
8692 }
8693 
8694 /// Add a stack map intrinsic call's live variable operands to a stackmap
8695 /// or patchpoint target node's operand list.
8696 ///
8697 /// Constants are converted to TargetConstants purely as an optimization to
8698 /// avoid constant materialization and register allocation.
8699 ///
8700 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8701 /// generate addess computation nodes, and so FinalizeISel can convert the
8702 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8703 /// address materialization and register allocation, but may also be required
8704 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8705 /// alloca in the entry block, then the runtime may assume that the alloca's
8706 /// StackMap location can be read immediately after compilation and that the
8707 /// location is valid at any point during execution (this is similar to the
8708 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8709 /// only available in a register, then the runtime would need to trap when
8710 /// execution reaches the StackMap in order to read the alloca's location.
8711 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8712                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8713                                 SelectionDAGBuilder &Builder) {
8714   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8715     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8716     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8717       Ops.push_back(
8718         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8719       Ops.push_back(
8720         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8721     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8722       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8723       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8724           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8725     } else
8726       Ops.push_back(OpVal);
8727   }
8728 }
8729 
8730 /// Lower llvm.experimental.stackmap directly to its target opcode.
8731 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8732   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8733   //                                  [live variables...])
8734 
8735   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8736 
8737   SDValue Chain, InFlag, Callee, NullPtr;
8738   SmallVector<SDValue, 32> Ops;
8739 
8740   SDLoc DL = getCurSDLoc();
8741   Callee = getValue(CI.getCalledOperand());
8742   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8743 
8744   // The stackmap intrinsic only records the live variables (the arguments
8745   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8746   // intrinsic, this won't be lowered to a function call. This means we don't
8747   // have to worry about calling conventions and target specific lowering code.
8748   // Instead we perform the call lowering right here.
8749   //
8750   // chain, flag = CALLSEQ_START(chain, 0, 0)
8751   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8752   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8753   //
8754   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8755   InFlag = Chain.getValue(1);
8756 
8757   // Add the <id> and <numBytes> constants.
8758   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8759   Ops.push_back(DAG.getTargetConstant(
8760                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8761   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8762   Ops.push_back(DAG.getTargetConstant(
8763                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8764                   MVT::i32));
8765 
8766   // Push live variables for the stack map.
8767   addStackMapLiveVars(CI, 2, DL, Ops, *this);
8768 
8769   // We are not pushing any register mask info here on the operands list,
8770   // because the stackmap doesn't clobber anything.
8771 
8772   // Push the chain and the glue flag.
8773   Ops.push_back(Chain);
8774   Ops.push_back(InFlag);
8775 
8776   // Create the STACKMAP node.
8777   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8778   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8779   Chain = SDValue(SM, 0);
8780   InFlag = Chain.getValue(1);
8781 
8782   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8783 
8784   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8785 
8786   // Set the root to the target-lowered call chain.
8787   DAG.setRoot(Chain);
8788 
8789   // Inform the Frame Information that we have a stackmap in this function.
8790   FuncInfo.MF->getFrameInfo().setHasStackMap();
8791 }
8792 
8793 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8794 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
8795                                           const BasicBlock *EHPadBB) {
8796   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8797   //                                                 i32 <numBytes>,
8798   //                                                 i8* <target>,
8799   //                                                 i32 <numArgs>,
8800   //                                                 [Args...],
8801   //                                                 [live variables...])
8802 
8803   CallingConv::ID CC = CB.getCallingConv();
8804   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8805   bool HasDef = !CB.getType()->isVoidTy();
8806   SDLoc dl = getCurSDLoc();
8807   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
8808 
8809   // Handle immediate and symbolic callees.
8810   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8811     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8812                                    /*isTarget=*/true);
8813   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8814     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8815                                          SDLoc(SymbolicCallee),
8816                                          SymbolicCallee->getValueType(0));
8817 
8818   // Get the real number of arguments participating in the call <numArgs>
8819   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
8820   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8821 
8822   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8823   // Intrinsics include all meta-operands up to but not including CC.
8824   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8825   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
8826          "Not enough arguments provided to the patchpoint intrinsic");
8827 
8828   // For AnyRegCC the arguments are lowered later on manually.
8829   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8830   Type *ReturnTy =
8831       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
8832 
8833   TargetLowering::CallLoweringInfo CLI(DAG);
8834   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
8835                            ReturnTy, true);
8836   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8837 
8838   SDNode *CallEnd = Result.second.getNode();
8839   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8840     CallEnd = CallEnd->getOperand(0).getNode();
8841 
8842   /// Get a call instruction from the call sequence chain.
8843   /// Tail calls are not allowed.
8844   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8845          "Expected a callseq node.");
8846   SDNode *Call = CallEnd->getOperand(0).getNode();
8847   bool HasGlue = Call->getGluedNode();
8848 
8849   // Replace the target specific call node with the patchable intrinsic.
8850   SmallVector<SDValue, 8> Ops;
8851 
8852   // Add the <id> and <numBytes> constants.
8853   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
8854   Ops.push_back(DAG.getTargetConstant(
8855                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8856   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
8857   Ops.push_back(DAG.getTargetConstant(
8858                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8859                   MVT::i32));
8860 
8861   // Add the callee.
8862   Ops.push_back(Callee);
8863 
8864   // Adjust <numArgs> to account for any arguments that have been passed on the
8865   // stack instead.
8866   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8867   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8868   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8869   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8870 
8871   // Add the calling convention
8872   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8873 
8874   // Add the arguments we omitted previously. The register allocator should
8875   // place these in any free register.
8876   if (IsAnyRegCC)
8877     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8878       Ops.push_back(getValue(CB.getArgOperand(i)));
8879 
8880   // Push the arguments from the call instruction up to the register mask.
8881   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8882   Ops.append(Call->op_begin() + 2, e);
8883 
8884   // Push live variables for the stack map.
8885   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
8886 
8887   // Push the register mask info.
8888   if (HasGlue)
8889     Ops.push_back(*(Call->op_end()-2));
8890   else
8891     Ops.push_back(*(Call->op_end()-1));
8892 
8893   // Push the chain (this is originally the first operand of the call, but
8894   // becomes now the last or second to last operand).
8895   Ops.push_back(*(Call->op_begin()));
8896 
8897   // Push the glue flag (last operand).
8898   if (HasGlue)
8899     Ops.push_back(*(Call->op_end()-1));
8900 
8901   SDVTList NodeTys;
8902   if (IsAnyRegCC && HasDef) {
8903     // Create the return types based on the intrinsic definition
8904     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8905     SmallVector<EVT, 3> ValueVTs;
8906     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
8907     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8908 
8909     // There is always a chain and a glue type at the end
8910     ValueVTs.push_back(MVT::Other);
8911     ValueVTs.push_back(MVT::Glue);
8912     NodeTys = DAG.getVTList(ValueVTs);
8913   } else
8914     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8915 
8916   // Replace the target specific call node with a PATCHPOINT node.
8917   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8918                                          dl, NodeTys, Ops);
8919 
8920   // Update the NodeMap.
8921   if (HasDef) {
8922     if (IsAnyRegCC)
8923       setValue(&CB, SDValue(MN, 0));
8924     else
8925       setValue(&CB, Result.first);
8926   }
8927 
8928   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8929   // call sequence. Furthermore the location of the chain and glue can change
8930   // when the AnyReg calling convention is used and the intrinsic returns a
8931   // value.
8932   if (IsAnyRegCC && HasDef) {
8933     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8934     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8935     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8936   } else
8937     DAG.ReplaceAllUsesWith(Call, MN);
8938   DAG.DeleteNode(Call);
8939 
8940   // Inform the Frame Information that we have a patchpoint in this function.
8941   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8942 }
8943 
8944 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8945                                             unsigned Intrinsic) {
8946   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8947   SDValue Op1 = getValue(I.getArgOperand(0));
8948   SDValue Op2;
8949   if (I.getNumArgOperands() > 1)
8950     Op2 = getValue(I.getArgOperand(1));
8951   SDLoc dl = getCurSDLoc();
8952   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8953   SDValue Res;
8954   FastMathFlags FMF;
8955   if (isa<FPMathOperator>(I))
8956     FMF = I.getFastMathFlags();
8957 
8958   switch (Intrinsic) {
8959   case Intrinsic::experimental_vector_reduce_v2_fadd:
8960     if (FMF.allowReassoc())
8961       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8962                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8963     else
8964       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8965     break;
8966   case Intrinsic::experimental_vector_reduce_v2_fmul:
8967     if (FMF.allowReassoc())
8968       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8969                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8970     else
8971       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8972     break;
8973   case Intrinsic::experimental_vector_reduce_add:
8974     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8975     break;
8976   case Intrinsic::experimental_vector_reduce_mul:
8977     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8978     break;
8979   case Intrinsic::experimental_vector_reduce_and:
8980     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8981     break;
8982   case Intrinsic::experimental_vector_reduce_or:
8983     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8984     break;
8985   case Intrinsic::experimental_vector_reduce_xor:
8986     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8987     break;
8988   case Intrinsic::experimental_vector_reduce_smax:
8989     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8990     break;
8991   case Intrinsic::experimental_vector_reduce_smin:
8992     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8993     break;
8994   case Intrinsic::experimental_vector_reduce_umax:
8995     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8996     break;
8997   case Intrinsic::experimental_vector_reduce_umin:
8998     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8999     break;
9000   case Intrinsic::experimental_vector_reduce_fmax:
9001     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
9002     break;
9003   case Intrinsic::experimental_vector_reduce_fmin:
9004     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
9005     break;
9006   default:
9007     llvm_unreachable("Unhandled vector reduce intrinsic");
9008   }
9009   setValue(&I, Res);
9010 }
9011 
9012 /// Returns an AttributeList representing the attributes applied to the return
9013 /// value of the given call.
9014 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9015   SmallVector<Attribute::AttrKind, 2> Attrs;
9016   if (CLI.RetSExt)
9017     Attrs.push_back(Attribute::SExt);
9018   if (CLI.RetZExt)
9019     Attrs.push_back(Attribute::ZExt);
9020   if (CLI.IsInReg)
9021     Attrs.push_back(Attribute::InReg);
9022 
9023   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9024                             Attrs);
9025 }
9026 
9027 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9028 /// implementation, which just calls LowerCall.
9029 /// FIXME: When all targets are
9030 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9031 std::pair<SDValue, SDValue>
9032 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9033   // Handle the incoming return values from the call.
9034   CLI.Ins.clear();
9035   Type *OrigRetTy = CLI.RetTy;
9036   SmallVector<EVT, 4> RetTys;
9037   SmallVector<uint64_t, 4> Offsets;
9038   auto &DL = CLI.DAG.getDataLayout();
9039   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9040 
9041   if (CLI.IsPostTypeLegalization) {
9042     // If we are lowering a libcall after legalization, split the return type.
9043     SmallVector<EVT, 4> OldRetTys;
9044     SmallVector<uint64_t, 4> OldOffsets;
9045     RetTys.swap(OldRetTys);
9046     Offsets.swap(OldOffsets);
9047 
9048     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9049       EVT RetVT = OldRetTys[i];
9050       uint64_t Offset = OldOffsets[i];
9051       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9052       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9053       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9054       RetTys.append(NumRegs, RegisterVT);
9055       for (unsigned j = 0; j != NumRegs; ++j)
9056         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9057     }
9058   }
9059 
9060   SmallVector<ISD::OutputArg, 4> Outs;
9061   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9062 
9063   bool CanLowerReturn =
9064       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9065                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9066 
9067   SDValue DemoteStackSlot;
9068   int DemoteStackIdx = -100;
9069   if (!CanLowerReturn) {
9070     // FIXME: equivalent assert?
9071     // assert(!CS.hasInAllocaArgument() &&
9072     //        "sret demotion is incompatible with inalloca");
9073     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9074     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9075     MachineFunction &MF = CLI.DAG.getMachineFunction();
9076     DemoteStackIdx =
9077         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9078     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9079                                               DL.getAllocaAddrSpace());
9080 
9081     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9082     ArgListEntry Entry;
9083     Entry.Node = DemoteStackSlot;
9084     Entry.Ty = StackSlotPtrType;
9085     Entry.IsSExt = false;
9086     Entry.IsZExt = false;
9087     Entry.IsInReg = false;
9088     Entry.IsSRet = true;
9089     Entry.IsNest = false;
9090     Entry.IsByVal = false;
9091     Entry.IsByRef = false;
9092     Entry.IsReturned = false;
9093     Entry.IsSwiftSelf = false;
9094     Entry.IsSwiftError = false;
9095     Entry.IsCFGuardTarget = false;
9096     Entry.Alignment = Alignment;
9097     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9098     CLI.NumFixedArgs += 1;
9099     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9100 
9101     // sret demotion isn't compatible with tail-calls, since the sret argument
9102     // points into the callers stack frame.
9103     CLI.IsTailCall = false;
9104   } else {
9105     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9106         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9107     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9108       ISD::ArgFlagsTy Flags;
9109       if (NeedsRegBlock) {
9110         Flags.setInConsecutiveRegs();
9111         if (I == RetTys.size() - 1)
9112           Flags.setInConsecutiveRegsLast();
9113       }
9114       EVT VT = RetTys[I];
9115       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9116                                                      CLI.CallConv, VT);
9117       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9118                                                        CLI.CallConv, VT);
9119       for (unsigned i = 0; i != NumRegs; ++i) {
9120         ISD::InputArg MyFlags;
9121         MyFlags.Flags = Flags;
9122         MyFlags.VT = RegisterVT;
9123         MyFlags.ArgVT = VT;
9124         MyFlags.Used = CLI.IsReturnValueUsed;
9125         if (CLI.RetTy->isPointerTy()) {
9126           MyFlags.Flags.setPointer();
9127           MyFlags.Flags.setPointerAddrSpace(
9128               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9129         }
9130         if (CLI.RetSExt)
9131           MyFlags.Flags.setSExt();
9132         if (CLI.RetZExt)
9133           MyFlags.Flags.setZExt();
9134         if (CLI.IsInReg)
9135           MyFlags.Flags.setInReg();
9136         CLI.Ins.push_back(MyFlags);
9137       }
9138     }
9139   }
9140 
9141   // We push in swifterror return as the last element of CLI.Ins.
9142   ArgListTy &Args = CLI.getArgs();
9143   if (supportSwiftError()) {
9144     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9145       if (Args[i].IsSwiftError) {
9146         ISD::InputArg MyFlags;
9147         MyFlags.VT = getPointerTy(DL);
9148         MyFlags.ArgVT = EVT(getPointerTy(DL));
9149         MyFlags.Flags.setSwiftError();
9150         CLI.Ins.push_back(MyFlags);
9151       }
9152     }
9153   }
9154 
9155   // Handle all of the outgoing arguments.
9156   CLI.Outs.clear();
9157   CLI.OutVals.clear();
9158   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9159     SmallVector<EVT, 4> ValueVTs;
9160     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9161     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9162     Type *FinalType = Args[i].Ty;
9163     if (Args[i].IsByVal)
9164       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9165     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9166         FinalType, CLI.CallConv, CLI.IsVarArg);
9167     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9168          ++Value) {
9169       EVT VT = ValueVTs[Value];
9170       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9171       SDValue Op = SDValue(Args[i].Node.getNode(),
9172                            Args[i].Node.getResNo() + Value);
9173       ISD::ArgFlagsTy Flags;
9174 
9175       // Certain targets (such as MIPS), may have a different ABI alignment
9176       // for a type depending on the context. Give the target a chance to
9177       // specify the alignment it wants.
9178       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9179 
9180       if (Args[i].Ty->isPointerTy()) {
9181         Flags.setPointer();
9182         Flags.setPointerAddrSpace(
9183             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9184       }
9185       if (Args[i].IsZExt)
9186         Flags.setZExt();
9187       if (Args[i].IsSExt)
9188         Flags.setSExt();
9189       if (Args[i].IsInReg) {
9190         // If we are using vectorcall calling convention, a structure that is
9191         // passed InReg - is surely an HVA
9192         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9193             isa<StructType>(FinalType)) {
9194           // The first value of a structure is marked
9195           if (0 == Value)
9196             Flags.setHvaStart();
9197           Flags.setHva();
9198         }
9199         // Set InReg Flag
9200         Flags.setInReg();
9201       }
9202       if (Args[i].IsSRet)
9203         Flags.setSRet();
9204       if (Args[i].IsSwiftSelf)
9205         Flags.setSwiftSelf();
9206       if (Args[i].IsSwiftError)
9207         Flags.setSwiftError();
9208       if (Args[i].IsCFGuardTarget)
9209         Flags.setCFGuardTarget();
9210       if (Args[i].IsByVal)
9211         Flags.setByVal();
9212       if (Args[i].IsByRef)
9213         Flags.setByRef();
9214       if (Args[i].IsPreallocated) {
9215         Flags.setPreallocated();
9216         // Set the byval flag for CCAssignFn callbacks that don't know about
9217         // preallocated.  This way we can know how many bytes we should've
9218         // allocated and how many bytes a callee cleanup function will pop.  If
9219         // we port preallocated to more targets, we'll have to add custom
9220         // preallocated handling in the various CC lowering callbacks.
9221         Flags.setByVal();
9222       }
9223       if (Args[i].IsInAlloca) {
9224         Flags.setInAlloca();
9225         // Set the byval flag for CCAssignFn callbacks that don't know about
9226         // inalloca.  This way we can know how many bytes we should've allocated
9227         // and how many bytes a callee cleanup function will pop.  If we port
9228         // inalloca to more targets, we'll have to add custom inalloca handling
9229         // in the various CC lowering callbacks.
9230         Flags.setByVal();
9231       }
9232       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9233         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9234         Type *ElementTy = Ty->getElementType();
9235 
9236         unsigned FrameSize = DL.getTypeAllocSize(
9237             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9238         Flags.setByValSize(FrameSize);
9239 
9240         // info is not there but there are cases it cannot get right.
9241         Align FrameAlign;
9242         if (auto MA = Args[i].Alignment)
9243           FrameAlign = *MA;
9244         else
9245           FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
9246         Flags.setByValAlign(FrameAlign);
9247       }
9248       if (Args[i].IsNest)
9249         Flags.setNest();
9250       if (NeedsRegBlock)
9251         Flags.setInConsecutiveRegs();
9252       Flags.setOrigAlign(OriginalAlignment);
9253 
9254       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9255                                                  CLI.CallConv, VT);
9256       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9257                                                         CLI.CallConv, VT);
9258       SmallVector<SDValue, 4> Parts(NumParts);
9259       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9260 
9261       if (Args[i].IsSExt)
9262         ExtendKind = ISD::SIGN_EXTEND;
9263       else if (Args[i].IsZExt)
9264         ExtendKind = ISD::ZERO_EXTEND;
9265 
9266       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9267       // for now.
9268       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9269           CanLowerReturn) {
9270         assert((CLI.RetTy == Args[i].Ty ||
9271                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9272                  CLI.RetTy->getPointerAddressSpace() ==
9273                      Args[i].Ty->getPointerAddressSpace())) &&
9274                RetTys.size() == NumValues && "unexpected use of 'returned'");
9275         // Before passing 'returned' to the target lowering code, ensure that
9276         // either the register MVT and the actual EVT are the same size or that
9277         // the return value and argument are extended in the same way; in these
9278         // cases it's safe to pass the argument register value unchanged as the
9279         // return register value (although it's at the target's option whether
9280         // to do so)
9281         // TODO: allow code generation to take advantage of partially preserved
9282         // registers rather than clobbering the entire register when the
9283         // parameter extension method is not compatible with the return
9284         // extension method
9285         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9286             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9287              CLI.RetZExt == Args[i].IsZExt))
9288           Flags.setReturned();
9289       }
9290 
9291       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9292                      CLI.CallConv, ExtendKind);
9293 
9294       for (unsigned j = 0; j != NumParts; ++j) {
9295         // if it isn't first piece, alignment must be 1
9296         // For scalable vectors the scalable part is currently handled
9297         // by individual targets, so we just use the known minimum size here.
9298         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9299                     i < CLI.NumFixedArgs, i,
9300                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9301         if (NumParts > 1 && j == 0)
9302           MyFlags.Flags.setSplit();
9303         else if (j != 0) {
9304           MyFlags.Flags.setOrigAlign(Align(1));
9305           if (j == NumParts - 1)
9306             MyFlags.Flags.setSplitEnd();
9307         }
9308 
9309         CLI.Outs.push_back(MyFlags);
9310         CLI.OutVals.push_back(Parts[j]);
9311       }
9312 
9313       if (NeedsRegBlock && Value == NumValues - 1)
9314         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9315     }
9316   }
9317 
9318   SmallVector<SDValue, 4> InVals;
9319   CLI.Chain = LowerCall(CLI, InVals);
9320 
9321   // Update CLI.InVals to use outside of this function.
9322   CLI.InVals = InVals;
9323 
9324   // Verify that the target's LowerCall behaved as expected.
9325   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9326          "LowerCall didn't return a valid chain!");
9327   assert((!CLI.IsTailCall || InVals.empty()) &&
9328          "LowerCall emitted a return value for a tail call!");
9329   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9330          "LowerCall didn't emit the correct number of values!");
9331 
9332   // For a tail call, the return value is merely live-out and there aren't
9333   // any nodes in the DAG representing it. Return a special value to
9334   // indicate that a tail call has been emitted and no more Instructions
9335   // should be processed in the current block.
9336   if (CLI.IsTailCall) {
9337     CLI.DAG.setRoot(CLI.Chain);
9338     return std::make_pair(SDValue(), SDValue());
9339   }
9340 
9341 #ifndef NDEBUG
9342   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9343     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9344     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9345            "LowerCall emitted a value with the wrong type!");
9346   }
9347 #endif
9348 
9349   SmallVector<SDValue, 4> ReturnValues;
9350   if (!CanLowerReturn) {
9351     // The instruction result is the result of loading from the
9352     // hidden sret parameter.
9353     SmallVector<EVT, 1> PVTs;
9354     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9355 
9356     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9357     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9358     EVT PtrVT = PVTs[0];
9359 
9360     unsigned NumValues = RetTys.size();
9361     ReturnValues.resize(NumValues);
9362     SmallVector<SDValue, 4> Chains(NumValues);
9363 
9364     // An aggregate return value cannot wrap around the address space, so
9365     // offsets to its parts don't wrap either.
9366     SDNodeFlags Flags;
9367     Flags.setNoUnsignedWrap(true);
9368 
9369     MachineFunction &MF = CLI.DAG.getMachineFunction();
9370     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9371     for (unsigned i = 0; i < NumValues; ++i) {
9372       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9373                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9374                                                         PtrVT), Flags);
9375       SDValue L = CLI.DAG.getLoad(
9376           RetTys[i], CLI.DL, CLI.Chain, Add,
9377           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9378                                             DemoteStackIdx, Offsets[i]),
9379           HiddenSRetAlign);
9380       ReturnValues[i] = L;
9381       Chains[i] = L.getValue(1);
9382     }
9383 
9384     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9385   } else {
9386     // Collect the legal value parts into potentially illegal values
9387     // that correspond to the original function's return values.
9388     Optional<ISD::NodeType> AssertOp;
9389     if (CLI.RetSExt)
9390       AssertOp = ISD::AssertSext;
9391     else if (CLI.RetZExt)
9392       AssertOp = ISD::AssertZext;
9393     unsigned CurReg = 0;
9394     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9395       EVT VT = RetTys[I];
9396       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9397                                                      CLI.CallConv, VT);
9398       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9399                                                        CLI.CallConv, VT);
9400 
9401       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9402                                               NumRegs, RegisterVT, VT, nullptr,
9403                                               CLI.CallConv, AssertOp));
9404       CurReg += NumRegs;
9405     }
9406 
9407     // For a function returning void, there is no return value. We can't create
9408     // such a node, so we just return a null return value in that case. In
9409     // that case, nothing will actually look at the value.
9410     if (ReturnValues.empty())
9411       return std::make_pair(SDValue(), CLI.Chain);
9412   }
9413 
9414   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9415                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9416   return std::make_pair(Res, CLI.Chain);
9417 }
9418 
9419 void TargetLowering::LowerOperationWrapper(SDNode *N,
9420                                            SmallVectorImpl<SDValue> &Results,
9421                                            SelectionDAG &DAG) const {
9422   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9423     Results.push_back(Res);
9424 }
9425 
9426 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9427   llvm_unreachable("LowerOperation not implemented for this target!");
9428 }
9429 
9430 void
9431 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9432   SDValue Op = getNonRegisterValue(V);
9433   assert((Op.getOpcode() != ISD::CopyFromReg ||
9434           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9435          "Copy from a reg to the same reg!");
9436   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9437 
9438   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9439   // If this is an InlineAsm we have to match the registers required, not the
9440   // notional registers required by the type.
9441 
9442   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9443                    None); // This is not an ABI copy.
9444   SDValue Chain = DAG.getEntryNode();
9445 
9446   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9447                               FuncInfo.PreferredExtendType.end())
9448                                  ? ISD::ANY_EXTEND
9449                                  : FuncInfo.PreferredExtendType[V];
9450   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9451   PendingExports.push_back(Chain);
9452 }
9453 
9454 #include "llvm/CodeGen/SelectionDAGISel.h"
9455 
9456 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9457 /// entry block, return true.  This includes arguments used by switches, since
9458 /// the switch may expand into multiple basic blocks.
9459 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9460   // With FastISel active, we may be splitting blocks, so force creation
9461   // of virtual registers for all non-dead arguments.
9462   if (FastISel)
9463     return A->use_empty();
9464 
9465   const BasicBlock &Entry = A->getParent()->front();
9466   for (const User *U : A->users())
9467     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9468       return false;  // Use not in entry block.
9469 
9470   return true;
9471 }
9472 
9473 using ArgCopyElisionMapTy =
9474     DenseMap<const Argument *,
9475              std::pair<const AllocaInst *, const StoreInst *>>;
9476 
9477 /// Scan the entry block of the function in FuncInfo for arguments that look
9478 /// like copies into a local alloca. Record any copied arguments in
9479 /// ArgCopyElisionCandidates.
9480 static void
9481 findArgumentCopyElisionCandidates(const DataLayout &DL,
9482                                   FunctionLoweringInfo *FuncInfo,
9483                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9484   // Record the state of every static alloca used in the entry block. Argument
9485   // allocas are all used in the entry block, so we need approximately as many
9486   // entries as we have arguments.
9487   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9488   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9489   unsigned NumArgs = FuncInfo->Fn->arg_size();
9490   StaticAllocas.reserve(NumArgs * 2);
9491 
9492   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9493     if (!V)
9494       return nullptr;
9495     V = V->stripPointerCasts();
9496     const auto *AI = dyn_cast<AllocaInst>(V);
9497     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9498       return nullptr;
9499     auto Iter = StaticAllocas.insert({AI, Unknown});
9500     return &Iter.first->second;
9501   };
9502 
9503   // Look for stores of arguments to static allocas. Look through bitcasts and
9504   // GEPs to handle type coercions, as long as the alloca is fully initialized
9505   // by the store. Any non-store use of an alloca escapes it and any subsequent
9506   // unanalyzed store might write it.
9507   // FIXME: Handle structs initialized with multiple stores.
9508   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9509     // Look for stores, and handle non-store uses conservatively.
9510     const auto *SI = dyn_cast<StoreInst>(&I);
9511     if (!SI) {
9512       // We will look through cast uses, so ignore them completely.
9513       if (I.isCast())
9514         continue;
9515       // Ignore debug info intrinsics, they don't escape or store to allocas.
9516       if (isa<DbgInfoIntrinsic>(I))
9517         continue;
9518       // This is an unknown instruction. Assume it escapes or writes to all
9519       // static alloca operands.
9520       for (const Use &U : I.operands()) {
9521         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9522           *Info = StaticAllocaInfo::Clobbered;
9523       }
9524       continue;
9525     }
9526 
9527     // If the stored value is a static alloca, mark it as escaped.
9528     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9529       *Info = StaticAllocaInfo::Clobbered;
9530 
9531     // Check if the destination is a static alloca.
9532     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9533     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9534     if (!Info)
9535       continue;
9536     const AllocaInst *AI = cast<AllocaInst>(Dst);
9537 
9538     // Skip allocas that have been initialized or clobbered.
9539     if (*Info != StaticAllocaInfo::Unknown)
9540       continue;
9541 
9542     // Check if the stored value is an argument, and that this store fully
9543     // initializes the alloca. Don't elide copies from the same argument twice.
9544     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9545     const auto *Arg = dyn_cast<Argument>(Val);
9546     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
9547         Arg->getType()->isEmptyTy() ||
9548         DL.getTypeStoreSize(Arg->getType()) !=
9549             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9550         ArgCopyElisionCandidates.count(Arg)) {
9551       *Info = StaticAllocaInfo::Clobbered;
9552       continue;
9553     }
9554 
9555     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9556                       << '\n');
9557 
9558     // Mark this alloca and store for argument copy elision.
9559     *Info = StaticAllocaInfo::Elidable;
9560     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9561 
9562     // Stop scanning if we've seen all arguments. This will happen early in -O0
9563     // builds, which is useful, because -O0 builds have large entry blocks and
9564     // many allocas.
9565     if (ArgCopyElisionCandidates.size() == NumArgs)
9566       break;
9567   }
9568 }
9569 
9570 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9571 /// ArgVal is a load from a suitable fixed stack object.
9572 static void tryToElideArgumentCopy(
9573     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9574     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9575     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9576     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9577     SDValue ArgVal, bool &ArgHasUses) {
9578   // Check if this is a load from a fixed stack object.
9579   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9580   if (!LNode)
9581     return;
9582   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9583   if (!FINode)
9584     return;
9585 
9586   // Check that the fixed stack object is the right size and alignment.
9587   // Look at the alignment that the user wrote on the alloca instead of looking
9588   // at the stack object.
9589   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9590   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9591   const AllocaInst *AI = ArgCopyIter->second.first;
9592   int FixedIndex = FINode->getIndex();
9593   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9594   int OldIndex = AllocaIndex;
9595   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9596   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9597     LLVM_DEBUG(
9598         dbgs() << "  argument copy elision failed due to bad fixed stack "
9599                   "object size\n");
9600     return;
9601   }
9602   Align RequiredAlignment = AI->getAlign();
9603   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9604     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9605                          "greater than stack argument alignment ("
9606                       << DebugStr(RequiredAlignment) << " vs "
9607                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9608     return;
9609   }
9610 
9611   // Perform the elision. Delete the old stack object and replace its only use
9612   // in the variable info map. Mark the stack object as mutable.
9613   LLVM_DEBUG({
9614     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9615            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9616            << '\n';
9617   });
9618   MFI.RemoveStackObject(OldIndex);
9619   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9620   AllocaIndex = FixedIndex;
9621   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9622   Chains.push_back(ArgVal.getValue(1));
9623 
9624   // Avoid emitting code for the store implementing the copy.
9625   const StoreInst *SI = ArgCopyIter->second.second;
9626   ElidedArgCopyInstrs.insert(SI);
9627 
9628   // Check for uses of the argument again so that we can avoid exporting ArgVal
9629   // if it is't used by anything other than the store.
9630   for (const Value *U : Arg.users()) {
9631     if (U != SI) {
9632       ArgHasUses = true;
9633       break;
9634     }
9635   }
9636 }
9637 
9638 void SelectionDAGISel::LowerArguments(const Function &F) {
9639   SelectionDAG &DAG = SDB->DAG;
9640   SDLoc dl = SDB->getCurSDLoc();
9641   const DataLayout &DL = DAG.getDataLayout();
9642   SmallVector<ISD::InputArg, 16> Ins;
9643 
9644   // In Naked functions we aren't going to save any registers.
9645   if (F.hasFnAttribute(Attribute::Naked))
9646     return;
9647 
9648   if (!FuncInfo->CanLowerReturn) {
9649     // Put in an sret pointer parameter before all the other parameters.
9650     SmallVector<EVT, 1> ValueVTs;
9651     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9652                     F.getReturnType()->getPointerTo(
9653                         DAG.getDataLayout().getAllocaAddrSpace()),
9654                     ValueVTs);
9655 
9656     // NOTE: Assuming that a pointer will never break down to more than one VT
9657     // or one register.
9658     ISD::ArgFlagsTy Flags;
9659     Flags.setSRet();
9660     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9661     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9662                          ISD::InputArg::NoArgIndex, 0);
9663     Ins.push_back(RetArg);
9664   }
9665 
9666   // Look for stores of arguments to static allocas. Mark such arguments with a
9667   // flag to ask the target to give us the memory location of that argument if
9668   // available.
9669   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9670   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9671                                     ArgCopyElisionCandidates);
9672 
9673   // Set up the incoming argument description vector.
9674   for (const Argument &Arg : F.args()) {
9675     unsigned ArgNo = Arg.getArgNo();
9676     SmallVector<EVT, 4> ValueVTs;
9677     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9678     bool isArgValueUsed = !Arg.use_empty();
9679     unsigned PartBase = 0;
9680     Type *FinalType = Arg.getType();
9681     if (Arg.hasAttribute(Attribute::ByVal))
9682       FinalType = Arg.getParamByValType();
9683     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9684         FinalType, F.getCallingConv(), F.isVarArg());
9685     for (unsigned Value = 0, NumValues = ValueVTs.size();
9686          Value != NumValues; ++Value) {
9687       EVT VT = ValueVTs[Value];
9688       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9689       ISD::ArgFlagsTy Flags;
9690 
9691       // Certain targets (such as MIPS), may have a different ABI alignment
9692       // for a type depending on the context. Give the target a chance to
9693       // specify the alignment it wants.
9694       const Align OriginalAlignment(
9695           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9696 
9697       if (Arg.getType()->isPointerTy()) {
9698         Flags.setPointer();
9699         Flags.setPointerAddrSpace(
9700             cast<PointerType>(Arg.getType())->getAddressSpace());
9701       }
9702       if (Arg.hasAttribute(Attribute::ZExt))
9703         Flags.setZExt();
9704       if (Arg.hasAttribute(Attribute::SExt))
9705         Flags.setSExt();
9706       if (Arg.hasAttribute(Attribute::InReg)) {
9707         // If we are using vectorcall calling convention, a structure that is
9708         // passed InReg - is surely an HVA
9709         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9710             isa<StructType>(Arg.getType())) {
9711           // The first value of a structure is marked
9712           if (0 == Value)
9713             Flags.setHvaStart();
9714           Flags.setHva();
9715         }
9716         // Set InReg Flag
9717         Flags.setInReg();
9718       }
9719       if (Arg.hasAttribute(Attribute::StructRet))
9720         Flags.setSRet();
9721       if (Arg.hasAttribute(Attribute::SwiftSelf))
9722         Flags.setSwiftSelf();
9723       if (Arg.hasAttribute(Attribute::SwiftError))
9724         Flags.setSwiftError();
9725       if (Arg.hasAttribute(Attribute::ByVal))
9726         Flags.setByVal();
9727       if (Arg.hasAttribute(Attribute::ByRef))
9728         Flags.setByRef();
9729       if (Arg.hasAttribute(Attribute::InAlloca)) {
9730         Flags.setInAlloca();
9731         // Set the byval flag for CCAssignFn callbacks that don't know about
9732         // inalloca.  This way we can know how many bytes we should've allocated
9733         // and how many bytes a callee cleanup function will pop.  If we port
9734         // inalloca to more targets, we'll have to add custom inalloca handling
9735         // in the various CC lowering callbacks.
9736         Flags.setByVal();
9737       }
9738       if (Arg.hasAttribute(Attribute::Preallocated)) {
9739         Flags.setPreallocated();
9740         // Set the byval flag for CCAssignFn callbacks that don't know about
9741         // preallocated.  This way we can know how many bytes we should've
9742         // allocated and how many bytes a callee cleanup function will pop.  If
9743         // we port preallocated to more targets, we'll have to add custom
9744         // preallocated handling in the various CC lowering callbacks.
9745         Flags.setByVal();
9746       }
9747 
9748       Type *ArgMemTy = nullptr;
9749       if (F.getCallingConv() == CallingConv::X86_INTR) {
9750         // IA Interrupt passes frame (1st parameter) by value in the stack.
9751         if (ArgNo == 0) {
9752           Flags.setByVal();
9753           // FIXME: Dependence on pointee element type. See bug 46672.
9754           ArgMemTy = Arg.getType()->getPointerElementType();
9755         }
9756       }
9757       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
9758           Flags.isByRef()) {
9759         if (!ArgMemTy)
9760           ArgMemTy = Arg.getPointeeInMemoryValueType();
9761 
9762         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
9763 
9764         // For in-memory arguments, size and alignment should be passed from FE.
9765         // BE will guess if this info is not there but there are cases it cannot
9766         // get right.
9767         MaybeAlign MemAlign = Arg.getParamAlign();
9768         if (!MemAlign)
9769           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
9770 
9771         if (Flags.isByRef()) {
9772           Flags.setByRefSize(MemSize);
9773           Flags.setByRefAlign(*MemAlign);
9774         } else {
9775           Flags.setByValSize(MemSize);
9776           Flags.setByValAlign(*MemAlign);
9777         }
9778       }
9779 
9780       if (Arg.hasAttribute(Attribute::Nest))
9781         Flags.setNest();
9782       if (NeedsRegBlock)
9783         Flags.setInConsecutiveRegs();
9784       Flags.setOrigAlign(OriginalAlignment);
9785       if (ArgCopyElisionCandidates.count(&Arg))
9786         Flags.setCopyElisionCandidate();
9787       if (Arg.hasAttribute(Attribute::Returned))
9788         Flags.setReturned();
9789 
9790       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9791           *CurDAG->getContext(), F.getCallingConv(), VT);
9792       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9793           *CurDAG->getContext(), F.getCallingConv(), VT);
9794       for (unsigned i = 0; i != NumRegs; ++i) {
9795         // For scalable vectors, use the minimum size; individual targets
9796         // are responsible for handling scalable vector arguments and
9797         // return values.
9798         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9799                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9800         if (NumRegs > 1 && i == 0)
9801           MyFlags.Flags.setSplit();
9802         // if it isn't first piece, alignment must be 1
9803         else if (i > 0) {
9804           MyFlags.Flags.setOrigAlign(Align(1));
9805           if (i == NumRegs - 1)
9806             MyFlags.Flags.setSplitEnd();
9807         }
9808         Ins.push_back(MyFlags);
9809       }
9810       if (NeedsRegBlock && Value == NumValues - 1)
9811         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9812       PartBase += VT.getStoreSize().getKnownMinSize();
9813     }
9814   }
9815 
9816   // Call the target to set up the argument values.
9817   SmallVector<SDValue, 8> InVals;
9818   SDValue NewRoot = TLI->LowerFormalArguments(
9819       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9820 
9821   // Verify that the target's LowerFormalArguments behaved as expected.
9822   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9823          "LowerFormalArguments didn't return a valid chain!");
9824   assert(InVals.size() == Ins.size() &&
9825          "LowerFormalArguments didn't emit the correct number of values!");
9826   LLVM_DEBUG({
9827     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9828       assert(InVals[i].getNode() &&
9829              "LowerFormalArguments emitted a null value!");
9830       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9831              "LowerFormalArguments emitted a value with the wrong type!");
9832     }
9833   });
9834 
9835   // Update the DAG with the new chain value resulting from argument lowering.
9836   DAG.setRoot(NewRoot);
9837 
9838   // Set up the argument values.
9839   unsigned i = 0;
9840   if (!FuncInfo->CanLowerReturn) {
9841     // Create a virtual register for the sret pointer, and put in a copy
9842     // from the sret argument into it.
9843     SmallVector<EVT, 1> ValueVTs;
9844     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9845                     F.getReturnType()->getPointerTo(
9846                         DAG.getDataLayout().getAllocaAddrSpace()),
9847                     ValueVTs);
9848     MVT VT = ValueVTs[0].getSimpleVT();
9849     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9850     Optional<ISD::NodeType> AssertOp = None;
9851     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9852                                         nullptr, F.getCallingConv(), AssertOp);
9853 
9854     MachineFunction& MF = SDB->DAG.getMachineFunction();
9855     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9856     Register SRetReg =
9857         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9858     FuncInfo->DemoteRegister = SRetReg;
9859     NewRoot =
9860         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9861     DAG.setRoot(NewRoot);
9862 
9863     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9864     ++i;
9865   }
9866 
9867   SmallVector<SDValue, 4> Chains;
9868   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9869   for (const Argument &Arg : F.args()) {
9870     SmallVector<SDValue, 4> ArgValues;
9871     SmallVector<EVT, 4> ValueVTs;
9872     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9873     unsigned NumValues = ValueVTs.size();
9874     if (NumValues == 0)
9875       continue;
9876 
9877     bool ArgHasUses = !Arg.use_empty();
9878 
9879     // Elide the copying store if the target loaded this argument from a
9880     // suitable fixed stack object.
9881     if (Ins[i].Flags.isCopyElisionCandidate()) {
9882       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9883                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9884                              InVals[i], ArgHasUses);
9885     }
9886 
9887     // If this argument is unused then remember its value. It is used to generate
9888     // debugging information.
9889     bool isSwiftErrorArg =
9890         TLI->supportSwiftError() &&
9891         Arg.hasAttribute(Attribute::SwiftError);
9892     if (!ArgHasUses && !isSwiftErrorArg) {
9893       SDB->setUnusedArgValue(&Arg, InVals[i]);
9894 
9895       // Also remember any frame index for use in FastISel.
9896       if (FrameIndexSDNode *FI =
9897           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9898         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9899     }
9900 
9901     for (unsigned Val = 0; Val != NumValues; ++Val) {
9902       EVT VT = ValueVTs[Val];
9903       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9904                                                       F.getCallingConv(), VT);
9905       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9906           *CurDAG->getContext(), F.getCallingConv(), VT);
9907 
9908       // Even an apparent 'unused' swifterror argument needs to be returned. So
9909       // we do generate a copy for it that can be used on return from the
9910       // function.
9911       if (ArgHasUses || isSwiftErrorArg) {
9912         Optional<ISD::NodeType> AssertOp;
9913         if (Arg.hasAttribute(Attribute::SExt))
9914           AssertOp = ISD::AssertSext;
9915         else if (Arg.hasAttribute(Attribute::ZExt))
9916           AssertOp = ISD::AssertZext;
9917 
9918         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9919                                              PartVT, VT, nullptr,
9920                                              F.getCallingConv(), AssertOp));
9921       }
9922 
9923       i += NumParts;
9924     }
9925 
9926     // We don't need to do anything else for unused arguments.
9927     if (ArgValues.empty())
9928       continue;
9929 
9930     // Note down frame index.
9931     if (FrameIndexSDNode *FI =
9932         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9933       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9934 
9935     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9936                                      SDB->getCurSDLoc());
9937 
9938     SDB->setValue(&Arg, Res);
9939     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9940       // We want to associate the argument with the frame index, among
9941       // involved operands, that correspond to the lowest address. The
9942       // getCopyFromParts function, called earlier, is swapping the order of
9943       // the operands to BUILD_PAIR depending on endianness. The result of
9944       // that swapping is that the least significant bits of the argument will
9945       // be in the first operand of the BUILD_PAIR node, and the most
9946       // significant bits will be in the second operand.
9947       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9948       if (LoadSDNode *LNode =
9949           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9950         if (FrameIndexSDNode *FI =
9951             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9952           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9953     }
9954 
9955     // Analyses past this point are naive and don't expect an assertion.
9956     if (Res.getOpcode() == ISD::AssertZext)
9957       Res = Res.getOperand(0);
9958 
9959     // Update the SwiftErrorVRegDefMap.
9960     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9961       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9962       if (Register::isVirtualRegister(Reg))
9963         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9964                                    Reg);
9965     }
9966 
9967     // If this argument is live outside of the entry block, insert a copy from
9968     // wherever we got it to the vreg that other BB's will reference it as.
9969     if (Res.getOpcode() == ISD::CopyFromReg) {
9970       // If we can, though, try to skip creating an unnecessary vreg.
9971       // FIXME: This isn't very clean... it would be nice to make this more
9972       // general.
9973       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9974       if (Register::isVirtualRegister(Reg)) {
9975         FuncInfo->ValueMap[&Arg] = Reg;
9976         continue;
9977       }
9978     }
9979     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9980       FuncInfo->InitializeRegForValue(&Arg);
9981       SDB->CopyToExportRegsIfNeeded(&Arg);
9982     }
9983   }
9984 
9985   if (!Chains.empty()) {
9986     Chains.push_back(NewRoot);
9987     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9988   }
9989 
9990   DAG.setRoot(NewRoot);
9991 
9992   assert(i == InVals.size() && "Argument register count mismatch!");
9993 
9994   // If any argument copy elisions occurred and we have debug info, update the
9995   // stale frame indices used in the dbg.declare variable info table.
9996   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9997   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9998     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9999       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10000       if (I != ArgCopyElisionFrameIndexMap.end())
10001         VI.Slot = I->second;
10002     }
10003   }
10004 
10005   // Finally, if the target has anything special to do, allow it to do so.
10006   emitFunctionEntryCode();
10007 }
10008 
10009 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10010 /// ensure constants are generated when needed.  Remember the virtual registers
10011 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10012 /// directly add them, because expansion might result in multiple MBB's for one
10013 /// BB.  As such, the start of the BB might correspond to a different MBB than
10014 /// the end.
10015 void
10016 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10017   const Instruction *TI = LLVMBB->getTerminator();
10018 
10019   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10020 
10021   // Check PHI nodes in successors that expect a value to be available from this
10022   // block.
10023   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10024     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10025     if (!isa<PHINode>(SuccBB->begin())) continue;
10026     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10027 
10028     // If this terminator has multiple identical successors (common for
10029     // switches), only handle each succ once.
10030     if (!SuccsHandled.insert(SuccMBB).second)
10031       continue;
10032 
10033     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10034 
10035     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10036     // nodes and Machine PHI nodes, but the incoming operands have not been
10037     // emitted yet.
10038     for (const PHINode &PN : SuccBB->phis()) {
10039       // Ignore dead phi's.
10040       if (PN.use_empty())
10041         continue;
10042 
10043       // Skip empty types
10044       if (PN.getType()->isEmptyTy())
10045         continue;
10046 
10047       unsigned Reg;
10048       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10049 
10050       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10051         unsigned &RegOut = ConstantsOut[C];
10052         if (RegOut == 0) {
10053           RegOut = FuncInfo.CreateRegs(C);
10054           CopyValueToVirtualRegister(C, RegOut);
10055         }
10056         Reg = RegOut;
10057       } else {
10058         DenseMap<const Value *, Register>::iterator I =
10059           FuncInfo.ValueMap.find(PHIOp);
10060         if (I != FuncInfo.ValueMap.end())
10061           Reg = I->second;
10062         else {
10063           assert(isa<AllocaInst>(PHIOp) &&
10064                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10065                  "Didn't codegen value into a register!??");
10066           Reg = FuncInfo.CreateRegs(PHIOp);
10067           CopyValueToVirtualRegister(PHIOp, Reg);
10068         }
10069       }
10070 
10071       // Remember that this register needs to added to the machine PHI node as
10072       // the input for this MBB.
10073       SmallVector<EVT, 4> ValueVTs;
10074       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10075       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10076       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10077         EVT VT = ValueVTs[vti];
10078         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10079         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10080           FuncInfo.PHINodesToUpdate.push_back(
10081               std::make_pair(&*MBBI++, Reg + i));
10082         Reg += NumRegisters;
10083       }
10084     }
10085   }
10086 
10087   ConstantsOut.clear();
10088 }
10089 
10090 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10091 /// is 0.
10092 MachineBasicBlock *
10093 SelectionDAGBuilder::StackProtectorDescriptor::
10094 AddSuccessorMBB(const BasicBlock *BB,
10095                 MachineBasicBlock *ParentMBB,
10096                 bool IsLikely,
10097                 MachineBasicBlock *SuccMBB) {
10098   // If SuccBB has not been created yet, create it.
10099   if (!SuccMBB) {
10100     MachineFunction *MF = ParentMBB->getParent();
10101     MachineFunction::iterator BBI(ParentMBB);
10102     SuccMBB = MF->CreateMachineBasicBlock(BB);
10103     MF->insert(++BBI, SuccMBB);
10104   }
10105   // Add it as a successor of ParentMBB.
10106   ParentMBB->addSuccessor(
10107       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10108   return SuccMBB;
10109 }
10110 
10111 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10112   MachineFunction::iterator I(MBB);
10113   if (++I == FuncInfo.MF->end())
10114     return nullptr;
10115   return &*I;
10116 }
10117 
10118 /// During lowering new call nodes can be created (such as memset, etc.).
10119 /// Those will become new roots of the current DAG, but complications arise
10120 /// when they are tail calls. In such cases, the call lowering will update
10121 /// the root, but the builder still needs to know that a tail call has been
10122 /// lowered in order to avoid generating an additional return.
10123 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10124   // If the node is null, we do have a tail call.
10125   if (MaybeTC.getNode() != nullptr)
10126     DAG.setRoot(MaybeTC);
10127   else
10128     HasTailCall = true;
10129 }
10130 
10131 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10132                                         MachineBasicBlock *SwitchMBB,
10133                                         MachineBasicBlock *DefaultMBB) {
10134   MachineFunction *CurMF = FuncInfo.MF;
10135   MachineBasicBlock *NextMBB = nullptr;
10136   MachineFunction::iterator BBI(W.MBB);
10137   if (++BBI != FuncInfo.MF->end())
10138     NextMBB = &*BBI;
10139 
10140   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10141 
10142   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10143 
10144   if (Size == 2 && W.MBB == SwitchMBB) {
10145     // If any two of the cases has the same destination, and if one value
10146     // is the same as the other, but has one bit unset that the other has set,
10147     // use bit manipulation to do two compares at once.  For example:
10148     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10149     // TODO: This could be extended to merge any 2 cases in switches with 3
10150     // cases.
10151     // TODO: Handle cases where W.CaseBB != SwitchBB.
10152     CaseCluster &Small = *W.FirstCluster;
10153     CaseCluster &Big = *W.LastCluster;
10154 
10155     if (Small.Low == Small.High && Big.Low == Big.High &&
10156         Small.MBB == Big.MBB) {
10157       const APInt &SmallValue = Small.Low->getValue();
10158       const APInt &BigValue = Big.Low->getValue();
10159 
10160       // Check that there is only one bit different.
10161       APInt CommonBit = BigValue ^ SmallValue;
10162       if (CommonBit.isPowerOf2()) {
10163         SDValue CondLHS = getValue(Cond);
10164         EVT VT = CondLHS.getValueType();
10165         SDLoc DL = getCurSDLoc();
10166 
10167         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10168                                  DAG.getConstant(CommonBit, DL, VT));
10169         SDValue Cond = DAG.getSetCC(
10170             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10171             ISD::SETEQ);
10172 
10173         // Update successor info.
10174         // Both Small and Big will jump to Small.BB, so we sum up the
10175         // probabilities.
10176         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10177         if (BPI)
10178           addSuccessorWithProb(
10179               SwitchMBB, DefaultMBB,
10180               // The default destination is the first successor in IR.
10181               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10182         else
10183           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10184 
10185         // Insert the true branch.
10186         SDValue BrCond =
10187             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10188                         DAG.getBasicBlock(Small.MBB));
10189         // Insert the false branch.
10190         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10191                              DAG.getBasicBlock(DefaultMBB));
10192 
10193         DAG.setRoot(BrCond);
10194         return;
10195       }
10196     }
10197   }
10198 
10199   if (TM.getOptLevel() != CodeGenOpt::None) {
10200     // Here, we order cases by probability so the most likely case will be
10201     // checked first. However, two clusters can have the same probability in
10202     // which case their relative ordering is non-deterministic. So we use Low
10203     // as a tie-breaker as clusters are guaranteed to never overlap.
10204     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10205                [](const CaseCluster &a, const CaseCluster &b) {
10206       return a.Prob != b.Prob ?
10207              a.Prob > b.Prob :
10208              a.Low->getValue().slt(b.Low->getValue());
10209     });
10210 
10211     // Rearrange the case blocks so that the last one falls through if possible
10212     // without changing the order of probabilities.
10213     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10214       --I;
10215       if (I->Prob > W.LastCluster->Prob)
10216         break;
10217       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10218         std::swap(*I, *W.LastCluster);
10219         break;
10220       }
10221     }
10222   }
10223 
10224   // Compute total probability.
10225   BranchProbability DefaultProb = W.DefaultProb;
10226   BranchProbability UnhandledProbs = DefaultProb;
10227   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10228     UnhandledProbs += I->Prob;
10229 
10230   MachineBasicBlock *CurMBB = W.MBB;
10231   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10232     bool FallthroughUnreachable = false;
10233     MachineBasicBlock *Fallthrough;
10234     if (I == W.LastCluster) {
10235       // For the last cluster, fall through to the default destination.
10236       Fallthrough = DefaultMBB;
10237       FallthroughUnreachable = isa<UnreachableInst>(
10238           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10239     } else {
10240       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10241       CurMF->insert(BBI, Fallthrough);
10242       // Put Cond in a virtual register to make it available from the new blocks.
10243       ExportFromCurrentBlock(Cond);
10244     }
10245     UnhandledProbs -= I->Prob;
10246 
10247     switch (I->Kind) {
10248       case CC_JumpTable: {
10249         // FIXME: Optimize away range check based on pivot comparisons.
10250         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10251         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10252 
10253         // The jump block hasn't been inserted yet; insert it here.
10254         MachineBasicBlock *JumpMBB = JT->MBB;
10255         CurMF->insert(BBI, JumpMBB);
10256 
10257         auto JumpProb = I->Prob;
10258         auto FallthroughProb = UnhandledProbs;
10259 
10260         // If the default statement is a target of the jump table, we evenly
10261         // distribute the default probability to successors of CurMBB. Also
10262         // update the probability on the edge from JumpMBB to Fallthrough.
10263         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10264                                               SE = JumpMBB->succ_end();
10265              SI != SE; ++SI) {
10266           if (*SI == DefaultMBB) {
10267             JumpProb += DefaultProb / 2;
10268             FallthroughProb -= DefaultProb / 2;
10269             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10270             JumpMBB->normalizeSuccProbs();
10271             break;
10272           }
10273         }
10274 
10275         if (FallthroughUnreachable) {
10276           // Skip the range check if the fallthrough block is unreachable.
10277           JTH->OmitRangeCheck = true;
10278         }
10279 
10280         if (!JTH->OmitRangeCheck)
10281           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10282         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10283         CurMBB->normalizeSuccProbs();
10284 
10285         // The jump table header will be inserted in our current block, do the
10286         // range check, and fall through to our fallthrough block.
10287         JTH->HeaderBB = CurMBB;
10288         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10289 
10290         // If we're in the right place, emit the jump table header right now.
10291         if (CurMBB == SwitchMBB) {
10292           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10293           JTH->Emitted = true;
10294         }
10295         break;
10296       }
10297       case CC_BitTests: {
10298         // FIXME: Optimize away range check based on pivot comparisons.
10299         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10300 
10301         // The bit test blocks haven't been inserted yet; insert them here.
10302         for (BitTestCase &BTC : BTB->Cases)
10303           CurMF->insert(BBI, BTC.ThisBB);
10304 
10305         // Fill in fields of the BitTestBlock.
10306         BTB->Parent = CurMBB;
10307         BTB->Default = Fallthrough;
10308 
10309         BTB->DefaultProb = UnhandledProbs;
10310         // If the cases in bit test don't form a contiguous range, we evenly
10311         // distribute the probability on the edge to Fallthrough to two
10312         // successors of CurMBB.
10313         if (!BTB->ContiguousRange) {
10314           BTB->Prob += DefaultProb / 2;
10315           BTB->DefaultProb -= DefaultProb / 2;
10316         }
10317 
10318         if (FallthroughUnreachable) {
10319           // Skip the range check if the fallthrough block is unreachable.
10320           BTB->OmitRangeCheck = true;
10321         }
10322 
10323         // If we're in the right place, emit the bit test header right now.
10324         if (CurMBB == SwitchMBB) {
10325           visitBitTestHeader(*BTB, SwitchMBB);
10326           BTB->Emitted = true;
10327         }
10328         break;
10329       }
10330       case CC_Range: {
10331         const Value *RHS, *LHS, *MHS;
10332         ISD::CondCode CC;
10333         if (I->Low == I->High) {
10334           // Check Cond == I->Low.
10335           CC = ISD::SETEQ;
10336           LHS = Cond;
10337           RHS=I->Low;
10338           MHS = nullptr;
10339         } else {
10340           // Check I->Low <= Cond <= I->High.
10341           CC = ISD::SETLE;
10342           LHS = I->Low;
10343           MHS = Cond;
10344           RHS = I->High;
10345         }
10346 
10347         // If Fallthrough is unreachable, fold away the comparison.
10348         if (FallthroughUnreachable)
10349           CC = ISD::SETTRUE;
10350 
10351         // The false probability is the sum of all unhandled cases.
10352         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10353                      getCurSDLoc(), I->Prob, UnhandledProbs);
10354 
10355         if (CurMBB == SwitchMBB)
10356           visitSwitchCase(CB, SwitchMBB);
10357         else
10358           SL->SwitchCases.push_back(CB);
10359 
10360         break;
10361       }
10362     }
10363     CurMBB = Fallthrough;
10364   }
10365 }
10366 
10367 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10368                                               CaseClusterIt First,
10369                                               CaseClusterIt Last) {
10370   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10371     if (X.Prob != CC.Prob)
10372       return X.Prob > CC.Prob;
10373 
10374     // Ties are broken by comparing the case value.
10375     return X.Low->getValue().slt(CC.Low->getValue());
10376   });
10377 }
10378 
10379 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10380                                         const SwitchWorkListItem &W,
10381                                         Value *Cond,
10382                                         MachineBasicBlock *SwitchMBB) {
10383   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10384          "Clusters not sorted?");
10385 
10386   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10387 
10388   // Balance the tree based on branch probabilities to create a near-optimal (in
10389   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10390   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10391   CaseClusterIt LastLeft = W.FirstCluster;
10392   CaseClusterIt FirstRight = W.LastCluster;
10393   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10394   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10395 
10396   // Move LastLeft and FirstRight towards each other from opposite directions to
10397   // find a partitioning of the clusters which balances the probability on both
10398   // sides. If LeftProb and RightProb are equal, alternate which side is
10399   // taken to ensure 0-probability nodes are distributed evenly.
10400   unsigned I = 0;
10401   while (LastLeft + 1 < FirstRight) {
10402     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10403       LeftProb += (++LastLeft)->Prob;
10404     else
10405       RightProb += (--FirstRight)->Prob;
10406     I++;
10407   }
10408 
10409   while (true) {
10410     // Our binary search tree differs from a typical BST in that ours can have up
10411     // to three values in each leaf. The pivot selection above doesn't take that
10412     // into account, which means the tree might require more nodes and be less
10413     // efficient. We compensate for this here.
10414 
10415     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10416     unsigned NumRight = W.LastCluster - FirstRight + 1;
10417 
10418     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10419       // If one side has less than 3 clusters, and the other has more than 3,
10420       // consider taking a cluster from the other side.
10421 
10422       if (NumLeft < NumRight) {
10423         // Consider moving the first cluster on the right to the left side.
10424         CaseCluster &CC = *FirstRight;
10425         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10426         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10427         if (LeftSideRank <= RightSideRank) {
10428           // Moving the cluster to the left does not demote it.
10429           ++LastLeft;
10430           ++FirstRight;
10431           continue;
10432         }
10433       } else {
10434         assert(NumRight < NumLeft);
10435         // Consider moving the last element on the left to the right side.
10436         CaseCluster &CC = *LastLeft;
10437         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10438         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10439         if (RightSideRank <= LeftSideRank) {
10440           // Moving the cluster to the right does not demot it.
10441           --LastLeft;
10442           --FirstRight;
10443           continue;
10444         }
10445       }
10446     }
10447     break;
10448   }
10449 
10450   assert(LastLeft + 1 == FirstRight);
10451   assert(LastLeft >= W.FirstCluster);
10452   assert(FirstRight <= W.LastCluster);
10453 
10454   // Use the first element on the right as pivot since we will make less-than
10455   // comparisons against it.
10456   CaseClusterIt PivotCluster = FirstRight;
10457   assert(PivotCluster > W.FirstCluster);
10458   assert(PivotCluster <= W.LastCluster);
10459 
10460   CaseClusterIt FirstLeft = W.FirstCluster;
10461   CaseClusterIt LastRight = W.LastCluster;
10462 
10463   const ConstantInt *Pivot = PivotCluster->Low;
10464 
10465   // New blocks will be inserted immediately after the current one.
10466   MachineFunction::iterator BBI(W.MBB);
10467   ++BBI;
10468 
10469   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10470   // we can branch to its destination directly if it's squeezed exactly in
10471   // between the known lower bound and Pivot - 1.
10472   MachineBasicBlock *LeftMBB;
10473   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10474       FirstLeft->Low == W.GE &&
10475       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10476     LeftMBB = FirstLeft->MBB;
10477   } else {
10478     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10479     FuncInfo.MF->insert(BBI, LeftMBB);
10480     WorkList.push_back(
10481         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10482     // Put Cond in a virtual register to make it available from the new blocks.
10483     ExportFromCurrentBlock(Cond);
10484   }
10485 
10486   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10487   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10488   // directly if RHS.High equals the current upper bound.
10489   MachineBasicBlock *RightMBB;
10490   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10491       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10492     RightMBB = FirstRight->MBB;
10493   } else {
10494     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10495     FuncInfo.MF->insert(BBI, RightMBB);
10496     WorkList.push_back(
10497         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10498     // Put Cond in a virtual register to make it available from the new blocks.
10499     ExportFromCurrentBlock(Cond);
10500   }
10501 
10502   // Create the CaseBlock record that will be used to lower the branch.
10503   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10504                getCurSDLoc(), LeftProb, RightProb);
10505 
10506   if (W.MBB == SwitchMBB)
10507     visitSwitchCase(CB, SwitchMBB);
10508   else
10509     SL->SwitchCases.push_back(CB);
10510 }
10511 
10512 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10513 // from the swith statement.
10514 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10515                                             BranchProbability PeeledCaseProb) {
10516   if (PeeledCaseProb == BranchProbability::getOne())
10517     return BranchProbability::getZero();
10518   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10519 
10520   uint32_t Numerator = CaseProb.getNumerator();
10521   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10522   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10523 }
10524 
10525 // Try to peel the top probability case if it exceeds the threshold.
10526 // Return current MachineBasicBlock for the switch statement if the peeling
10527 // does not occur.
10528 // If the peeling is performed, return the newly created MachineBasicBlock
10529 // for the peeled switch statement. Also update Clusters to remove the peeled
10530 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10531 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10532     const SwitchInst &SI, CaseClusterVector &Clusters,
10533     BranchProbability &PeeledCaseProb) {
10534   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10535   // Don't perform if there is only one cluster or optimizing for size.
10536   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10537       TM.getOptLevel() == CodeGenOpt::None ||
10538       SwitchMBB->getParent()->getFunction().hasMinSize())
10539     return SwitchMBB;
10540 
10541   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10542   unsigned PeeledCaseIndex = 0;
10543   bool SwitchPeeled = false;
10544   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10545     CaseCluster &CC = Clusters[Index];
10546     if (CC.Prob < TopCaseProb)
10547       continue;
10548     TopCaseProb = CC.Prob;
10549     PeeledCaseIndex = Index;
10550     SwitchPeeled = true;
10551   }
10552   if (!SwitchPeeled)
10553     return SwitchMBB;
10554 
10555   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10556                     << TopCaseProb << "\n");
10557 
10558   // Record the MBB for the peeled switch statement.
10559   MachineFunction::iterator BBI(SwitchMBB);
10560   ++BBI;
10561   MachineBasicBlock *PeeledSwitchMBB =
10562       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10563   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10564 
10565   ExportFromCurrentBlock(SI.getCondition());
10566   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10567   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10568                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10569   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10570 
10571   Clusters.erase(PeeledCaseIt);
10572   for (CaseCluster &CC : Clusters) {
10573     LLVM_DEBUG(
10574         dbgs() << "Scale the probablity for one cluster, before scaling: "
10575                << CC.Prob << "\n");
10576     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10577     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10578   }
10579   PeeledCaseProb = TopCaseProb;
10580   return PeeledSwitchMBB;
10581 }
10582 
10583 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10584   // Extract cases from the switch.
10585   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10586   CaseClusterVector Clusters;
10587   Clusters.reserve(SI.getNumCases());
10588   for (auto I : SI.cases()) {
10589     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10590     const ConstantInt *CaseVal = I.getCaseValue();
10591     BranchProbability Prob =
10592         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10593             : BranchProbability(1, SI.getNumCases() + 1);
10594     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10595   }
10596 
10597   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10598 
10599   // Cluster adjacent cases with the same destination. We do this at all
10600   // optimization levels because it's cheap to do and will make codegen faster
10601   // if there are many clusters.
10602   sortAndRangeify(Clusters);
10603 
10604   // The branch probablity of the peeled case.
10605   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10606   MachineBasicBlock *PeeledSwitchMBB =
10607       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10608 
10609   // If there is only the default destination, jump there directly.
10610   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10611   if (Clusters.empty()) {
10612     assert(PeeledSwitchMBB == SwitchMBB);
10613     SwitchMBB->addSuccessor(DefaultMBB);
10614     if (DefaultMBB != NextBlock(SwitchMBB)) {
10615       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10616                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10617     }
10618     return;
10619   }
10620 
10621   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10622   SL->findBitTestClusters(Clusters, &SI);
10623 
10624   LLVM_DEBUG({
10625     dbgs() << "Case clusters: ";
10626     for (const CaseCluster &C : Clusters) {
10627       if (C.Kind == CC_JumpTable)
10628         dbgs() << "JT:";
10629       if (C.Kind == CC_BitTests)
10630         dbgs() << "BT:";
10631 
10632       C.Low->getValue().print(dbgs(), true);
10633       if (C.Low != C.High) {
10634         dbgs() << '-';
10635         C.High->getValue().print(dbgs(), true);
10636       }
10637       dbgs() << ' ';
10638     }
10639     dbgs() << '\n';
10640   });
10641 
10642   assert(!Clusters.empty());
10643   SwitchWorkList WorkList;
10644   CaseClusterIt First = Clusters.begin();
10645   CaseClusterIt Last = Clusters.end() - 1;
10646   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10647   // Scale the branchprobability for DefaultMBB if the peel occurs and
10648   // DefaultMBB is not replaced.
10649   if (PeeledCaseProb != BranchProbability::getZero() &&
10650       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10651     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10652   WorkList.push_back(
10653       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10654 
10655   while (!WorkList.empty()) {
10656     SwitchWorkListItem W = WorkList.back();
10657     WorkList.pop_back();
10658     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10659 
10660     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10661         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10662       // For optimized builds, lower large range as a balanced binary tree.
10663       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10664       continue;
10665     }
10666 
10667     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10668   }
10669 }
10670 
10671 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10672   SmallVector<EVT, 4> ValueVTs;
10673   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10674                   ValueVTs);
10675   unsigned NumValues = ValueVTs.size();
10676   if (NumValues == 0) return;
10677 
10678   SmallVector<SDValue, 4> Values(NumValues);
10679   SDValue Op = getValue(I.getOperand(0));
10680 
10681   for (unsigned i = 0; i != NumValues; ++i)
10682     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10683                             SDValue(Op.getNode(), Op.getResNo() + i));
10684 
10685   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10686                            DAG.getVTList(ValueVTs), Values));
10687 }
10688