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