xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision d0943537e10e25281164bb27df843e283dc6666c)
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/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BlockFrequencyInfo.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/ProfileSummaryInfo.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/ValueTracking.h"
39 #include "llvm/Analysis/VectorUtils.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/FunctionLoweringInfo.h"
42 #include "llvm/CodeGen/GCMetadata.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineJumpTableInfo.h"
50 #include "llvm/CodeGen/MachineMemOperand.h"
51 #include "llvm/CodeGen/MachineModuleInfo.h"
52 #include "llvm/CodeGen/MachineOperand.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/RuntimeLibcalls.h"
55 #include "llvm/CodeGen/SelectionDAG.h"
56 #include "llvm/CodeGen/SelectionDAGNodes.h"
57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
58 #include "llvm/CodeGen/StackMaps.h"
59 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
60 #include "llvm/CodeGen/TargetFrameLowering.h"
61 #include "llvm/CodeGen/TargetInstrInfo.h"
62 #include "llvm/CodeGen/TargetLowering.h"
63 #include "llvm/CodeGen/TargetOpcodes.h"
64 #include "llvm/CodeGen/TargetRegisterInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include "llvm/CodeGen/ValueTypes.h"
67 #include "llvm/CodeGen/WinEHFuncInfo.h"
68 #include "llvm/IR/Argument.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/BasicBlock.h"
71 #include "llvm/IR/CFG.h"
72 #include "llvm/IR/CallSite.h"
73 #include "llvm/IR/CallingConv.h"
74 #include "llvm/IR/Constant.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DebugInfoMetadata.h"
79 #include "llvm/IR/DebugLoc.h"
80 #include "llvm/IR/DerivedTypes.h"
81 #include "llvm/IR/Function.h"
82 #include "llvm/IR/GetElementPtrTypeIterator.h"
83 #include "llvm/IR/InlineAsm.h"
84 #include "llvm/IR/InstrTypes.h"
85 #include "llvm/IR/Instruction.h"
86 #include "llvm/IR/Instructions.h"
87 #include "llvm/IR/IntrinsicInst.h"
88 #include "llvm/IR/Intrinsics.h"
89 #include "llvm/IR/IntrinsicsAArch64.h"
90 #include "llvm/IR/IntrinsicsWebAssembly.h"
91 #include "llvm/IR/LLVMContext.h"
92 #include "llvm/IR/Metadata.h"
93 #include "llvm/IR/Module.h"
94 #include "llvm/IR/Operator.h"
95 #include "llvm/IR/PatternMatch.h"
96 #include "llvm/IR/Statepoint.h"
97 #include "llvm/IR/Type.h"
98 #include "llvm/IR/User.h"
99 #include "llvm/IR/Value.h"
100 #include "llvm/MC/MCContext.h"
101 #include "llvm/MC/MCSymbol.h"
102 #include "llvm/Support/AtomicOrdering.h"
103 #include "llvm/Support/BranchProbability.h"
104 #include "llvm/Support/Casting.h"
105 #include "llvm/Support/CodeGen.h"
106 #include "llvm/Support/CommandLine.h"
107 #include "llvm/Support/Compiler.h"
108 #include "llvm/Support/Debug.h"
109 #include "llvm/Support/ErrorHandling.h"
110 #include "llvm/Support/MachineValueType.h"
111 #include "llvm/Support/MathExtras.h"
112 #include "llvm/Support/raw_ostream.h"
113 #include "llvm/Target/TargetIntrinsicInfo.h"
114 #include "llvm/Target/TargetMachine.h"
115 #include "llvm/Target/TargetOptions.h"
116 #include "llvm/Transforms/Utils/Local.h"
117 #include <algorithm>
118 #include <cassert>
119 #include <cstddef>
120 #include <cstdint>
121 #include <cstring>
122 #include <iterator>
123 #include <limits>
124 #include <numeric>
125 #include <tuple>
126 #include <utility>
127 #include <vector>
128 
129 using namespace llvm;
130 using namespace PatternMatch;
131 using namespace SwitchCG;
132 
133 #define DEBUG_TYPE "isel"
134 
135 /// LimitFloatPrecision - Generate low-precision inline sequences for
136 /// some float libcalls (6, 8 or 12 bits).
137 static unsigned LimitFloatPrecision;
138 
139 static cl::opt<unsigned, true>
140     LimitFPPrecision("limit-float-precision",
141                      cl::desc("Generate low-precision inline sequences "
142                               "for some float libcalls"),
143                      cl::location(LimitFloatPrecision), cl::Hidden,
144                      cl::init(0));
145 
146 static cl::opt<unsigned> SwitchPeelThreshold(
147     "switch-peel-threshold", cl::Hidden, cl::init(66),
148     cl::desc("Set the case probability threshold for peeling the case from a "
149              "switch statement. A value greater than 100 will void this "
150              "optimization"));
151 
152 // Limit the width of DAG chains. This is important in general to prevent
153 // DAG-based analysis from blowing up. For example, alias analysis and
154 // load clustering may not complete in reasonable time. It is difficult to
155 // recognize and avoid this situation within each individual analysis, and
156 // future analyses are likely to have the same behavior. Limiting DAG width is
157 // the safe approach and will be especially important with global DAGs.
158 //
159 // MaxParallelChains default is arbitrarily high to avoid affecting
160 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
161 // sequence over this should have been converted to llvm.memcpy by the
162 // frontend. It is easy to induce this behavior with .ll code such as:
163 // %buffer = alloca [4096 x i8]
164 // %data = load [4096 x i8]* %argPtr
165 // store [4096 x i8] %data, [4096 x i8]* %buffer
166 static const unsigned MaxParallelChains = 64;
167 
168 // Return the calling convention if the Value passed requires ABI mangling as it
169 // is a parameter to a function or a return value from a function which is not
170 // an intrinsic.
171 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
172   if (auto *R = dyn_cast<ReturnInst>(V))
173     return R->getParent()->getParent()->getCallingConv();
174 
175   if (auto *CI = dyn_cast<CallInst>(V)) {
176     const bool IsInlineAsm = CI->isInlineAsm();
177     const bool IsIndirectFunctionCall =
178         !IsInlineAsm && !CI->getCalledFunction();
179 
180     // It is possible that the call instruction is an inline asm statement or an
181     // indirect function call in which case the return value of
182     // getCalledFunction() would be nullptr.
183     const bool IsInstrinsicCall =
184         !IsInlineAsm && !IsIndirectFunctionCall &&
185         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
186 
187     if (!IsInlineAsm && !IsInstrinsicCall)
188       return CI->getCallingConv();
189   }
190 
191   return None;
192 }
193 
194 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
195                                       const SDValue *Parts, unsigned NumParts,
196                                       MVT PartVT, EVT ValueVT, const Value *V,
197                                       Optional<CallingConv::ID> CC);
198 
199 /// getCopyFromParts - Create a value that contains the specified legal parts
200 /// combined into the value they represent.  If the parts combine to a type
201 /// larger than ValueVT then AssertOp can be used to specify whether the extra
202 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
203 /// (ISD::AssertSext).
204 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
205                                 const SDValue *Parts, unsigned NumParts,
206                                 MVT PartVT, EVT ValueVT, const Value *V,
207                                 Optional<CallingConv::ID> CC = None,
208                                 Optional<ISD::NodeType> AssertOp = None) {
209   if (ValueVT.isVector())
210     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
211                                   CC);
212 
213   assert(NumParts > 0 && "No parts to assemble!");
214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
215   SDValue Val = Parts[0];
216 
217   if (NumParts > 1) {
218     // Assemble the value from multiple parts.
219     if (ValueVT.isInteger()) {
220       unsigned PartBits = PartVT.getSizeInBits();
221       unsigned ValueBits = ValueVT.getSizeInBits();
222 
223       // Assemble the power of 2 part.
224       unsigned RoundParts =
225           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
226       unsigned RoundBits = PartBits * RoundParts;
227       EVT RoundVT = RoundBits == ValueBits ?
228         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
229       SDValue Lo, Hi;
230 
231       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
232 
233       if (RoundParts > 2) {
234         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
235                               PartVT, HalfVT, V);
236         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
237                               RoundParts / 2, PartVT, HalfVT, V);
238       } else {
239         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
240         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
241       }
242 
243       if (DAG.getDataLayout().isBigEndian())
244         std::swap(Lo, Hi);
245 
246       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
247 
248       if (RoundParts < NumParts) {
249         // Assemble the trailing non-power-of-2 part.
250         unsigned OddParts = NumParts - RoundParts;
251         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
252         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
253                               OddVT, V, CC);
254 
255         // Combine the round and odd parts.
256         Lo = Val;
257         if (DAG.getDataLayout().isBigEndian())
258           std::swap(Lo, Hi);
259         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
260         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
261         Hi =
262             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
263                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
264                                         TLI.getPointerTy(DAG.getDataLayout())));
265         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
266         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
267       }
268     } else if (PartVT.isFloatingPoint()) {
269       // FP split into multiple FP parts (for ppcf128)
270       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
271              "Unexpected split");
272       SDValue Lo, Hi;
273       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
274       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
275       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
276         std::swap(Lo, Hi);
277       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
278     } else {
279       // FP split into integer parts (soft fp)
280       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
281              !PartVT.isVector() && "Unexpected split");
282       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
283       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
284     }
285   }
286 
287   // There is now one part, held in Val.  Correct it to match ValueVT.
288   // PartEVT is the type of the register class that holds the value.
289   // ValueVT is the type of the inline asm operation.
290   EVT PartEVT = Val.getValueType();
291 
292   if (PartEVT == ValueVT)
293     return Val;
294 
295   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
296       ValueVT.bitsLT(PartEVT)) {
297     // For an FP value in an integer part, we need to truncate to the right
298     // width first.
299     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
300     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
301   }
302 
303   // Handle types that have the same size.
304   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
305     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
306 
307   // Handle types with different sizes.
308   if (PartEVT.isInteger() && ValueVT.isInteger()) {
309     if (ValueVT.bitsLT(PartEVT)) {
310       // For a truncate, see if we have any information to
311       // indicate whether the truncated bits will always be
312       // zero or sign-extension.
313       if (AssertOp.hasValue())
314         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
315                           DAG.getValueType(ValueVT));
316       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317     }
318     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
319   }
320 
321   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
322     // FP_ROUND's are always exact here.
323     if (ValueVT.bitsLT(Val.getValueType()))
324       return DAG.getNode(
325           ISD::FP_ROUND, DL, ValueVT, Val,
326           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
327 
328     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
329   }
330 
331   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
332   // then truncating.
333   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
334       ValueVT.bitsLT(PartEVT)) {
335     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
336     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
337   }
338 
339   report_fatal_error("Unknown mismatch in getCopyFromParts!");
340 }
341 
342 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
343                                               const Twine &ErrMsg) {
344   const Instruction *I = dyn_cast_or_null<Instruction>(V);
345   if (!V)
346     return Ctx.emitError(ErrMsg);
347 
348   const char *AsmError = ", possible invalid constraint for vector type";
349   if (const CallInst *CI = dyn_cast<CallInst>(I))
350     if (isa<InlineAsm>(CI->getCalledValue()))
351       return Ctx.emitError(I, ErrMsg + AsmError);
352 
353   return Ctx.emitError(I, ErrMsg);
354 }
355 
356 /// getCopyFromPartsVector - Create a value that contains the specified legal
357 /// parts combined into the value they represent.  If the parts combine to a
358 /// type larger than ValueVT then AssertOp can be used to specify whether the
359 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
360 /// ValueVT (ISD::AssertSext).
361 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
362                                       const SDValue *Parts, unsigned NumParts,
363                                       MVT PartVT, EVT ValueVT, const Value *V,
364                                       Optional<CallingConv::ID> CallConv) {
365   assert(ValueVT.isVector() && "Not a vector value");
366   assert(NumParts > 0 && "No parts to assemble!");
367   const bool IsABIRegCopy = CallConv.hasValue();
368 
369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
370   SDValue Val = Parts[0];
371 
372   // Handle a multi-element vector.
373   if (NumParts > 1) {
374     EVT IntermediateVT;
375     MVT RegisterVT;
376     unsigned NumIntermediates;
377     unsigned NumRegs;
378 
379     if (IsABIRegCopy) {
380       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
381           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
382           NumIntermediates, RegisterVT);
383     } else {
384       NumRegs =
385           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
386                                      NumIntermediates, RegisterVT);
387     }
388 
389     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
390     NumParts = NumRegs; // Silence a compiler warning.
391     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
392     assert(RegisterVT.getSizeInBits() ==
393            Parts[0].getSimpleValueType().getSizeInBits() &&
394            "Part type sizes don't match!");
395 
396     // Assemble the parts into intermediate operands.
397     SmallVector<SDValue, 8> Ops(NumIntermediates);
398     if (NumIntermediates == NumParts) {
399       // If the register was not expanded, truncate or copy the value,
400       // as appropriate.
401       for (unsigned i = 0; i != NumParts; ++i)
402         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
403                                   PartVT, IntermediateVT, V);
404     } else if (NumParts > 0) {
405       // If the intermediate type was expanded, build the intermediate
406       // operands from the parts.
407       assert(NumParts % NumIntermediates == 0 &&
408              "Must expand into a divisible number of parts!");
409       unsigned Factor = NumParts / NumIntermediates;
410       for (unsigned i = 0; i != NumIntermediates; ++i)
411         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
412                                   PartVT, IntermediateVT, V);
413     }
414 
415     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
416     // intermediate operands.
417     EVT BuiltVectorTy =
418         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
419                          (IntermediateVT.isVector()
420                               ? IntermediateVT.getVectorNumElements() * NumParts
421                               : NumIntermediates));
422     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
423                                                 : ISD::BUILD_VECTOR,
424                       DL, BuiltVectorTy, Ops);
425   }
426 
427   // There is now one part, held in Val.  Correct it to match ValueVT.
428   EVT PartEVT = Val.getValueType();
429 
430   if (PartEVT == ValueVT)
431     return Val;
432 
433   if (PartEVT.isVector()) {
434     // If the element type of the source/dest vectors are the same, but the
435     // parts vector has more elements than the value vector, then we have a
436     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
437     // elements we want.
438     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
439       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
440              "Cannot narrow, it would be a lossy transformation");
441       return DAG.getNode(
442           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
443           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
444     }
445 
446     // Vector/Vector bitcast.
447     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
448       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
449 
450     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
451       "Cannot handle this kind of promotion");
452     // Promoted vector extract
453     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
454 
455   }
456 
457   // Trivial bitcast if the types are the same size and the destination
458   // vector type is legal.
459   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
460       TLI.isTypeLegal(ValueVT))
461     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
462 
463   if (ValueVT.getVectorNumElements() != 1) {
464      // Certain ABIs require that vectors are passed as integers. For vectors
465      // are the same size, this is an obvious bitcast.
466      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
467        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
468      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
469        // Bitcast Val back the original type and extract the corresponding
470        // vector we want.
471        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
472        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
473                                            ValueVT.getVectorElementType(), Elts);
474        Val = DAG.getBitcast(WiderVecType, Val);
475        return DAG.getNode(
476            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
477            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
478      }
479 
480      diagnosePossiblyInvalidConstraint(
481          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
482      return DAG.getUNDEF(ValueVT);
483   }
484 
485   // Handle cases such as i8 -> <1 x i1>
486   EVT ValueSVT = ValueVT.getVectorElementType();
487   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
488     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
489                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
490 
491   return DAG.getBuildVector(ValueVT, DL, Val);
492 }
493 
494 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
495                                  SDValue Val, SDValue *Parts, unsigned NumParts,
496                                  MVT PartVT, const Value *V,
497                                  Optional<CallingConv::ID> CallConv);
498 
499 /// getCopyToParts - Create a series of nodes that contain the specified value
500 /// split into legal parts.  If the parts contain more bits than Val, then, for
501 /// integers, ExtendKind can be used to specify how to generate the extra bits.
502 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
503                            SDValue *Parts, unsigned NumParts, MVT PartVT,
504                            const Value *V,
505                            Optional<CallingConv::ID> CallConv = None,
506                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
507   EVT ValueVT = Val.getValueType();
508 
509   // Handle the vector case separately.
510   if (ValueVT.isVector())
511     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
512                                 CallConv);
513 
514   unsigned PartBits = PartVT.getSizeInBits();
515   unsigned OrigNumParts = NumParts;
516   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
517          "Copying to an illegal type!");
518 
519   if (NumParts == 0)
520     return;
521 
522   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
523   EVT PartEVT = PartVT;
524   if (PartEVT == ValueVT) {
525     assert(NumParts == 1 && "No-op copy with multiple parts!");
526     Parts[0] = Val;
527     return;
528   }
529 
530   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
531     // If the parts cover more bits than the value has, promote the value.
532     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
533       assert(NumParts == 1 && "Do not know what to promote to!");
534       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
535     } else {
536       if (ValueVT.isFloatingPoint()) {
537         // FP values need to be bitcast, then extended if they are being put
538         // into a larger container.
539         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
540         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
541       }
542       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
543              ValueVT.isInteger() &&
544              "Unknown mismatch!");
545       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
546       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
547       if (PartVT == MVT::x86mmx)
548         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
549     }
550   } else if (PartBits == ValueVT.getSizeInBits()) {
551     // Different types of the same size.
552     assert(NumParts == 1 && PartEVT != ValueVT);
553     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
555     // If the parts cover less bits than value has, truncate the value.
556     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
557            ValueVT.isInteger() &&
558            "Unknown mismatch!");
559     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
560     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
561     if (PartVT == MVT::x86mmx)
562       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
563   }
564 
565   // The value may have changed - recompute ValueVT.
566   ValueVT = Val.getValueType();
567   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
568          "Failed to tile the value with PartVT!");
569 
570   if (NumParts == 1) {
571     if (PartEVT != ValueVT) {
572       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
573                                         "scalar-to-vector conversion failed");
574       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
575     }
576 
577     Parts[0] = Val;
578     return;
579   }
580 
581   // Expand the value into multiple parts.
582   if (NumParts & (NumParts - 1)) {
583     // The number of parts is not a power of 2.  Split off and copy the tail.
584     assert(PartVT.isInteger() && ValueVT.isInteger() &&
585            "Do not know what to expand to!");
586     unsigned RoundParts = 1 << Log2_32(NumParts);
587     unsigned RoundBits = RoundParts * PartBits;
588     unsigned OddParts = NumParts - RoundParts;
589     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
590       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
591 
592     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
593                    CallConv);
594 
595     if (DAG.getDataLayout().isBigEndian())
596       // The odd parts were reversed by getCopyToParts - unreverse them.
597       std::reverse(Parts + RoundParts, Parts + NumParts);
598 
599     NumParts = RoundParts;
600     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
601     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
602   }
603 
604   // The number of parts is a power of 2.  Repeatedly bisect the value using
605   // EXTRACT_ELEMENT.
606   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
607                          EVT::getIntegerVT(*DAG.getContext(),
608                                            ValueVT.getSizeInBits()),
609                          Val);
610 
611   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
612     for (unsigned i = 0; i < NumParts; i += StepSize) {
613       unsigned ThisBits = StepSize * PartBits / 2;
614       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
615       SDValue &Part0 = Parts[i];
616       SDValue &Part1 = Parts[i+StepSize/2];
617 
618       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
619                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
620       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
621                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
622 
623       if (ThisBits == PartBits && ThisVT != PartVT) {
624         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
625         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
626       }
627     }
628   }
629 
630   if (DAG.getDataLayout().isBigEndian())
631     std::reverse(Parts, Parts + OrigNumParts);
632 }
633 
634 static SDValue widenVectorToPartType(SelectionDAG &DAG,
635                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
636   if (!PartVT.isVector())
637     return SDValue();
638 
639   EVT ValueVT = Val.getValueType();
640   unsigned PartNumElts = PartVT.getVectorNumElements();
641   unsigned ValueNumElts = ValueVT.getVectorNumElements();
642   if (PartNumElts > ValueNumElts &&
643       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
644     EVT ElementVT = PartVT.getVectorElementType();
645     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
646     // undef elements.
647     SmallVector<SDValue, 16> Ops;
648     DAG.ExtractVectorElements(Val, Ops);
649     SDValue EltUndef = DAG.getUNDEF(ElementVT);
650     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
651       Ops.push_back(EltUndef);
652 
653     // FIXME: Use CONCAT for 2x -> 4x.
654     return DAG.getBuildVector(PartVT, DL, Ops);
655   }
656 
657   return SDValue();
658 }
659 
660 /// getCopyToPartsVector - Create a series of nodes that contain the specified
661 /// value split into legal parts.
662 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
663                                  SDValue Val, SDValue *Parts, unsigned NumParts,
664                                  MVT PartVT, const Value *V,
665                                  Optional<CallingConv::ID> CallConv) {
666   EVT ValueVT = Val.getValueType();
667   assert(ValueVT.isVector() && "Not a vector");
668   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
669   const bool IsABIRegCopy = CallConv.hasValue();
670 
671   if (NumParts == 1) {
672     EVT PartEVT = PartVT;
673     if (PartEVT == ValueVT) {
674       // Nothing to do.
675     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
676       // Bitconvert vector->vector case.
677       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
678     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
679       Val = Widened;
680     } else if (PartVT.isVector() &&
681                PartEVT.getVectorElementType().bitsGE(
682                  ValueVT.getVectorElementType()) &&
683                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
684 
685       // Promoted vector extract
686       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
687     } else {
688       if (ValueVT.getVectorNumElements() == 1) {
689         Val = DAG.getNode(
690             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
691             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
692       } else {
693         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
694                "lossy conversion of vector to scalar type");
695         EVT IntermediateType =
696             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
697         Val = DAG.getBitcast(IntermediateType, Val);
698         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
699       }
700     }
701 
702     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
703     Parts[0] = Val;
704     return;
705   }
706 
707   // Handle a multi-element vector.
708   EVT IntermediateVT;
709   MVT RegisterVT;
710   unsigned NumIntermediates;
711   unsigned NumRegs;
712   if (IsABIRegCopy) {
713     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
714         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
715         NumIntermediates, RegisterVT);
716   } else {
717     NumRegs =
718         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
719                                    NumIntermediates, RegisterVT);
720   }
721 
722   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
723   NumParts = NumRegs; // Silence a compiler warning.
724   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
725 
726   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
727     IntermediateVT.getVectorNumElements() : 1;
728 
729   // Convert the vector to the appropriate type if necessary.
730   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
731 
732   EVT BuiltVectorTy = EVT::getVectorVT(
733       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
734   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
735   if (ValueVT != BuiltVectorTy) {
736     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
737       Val = Widened;
738 
739     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
740   }
741 
742   // Split the vector into intermediate operands.
743   SmallVector<SDValue, 8> Ops(NumIntermediates);
744   for (unsigned i = 0; i != NumIntermediates; ++i) {
745     if (IntermediateVT.isVector()) {
746       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
747                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
748     } else {
749       Ops[i] = DAG.getNode(
750           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
751           DAG.getConstant(i, DL, IdxVT));
752     }
753   }
754 
755   // Split the intermediate operands into legal parts.
756   if (NumParts == NumIntermediates) {
757     // If the register was not expanded, promote or copy the value,
758     // as appropriate.
759     for (unsigned i = 0; i != NumParts; ++i)
760       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
761   } else if (NumParts > 0) {
762     // If the intermediate type was expanded, split each the value into
763     // legal parts.
764     assert(NumIntermediates != 0 && "division by zero");
765     assert(NumParts % NumIntermediates == 0 &&
766            "Must expand into a divisible number of parts!");
767     unsigned Factor = NumParts / NumIntermediates;
768     for (unsigned i = 0; i != NumIntermediates; ++i)
769       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
770                      CallConv);
771   }
772 }
773 
774 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
775                            EVT valuevt, Optional<CallingConv::ID> CC)
776     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
777       RegCount(1, regs.size()), CallConv(CC) {}
778 
779 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
780                            const DataLayout &DL, unsigned Reg, Type *Ty,
781                            Optional<CallingConv::ID> CC) {
782   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
783 
784   CallConv = CC;
785 
786   for (EVT ValueVT : ValueVTs) {
787     unsigned NumRegs =
788         isABIMangled()
789             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
790             : TLI.getNumRegisters(Context, ValueVT);
791     MVT RegisterVT =
792         isABIMangled()
793             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
794             : TLI.getRegisterType(Context, ValueVT);
795     for (unsigned i = 0; i != NumRegs; ++i)
796       Regs.push_back(Reg + i);
797     RegVTs.push_back(RegisterVT);
798     RegCount.push_back(NumRegs);
799     Reg += NumRegs;
800   }
801 }
802 
803 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
804                                       FunctionLoweringInfo &FuncInfo,
805                                       const SDLoc &dl, SDValue &Chain,
806                                       SDValue *Flag, const Value *V) const {
807   // A Value with type {} or [0 x %t] needs no registers.
808   if (ValueVTs.empty())
809     return SDValue();
810 
811   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
812 
813   // Assemble the legal parts into the final values.
814   SmallVector<SDValue, 4> Values(ValueVTs.size());
815   SmallVector<SDValue, 8> Parts;
816   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
817     // Copy the legal parts from the registers.
818     EVT ValueVT = ValueVTs[Value];
819     unsigned NumRegs = RegCount[Value];
820     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
821                                           *DAG.getContext(),
822                                           CallConv.getValue(), RegVTs[Value])
823                                     : RegVTs[Value];
824 
825     Parts.resize(NumRegs);
826     for (unsigned i = 0; i != NumRegs; ++i) {
827       SDValue P;
828       if (!Flag) {
829         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
830       } else {
831         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
832         *Flag = P.getValue(2);
833       }
834 
835       Chain = P.getValue(1);
836       Parts[i] = P;
837 
838       // If the source register was virtual and if we know something about it,
839       // add an assert node.
840       if (!Register::isVirtualRegister(Regs[Part + i]) ||
841           !RegisterVT.isInteger())
842         continue;
843 
844       const FunctionLoweringInfo::LiveOutInfo *LOI =
845         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
846       if (!LOI)
847         continue;
848 
849       unsigned RegSize = RegisterVT.getScalarSizeInBits();
850       unsigned NumSignBits = LOI->NumSignBits;
851       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
852 
853       if (NumZeroBits == RegSize) {
854         // The current value is a zero.
855         // Explicitly express that as it would be easier for
856         // optimizations to kick in.
857         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
858         continue;
859       }
860 
861       // FIXME: We capture more information than the dag can represent.  For
862       // now, just use the tightest assertzext/assertsext possible.
863       bool isSExt;
864       EVT FromVT(MVT::Other);
865       if (NumZeroBits) {
866         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
867         isSExt = false;
868       } else if (NumSignBits > 1) {
869         FromVT =
870             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
871         isSExt = true;
872       } else {
873         continue;
874       }
875       // Add an assertion node.
876       assert(FromVT != MVT::Other);
877       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
878                              RegisterVT, P, DAG.getValueType(FromVT));
879     }
880 
881     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
882                                      RegisterVT, ValueVT, V, CallConv);
883     Part += NumRegs;
884     Parts.clear();
885   }
886 
887   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
888 }
889 
890 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
891                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
892                                  const Value *V,
893                                  ISD::NodeType PreferredExtendType) const {
894   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
895   ISD::NodeType ExtendKind = PreferredExtendType;
896 
897   // Get the list of the values's legal parts.
898   unsigned NumRegs = Regs.size();
899   SmallVector<SDValue, 8> Parts(NumRegs);
900   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
901     unsigned NumParts = RegCount[Value];
902 
903     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
904                                           *DAG.getContext(),
905                                           CallConv.getValue(), RegVTs[Value])
906                                     : RegVTs[Value];
907 
908     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
909       ExtendKind = ISD::ZERO_EXTEND;
910 
911     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
912                    NumParts, RegisterVT, V, CallConv, ExtendKind);
913     Part += NumParts;
914   }
915 
916   // Copy the parts into the registers.
917   SmallVector<SDValue, 8> Chains(NumRegs);
918   for (unsigned i = 0; i != NumRegs; ++i) {
919     SDValue Part;
920     if (!Flag) {
921       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
922     } else {
923       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
924       *Flag = Part.getValue(1);
925     }
926 
927     Chains[i] = Part.getValue(0);
928   }
929 
930   if (NumRegs == 1 || Flag)
931     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
932     // flagged to it. That is the CopyToReg nodes and the user are considered
933     // a single scheduling unit. If we create a TokenFactor and return it as
934     // chain, then the TokenFactor is both a predecessor (operand) of the
935     // user as well as a successor (the TF operands are flagged to the user).
936     // c1, f1 = CopyToReg
937     // c2, f2 = CopyToReg
938     // c3     = TokenFactor c1, c2
939     // ...
940     //        = op c3, ..., f2
941     Chain = Chains[NumRegs-1];
942   else
943     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
944 }
945 
946 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
947                                         unsigned MatchingIdx, const SDLoc &dl,
948                                         SelectionDAG &DAG,
949                                         std::vector<SDValue> &Ops) const {
950   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
951 
952   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
953   if (HasMatching)
954     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
955   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
956     // Put the register class of the virtual registers in the flag word.  That
957     // way, later passes can recompute register class constraints for inline
958     // assembly as well as normal instructions.
959     // Don't do this for tied operands that can use the regclass information
960     // from the def.
961     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
962     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
963     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
964   }
965 
966   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
967   Ops.push_back(Res);
968 
969   if (Code == InlineAsm::Kind_Clobber) {
970     // Clobbers should always have a 1:1 mapping with registers, and may
971     // reference registers that have illegal (e.g. vector) types. Hence, we
972     // shouldn't try to apply any sort of splitting logic to them.
973     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
974            "No 1:1 mapping from clobbers to regs?");
975     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
976     (void)SP;
977     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
978       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
979       assert(
980           (Regs[I] != SP ||
981            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
982           "If we clobbered the stack pointer, MFI should know about it.");
983     }
984     return;
985   }
986 
987   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
988     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
989     MVT RegisterVT = RegVTs[Value];
990     for (unsigned i = 0; i != NumRegs; ++i) {
991       assert(Reg < Regs.size() && "Mismatch in # registers expected");
992       unsigned TheReg = Regs[Reg++];
993       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
994     }
995   }
996 }
997 
998 SmallVector<std::pair<unsigned, unsigned>, 4>
999 RegsForValue::getRegsAndSizes() const {
1000   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1001   unsigned I = 0;
1002   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1003     unsigned RegCount = std::get<0>(CountAndVT);
1004     MVT RegisterVT = std::get<1>(CountAndVT);
1005     unsigned RegisterSize = RegisterVT.getSizeInBits();
1006     for (unsigned E = I + RegCount; I != E; ++I)
1007       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1008   }
1009   return OutVec;
1010 }
1011 
1012 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1013                                const TargetLibraryInfo *li) {
1014   AA = aa;
1015   GFI = gfi;
1016   LibInfo = li;
1017   DL = &DAG.getDataLayout();
1018   Context = DAG.getContext();
1019   LPadToCallSiteMap.clear();
1020   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1021 }
1022 
1023 void SelectionDAGBuilder::clear() {
1024   NodeMap.clear();
1025   UnusedArgNodeMap.clear();
1026   PendingLoads.clear();
1027   PendingExports.clear();
1028   PendingConstrainedFP.clear();
1029   PendingConstrainedFPStrict.clear();
1030   CurInst = nullptr;
1031   HasTailCall = false;
1032   SDNodeOrder = LowestSDNodeOrder;
1033   StatepointLowering.clear();
1034 }
1035 
1036 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1037   DanglingDebugInfoMap.clear();
1038 }
1039 
1040 // Update DAG root to include dependencies on Pending chains.
1041 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1042   SDValue Root = DAG.getRoot();
1043 
1044   if (Pending.empty())
1045     return Root;
1046 
1047   // Add current root to PendingChains, unless we already indirectly
1048   // depend on it.
1049   if (Root.getOpcode() != ISD::EntryToken) {
1050     unsigned i = 0, e = Pending.size();
1051     for (; i != e; ++i) {
1052       assert(Pending[i].getNode()->getNumOperands() > 1);
1053       if (Pending[i].getNode()->getOperand(0) == Root)
1054         break;  // Don't add the root if we already indirectly depend on it.
1055     }
1056 
1057     if (i == e)
1058       Pending.push_back(Root);
1059   }
1060 
1061   if (Pending.size() == 1)
1062     Root = Pending[0];
1063   else
1064     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1065 
1066   DAG.setRoot(Root);
1067   Pending.clear();
1068   return Root;
1069 }
1070 
1071 SDValue SelectionDAGBuilder::getMemoryRoot() {
1072   return updateRoot(PendingLoads);
1073 }
1074 
1075 SDValue SelectionDAGBuilder::getRoot() {
1076   // Chain up all pending constrained intrinsics together with all
1077   // pending loads, by simply appending them to PendingLoads and
1078   // then calling getMemoryRoot().
1079   PendingLoads.reserve(PendingLoads.size() +
1080                        PendingConstrainedFP.size() +
1081                        PendingConstrainedFPStrict.size());
1082   PendingLoads.append(PendingConstrainedFP.begin(),
1083                       PendingConstrainedFP.end());
1084   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1085                       PendingConstrainedFPStrict.end());
1086   PendingConstrainedFP.clear();
1087   PendingConstrainedFPStrict.clear();
1088   return getMemoryRoot();
1089 }
1090 
1091 SDValue SelectionDAGBuilder::getControlRoot() {
1092   // We need to emit pending fpexcept.strict constrained intrinsics,
1093   // so append them to the PendingExports list.
1094   PendingExports.append(PendingConstrainedFPStrict.begin(),
1095                         PendingConstrainedFPStrict.end());
1096   PendingConstrainedFPStrict.clear();
1097   return updateRoot(PendingExports);
1098 }
1099 
1100 void SelectionDAGBuilder::visit(const Instruction &I) {
1101   // Set up outgoing PHI node register values before emitting the terminator.
1102   if (I.isTerminator()) {
1103     HandlePHINodesInSuccessorBlocks(I.getParent());
1104   }
1105 
1106   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1107   if (!isa<DbgInfoIntrinsic>(I))
1108     ++SDNodeOrder;
1109 
1110   CurInst = &I;
1111 
1112   visit(I.getOpcode(), I);
1113 
1114   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1115     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1116     // maps to this instruction.
1117     // TODO: We could handle all flags (nsw, etc) here.
1118     // TODO: If an IR instruction maps to >1 node, only the final node will have
1119     //       flags set.
1120     if (SDNode *Node = getNodeForIRValue(&I)) {
1121       SDNodeFlags IncomingFlags;
1122       IncomingFlags.copyFMF(*FPMO);
1123       if (!Node->getFlags().isDefined())
1124         Node->setFlags(IncomingFlags);
1125       else
1126         Node->intersectFlagsWith(IncomingFlags);
1127     }
1128   }
1129   // Constrained FP intrinsics with fpexcept.ignore should also get
1130   // the NoFPExcept flag.
1131   if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(&I))
1132     if (FPI->getExceptionBehavior() == fp::ExceptionBehavior::ebIgnore)
1133       if (SDNode *Node = getNodeForIRValue(&I)) {
1134         SDNodeFlags Flags = Node->getFlags();
1135         Flags.setNoFPExcept(true);
1136         Node->setFlags(Flags);
1137       }
1138 
1139   if (!I.isTerminator() && !HasTailCall &&
1140       !isStatepoint(&I)) // statepoints handle their exports internally
1141     CopyToExportRegsIfNeeded(&I);
1142 
1143   CurInst = nullptr;
1144 }
1145 
1146 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1147   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1148 }
1149 
1150 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1151   // Note: this doesn't use InstVisitor, because it has to work with
1152   // ConstantExpr's in addition to instructions.
1153   switch (Opcode) {
1154   default: llvm_unreachable("Unknown instruction type encountered!");
1155     // Build the switch statement using the Instruction.def file.
1156 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1157     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1158 #include "llvm/IR/Instruction.def"
1159   }
1160 }
1161 
1162 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1163                                                 const DIExpression *Expr) {
1164   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1165     const DbgValueInst *DI = DDI.getDI();
1166     DIVariable *DanglingVariable = DI->getVariable();
1167     DIExpression *DanglingExpr = DI->getExpression();
1168     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1169       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1170       return true;
1171     }
1172     return false;
1173   };
1174 
1175   for (auto &DDIMI : DanglingDebugInfoMap) {
1176     DanglingDebugInfoVector &DDIV = DDIMI.second;
1177 
1178     // If debug info is to be dropped, run it through final checks to see
1179     // whether it can be salvaged.
1180     for (auto &DDI : DDIV)
1181       if (isMatchingDbgValue(DDI))
1182         salvageUnresolvedDbgValue(DDI);
1183 
1184     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1185   }
1186 }
1187 
1188 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1189 // generate the debug data structures now that we've seen its definition.
1190 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1191                                                    SDValue Val) {
1192   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1193   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1194     return;
1195 
1196   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1197   for (auto &DDI : DDIV) {
1198     const DbgValueInst *DI = DDI.getDI();
1199     assert(DI && "Ill-formed DanglingDebugInfo");
1200     DebugLoc dl = DDI.getdl();
1201     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1202     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1203     DILocalVariable *Variable = DI->getVariable();
1204     DIExpression *Expr = DI->getExpression();
1205     assert(Variable->isValidLocationForIntrinsic(dl) &&
1206            "Expected inlined-at fields to agree");
1207     SDDbgValue *SDV;
1208     if (Val.getNode()) {
1209       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1210       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1211       // we couldn't resolve it directly when examining the DbgValue intrinsic
1212       // in the first place we should not be more successful here). Unless we
1213       // have some test case that prove this to be correct we should avoid
1214       // calling EmitFuncArgumentDbgValue here.
1215       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1216         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1217                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1218         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1219         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1220         // inserted after the definition of Val when emitting the instructions
1221         // after ISel. An alternative could be to teach
1222         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1223         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1224                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1225                    << ValSDNodeOrder << "\n");
1226         SDV = getDbgValue(Val, Variable, Expr, dl,
1227                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1228         DAG.AddDbgValue(SDV, Val.getNode(), false);
1229       } else
1230         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1231                           << "in EmitFuncArgumentDbgValue\n");
1232     } else {
1233       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1234       auto Undef =
1235           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1236       auto SDV =
1237           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1238       DAG.AddDbgValue(SDV, nullptr, false);
1239     }
1240   }
1241   DDIV.clear();
1242 }
1243 
1244 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1245   Value *V = DDI.getDI()->getValue();
1246   DILocalVariable *Var = DDI.getDI()->getVariable();
1247   DIExpression *Expr = DDI.getDI()->getExpression();
1248   DebugLoc DL = DDI.getdl();
1249   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1250   unsigned SDOrder = DDI.getSDNodeOrder();
1251 
1252   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1253   // that DW_OP_stack_value is desired.
1254   assert(isa<DbgValueInst>(DDI.getDI()));
1255   bool StackValue = true;
1256 
1257   // Can this Value can be encoded without any further work?
1258   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1259     return;
1260 
1261   // Attempt to salvage back through as many instructions as possible. Bail if
1262   // a non-instruction is seen, such as a constant expression or global
1263   // variable. FIXME: Further work could recover those too.
1264   while (isa<Instruction>(V)) {
1265     Instruction &VAsInst = *cast<Instruction>(V);
1266     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1267 
1268     // If we cannot salvage any further, and haven't yet found a suitable debug
1269     // expression, bail out.
1270     if (!NewExpr)
1271       break;
1272 
1273     // New value and expr now represent this debuginfo.
1274     V = VAsInst.getOperand(0);
1275     Expr = NewExpr;
1276 
1277     // Some kind of simplification occurred: check whether the operand of the
1278     // salvaged debug expression can be encoded in this DAG.
1279     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1280       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1281                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1282       return;
1283     }
1284   }
1285 
1286   // This was the final opportunity to salvage this debug information, and it
1287   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1288   // any earlier variable location.
1289   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1290   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1291   DAG.AddDbgValue(SDV, nullptr, false);
1292 
1293   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1294                     << "\n");
1295   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1296                     << "\n");
1297 }
1298 
1299 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1300                                            DIExpression *Expr, DebugLoc dl,
1301                                            DebugLoc InstDL, unsigned Order) {
1302   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1303   SDDbgValue *SDV;
1304   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1305       isa<ConstantPointerNull>(V)) {
1306     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1307     DAG.AddDbgValue(SDV, nullptr, false);
1308     return true;
1309   }
1310 
1311   // If the Value is a frame index, we can create a FrameIndex debug value
1312   // without relying on the DAG at all.
1313   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1314     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1315     if (SI != FuncInfo.StaticAllocaMap.end()) {
1316       auto SDV =
1317           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1318                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1319       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1320       // is still available even if the SDNode gets optimized out.
1321       DAG.AddDbgValue(SDV, nullptr, false);
1322       return true;
1323     }
1324   }
1325 
1326   // Do not use getValue() in here; we don't want to generate code at
1327   // this point if it hasn't been done yet.
1328   SDValue N = NodeMap[V];
1329   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1330     N = UnusedArgNodeMap[V];
1331   if (N.getNode()) {
1332     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1333       return true;
1334     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1335     DAG.AddDbgValue(SDV, N.getNode(), false);
1336     return true;
1337   }
1338 
1339   // Special rules apply for the first dbg.values of parameter variables in a
1340   // function. Identify them by the fact they reference Argument Values, that
1341   // they're parameters, and they are parameters of the current function. We
1342   // need to let them dangle until they get an SDNode.
1343   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1344                        !InstDL.getInlinedAt();
1345   if (!IsParamOfFunc) {
1346     // The value is not used in this block yet (or it would have an SDNode).
1347     // We still want the value to appear for the user if possible -- if it has
1348     // an associated VReg, we can refer to that instead.
1349     auto VMI = FuncInfo.ValueMap.find(V);
1350     if (VMI != FuncInfo.ValueMap.end()) {
1351       unsigned Reg = VMI->second;
1352       // If this is a PHI node, it may be split up into several MI PHI nodes
1353       // (in FunctionLoweringInfo::set).
1354       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1355                        V->getType(), None);
1356       if (RFV.occupiesMultipleRegs()) {
1357         unsigned Offset = 0;
1358         unsigned BitsToDescribe = 0;
1359         if (auto VarSize = Var->getSizeInBits())
1360           BitsToDescribe = *VarSize;
1361         if (auto Fragment = Expr->getFragmentInfo())
1362           BitsToDescribe = Fragment->SizeInBits;
1363         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1364           unsigned RegisterSize = RegAndSize.second;
1365           // Bail out if all bits are described already.
1366           if (Offset >= BitsToDescribe)
1367             break;
1368           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1369               ? BitsToDescribe - Offset
1370               : RegisterSize;
1371           auto FragmentExpr = DIExpression::createFragmentExpression(
1372               Expr, Offset, FragmentSize);
1373           if (!FragmentExpr)
1374               continue;
1375           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1376                                     false, dl, SDNodeOrder);
1377           DAG.AddDbgValue(SDV, nullptr, false);
1378           Offset += RegisterSize;
1379         }
1380       } else {
1381         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1382         DAG.AddDbgValue(SDV, nullptr, false);
1383       }
1384       return true;
1385     }
1386   }
1387 
1388   return false;
1389 }
1390 
1391 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1392   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1393   for (auto &Pair : DanglingDebugInfoMap)
1394     for (auto &DDI : Pair.second)
1395       salvageUnresolvedDbgValue(DDI);
1396   clearDanglingDebugInfo();
1397 }
1398 
1399 /// getCopyFromRegs - If there was virtual register allocated for the value V
1400 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1401 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1402   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1403   SDValue Result;
1404 
1405   if (It != FuncInfo.ValueMap.end()) {
1406     unsigned InReg = It->second;
1407 
1408     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1409                      DAG.getDataLayout(), InReg, Ty,
1410                      None); // This is not an ABI copy.
1411     SDValue Chain = DAG.getEntryNode();
1412     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1413                                  V);
1414     resolveDanglingDebugInfo(V, Result);
1415   }
1416 
1417   return Result;
1418 }
1419 
1420 /// getValue - Return an SDValue for the given Value.
1421 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1422   // If we already have an SDValue for this value, use it. It's important
1423   // to do this first, so that we don't create a CopyFromReg if we already
1424   // have a regular SDValue.
1425   SDValue &N = NodeMap[V];
1426   if (N.getNode()) return N;
1427 
1428   // If there's a virtual register allocated and initialized for this
1429   // value, use it.
1430   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1431     return copyFromReg;
1432 
1433   // Otherwise create a new SDValue and remember it.
1434   SDValue Val = getValueImpl(V);
1435   NodeMap[V] = Val;
1436   resolveDanglingDebugInfo(V, Val);
1437   return Val;
1438 }
1439 
1440 // Return true if SDValue exists for the given Value
1441 bool SelectionDAGBuilder::findValue(const Value *V) const {
1442   return (NodeMap.find(V) != NodeMap.end()) ||
1443     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1444 }
1445 
1446 /// getNonRegisterValue - Return an SDValue for the given Value, but
1447 /// don't look in FuncInfo.ValueMap for a virtual register.
1448 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1449   // If we already have an SDValue for this value, use it.
1450   SDValue &N = NodeMap[V];
1451   if (N.getNode()) {
1452     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1453       // Remove the debug location from the node as the node is about to be used
1454       // in a location which may differ from the original debug location.  This
1455       // is relevant to Constant and ConstantFP nodes because they can appear
1456       // as constant expressions inside PHI nodes.
1457       N->setDebugLoc(DebugLoc());
1458     }
1459     return N;
1460   }
1461 
1462   // Otherwise create a new SDValue and remember it.
1463   SDValue Val = getValueImpl(V);
1464   NodeMap[V] = Val;
1465   resolveDanglingDebugInfo(V, Val);
1466   return Val;
1467 }
1468 
1469 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1470 /// Create an SDValue for the given value.
1471 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1472   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1473 
1474   if (const Constant *C = dyn_cast<Constant>(V)) {
1475     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1476 
1477     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1478       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1479 
1480     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1481       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1482 
1483     if (isa<ConstantPointerNull>(C)) {
1484       unsigned AS = V->getType()->getPointerAddressSpace();
1485       return DAG.getConstant(0, getCurSDLoc(),
1486                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1487     }
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     unsigned NumElements = VecTy->getNumElements();
1562 
1563     // Now that we know the number and type of the elements, get that number of
1564     // elements into the Ops array based on what kind of constant it is.
1565     SmallVector<SDValue, 16> Ops;
1566     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1567       for (unsigned i = 0; i != NumElements; ++i)
1568         Ops.push_back(getValue(CV->getOperand(i)));
1569     } else {
1570       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1571       EVT EltVT =
1572           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1573 
1574       SDValue Op;
1575       if (EltVT.isFloatingPoint())
1576         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1577       else
1578         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1579       Ops.assign(NumElements, Op);
1580     }
1581 
1582     // Create a BUILD_VECTOR node.
1583     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1584   }
1585 
1586   // If this is a static alloca, generate it as the frameindex instead of
1587   // computation.
1588   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1589     DenseMap<const AllocaInst*, int>::iterator SI =
1590       FuncInfo.StaticAllocaMap.find(AI);
1591     if (SI != FuncInfo.StaticAllocaMap.end())
1592       return DAG.getFrameIndex(SI->second,
1593                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1594   }
1595 
1596   // If this is an instruction which fast-isel has deferred, select it now.
1597   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1598     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1599 
1600     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1601                      Inst->getType(), getABIRegCopyCC(V));
1602     SDValue Chain = DAG.getEntryNode();
1603     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1604   }
1605 
1606   llvm_unreachable("Can't get register for value!");
1607 }
1608 
1609 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1610   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1611   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1612   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1613   bool IsSEH = isAsynchronousEHPersonality(Pers);
1614   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1615   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1616   if (!IsSEH)
1617     CatchPadMBB->setIsEHScopeEntry();
1618   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1619   if (IsMSVCCXX || IsCoreCLR)
1620     CatchPadMBB->setIsEHFuncletEntry();
1621   // Wasm does not need catchpads anymore
1622   if (!IsWasmCXX)
1623     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1624                             getControlRoot()));
1625 }
1626 
1627 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1628   // Update machine-CFG edge.
1629   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1630   FuncInfo.MBB->addSuccessor(TargetMBB);
1631 
1632   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1633   bool IsSEH = isAsynchronousEHPersonality(Pers);
1634   if (IsSEH) {
1635     // If this is not a fall-through branch or optimizations are switched off,
1636     // emit the branch.
1637     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1638         TM.getOptLevel() == CodeGenOpt::None)
1639       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1640                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1641     return;
1642   }
1643 
1644   // Figure out the funclet membership for the catchret's successor.
1645   // This will be used by the FuncletLayout pass to determine how to order the
1646   // BB's.
1647   // A 'catchret' returns to the outer scope's color.
1648   Value *ParentPad = I.getCatchSwitchParentPad();
1649   const BasicBlock *SuccessorColor;
1650   if (isa<ConstantTokenNone>(ParentPad))
1651     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1652   else
1653     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1654   assert(SuccessorColor && "No parent funclet for catchret!");
1655   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1656   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1657 
1658   // Create the terminator node.
1659   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1660                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1661                             DAG.getBasicBlock(SuccessorColorMBB));
1662   DAG.setRoot(Ret);
1663 }
1664 
1665 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1666   // Don't emit any special code for the cleanuppad instruction. It just marks
1667   // the start of an EH scope/funclet.
1668   FuncInfo.MBB->setIsEHScopeEntry();
1669   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1670   if (Pers != EHPersonality::Wasm_CXX) {
1671     FuncInfo.MBB->setIsEHFuncletEntry();
1672     FuncInfo.MBB->setIsCleanupFuncletEntry();
1673   }
1674 }
1675 
1676 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1677 // the control flow always stops at the single catch pad, as it does for a
1678 // cleanup pad. In case the exception caught is not of the types the catch pad
1679 // catches, it will be rethrown by a rethrow.
1680 static void findWasmUnwindDestinations(
1681     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1682     BranchProbability Prob,
1683     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1684         &UnwindDests) {
1685   while (EHPadBB) {
1686     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1687     if (isa<CleanupPadInst>(Pad)) {
1688       // Stop on cleanup pads.
1689       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1690       UnwindDests.back().first->setIsEHScopeEntry();
1691       break;
1692     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1693       // Add the catchpad handlers to the possible destinations. We don't
1694       // continue to the unwind destination of the catchswitch for wasm.
1695       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1696         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1697         UnwindDests.back().first->setIsEHScopeEntry();
1698       }
1699       break;
1700     } else {
1701       continue;
1702     }
1703   }
1704 }
1705 
1706 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1707 /// many places it could ultimately go. In the IR, we have a single unwind
1708 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1709 /// This function skips over imaginary basic blocks that hold catchswitch
1710 /// instructions, and finds all the "real" machine
1711 /// basic block destinations. As those destinations may not be successors of
1712 /// EHPadBB, here we also calculate the edge probability to those destinations.
1713 /// The passed-in Prob is the edge probability to EHPadBB.
1714 static void findUnwindDestinations(
1715     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1716     BranchProbability Prob,
1717     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1718         &UnwindDests) {
1719   EHPersonality Personality =
1720     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1721   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1722   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1723   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1724   bool IsSEH = isAsynchronousEHPersonality(Personality);
1725 
1726   if (IsWasmCXX) {
1727     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1728     assert(UnwindDests.size() <= 1 &&
1729            "There should be at most one unwind destination for wasm");
1730     return;
1731   }
1732 
1733   while (EHPadBB) {
1734     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1735     BasicBlock *NewEHPadBB = nullptr;
1736     if (isa<LandingPadInst>(Pad)) {
1737       // Stop on landingpads. They are not funclets.
1738       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1739       break;
1740     } else if (isa<CleanupPadInst>(Pad)) {
1741       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1742       // personalities.
1743       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1744       UnwindDests.back().first->setIsEHScopeEntry();
1745       UnwindDests.back().first->setIsEHFuncletEntry();
1746       break;
1747     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1748       // Add the catchpad handlers to the possible destinations.
1749       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1750         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1751         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1752         if (IsMSVCCXX || IsCoreCLR)
1753           UnwindDests.back().first->setIsEHFuncletEntry();
1754         if (!IsSEH)
1755           UnwindDests.back().first->setIsEHScopeEntry();
1756       }
1757       NewEHPadBB = CatchSwitch->getUnwindDest();
1758     } else {
1759       continue;
1760     }
1761 
1762     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1763     if (BPI && NewEHPadBB)
1764       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1765     EHPadBB = NewEHPadBB;
1766   }
1767 }
1768 
1769 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1770   // Update successor info.
1771   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1772   auto UnwindDest = I.getUnwindDest();
1773   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1774   BranchProbability UnwindDestProb =
1775       (BPI && UnwindDest)
1776           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1777           : BranchProbability::getZero();
1778   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1779   for (auto &UnwindDest : UnwindDests) {
1780     UnwindDest.first->setIsEHPad();
1781     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1782   }
1783   FuncInfo.MBB->normalizeSuccProbs();
1784 
1785   // Create the terminator node.
1786   SDValue Ret =
1787       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1788   DAG.setRoot(Ret);
1789 }
1790 
1791 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1792   report_fatal_error("visitCatchSwitch not yet implemented!");
1793 }
1794 
1795 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1797   auto &DL = DAG.getDataLayout();
1798   SDValue Chain = getControlRoot();
1799   SmallVector<ISD::OutputArg, 8> Outs;
1800   SmallVector<SDValue, 8> OutVals;
1801 
1802   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1803   // lower
1804   //
1805   //   %val = call <ty> @llvm.experimental.deoptimize()
1806   //   ret <ty> %val
1807   //
1808   // differently.
1809   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1810     LowerDeoptimizingReturn();
1811     return;
1812   }
1813 
1814   if (!FuncInfo.CanLowerReturn) {
1815     unsigned DemoteReg = FuncInfo.DemoteRegister;
1816     const Function *F = I.getParent()->getParent();
1817 
1818     // Emit a store of the return value through the virtual register.
1819     // Leave Outs empty so that LowerReturn won't try to load return
1820     // registers the usual way.
1821     SmallVector<EVT, 1> PtrValueVTs;
1822     ComputeValueVTs(TLI, DL,
1823                     F->getReturnType()->getPointerTo(
1824                         DAG.getDataLayout().getAllocaAddrSpace()),
1825                     PtrValueVTs);
1826 
1827     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1828                                         DemoteReg, PtrValueVTs[0]);
1829     SDValue RetOp = getValue(I.getOperand(0));
1830 
1831     SmallVector<EVT, 4> ValueVTs, MemVTs;
1832     SmallVector<uint64_t, 4> Offsets;
1833     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1834                     &Offsets);
1835     unsigned NumValues = ValueVTs.size();
1836 
1837     SmallVector<SDValue, 4> Chains(NumValues);
1838     for (unsigned i = 0; i != NumValues; ++i) {
1839       // An aggregate return value cannot wrap around the address space, so
1840       // offsets to its parts don't wrap either.
1841       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1842 
1843       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1844       if (MemVTs[i] != ValueVTs[i])
1845         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1846       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1847           // FIXME: better loc info would be nice.
1848           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1849     }
1850 
1851     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1852                         MVT::Other, Chains);
1853   } else if (I.getNumOperands() != 0) {
1854     SmallVector<EVT, 4> ValueVTs;
1855     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1856     unsigned NumValues = ValueVTs.size();
1857     if (NumValues) {
1858       SDValue RetOp = getValue(I.getOperand(0));
1859 
1860       const Function *F = I.getParent()->getParent();
1861 
1862       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1863           I.getOperand(0)->getType(), F->getCallingConv(),
1864           /*IsVarArg*/ false);
1865 
1866       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1867       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1868                                           Attribute::SExt))
1869         ExtendKind = ISD::SIGN_EXTEND;
1870       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1871                                                Attribute::ZExt))
1872         ExtendKind = ISD::ZERO_EXTEND;
1873 
1874       LLVMContext &Context = F->getContext();
1875       bool RetInReg = F->getAttributes().hasAttribute(
1876           AttributeList::ReturnIndex, Attribute::InReg);
1877 
1878       for (unsigned j = 0; j != NumValues; ++j) {
1879         EVT VT = ValueVTs[j];
1880 
1881         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1882           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1883 
1884         CallingConv::ID CC = F->getCallingConv();
1885 
1886         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1887         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1888         SmallVector<SDValue, 4> Parts(NumParts);
1889         getCopyToParts(DAG, getCurSDLoc(),
1890                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1891                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1892 
1893         // 'inreg' on function refers to return value
1894         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1895         if (RetInReg)
1896           Flags.setInReg();
1897 
1898         if (I.getOperand(0)->getType()->isPointerTy()) {
1899           Flags.setPointer();
1900           Flags.setPointerAddrSpace(
1901               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1902         }
1903 
1904         if (NeedsRegBlock) {
1905           Flags.setInConsecutiveRegs();
1906           if (j == NumValues - 1)
1907             Flags.setInConsecutiveRegsLast();
1908         }
1909 
1910         // Propagate extension type if any
1911         if (ExtendKind == ISD::SIGN_EXTEND)
1912           Flags.setSExt();
1913         else if (ExtendKind == ISD::ZERO_EXTEND)
1914           Flags.setZExt();
1915 
1916         for (unsigned i = 0; i < NumParts; ++i) {
1917           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1918                                         VT, /*isfixed=*/true, 0, 0));
1919           OutVals.push_back(Parts[i]);
1920         }
1921       }
1922     }
1923   }
1924 
1925   // Push in swifterror virtual register as the last element of Outs. This makes
1926   // sure swifterror virtual register will be returned in the swifterror
1927   // physical register.
1928   const Function *F = I.getParent()->getParent();
1929   if (TLI.supportSwiftError() &&
1930       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1931     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1932     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1933     Flags.setSwiftError();
1934     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1935                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1936                                   true /*isfixed*/, 1 /*origidx*/,
1937                                   0 /*partOffs*/));
1938     // Create SDNode for the swifterror virtual register.
1939     OutVals.push_back(
1940         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1941                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1942                         EVT(TLI.getPointerTy(DL))));
1943   }
1944 
1945   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1946   CallingConv::ID CallConv =
1947     DAG.getMachineFunction().getFunction().getCallingConv();
1948   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1949       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1950 
1951   // Verify that the target's LowerReturn behaved as expected.
1952   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1953          "LowerReturn didn't return a valid chain!");
1954 
1955   // Update the DAG with the new chain value resulting from return lowering.
1956   DAG.setRoot(Chain);
1957 }
1958 
1959 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1960 /// created for it, emit nodes to copy the value into the virtual
1961 /// registers.
1962 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1963   // Skip empty types
1964   if (V->getType()->isEmptyTy())
1965     return;
1966 
1967   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1968   if (VMI != FuncInfo.ValueMap.end()) {
1969     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1970     CopyValueToVirtualRegister(V, VMI->second);
1971   }
1972 }
1973 
1974 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1975 /// the current basic block, add it to ValueMap now so that we'll get a
1976 /// CopyTo/FromReg.
1977 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1978   // No need to export constants.
1979   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1980 
1981   // Already exported?
1982   if (FuncInfo.isExportedInst(V)) return;
1983 
1984   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1985   CopyValueToVirtualRegister(V, Reg);
1986 }
1987 
1988 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1989                                                      const BasicBlock *FromBB) {
1990   // The operands of the setcc have to be in this block.  We don't know
1991   // how to export them from some other block.
1992   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1993     // Can export from current BB.
1994     if (VI->getParent() == FromBB)
1995       return true;
1996 
1997     // Is already exported, noop.
1998     return FuncInfo.isExportedInst(V);
1999   }
2000 
2001   // If this is an argument, we can export it if the BB is the entry block or
2002   // if it is already exported.
2003   if (isa<Argument>(V)) {
2004     if (FromBB == &FromBB->getParent()->getEntryBlock())
2005       return true;
2006 
2007     // Otherwise, can only export this if it is already exported.
2008     return FuncInfo.isExportedInst(V);
2009   }
2010 
2011   // Otherwise, constants can always be exported.
2012   return true;
2013 }
2014 
2015 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2016 BranchProbability
2017 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2018                                         const MachineBasicBlock *Dst) const {
2019   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2020   const BasicBlock *SrcBB = Src->getBasicBlock();
2021   const BasicBlock *DstBB = Dst->getBasicBlock();
2022   if (!BPI) {
2023     // If BPI is not available, set the default probability as 1 / N, where N is
2024     // the number of successors.
2025     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2026     return BranchProbability(1, SuccSize);
2027   }
2028   return BPI->getEdgeProbability(SrcBB, DstBB);
2029 }
2030 
2031 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2032                                                MachineBasicBlock *Dst,
2033                                                BranchProbability Prob) {
2034   if (!FuncInfo.BPI)
2035     Src->addSuccessorWithoutProb(Dst);
2036   else {
2037     if (Prob.isUnknown())
2038       Prob = getEdgeProbability(Src, Dst);
2039     Src->addSuccessor(Dst, Prob);
2040   }
2041 }
2042 
2043 static bool InBlock(const Value *V, const BasicBlock *BB) {
2044   if (const Instruction *I = dyn_cast<Instruction>(V))
2045     return I->getParent() == BB;
2046   return true;
2047 }
2048 
2049 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2050 /// This function emits a branch and is used at the leaves of an OR or an
2051 /// AND operator tree.
2052 void
2053 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2054                                                   MachineBasicBlock *TBB,
2055                                                   MachineBasicBlock *FBB,
2056                                                   MachineBasicBlock *CurBB,
2057                                                   MachineBasicBlock *SwitchBB,
2058                                                   BranchProbability TProb,
2059                                                   BranchProbability FProb,
2060                                                   bool InvertCond) {
2061   const BasicBlock *BB = CurBB->getBasicBlock();
2062 
2063   // If the leaf of the tree is a comparison, merge the condition into
2064   // the caseblock.
2065   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2066     // The operands of the cmp have to be in this block.  We don't know
2067     // how to export them from some other block.  If this is the first block
2068     // of the sequence, no exporting is needed.
2069     if (CurBB == SwitchBB ||
2070         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2071          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2072       ISD::CondCode Condition;
2073       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2074         ICmpInst::Predicate Pred =
2075             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2076         Condition = getICmpCondCode(Pred);
2077       } else {
2078         const FCmpInst *FC = cast<FCmpInst>(Cond);
2079         FCmpInst::Predicate Pred =
2080             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2081         Condition = getFCmpCondCode(Pred);
2082         if (TM.Options.NoNaNsFPMath)
2083           Condition = getFCmpCodeWithoutNaN(Condition);
2084       }
2085 
2086       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2087                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2088       SL->SwitchCases.push_back(CB);
2089       return;
2090     }
2091   }
2092 
2093   // Create a CaseBlock record representing this branch.
2094   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2095   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2096                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2097   SL->SwitchCases.push_back(CB);
2098 }
2099 
2100 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2101                                                MachineBasicBlock *TBB,
2102                                                MachineBasicBlock *FBB,
2103                                                MachineBasicBlock *CurBB,
2104                                                MachineBasicBlock *SwitchBB,
2105                                                Instruction::BinaryOps Opc,
2106                                                BranchProbability TProb,
2107                                                BranchProbability FProb,
2108                                                bool InvertCond) {
2109   // Skip over not part of the tree and remember to invert op and operands at
2110   // next level.
2111   Value *NotCond;
2112   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2113       InBlock(NotCond, CurBB->getBasicBlock())) {
2114     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2115                          !InvertCond);
2116     return;
2117   }
2118 
2119   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2120   // Compute the effective opcode for Cond, taking into account whether it needs
2121   // to be inverted, e.g.
2122   //   and (not (or A, B)), C
2123   // gets lowered as
2124   //   and (and (not A, not B), C)
2125   unsigned BOpc = 0;
2126   if (BOp) {
2127     BOpc = BOp->getOpcode();
2128     if (InvertCond) {
2129       if (BOpc == Instruction::And)
2130         BOpc = Instruction::Or;
2131       else if (BOpc == Instruction::Or)
2132         BOpc = Instruction::And;
2133     }
2134   }
2135 
2136   // If this node is not part of the or/and tree, emit it as a branch.
2137   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2138       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2139       BOp->getParent() != CurBB->getBasicBlock() ||
2140       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2141       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2142     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2143                                  TProb, FProb, InvertCond);
2144     return;
2145   }
2146 
2147   //  Create TmpBB after CurBB.
2148   MachineFunction::iterator BBI(CurBB);
2149   MachineFunction &MF = DAG.getMachineFunction();
2150   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2151   CurBB->getParent()->insert(++BBI, TmpBB);
2152 
2153   if (Opc == Instruction::Or) {
2154     // Codegen X | Y as:
2155     // BB1:
2156     //   jmp_if_X TBB
2157     //   jmp TmpBB
2158     // TmpBB:
2159     //   jmp_if_Y TBB
2160     //   jmp FBB
2161     //
2162 
2163     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2164     // The requirement is that
2165     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2166     //     = TrueProb for original BB.
2167     // Assuming the original probabilities are A and B, one choice is to set
2168     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2169     // A/(1+B) and 2B/(1+B). This choice assumes that
2170     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2171     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2172     // TmpBB, but the math is more complicated.
2173 
2174     auto NewTrueProb = TProb / 2;
2175     auto NewFalseProb = TProb / 2 + FProb;
2176     // Emit the LHS condition.
2177     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2178                          NewTrueProb, NewFalseProb, InvertCond);
2179 
2180     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2181     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2182     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2183     // Emit the RHS condition into TmpBB.
2184     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2185                          Probs[0], Probs[1], InvertCond);
2186   } else {
2187     assert(Opc == Instruction::And && "Unknown merge op!");
2188     // Codegen X & Y as:
2189     // BB1:
2190     //   jmp_if_X TmpBB
2191     //   jmp FBB
2192     // TmpBB:
2193     //   jmp_if_Y TBB
2194     //   jmp FBB
2195     //
2196     //  This requires creation of TmpBB after CurBB.
2197 
2198     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2199     // The requirement is that
2200     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2201     //     = FalseProb for original BB.
2202     // Assuming the original probabilities are A and B, one choice is to set
2203     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2204     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2205     // TrueProb for BB1 * FalseProb for TmpBB.
2206 
2207     auto NewTrueProb = TProb + FProb / 2;
2208     auto NewFalseProb = FProb / 2;
2209     // Emit the LHS condition.
2210     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2211                          NewTrueProb, NewFalseProb, InvertCond);
2212 
2213     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2214     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2215     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2216     // Emit the RHS condition into TmpBB.
2217     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2218                          Probs[0], Probs[1], InvertCond);
2219   }
2220 }
2221 
2222 /// If the set of cases should be emitted as a series of branches, return true.
2223 /// If we should emit this as a bunch of and/or'd together conditions, return
2224 /// false.
2225 bool
2226 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2227   if (Cases.size() != 2) return true;
2228 
2229   // If this is two comparisons of the same values or'd or and'd together, they
2230   // will get folded into a single comparison, so don't emit two blocks.
2231   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2232        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2233       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2234        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2235     return false;
2236   }
2237 
2238   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2239   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2240   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2241       Cases[0].CC == Cases[1].CC &&
2242       isa<Constant>(Cases[0].CmpRHS) &&
2243       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2244     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2245       return false;
2246     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2247       return false;
2248   }
2249 
2250   return true;
2251 }
2252 
2253 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2254   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2255 
2256   // Update machine-CFG edges.
2257   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2258 
2259   if (I.isUnconditional()) {
2260     // Update machine-CFG edges.
2261     BrMBB->addSuccessor(Succ0MBB);
2262 
2263     // If this is not a fall-through branch or optimizations are switched off,
2264     // emit the branch.
2265     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2266       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2267                               MVT::Other, getControlRoot(),
2268                               DAG.getBasicBlock(Succ0MBB)));
2269 
2270     return;
2271   }
2272 
2273   // If this condition is one of the special cases we handle, do special stuff
2274   // now.
2275   const Value *CondVal = I.getCondition();
2276   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2277 
2278   // If this is a series of conditions that are or'd or and'd together, emit
2279   // this as a sequence of branches instead of setcc's with and/or operations.
2280   // As long as jumps are not expensive, this should improve performance.
2281   // For example, instead of something like:
2282   //     cmp A, B
2283   //     C = seteq
2284   //     cmp D, E
2285   //     F = setle
2286   //     or C, F
2287   //     jnz foo
2288   // Emit:
2289   //     cmp A, B
2290   //     je foo
2291   //     cmp D, E
2292   //     jle foo
2293   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2294     Instruction::BinaryOps Opcode = BOp->getOpcode();
2295     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2296         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2297         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2298       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2299                            Opcode,
2300                            getEdgeProbability(BrMBB, Succ0MBB),
2301                            getEdgeProbability(BrMBB, Succ1MBB),
2302                            /*InvertCond=*/false);
2303       // If the compares in later blocks need to use values not currently
2304       // exported from this block, export them now.  This block should always
2305       // be the first entry.
2306       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2307 
2308       // Allow some cases to be rejected.
2309       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2310         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2311           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2312           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2313         }
2314 
2315         // Emit the branch for this block.
2316         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2317         SL->SwitchCases.erase(SL->SwitchCases.begin());
2318         return;
2319       }
2320 
2321       // Okay, we decided not to do this, remove any inserted MBB's and clear
2322       // SwitchCases.
2323       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2324         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2325 
2326       SL->SwitchCases.clear();
2327     }
2328   }
2329 
2330   // Create a CaseBlock record representing this branch.
2331   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2332                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2333 
2334   // Use visitSwitchCase to actually insert the fast branch sequence for this
2335   // cond branch.
2336   visitSwitchCase(CB, BrMBB);
2337 }
2338 
2339 /// visitSwitchCase - Emits the necessary code to represent a single node in
2340 /// the binary search tree resulting from lowering a switch instruction.
2341 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2342                                           MachineBasicBlock *SwitchBB) {
2343   SDValue Cond;
2344   SDValue CondLHS = getValue(CB.CmpLHS);
2345   SDLoc dl = CB.DL;
2346 
2347   if (CB.CC == ISD::SETTRUE) {
2348     // Branch or fall through to TrueBB.
2349     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2350     SwitchBB->normalizeSuccProbs();
2351     if (CB.TrueBB != NextBlock(SwitchBB)) {
2352       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2353                               DAG.getBasicBlock(CB.TrueBB)));
2354     }
2355     return;
2356   }
2357 
2358   auto &TLI = DAG.getTargetLoweringInfo();
2359   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2360 
2361   // Build the setcc now.
2362   if (!CB.CmpMHS) {
2363     // Fold "(X == true)" to X and "(X == false)" to !X to
2364     // handle common cases produced by branch lowering.
2365     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2366         CB.CC == ISD::SETEQ)
2367       Cond = CondLHS;
2368     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2369              CB.CC == ISD::SETEQ) {
2370       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2371       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2372     } else {
2373       SDValue CondRHS = getValue(CB.CmpRHS);
2374 
2375       // If a pointer's DAG type is larger than its memory type then the DAG
2376       // values are zero-extended. This breaks signed comparisons so truncate
2377       // back to the underlying type before doing the compare.
2378       if (CondLHS.getValueType() != MemVT) {
2379         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2380         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2381       }
2382       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2383     }
2384   } else {
2385     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2386 
2387     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2388     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2389 
2390     SDValue CmpOp = getValue(CB.CmpMHS);
2391     EVT VT = CmpOp.getValueType();
2392 
2393     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2394       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2395                           ISD::SETLE);
2396     } else {
2397       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2398                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2399       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2400                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2401     }
2402   }
2403 
2404   // Update successor info
2405   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2406   // TrueBB and FalseBB are always different unless the incoming IR is
2407   // degenerate. This only happens when running llc on weird IR.
2408   if (CB.TrueBB != CB.FalseBB)
2409     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2410   SwitchBB->normalizeSuccProbs();
2411 
2412   // If the lhs block is the next block, invert the condition so that we can
2413   // fall through to the lhs instead of the rhs block.
2414   if (CB.TrueBB == NextBlock(SwitchBB)) {
2415     std::swap(CB.TrueBB, CB.FalseBB);
2416     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2417     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2418   }
2419 
2420   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2421                                MVT::Other, getControlRoot(), Cond,
2422                                DAG.getBasicBlock(CB.TrueBB));
2423 
2424   // Insert the false branch. Do this even if it's a fall through branch,
2425   // this makes it easier to do DAG optimizations which require inverting
2426   // the branch condition.
2427   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2428                        DAG.getBasicBlock(CB.FalseBB));
2429 
2430   DAG.setRoot(BrCond);
2431 }
2432 
2433 /// visitJumpTable - Emit JumpTable node in the current MBB
2434 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2435   // Emit the code for the jump table
2436   assert(JT.Reg != -1U && "Should lower JT Header first!");
2437   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2438   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2439                                      JT.Reg, PTy);
2440   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2441   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2442                                     MVT::Other, Index.getValue(1),
2443                                     Table, Index);
2444   DAG.setRoot(BrJumpTable);
2445 }
2446 
2447 /// visitJumpTableHeader - This function emits necessary code to produce index
2448 /// in the JumpTable from switch case.
2449 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2450                                                JumpTableHeader &JTH,
2451                                                MachineBasicBlock *SwitchBB) {
2452   SDLoc dl = getCurSDLoc();
2453 
2454   // Subtract the lowest switch case value from the value being switched on.
2455   SDValue SwitchOp = getValue(JTH.SValue);
2456   EVT VT = SwitchOp.getValueType();
2457   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2458                             DAG.getConstant(JTH.First, dl, VT));
2459 
2460   // The SDNode we just created, which holds the value being switched on minus
2461   // the smallest case value, needs to be copied to a virtual register so it
2462   // can be used as an index into the jump table in a subsequent basic block.
2463   // This value may be smaller or larger than the target's pointer type, and
2464   // therefore require extension or truncating.
2465   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2466   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2467 
2468   unsigned JumpTableReg =
2469       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2470   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2471                                     JumpTableReg, SwitchOp);
2472   JT.Reg = JumpTableReg;
2473 
2474   if (!JTH.OmitRangeCheck) {
2475     // Emit the range check for the jump table, and branch to the default block
2476     // for the switch statement if the value being switched on exceeds the
2477     // largest case in the switch.
2478     SDValue CMP = DAG.getSetCC(
2479         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2480                                    Sub.getValueType()),
2481         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2482 
2483     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2484                                  MVT::Other, CopyTo, CMP,
2485                                  DAG.getBasicBlock(JT.Default));
2486 
2487     // Avoid emitting unnecessary branches to the next block.
2488     if (JT.MBB != NextBlock(SwitchBB))
2489       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2490                            DAG.getBasicBlock(JT.MBB));
2491 
2492     DAG.setRoot(BrCond);
2493   } else {
2494     // Avoid emitting unnecessary branches to the next block.
2495     if (JT.MBB != NextBlock(SwitchBB))
2496       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2497                               DAG.getBasicBlock(JT.MBB)));
2498     else
2499       DAG.setRoot(CopyTo);
2500   }
2501 }
2502 
2503 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2504 /// variable if there exists one.
2505 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2506                                  SDValue &Chain) {
2507   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2508   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2509   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2510   MachineFunction &MF = DAG.getMachineFunction();
2511   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2512   MachineSDNode *Node =
2513       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2514   if (Global) {
2515     MachinePointerInfo MPInfo(Global);
2516     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2517                  MachineMemOperand::MODereferenceable;
2518     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2519         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2520     DAG.setNodeMemRefs(Node, {MemRef});
2521   }
2522   if (PtrTy != PtrMemTy)
2523     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2524   return SDValue(Node, 0);
2525 }
2526 
2527 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2528 /// tail spliced into a stack protector check success bb.
2529 ///
2530 /// For a high level explanation of how this fits into the stack protector
2531 /// generation see the comment on the declaration of class
2532 /// StackProtectorDescriptor.
2533 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2534                                                   MachineBasicBlock *ParentBB) {
2535 
2536   // First create the loads to the guard/stack slot for the comparison.
2537   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2538   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2539   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2540 
2541   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2542   int FI = MFI.getStackProtectorIndex();
2543 
2544   SDValue Guard;
2545   SDLoc dl = getCurSDLoc();
2546   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2547   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2548   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2549 
2550   // Generate code to load the content of the guard slot.
2551   SDValue GuardVal = DAG.getLoad(
2552       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2553       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2554       MachineMemOperand::MOVolatile);
2555 
2556   if (TLI.useStackGuardXorFP())
2557     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2558 
2559   // Retrieve guard check function, nullptr if instrumentation is inlined.
2560   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2561     // The target provides a guard check function to validate the guard value.
2562     // Generate a call to that function with the content of the guard slot as
2563     // argument.
2564     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2565     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2566 
2567     TargetLowering::ArgListTy Args;
2568     TargetLowering::ArgListEntry Entry;
2569     Entry.Node = GuardVal;
2570     Entry.Ty = FnTy->getParamType(0);
2571     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2572       Entry.IsInReg = true;
2573     Args.push_back(Entry);
2574 
2575     TargetLowering::CallLoweringInfo CLI(DAG);
2576     CLI.setDebugLoc(getCurSDLoc())
2577         .setChain(DAG.getEntryNode())
2578         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2579                    getValue(GuardCheckFn), std::move(Args));
2580 
2581     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2582     DAG.setRoot(Result.second);
2583     return;
2584   }
2585 
2586   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2587   // Otherwise, emit a volatile load to retrieve the stack guard value.
2588   SDValue Chain = DAG.getEntryNode();
2589   if (TLI.useLoadStackGuardNode()) {
2590     Guard = getLoadStackGuard(DAG, dl, Chain);
2591   } else {
2592     const Value *IRGuard = TLI.getSDagStackGuard(M);
2593     SDValue GuardPtr = getValue(IRGuard);
2594 
2595     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2596                         MachinePointerInfo(IRGuard, 0), Align,
2597                         MachineMemOperand::MOVolatile);
2598   }
2599 
2600   // Perform the comparison via a subtract/getsetcc.
2601   EVT VT = Guard.getValueType();
2602   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2603 
2604   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2605                                                         *DAG.getContext(),
2606                                                         Sub.getValueType()),
2607                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2608 
2609   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2610   // branch to failure MBB.
2611   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2612                                MVT::Other, GuardVal.getOperand(0),
2613                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2614   // Otherwise branch to success MBB.
2615   SDValue Br = DAG.getNode(ISD::BR, dl,
2616                            MVT::Other, BrCond,
2617                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2618 
2619   DAG.setRoot(Br);
2620 }
2621 
2622 /// Codegen the failure basic block for a stack protector check.
2623 ///
2624 /// A failure stack protector machine basic block consists simply of a call to
2625 /// __stack_chk_fail().
2626 ///
2627 /// For a high level explanation of how this fits into the stack protector
2628 /// generation see the comment on the declaration of class
2629 /// StackProtectorDescriptor.
2630 void
2631 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2633   TargetLowering::MakeLibCallOptions CallOptions;
2634   CallOptions.setDiscardResult(true);
2635   SDValue Chain =
2636       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2637                       None, CallOptions, getCurSDLoc()).second;
2638   // On PS4, the "return address" must still be within the calling function,
2639   // even if it's at the very end, so emit an explicit TRAP here.
2640   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2641   if (TM.getTargetTriple().isPS4CPU())
2642     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2643 
2644   DAG.setRoot(Chain);
2645 }
2646 
2647 /// visitBitTestHeader - This function emits necessary code to produce value
2648 /// suitable for "bit tests"
2649 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2650                                              MachineBasicBlock *SwitchBB) {
2651   SDLoc dl = getCurSDLoc();
2652 
2653   // Subtract the minimum value.
2654   SDValue SwitchOp = getValue(B.SValue);
2655   EVT VT = SwitchOp.getValueType();
2656   SDValue RangeSub =
2657       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2658 
2659   // Determine the type of the test operands.
2660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2661   bool UsePtrType = false;
2662   if (!TLI.isTypeLegal(VT)) {
2663     UsePtrType = true;
2664   } else {
2665     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2666       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2667         // Switch table case range are encoded into series of masks.
2668         // Just use pointer type, it's guaranteed to fit.
2669         UsePtrType = true;
2670         break;
2671       }
2672   }
2673   SDValue Sub = RangeSub;
2674   if (UsePtrType) {
2675     VT = TLI.getPointerTy(DAG.getDataLayout());
2676     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2677   }
2678 
2679   B.RegVT = VT.getSimpleVT();
2680   B.Reg = FuncInfo.CreateReg(B.RegVT);
2681   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2682 
2683   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2684 
2685   if (!B.OmitRangeCheck)
2686     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2687   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2688   SwitchBB->normalizeSuccProbs();
2689 
2690   SDValue Root = CopyTo;
2691   if (!B.OmitRangeCheck) {
2692     // Conditional branch to the default block.
2693     SDValue RangeCmp = DAG.getSetCC(dl,
2694         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2695                                RangeSub.getValueType()),
2696         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2697         ISD::SETUGT);
2698 
2699     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2700                        DAG.getBasicBlock(B.Default));
2701   }
2702 
2703   // Avoid emitting unnecessary branches to the next block.
2704   if (MBB != NextBlock(SwitchBB))
2705     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2706 
2707   DAG.setRoot(Root);
2708 }
2709 
2710 /// visitBitTestCase - this function produces one "bit test"
2711 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2712                                            MachineBasicBlock* NextMBB,
2713                                            BranchProbability BranchProbToNext,
2714                                            unsigned Reg,
2715                                            BitTestCase &B,
2716                                            MachineBasicBlock *SwitchBB) {
2717   SDLoc dl = getCurSDLoc();
2718   MVT VT = BB.RegVT;
2719   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2720   SDValue Cmp;
2721   unsigned PopCount = countPopulation(B.Mask);
2722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2723   if (PopCount == 1) {
2724     // Testing for a single bit; just compare the shift count with what it
2725     // would need to be to shift a 1 bit in that position.
2726     Cmp = DAG.getSetCC(
2727         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2728         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2729         ISD::SETEQ);
2730   } else if (PopCount == BB.Range) {
2731     // There is only one zero bit in the range, test for it directly.
2732     Cmp = DAG.getSetCC(
2733         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2734         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2735         ISD::SETNE);
2736   } else {
2737     // Make desired shift
2738     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2739                                     DAG.getConstant(1, dl, VT), ShiftOp);
2740 
2741     // Emit bit tests and jumps
2742     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2743                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2744     Cmp = DAG.getSetCC(
2745         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2746         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2747   }
2748 
2749   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2750   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2751   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2752   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2753   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2754   // one as they are relative probabilities (and thus work more like weights),
2755   // and hence we need to normalize them to let the sum of them become one.
2756   SwitchBB->normalizeSuccProbs();
2757 
2758   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2759                               MVT::Other, getControlRoot(),
2760                               Cmp, DAG.getBasicBlock(B.TargetBB));
2761 
2762   // Avoid emitting unnecessary branches to the next block.
2763   if (NextMBB != NextBlock(SwitchBB))
2764     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2765                         DAG.getBasicBlock(NextMBB));
2766 
2767   DAG.setRoot(BrAnd);
2768 }
2769 
2770 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2771   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2772 
2773   // Retrieve successors. Look through artificial IR level blocks like
2774   // catchswitch for successors.
2775   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2776   const BasicBlock *EHPadBB = I.getSuccessor(1);
2777 
2778   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2779   // have to do anything here to lower funclet bundles.
2780   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2781                                         LLVMContext::OB_funclet,
2782                                         LLVMContext::OB_cfguardtarget}) &&
2783          "Cannot lower invokes with arbitrary operand bundles yet!");
2784 
2785   const Value *Callee(I.getCalledValue());
2786   const Function *Fn = dyn_cast<Function>(Callee);
2787   if (isa<InlineAsm>(Callee))
2788     visitInlineAsm(&I);
2789   else if (Fn && Fn->isIntrinsic()) {
2790     switch (Fn->getIntrinsicID()) {
2791     default:
2792       llvm_unreachable("Cannot invoke this intrinsic");
2793     case Intrinsic::donothing:
2794       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2795       break;
2796     case Intrinsic::experimental_patchpoint_void:
2797     case Intrinsic::experimental_patchpoint_i64:
2798       visitPatchpoint(&I, EHPadBB);
2799       break;
2800     case Intrinsic::experimental_gc_statepoint:
2801       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2802       break;
2803     case Intrinsic::wasm_rethrow_in_catch: {
2804       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2805       // special because it can be invoked, so we manually lower it to a DAG
2806       // node here.
2807       SmallVector<SDValue, 8> Ops;
2808       Ops.push_back(getRoot()); // inchain
2809       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2810       Ops.push_back(
2811           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2812                                 TLI.getPointerTy(DAG.getDataLayout())));
2813       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2814       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2815       break;
2816     }
2817     }
2818   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2819     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2820     // Eventually we will support lowering the @llvm.experimental.deoptimize
2821     // intrinsic, and right now there are no plans to support other intrinsics
2822     // with deopt state.
2823     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2824   } else {
2825     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2826   }
2827 
2828   // If the value of the invoke is used outside of its defining block, make it
2829   // available as a virtual register.
2830   // We already took care of the exported value for the statepoint instruction
2831   // during call to the LowerStatepoint.
2832   if (!isStatepoint(I)) {
2833     CopyToExportRegsIfNeeded(&I);
2834   }
2835 
2836   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2837   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2838   BranchProbability EHPadBBProb =
2839       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2840           : BranchProbability::getZero();
2841   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2842 
2843   // Update successor info.
2844   addSuccessorWithProb(InvokeMBB, Return);
2845   for (auto &UnwindDest : UnwindDests) {
2846     UnwindDest.first->setIsEHPad();
2847     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2848   }
2849   InvokeMBB->normalizeSuccProbs();
2850 
2851   // Drop into normal successor.
2852   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2853                           DAG.getBasicBlock(Return)));
2854 }
2855 
2856 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2857   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2858 
2859   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2860   // have to do anything here to lower funclet bundles.
2861   assert(!I.hasOperandBundlesOtherThan(
2862              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2863          "Cannot lower callbrs with arbitrary operand bundles yet!");
2864 
2865   assert(isa<InlineAsm>(I.getCalledValue()) &&
2866          "Only know how to handle inlineasm callbr");
2867   visitInlineAsm(&I);
2868 
2869   // Retrieve successors.
2870   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2871 
2872   // Update successor info.
2873   addSuccessorWithProb(CallBrMBB, Return);
2874   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2875     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2876     addSuccessorWithProb(CallBrMBB, Target);
2877   }
2878   CallBrMBB->normalizeSuccProbs();
2879 
2880   // Drop into default successor.
2881   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2882                           MVT::Other, getControlRoot(),
2883                           DAG.getBasicBlock(Return)));
2884 }
2885 
2886 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2887   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2888 }
2889 
2890 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2891   assert(FuncInfo.MBB->isEHPad() &&
2892          "Call to landingpad not in landing pad!");
2893 
2894   // If there aren't registers to copy the values into (e.g., during SjLj
2895   // exceptions), then don't bother to create these DAG nodes.
2896   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2897   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2898   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2899       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2900     return;
2901 
2902   // If landingpad's return type is token type, we don't create DAG nodes
2903   // for its exception pointer and selector value. The extraction of exception
2904   // pointer or selector value from token type landingpads is not currently
2905   // supported.
2906   if (LP.getType()->isTokenTy())
2907     return;
2908 
2909   SmallVector<EVT, 2> ValueVTs;
2910   SDLoc dl = getCurSDLoc();
2911   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2912   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2913 
2914   // Get the two live-in registers as SDValues. The physregs have already been
2915   // copied into virtual registers.
2916   SDValue Ops[2];
2917   if (FuncInfo.ExceptionPointerVirtReg) {
2918     Ops[0] = DAG.getZExtOrTrunc(
2919         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2920                            FuncInfo.ExceptionPointerVirtReg,
2921                            TLI.getPointerTy(DAG.getDataLayout())),
2922         dl, ValueVTs[0]);
2923   } else {
2924     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2925   }
2926   Ops[1] = DAG.getZExtOrTrunc(
2927       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2928                          FuncInfo.ExceptionSelectorVirtReg,
2929                          TLI.getPointerTy(DAG.getDataLayout())),
2930       dl, ValueVTs[1]);
2931 
2932   // Merge into one.
2933   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2934                             DAG.getVTList(ValueVTs), Ops);
2935   setValue(&LP, Res);
2936 }
2937 
2938 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2939                                            MachineBasicBlock *Last) {
2940   // Update JTCases.
2941   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2942     if (SL->JTCases[i].first.HeaderBB == First)
2943       SL->JTCases[i].first.HeaderBB = Last;
2944 
2945   // Update BitTestCases.
2946   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2947     if (SL->BitTestCases[i].Parent == First)
2948       SL->BitTestCases[i].Parent = Last;
2949 }
2950 
2951 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2952   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2953 
2954   // Update machine-CFG edges with unique successors.
2955   SmallSet<BasicBlock*, 32> Done;
2956   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2957     BasicBlock *BB = I.getSuccessor(i);
2958     bool Inserted = Done.insert(BB).second;
2959     if (!Inserted)
2960         continue;
2961 
2962     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2963     addSuccessorWithProb(IndirectBrMBB, Succ);
2964   }
2965   IndirectBrMBB->normalizeSuccProbs();
2966 
2967   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2968                           MVT::Other, getControlRoot(),
2969                           getValue(I.getAddress())));
2970 }
2971 
2972 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2973   if (!DAG.getTarget().Options.TrapUnreachable)
2974     return;
2975 
2976   // We may be able to ignore unreachable behind a noreturn call.
2977   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2978     const BasicBlock &BB = *I.getParent();
2979     if (&I != &BB.front()) {
2980       BasicBlock::const_iterator PredI =
2981         std::prev(BasicBlock::const_iterator(&I));
2982       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2983         if (Call->doesNotReturn())
2984           return;
2985       }
2986     }
2987   }
2988 
2989   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2990 }
2991 
2992 void SelectionDAGBuilder::visitFSub(const User &I) {
2993   // -0.0 - X --> fneg
2994   Type *Ty = I.getType();
2995   if (isa<Constant>(I.getOperand(0)) &&
2996       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2997     SDValue Op2 = getValue(I.getOperand(1));
2998     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2999                              Op2.getValueType(), Op2));
3000     return;
3001   }
3002 
3003   visitBinary(I, ISD::FSUB);
3004 }
3005 
3006 /// Checks if the given instruction performs a vector reduction, in which case
3007 /// we have the freedom to alter the elements in the result as long as the
3008 /// reduction of them stays unchanged.
3009 static bool isVectorReductionOp(const User *I) {
3010   const Instruction *Inst = dyn_cast<Instruction>(I);
3011   if (!Inst || !Inst->getType()->isVectorTy())
3012     return false;
3013 
3014   auto OpCode = Inst->getOpcode();
3015   switch (OpCode) {
3016   case Instruction::Add:
3017   case Instruction::Mul:
3018   case Instruction::And:
3019   case Instruction::Or:
3020   case Instruction::Xor:
3021     break;
3022   case Instruction::FAdd:
3023   case Instruction::FMul:
3024     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3025       if (FPOp->getFastMathFlags().isFast())
3026         break;
3027     LLVM_FALLTHROUGH;
3028   default:
3029     return false;
3030   }
3031 
3032   unsigned ElemNum = Inst->getType()->getVectorNumElements();
3033   // Ensure the reduction size is a power of 2.
3034   if (!isPowerOf2_32(ElemNum))
3035     return false;
3036 
3037   unsigned ElemNumToReduce = ElemNum;
3038 
3039   // Do DFS search on the def-use chain from the given instruction. We only
3040   // allow four kinds of operations during the search until we reach the
3041   // instruction that extracts the first element from the vector:
3042   //
3043   //   1. The reduction operation of the same opcode as the given instruction.
3044   //
3045   //   2. PHI node.
3046   //
3047   //   3. ShuffleVector instruction together with a reduction operation that
3048   //      does a partial reduction.
3049   //
3050   //   4. ExtractElement that extracts the first element from the vector, and we
3051   //      stop searching the def-use chain here.
3052   //
3053   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3054   // from 1-3 to the stack to continue the DFS. The given instruction is not
3055   // a reduction operation if we meet any other instructions other than those
3056   // listed above.
3057 
3058   SmallVector<const User *, 16> UsersToVisit{Inst};
3059   SmallPtrSet<const User *, 16> Visited;
3060   bool ReduxExtracted = false;
3061 
3062   while (!UsersToVisit.empty()) {
3063     auto User = UsersToVisit.back();
3064     UsersToVisit.pop_back();
3065     if (!Visited.insert(User).second)
3066       continue;
3067 
3068     for (const auto *U : User->users()) {
3069       auto Inst = dyn_cast<Instruction>(U);
3070       if (!Inst)
3071         return false;
3072 
3073       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3074         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3075           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3076             return false;
3077         UsersToVisit.push_back(U);
3078       } else if (const ShuffleVectorInst *ShufInst =
3079                      dyn_cast<ShuffleVectorInst>(U)) {
3080         // Detect the following pattern: A ShuffleVector instruction together
3081         // with a reduction that do partial reduction on the first and second
3082         // ElemNumToReduce / 2 elements, and store the result in
3083         // ElemNumToReduce / 2 elements in another vector.
3084 
3085         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3086         if (ResultElements < ElemNum)
3087           return false;
3088 
3089         if (ElemNumToReduce == 1)
3090           return false;
3091         if (!isa<UndefValue>(U->getOperand(1)))
3092           return false;
3093         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3094           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3095             return false;
3096         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3097           if (ShufInst->getMaskValue(i) != -1)
3098             return false;
3099 
3100         // There is only one user of this ShuffleVector instruction, which
3101         // must be a reduction operation.
3102         if (!U->hasOneUse())
3103           return false;
3104 
3105         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3106         if (!U2 || U2->getOpcode() != OpCode)
3107           return false;
3108 
3109         // Check operands of the reduction operation.
3110         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3111             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3112           UsersToVisit.push_back(U2);
3113           ElemNumToReduce /= 2;
3114         } else
3115           return false;
3116       } else if (isa<ExtractElementInst>(U)) {
3117         // At this moment we should have reduced all elements in the vector.
3118         if (ElemNumToReduce != 1)
3119           return false;
3120 
3121         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3122         if (!Val || !Val->isZero())
3123           return false;
3124 
3125         ReduxExtracted = true;
3126       } else
3127         return false;
3128     }
3129   }
3130   return ReduxExtracted;
3131 }
3132 
3133 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3134   SDNodeFlags Flags;
3135 
3136   SDValue Op = getValue(I.getOperand(0));
3137   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3138                                     Op, Flags);
3139   setValue(&I, UnNodeValue);
3140 }
3141 
3142 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3143   SDNodeFlags Flags;
3144   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3145     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3146     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3147   }
3148   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3149     Flags.setExact(ExactOp->isExact());
3150   }
3151   if (isVectorReductionOp(&I)) {
3152     Flags.setVectorReduction(true);
3153     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3154 
3155     // If no flags are set we will propagate the incoming flags, if any flags
3156     // are set, we will intersect them with the incoming flag and so we need to
3157     // copy the FMF flags here.
3158     if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) {
3159       Flags.copyFMF(*FPOp);
3160     }
3161   }
3162 
3163   SDValue Op1 = getValue(I.getOperand(0));
3164   SDValue Op2 = getValue(I.getOperand(1));
3165   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3166                                      Op1, Op2, Flags);
3167   setValue(&I, BinNodeValue);
3168 }
3169 
3170 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3171   SDValue Op1 = getValue(I.getOperand(0));
3172   SDValue Op2 = getValue(I.getOperand(1));
3173 
3174   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3175       Op1.getValueType(), DAG.getDataLayout());
3176 
3177   // Coerce the shift amount to the right type if we can.
3178   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3179     unsigned ShiftSize = ShiftTy.getSizeInBits();
3180     unsigned Op2Size = Op2.getValueSizeInBits();
3181     SDLoc DL = getCurSDLoc();
3182 
3183     // If the operand is smaller than the shift count type, promote it.
3184     if (ShiftSize > Op2Size)
3185       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3186 
3187     // If the operand is larger than the shift count type but the shift
3188     // count type has enough bits to represent any shift value, truncate
3189     // it now. This is a common case and it exposes the truncate to
3190     // optimization early.
3191     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3192       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3193     // Otherwise we'll need to temporarily settle for some other convenient
3194     // type.  Type legalization will make adjustments once the shiftee is split.
3195     else
3196       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3197   }
3198 
3199   bool nuw = false;
3200   bool nsw = false;
3201   bool exact = false;
3202 
3203   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3204 
3205     if (const OverflowingBinaryOperator *OFBinOp =
3206             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3207       nuw = OFBinOp->hasNoUnsignedWrap();
3208       nsw = OFBinOp->hasNoSignedWrap();
3209     }
3210     if (const PossiblyExactOperator *ExactOp =
3211             dyn_cast<const PossiblyExactOperator>(&I))
3212       exact = ExactOp->isExact();
3213   }
3214   SDNodeFlags Flags;
3215   Flags.setExact(exact);
3216   Flags.setNoSignedWrap(nsw);
3217   Flags.setNoUnsignedWrap(nuw);
3218   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3219                             Flags);
3220   setValue(&I, Res);
3221 }
3222 
3223 void SelectionDAGBuilder::visitSDiv(const User &I) {
3224   SDValue Op1 = getValue(I.getOperand(0));
3225   SDValue Op2 = getValue(I.getOperand(1));
3226 
3227   SDNodeFlags Flags;
3228   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3229                  cast<PossiblyExactOperator>(&I)->isExact());
3230   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3231                            Op2, Flags));
3232 }
3233 
3234 void SelectionDAGBuilder::visitICmp(const User &I) {
3235   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3236   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3237     predicate = IC->getPredicate();
3238   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3239     predicate = ICmpInst::Predicate(IC->getPredicate());
3240   SDValue Op1 = getValue(I.getOperand(0));
3241   SDValue Op2 = getValue(I.getOperand(1));
3242   ISD::CondCode Opcode = getICmpCondCode(predicate);
3243 
3244   auto &TLI = DAG.getTargetLoweringInfo();
3245   EVT MemVT =
3246       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3247 
3248   // If a pointer's DAG type is larger than its memory type then the DAG values
3249   // are zero-extended. This breaks signed comparisons so truncate back to the
3250   // underlying type before doing the compare.
3251   if (Op1.getValueType() != MemVT) {
3252     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3253     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3254   }
3255 
3256   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3257                                                         I.getType());
3258   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3259 }
3260 
3261 void SelectionDAGBuilder::visitFCmp(const User &I) {
3262   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3263   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3264     predicate = FC->getPredicate();
3265   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3266     predicate = FCmpInst::Predicate(FC->getPredicate());
3267   SDValue Op1 = getValue(I.getOperand(0));
3268   SDValue Op2 = getValue(I.getOperand(1));
3269 
3270   ISD::CondCode Condition = getFCmpCondCode(predicate);
3271   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3272   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3273     Condition = getFCmpCodeWithoutNaN(Condition);
3274 
3275   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3276                                                         I.getType());
3277   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3278 }
3279 
3280 // Check if the condition of the select has one use or two users that are both
3281 // selects with the same condition.
3282 static bool hasOnlySelectUsers(const Value *Cond) {
3283   return llvm::all_of(Cond->users(), [](const Value *V) {
3284     return isa<SelectInst>(V);
3285   });
3286 }
3287 
3288 void SelectionDAGBuilder::visitSelect(const User &I) {
3289   SmallVector<EVT, 4> ValueVTs;
3290   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3291                   ValueVTs);
3292   unsigned NumValues = ValueVTs.size();
3293   if (NumValues == 0) return;
3294 
3295   SmallVector<SDValue, 4> Values(NumValues);
3296   SDValue Cond     = getValue(I.getOperand(0));
3297   SDValue LHSVal   = getValue(I.getOperand(1));
3298   SDValue RHSVal   = getValue(I.getOperand(2));
3299   auto BaseOps = {Cond};
3300   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3301     ISD::VSELECT : ISD::SELECT;
3302 
3303   bool IsUnaryAbs = false;
3304 
3305   // Min/max matching is only viable if all output VTs are the same.
3306   if (is_splat(ValueVTs)) {
3307     EVT VT = ValueVTs[0];
3308     LLVMContext &Ctx = *DAG.getContext();
3309     auto &TLI = DAG.getTargetLoweringInfo();
3310 
3311     // We care about the legality of the operation after it has been type
3312     // legalized.
3313     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3314       VT = TLI.getTypeToTransformTo(Ctx, VT);
3315 
3316     // If the vselect is legal, assume we want to leave this as a vector setcc +
3317     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3318     // min/max is legal on the scalar type.
3319     bool UseScalarMinMax = VT.isVector() &&
3320       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3321 
3322     Value *LHS, *RHS;
3323     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3324     ISD::NodeType Opc = ISD::DELETED_NODE;
3325     switch (SPR.Flavor) {
3326     case SPF_UMAX:    Opc = ISD::UMAX; break;
3327     case SPF_UMIN:    Opc = ISD::UMIN; break;
3328     case SPF_SMAX:    Opc = ISD::SMAX; break;
3329     case SPF_SMIN:    Opc = ISD::SMIN; break;
3330     case SPF_FMINNUM:
3331       switch (SPR.NaNBehavior) {
3332       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3333       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3334       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3335       case SPNB_RETURNS_ANY: {
3336         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3337           Opc = ISD::FMINNUM;
3338         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3339           Opc = ISD::FMINIMUM;
3340         else if (UseScalarMinMax)
3341           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3342             ISD::FMINNUM : ISD::FMINIMUM;
3343         break;
3344       }
3345       }
3346       break;
3347     case SPF_FMAXNUM:
3348       switch (SPR.NaNBehavior) {
3349       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3350       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3351       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3352       case SPNB_RETURNS_ANY:
3353 
3354         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3355           Opc = ISD::FMAXNUM;
3356         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3357           Opc = ISD::FMAXIMUM;
3358         else if (UseScalarMinMax)
3359           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3360             ISD::FMAXNUM : ISD::FMAXIMUM;
3361         break;
3362       }
3363       break;
3364     case SPF_ABS:
3365       IsUnaryAbs = true;
3366       Opc = ISD::ABS;
3367       break;
3368     case SPF_NABS:
3369       // TODO: we need to produce sub(0, abs(X)).
3370     default: break;
3371     }
3372 
3373     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3374         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3375          (UseScalarMinMax &&
3376           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3377         // If the underlying comparison instruction is used by any other
3378         // instruction, the consumed instructions won't be destroyed, so it is
3379         // not profitable to convert to a min/max.
3380         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3381       OpCode = Opc;
3382       LHSVal = getValue(LHS);
3383       RHSVal = getValue(RHS);
3384       BaseOps = {};
3385     }
3386 
3387     if (IsUnaryAbs) {
3388       OpCode = Opc;
3389       LHSVal = getValue(LHS);
3390       BaseOps = {};
3391     }
3392   }
3393 
3394   if (IsUnaryAbs) {
3395     for (unsigned i = 0; i != NumValues; ++i) {
3396       Values[i] =
3397           DAG.getNode(OpCode, getCurSDLoc(),
3398                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3399                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3400     }
3401   } else {
3402     for (unsigned i = 0; i != NumValues; ++i) {
3403       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3404       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3405       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3406       Values[i] = DAG.getNode(
3407           OpCode, getCurSDLoc(),
3408           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3409     }
3410   }
3411 
3412   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3413                            DAG.getVTList(ValueVTs), Values));
3414 }
3415 
3416 void SelectionDAGBuilder::visitTrunc(const User &I) {
3417   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3418   SDValue N = getValue(I.getOperand(0));
3419   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3420                                                         I.getType());
3421   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3422 }
3423 
3424 void SelectionDAGBuilder::visitZExt(const User &I) {
3425   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3426   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3427   SDValue N = getValue(I.getOperand(0));
3428   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3429                                                         I.getType());
3430   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3431 }
3432 
3433 void SelectionDAGBuilder::visitSExt(const User &I) {
3434   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3435   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3436   SDValue N = getValue(I.getOperand(0));
3437   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3438                                                         I.getType());
3439   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3440 }
3441 
3442 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3443   // FPTrunc is never a no-op cast, no need to check
3444   SDValue N = getValue(I.getOperand(0));
3445   SDLoc dl = getCurSDLoc();
3446   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3447   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3448   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3449                            DAG.getTargetConstant(
3450                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3451 }
3452 
3453 void SelectionDAGBuilder::visitFPExt(const User &I) {
3454   // FPExt is never a no-op cast, no need to check
3455   SDValue N = getValue(I.getOperand(0));
3456   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3457                                                         I.getType());
3458   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3459 }
3460 
3461 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3462   // FPToUI is never a no-op cast, no need to check
3463   SDValue N = getValue(I.getOperand(0));
3464   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3465                                                         I.getType());
3466   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3467 }
3468 
3469 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3470   // FPToSI is never a no-op cast, no need to check
3471   SDValue N = getValue(I.getOperand(0));
3472   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3473                                                         I.getType());
3474   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3475 }
3476 
3477 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3478   // UIToFP is never a no-op cast, no need to check
3479   SDValue N = getValue(I.getOperand(0));
3480   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3481                                                         I.getType());
3482   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3483 }
3484 
3485 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3486   // SIToFP is never a no-op cast, no need to check
3487   SDValue N = getValue(I.getOperand(0));
3488   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3489                                                         I.getType());
3490   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3491 }
3492 
3493 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3494   // What to do depends on the size of the integer and the size of the pointer.
3495   // We can either truncate, zero extend, or no-op, accordingly.
3496   SDValue N = getValue(I.getOperand(0));
3497   auto &TLI = DAG.getTargetLoweringInfo();
3498   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3499                                                         I.getType());
3500   EVT PtrMemVT =
3501       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3502   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3503   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3504   setValue(&I, N);
3505 }
3506 
3507 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3508   // What to do depends on the size of the integer and the size of the pointer.
3509   // We can either truncate, zero extend, or no-op, accordingly.
3510   SDValue N = getValue(I.getOperand(0));
3511   auto &TLI = DAG.getTargetLoweringInfo();
3512   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3513   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3514   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3515   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3516   setValue(&I, N);
3517 }
3518 
3519 void SelectionDAGBuilder::visitBitCast(const User &I) {
3520   SDValue N = getValue(I.getOperand(0));
3521   SDLoc dl = getCurSDLoc();
3522   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3523                                                         I.getType());
3524 
3525   // BitCast assures us that source and destination are the same size so this is
3526   // either a BITCAST or a no-op.
3527   if (DestVT != N.getValueType())
3528     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3529                              DestVT, N)); // convert types.
3530   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3531   // might fold any kind of constant expression to an integer constant and that
3532   // is not what we are looking for. Only recognize a bitcast of a genuine
3533   // constant integer as an opaque constant.
3534   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3535     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3536                                  /*isOpaque*/true));
3537   else
3538     setValue(&I, N);            // noop cast.
3539 }
3540 
3541 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3542   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3543   const Value *SV = I.getOperand(0);
3544   SDValue N = getValue(SV);
3545   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3546 
3547   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3548   unsigned DestAS = I.getType()->getPointerAddressSpace();
3549 
3550   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3551     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3552 
3553   setValue(&I, N);
3554 }
3555 
3556 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3557   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3558   SDValue InVec = getValue(I.getOperand(0));
3559   SDValue InVal = getValue(I.getOperand(1));
3560   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3561                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3562   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3563                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3564                            InVec, InVal, InIdx));
3565 }
3566 
3567 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3568   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3569   SDValue InVec = getValue(I.getOperand(0));
3570   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3571                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3572   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3573                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3574                            InVec, InIdx));
3575 }
3576 
3577 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3578   SDValue Src1 = getValue(I.getOperand(0));
3579   SDValue Src2 = getValue(I.getOperand(1));
3580   Constant *MaskV = cast<Constant>(I.getOperand(2));
3581   SDLoc DL = getCurSDLoc();
3582   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3583   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3584   EVT SrcVT = Src1.getValueType();
3585   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3586 
3587   if (MaskV->isNullValue() && VT.isScalableVector()) {
3588     // Canonical splat form of first element of first input vector.
3589     SDValue FirstElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3590                                    SrcVT.getScalarType(), Src1,
3591                                    DAG.getConstant(0, DL,
3592                                    TLI.getVectorIdxTy(DAG.getDataLayout())));
3593     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3594     return;
3595   }
3596 
3597   // For now, we only handle splats for scalable vectors.
3598   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3599   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3600   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3601 
3602   SmallVector<int, 8> Mask;
3603   ShuffleVectorInst::getShuffleMask(MaskV, Mask);
3604   unsigned MaskNumElts = Mask.size();
3605 
3606   if (SrcNumElts == MaskNumElts) {
3607     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3608     return;
3609   }
3610 
3611   // Normalize the shuffle vector since mask and vector length don't match.
3612   if (SrcNumElts < MaskNumElts) {
3613     // Mask is longer than the source vectors. We can use concatenate vector to
3614     // make the mask and vectors lengths match.
3615 
3616     if (MaskNumElts % SrcNumElts == 0) {
3617       // Mask length is a multiple of the source vector length.
3618       // Check if the shuffle is some kind of concatenation of the input
3619       // vectors.
3620       unsigned NumConcat = MaskNumElts / SrcNumElts;
3621       bool IsConcat = true;
3622       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3623       for (unsigned i = 0; i != MaskNumElts; ++i) {
3624         int Idx = Mask[i];
3625         if (Idx < 0)
3626           continue;
3627         // Ensure the indices in each SrcVT sized piece are sequential and that
3628         // the same source is used for the whole piece.
3629         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3630             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3631              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3632           IsConcat = false;
3633           break;
3634         }
3635         // Remember which source this index came from.
3636         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3637       }
3638 
3639       // The shuffle is concatenating multiple vectors together. Just emit
3640       // a CONCAT_VECTORS operation.
3641       if (IsConcat) {
3642         SmallVector<SDValue, 8> ConcatOps;
3643         for (auto Src : ConcatSrcs) {
3644           if (Src < 0)
3645             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3646           else if (Src == 0)
3647             ConcatOps.push_back(Src1);
3648           else
3649             ConcatOps.push_back(Src2);
3650         }
3651         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3652         return;
3653       }
3654     }
3655 
3656     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3657     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3658     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3659                                     PaddedMaskNumElts);
3660 
3661     // Pad both vectors with undefs to make them the same length as the mask.
3662     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3663 
3664     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3665     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3666     MOps1[0] = Src1;
3667     MOps2[0] = Src2;
3668 
3669     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3670     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3671 
3672     // Readjust mask for new input vector length.
3673     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3674     for (unsigned i = 0; i != MaskNumElts; ++i) {
3675       int Idx = Mask[i];
3676       if (Idx >= (int)SrcNumElts)
3677         Idx -= SrcNumElts - PaddedMaskNumElts;
3678       MappedOps[i] = Idx;
3679     }
3680 
3681     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3682 
3683     // If the concatenated vector was padded, extract a subvector with the
3684     // correct number of elements.
3685     if (MaskNumElts != PaddedMaskNumElts)
3686       Result = DAG.getNode(
3687           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3688           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3689 
3690     setValue(&I, Result);
3691     return;
3692   }
3693 
3694   if (SrcNumElts > MaskNumElts) {
3695     // Analyze the access pattern of the vector to see if we can extract
3696     // two subvectors and do the shuffle.
3697     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3698     bool CanExtract = true;
3699     for (int Idx : Mask) {
3700       unsigned Input = 0;
3701       if (Idx < 0)
3702         continue;
3703 
3704       if (Idx >= (int)SrcNumElts) {
3705         Input = 1;
3706         Idx -= SrcNumElts;
3707       }
3708 
3709       // If all the indices come from the same MaskNumElts sized portion of
3710       // the sources we can use extract. Also make sure the extract wouldn't
3711       // extract past the end of the source.
3712       int NewStartIdx = alignDown(Idx, MaskNumElts);
3713       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3714           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3715         CanExtract = false;
3716       // Make sure we always update StartIdx as we use it to track if all
3717       // elements are undef.
3718       StartIdx[Input] = NewStartIdx;
3719     }
3720 
3721     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3722       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3723       return;
3724     }
3725     if (CanExtract) {
3726       // Extract appropriate subvector and generate a vector shuffle
3727       for (unsigned Input = 0; Input < 2; ++Input) {
3728         SDValue &Src = Input == 0 ? Src1 : Src2;
3729         if (StartIdx[Input] < 0)
3730           Src = DAG.getUNDEF(VT);
3731         else {
3732           Src = DAG.getNode(
3733               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3734               DAG.getConstant(StartIdx[Input], DL,
3735                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3736         }
3737       }
3738 
3739       // Calculate new mask.
3740       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3741       for (int &Idx : MappedOps) {
3742         if (Idx >= (int)SrcNumElts)
3743           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3744         else if (Idx >= 0)
3745           Idx -= StartIdx[0];
3746       }
3747 
3748       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3749       return;
3750     }
3751   }
3752 
3753   // We can't use either concat vectors or extract subvectors so fall back to
3754   // replacing the shuffle with extract and build vector.
3755   // to insert and build vector.
3756   EVT EltVT = VT.getVectorElementType();
3757   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3758   SmallVector<SDValue,8> Ops;
3759   for (int Idx : Mask) {
3760     SDValue Res;
3761 
3762     if (Idx < 0) {
3763       Res = DAG.getUNDEF(EltVT);
3764     } else {
3765       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3766       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3767 
3768       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3769                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3770     }
3771 
3772     Ops.push_back(Res);
3773   }
3774 
3775   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3776 }
3777 
3778 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3779   ArrayRef<unsigned> Indices;
3780   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3781     Indices = IV->getIndices();
3782   else
3783     Indices = cast<ConstantExpr>(&I)->getIndices();
3784 
3785   const Value *Op0 = I.getOperand(0);
3786   const Value *Op1 = I.getOperand(1);
3787   Type *AggTy = I.getType();
3788   Type *ValTy = Op1->getType();
3789   bool IntoUndef = isa<UndefValue>(Op0);
3790   bool FromUndef = isa<UndefValue>(Op1);
3791 
3792   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3793 
3794   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3795   SmallVector<EVT, 4> AggValueVTs;
3796   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3797   SmallVector<EVT, 4> ValValueVTs;
3798   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3799 
3800   unsigned NumAggValues = AggValueVTs.size();
3801   unsigned NumValValues = ValValueVTs.size();
3802   SmallVector<SDValue, 4> Values(NumAggValues);
3803 
3804   // Ignore an insertvalue that produces an empty object
3805   if (!NumAggValues) {
3806     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3807     return;
3808   }
3809 
3810   SDValue Agg = getValue(Op0);
3811   unsigned i = 0;
3812   // Copy the beginning value(s) from the original aggregate.
3813   for (; i != LinearIndex; ++i)
3814     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3815                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3816   // Copy values from the inserted value(s).
3817   if (NumValValues) {
3818     SDValue Val = getValue(Op1);
3819     for (; i != LinearIndex + NumValValues; ++i)
3820       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3821                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3822   }
3823   // Copy remaining value(s) from the original aggregate.
3824   for (; i != NumAggValues; ++i)
3825     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3826                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3827 
3828   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3829                            DAG.getVTList(AggValueVTs), Values));
3830 }
3831 
3832 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3833   ArrayRef<unsigned> Indices;
3834   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3835     Indices = EV->getIndices();
3836   else
3837     Indices = cast<ConstantExpr>(&I)->getIndices();
3838 
3839   const Value *Op0 = I.getOperand(0);
3840   Type *AggTy = Op0->getType();
3841   Type *ValTy = I.getType();
3842   bool OutOfUndef = isa<UndefValue>(Op0);
3843 
3844   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3845 
3846   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3847   SmallVector<EVT, 4> ValValueVTs;
3848   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3849 
3850   unsigned NumValValues = ValValueVTs.size();
3851 
3852   // Ignore a extractvalue that produces an empty object
3853   if (!NumValValues) {
3854     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3855     return;
3856   }
3857 
3858   SmallVector<SDValue, 4> Values(NumValValues);
3859 
3860   SDValue Agg = getValue(Op0);
3861   // Copy out the selected value(s).
3862   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3863     Values[i - LinearIndex] =
3864       OutOfUndef ?
3865         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3866         SDValue(Agg.getNode(), Agg.getResNo() + i);
3867 
3868   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3869                            DAG.getVTList(ValValueVTs), Values));
3870 }
3871 
3872 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3873   Value *Op0 = I.getOperand(0);
3874   // Note that the pointer operand may be a vector of pointers. Take the scalar
3875   // element which holds a pointer.
3876   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3877   SDValue N = getValue(Op0);
3878   SDLoc dl = getCurSDLoc();
3879   auto &TLI = DAG.getTargetLoweringInfo();
3880   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3881   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3882 
3883   // Normalize Vector GEP - all scalar operands should be converted to the
3884   // splat vector.
3885   unsigned VectorWidth = I.getType()->isVectorTy() ?
3886     I.getType()->getVectorNumElements() : 0;
3887 
3888   if (VectorWidth && !N.getValueType().isVector()) {
3889     LLVMContext &Context = *DAG.getContext();
3890     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3891     N = DAG.getSplatBuildVector(VT, dl, N);
3892   }
3893 
3894   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3895        GTI != E; ++GTI) {
3896     const Value *Idx = GTI.getOperand();
3897     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3898       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3899       if (Field) {
3900         // N = N + Offset
3901         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3902 
3903         // In an inbounds GEP with an offset that is nonnegative even when
3904         // interpreted as signed, assume there is no unsigned overflow.
3905         SDNodeFlags Flags;
3906         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3907           Flags.setNoUnsignedWrap(true);
3908 
3909         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3910                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3911       }
3912     } else {
3913       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3914       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3915       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3916 
3917       // If this is a scalar constant or a splat vector of constants,
3918       // handle it quickly.
3919       const auto *C = dyn_cast<Constant>(Idx);
3920       if (C && isa<VectorType>(C->getType()))
3921         C = C->getSplatValue();
3922 
3923       if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
3924         if (CI->isZero())
3925           continue;
3926         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3927         LLVMContext &Context = *DAG.getContext();
3928         SDValue OffsVal = VectorWidth ?
3929           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3930           DAG.getConstant(Offs, dl, IdxTy);
3931 
3932         // In an inbounds GEP with an offset that is nonnegative even when
3933         // interpreted as signed, assume there is no unsigned overflow.
3934         SDNodeFlags Flags;
3935         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3936           Flags.setNoUnsignedWrap(true);
3937 
3938         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3939 
3940         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3941         continue;
3942       }
3943 
3944       // N = N + Idx * ElementSize;
3945       SDValue IdxN = getValue(Idx);
3946 
3947       if (!IdxN.getValueType().isVector() && VectorWidth) {
3948         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3949         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3950       }
3951 
3952       // If the index is smaller or larger than intptr_t, truncate or extend
3953       // it.
3954       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3955 
3956       // If this is a multiply by a power of two, turn it into a shl
3957       // immediately.  This is a very common case.
3958       if (ElementSize != 1) {
3959         if (ElementSize.isPowerOf2()) {
3960           unsigned Amt = ElementSize.logBase2();
3961           IdxN = DAG.getNode(ISD::SHL, dl,
3962                              N.getValueType(), IdxN,
3963                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3964         } else {
3965           SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
3966                                           IdxN.getValueType());
3967           IdxN = DAG.getNode(ISD::MUL, dl,
3968                              N.getValueType(), IdxN, Scale);
3969         }
3970       }
3971 
3972       N = DAG.getNode(ISD::ADD, dl,
3973                       N.getValueType(), N, IdxN);
3974     }
3975   }
3976 
3977   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3978     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3979 
3980   setValue(&I, N);
3981 }
3982 
3983 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3984   // If this is a fixed sized alloca in the entry block of the function,
3985   // allocate it statically on the stack.
3986   if (FuncInfo.StaticAllocaMap.count(&I))
3987     return;   // getValue will auto-populate this.
3988 
3989   SDLoc dl = getCurSDLoc();
3990   Type *Ty = I.getAllocatedType();
3991   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3992   auto &DL = DAG.getDataLayout();
3993   uint64_t TySize = DL.getTypeAllocSize(Ty);
3994   unsigned Align =
3995       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3996 
3997   SDValue AllocSize = getValue(I.getArraySize());
3998 
3999   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4000   if (AllocSize.getValueType() != IntPtr)
4001     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4002 
4003   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
4004                           AllocSize,
4005                           DAG.getConstant(TySize, dl, IntPtr));
4006 
4007   // Handle alignment.  If the requested alignment is less than or equal to
4008   // the stack alignment, ignore it.  If the size is greater than or equal to
4009   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4010   unsigned StackAlign =
4011       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
4012   if (Align <= StackAlign)
4013     Align = 0;
4014 
4015   // Round the size of the allocation up to the stack alignment size
4016   // by add SA-1 to the size. This doesn't overflow because we're computing
4017   // an address inside an alloca.
4018   SDNodeFlags Flags;
4019   Flags.setNoUnsignedWrap(true);
4020   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4021                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
4022 
4023   // Mask out the low bits for alignment purposes.
4024   AllocSize =
4025       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4026                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
4027 
4028   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
4029   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4030   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4031   setValue(&I, DSA);
4032   DAG.setRoot(DSA.getValue(1));
4033 
4034   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4035 }
4036 
4037 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4038   if (I.isAtomic())
4039     return visitAtomicLoad(I);
4040 
4041   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4042   const Value *SV = I.getOperand(0);
4043   if (TLI.supportSwiftError()) {
4044     // Swifterror values can come from either a function parameter with
4045     // swifterror attribute or an alloca with swifterror attribute.
4046     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4047       if (Arg->hasSwiftErrorAttr())
4048         return visitLoadFromSwiftError(I);
4049     }
4050 
4051     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4052       if (Alloca->isSwiftError())
4053         return visitLoadFromSwiftError(I);
4054     }
4055   }
4056 
4057   SDValue Ptr = getValue(SV);
4058 
4059   Type *Ty = I.getType();
4060   unsigned Alignment = I.getAlignment();
4061 
4062   AAMDNodes AAInfo;
4063   I.getAAMetadata(AAInfo);
4064   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4065 
4066   SmallVector<EVT, 4> ValueVTs, MemVTs;
4067   SmallVector<uint64_t, 4> Offsets;
4068   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4069   unsigned NumValues = ValueVTs.size();
4070   if (NumValues == 0)
4071     return;
4072 
4073   bool isVolatile = I.isVolatile();
4074 
4075   SDValue Root;
4076   bool ConstantMemory = false;
4077   if (isVolatile)
4078     // Serialize volatile loads with other side effects.
4079     Root = getRoot();
4080   else if (NumValues > MaxParallelChains)
4081     Root = getMemoryRoot();
4082   else if (AA &&
4083            AA->pointsToConstantMemory(MemoryLocation(
4084                SV,
4085                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4086                AAInfo))) {
4087     // Do not serialize (non-volatile) loads of constant memory with anything.
4088     Root = DAG.getEntryNode();
4089     ConstantMemory = true;
4090   } else {
4091     // Do not serialize non-volatile loads against each other.
4092     Root = DAG.getRoot();
4093   }
4094 
4095   SDLoc dl = getCurSDLoc();
4096 
4097   if (isVolatile)
4098     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4099 
4100   // An aggregate load cannot wrap around the address space, so offsets to its
4101   // parts don't wrap either.
4102   SDNodeFlags Flags;
4103   Flags.setNoUnsignedWrap(true);
4104 
4105   SmallVector<SDValue, 4> Values(NumValues);
4106   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4107   EVT PtrVT = Ptr.getValueType();
4108 
4109   MachineMemOperand::Flags MMOFlags
4110     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4111 
4112   unsigned ChainI = 0;
4113   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4114     // Serializing loads here may result in excessive register pressure, and
4115     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4116     // could recover a bit by hoisting nodes upward in the chain by recognizing
4117     // they are side-effect free or do not alias. The optimizer should really
4118     // avoid this case by converting large object/array copies to llvm.memcpy
4119     // (MaxParallelChains should always remain as failsafe).
4120     if (ChainI == MaxParallelChains) {
4121       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4122       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4123                                   makeArrayRef(Chains.data(), ChainI));
4124       Root = Chain;
4125       ChainI = 0;
4126     }
4127     SDValue A = DAG.getNode(ISD::ADD, dl,
4128                             PtrVT, Ptr,
4129                             DAG.getConstant(Offsets[i], dl, PtrVT),
4130                             Flags);
4131 
4132     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4133                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4134                             MMOFlags, AAInfo, Ranges);
4135     Chains[ChainI] = L.getValue(1);
4136 
4137     if (MemVTs[i] != ValueVTs[i])
4138       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4139 
4140     Values[i] = L;
4141   }
4142 
4143   if (!ConstantMemory) {
4144     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4145                                 makeArrayRef(Chains.data(), ChainI));
4146     if (isVolatile)
4147       DAG.setRoot(Chain);
4148     else
4149       PendingLoads.push_back(Chain);
4150   }
4151 
4152   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4153                            DAG.getVTList(ValueVTs), Values));
4154 }
4155 
4156 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4157   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4158          "call visitStoreToSwiftError when backend supports swifterror");
4159 
4160   SmallVector<EVT, 4> ValueVTs;
4161   SmallVector<uint64_t, 4> Offsets;
4162   const Value *SrcV = I.getOperand(0);
4163   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4164                   SrcV->getType(), ValueVTs, &Offsets);
4165   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4166          "expect a single EVT for swifterror");
4167 
4168   SDValue Src = getValue(SrcV);
4169   // Create a virtual register, then update the virtual register.
4170   Register VReg =
4171       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4172   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4173   // Chain can be getRoot or getControlRoot.
4174   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4175                                       SDValue(Src.getNode(), Src.getResNo()));
4176   DAG.setRoot(CopyNode);
4177 }
4178 
4179 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4180   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4181          "call visitLoadFromSwiftError when backend supports swifterror");
4182 
4183   assert(!I.isVolatile() &&
4184          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4185          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4186          "Support volatile, non temporal, invariant for load_from_swift_error");
4187 
4188   const Value *SV = I.getOperand(0);
4189   Type *Ty = I.getType();
4190   AAMDNodes AAInfo;
4191   I.getAAMetadata(AAInfo);
4192   assert(
4193       (!AA ||
4194        !AA->pointsToConstantMemory(MemoryLocation(
4195            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4196            AAInfo))) &&
4197       "load_from_swift_error should not be constant memory");
4198 
4199   SmallVector<EVT, 4> ValueVTs;
4200   SmallVector<uint64_t, 4> Offsets;
4201   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4202                   ValueVTs, &Offsets);
4203   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4204          "expect a single EVT for swifterror");
4205 
4206   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4207   SDValue L = DAG.getCopyFromReg(
4208       getRoot(), getCurSDLoc(),
4209       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4210 
4211   setValue(&I, L);
4212 }
4213 
4214 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4215   if (I.isAtomic())
4216     return visitAtomicStore(I);
4217 
4218   const Value *SrcV = I.getOperand(0);
4219   const Value *PtrV = I.getOperand(1);
4220 
4221   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4222   if (TLI.supportSwiftError()) {
4223     // Swifterror values can come from either a function parameter with
4224     // swifterror attribute or an alloca with swifterror attribute.
4225     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4226       if (Arg->hasSwiftErrorAttr())
4227         return visitStoreToSwiftError(I);
4228     }
4229 
4230     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4231       if (Alloca->isSwiftError())
4232         return visitStoreToSwiftError(I);
4233     }
4234   }
4235 
4236   SmallVector<EVT, 4> ValueVTs, MemVTs;
4237   SmallVector<uint64_t, 4> Offsets;
4238   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4239                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4240   unsigned NumValues = ValueVTs.size();
4241   if (NumValues == 0)
4242     return;
4243 
4244   // Get the lowered operands. Note that we do this after
4245   // checking if NumResults is zero, because with zero results
4246   // the operands won't have values in the map.
4247   SDValue Src = getValue(SrcV);
4248   SDValue Ptr = getValue(PtrV);
4249 
4250   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4251   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4252   SDLoc dl = getCurSDLoc();
4253   unsigned Alignment = I.getAlignment();
4254   AAMDNodes AAInfo;
4255   I.getAAMetadata(AAInfo);
4256 
4257   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4258 
4259   // An aggregate load cannot wrap around the address space, so offsets to its
4260   // parts don't wrap either.
4261   SDNodeFlags Flags;
4262   Flags.setNoUnsignedWrap(true);
4263 
4264   unsigned ChainI = 0;
4265   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4266     // See visitLoad comments.
4267     if (ChainI == MaxParallelChains) {
4268       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4269                                   makeArrayRef(Chains.data(), ChainI));
4270       Root = Chain;
4271       ChainI = 0;
4272     }
4273     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4274     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4275     if (MemVTs[i] != ValueVTs[i])
4276       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4277     SDValue St =
4278         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4279                      Alignment, MMOFlags, AAInfo);
4280     Chains[ChainI] = St;
4281   }
4282 
4283   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4284                                   makeArrayRef(Chains.data(), ChainI));
4285   DAG.setRoot(StoreNode);
4286 }
4287 
4288 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4289                                            bool IsCompressing) {
4290   SDLoc sdl = getCurSDLoc();
4291 
4292   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4293                            unsigned& Alignment) {
4294     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4295     Src0 = I.getArgOperand(0);
4296     Ptr = I.getArgOperand(1);
4297     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4298     Mask = I.getArgOperand(3);
4299   };
4300   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4301                            unsigned& Alignment) {
4302     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4303     Src0 = I.getArgOperand(0);
4304     Ptr = I.getArgOperand(1);
4305     Mask = I.getArgOperand(2);
4306     Alignment = 0;
4307   };
4308 
4309   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4310   unsigned Alignment;
4311   if (IsCompressing)
4312     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4313   else
4314     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4315 
4316   SDValue Ptr = getValue(PtrOperand);
4317   SDValue Src0 = getValue(Src0Operand);
4318   SDValue Mask = getValue(MaskOperand);
4319   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4320 
4321   EVT VT = Src0.getValueType();
4322   if (!Alignment)
4323     Alignment = DAG.getEVTAlignment(VT);
4324 
4325   AAMDNodes AAInfo;
4326   I.getAAMetadata(AAInfo);
4327 
4328   MachineMemOperand *MMO =
4329     DAG.getMachineFunction().
4330     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4331                           MachineMemOperand::MOStore,
4332                           // TODO: Make MachineMemOperands aware of scalable
4333                           // vectors.
4334                           VT.getStoreSize().getKnownMinSize(),
4335                           Alignment, AAInfo);
4336   SDValue StoreNode =
4337       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4338                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4339   DAG.setRoot(StoreNode);
4340   setValue(&I, StoreNode);
4341 }
4342 
4343 // Get a uniform base for the Gather/Scatter intrinsic.
4344 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4345 // We try to represent it as a base pointer + vector of indices.
4346 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4347 // The first operand of the GEP may be a single pointer or a vector of pointers
4348 // Example:
4349 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4350 //  or
4351 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4352 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4353 //
4354 // When the first GEP operand is a single pointer - it is the uniform base we
4355 // are looking for. If first operand of the GEP is a splat vector - we
4356 // extract the splat value and use it as a uniform base.
4357 // In all other cases the function returns 'false'.
4358 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
4359                            ISD::MemIndexType &IndexType, SDValue &Scale,
4360                            SelectionDAGBuilder *SDB) {
4361   SelectionDAG& DAG = SDB->DAG;
4362   LLVMContext &Context = *DAG.getContext();
4363 
4364   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4365   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4366   if (!GEP)
4367     return false;
4368 
4369   const Value *GEPPtr = GEP->getPointerOperand();
4370   if (!GEPPtr->getType()->isVectorTy())
4371     Ptr = GEPPtr;
4372   else if (!(Ptr = getSplatValue(GEPPtr)))
4373     return false;
4374 
4375   unsigned FinalIndex = GEP->getNumOperands() - 1;
4376   Value *IndexVal = GEP->getOperand(FinalIndex);
4377   gep_type_iterator GTI = gep_type_begin(*GEP);
4378 
4379   // Ensure all the other indices are 0.
4380   for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) {
4381     auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4382     if (!C)
4383       return false;
4384     if (isa<VectorType>(C->getType()))
4385       C = C->getSplatValue();
4386     auto *CI = dyn_cast_or_null<ConstantInt>(C);
4387     if (!CI || !CI->isZero())
4388       return false;
4389   }
4390 
4391   // The operands of the GEP may be defined in another basic block.
4392   // In this case we'll not find nodes for the operands.
4393   if (!SDB->findValue(Ptr))
4394     return false;
4395   Constant *C = dyn_cast<Constant>(IndexVal);
4396   if (!C && !SDB->findValue(IndexVal))
4397     return false;
4398 
4399   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4400   const DataLayout &DL = DAG.getDataLayout();
4401   StructType *STy = GTI.getStructTypeOrNull();
4402 
4403   if (STy) {
4404     const StructLayout *SL = DL.getStructLayout(STy);
4405     if (isa<VectorType>(C->getType())) {
4406       C = C->getSplatValue();
4407       // FIXME: If getSplatValue may return nullptr for a structure?
4408       // If not, the following check can be removed.
4409       if (!C)
4410         return false;
4411     }
4412     auto *CI = cast<ConstantInt>(C);
4413     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4414     Index = DAG.getConstant(SL->getElementOffset(CI->getZExtValue()),
4415                             SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4416   } else {
4417     Scale = DAG.getTargetConstant(
4418                 DL.getTypeAllocSize(GEP->getResultElementType()),
4419                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4420     Index = SDB->getValue(IndexVal);
4421   }
4422   Base = SDB->getValue(Ptr);
4423   IndexType = ISD::SIGNED_SCALED;
4424 
4425   if (STy || !Index.getValueType().isVector()) {
4426     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4427     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4428     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4429   }
4430   return true;
4431 }
4432 
4433 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4434   SDLoc sdl = getCurSDLoc();
4435 
4436   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4437   const Value *Ptr = I.getArgOperand(1);
4438   SDValue Src0 = getValue(I.getArgOperand(0));
4439   SDValue Mask = getValue(I.getArgOperand(3));
4440   EVT VT = Src0.getValueType();
4441   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4442   if (!Alignment)
4443     Alignment = DAG.getEVTAlignment(VT);
4444   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4445 
4446   AAMDNodes AAInfo;
4447   I.getAAMetadata(AAInfo);
4448 
4449   SDValue Base;
4450   SDValue Index;
4451   ISD::MemIndexType IndexType;
4452   SDValue Scale;
4453   const Value *BasePtr = Ptr;
4454   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4455                                     this);
4456 
4457   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4458   MachineMemOperand *MMO = DAG.getMachineFunction().
4459     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4460                          MachineMemOperand::MOStore,
4461                          // TODO: Make MachineMemOperands aware of scalable
4462                          // vectors.
4463                          VT.getStoreSize().getKnownMinSize(),
4464                          Alignment, AAInfo);
4465   if (!UniformBase) {
4466     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4467     Index = getValue(Ptr);
4468     IndexType = ISD::SIGNED_SCALED;
4469     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4470   }
4471   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4472   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4473                                          Ops, MMO, IndexType);
4474   DAG.setRoot(Scatter);
4475   setValue(&I, Scatter);
4476 }
4477 
4478 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4479   SDLoc sdl = getCurSDLoc();
4480 
4481   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4482                            unsigned& Alignment) {
4483     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4484     Ptr = I.getArgOperand(0);
4485     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4486     Mask = I.getArgOperand(2);
4487     Src0 = I.getArgOperand(3);
4488   };
4489   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4490                            unsigned& Alignment) {
4491     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4492     Ptr = I.getArgOperand(0);
4493     Alignment = 0;
4494     Mask = I.getArgOperand(1);
4495     Src0 = I.getArgOperand(2);
4496   };
4497 
4498   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4499   unsigned Alignment;
4500   if (IsExpanding)
4501     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4502   else
4503     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4504 
4505   SDValue Ptr = getValue(PtrOperand);
4506   SDValue Src0 = getValue(Src0Operand);
4507   SDValue Mask = getValue(MaskOperand);
4508   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4509 
4510   EVT VT = Src0.getValueType();
4511   if (!Alignment)
4512     Alignment = DAG.getEVTAlignment(VT);
4513 
4514   AAMDNodes AAInfo;
4515   I.getAAMetadata(AAInfo);
4516   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4517 
4518   // Do not serialize masked loads of constant memory with anything.
4519   MemoryLocation ML;
4520   if (VT.isScalableVector())
4521     ML = MemoryLocation(PtrOperand);
4522   else
4523     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4524                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4525                            AAInfo);
4526   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4527 
4528   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4529 
4530   MachineMemOperand *MMO =
4531     DAG.getMachineFunction().
4532     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4533                           MachineMemOperand::MOLoad,
4534                           // TODO: Make MachineMemOperands aware of scalable
4535                           // vectors.
4536                           VT.getStoreSize().getKnownMinSize(),
4537                           Alignment, AAInfo, Ranges);
4538 
4539   SDValue Load =
4540       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4541                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4542   if (AddToChain)
4543     PendingLoads.push_back(Load.getValue(1));
4544   setValue(&I, Load);
4545 }
4546 
4547 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4548   SDLoc sdl = getCurSDLoc();
4549 
4550   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4551   const Value *Ptr = I.getArgOperand(0);
4552   SDValue Src0 = getValue(I.getArgOperand(3));
4553   SDValue Mask = getValue(I.getArgOperand(2));
4554 
4555   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4556   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4557   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4558   if (!Alignment)
4559     Alignment = DAG.getEVTAlignment(VT);
4560 
4561   AAMDNodes AAInfo;
4562   I.getAAMetadata(AAInfo);
4563   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4564 
4565   SDValue Root = DAG.getRoot();
4566   SDValue Base;
4567   SDValue Index;
4568   ISD::MemIndexType IndexType;
4569   SDValue Scale;
4570   const Value *BasePtr = Ptr;
4571   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4572                                     this);
4573   bool ConstantMemory = false;
4574   if (UniformBase && AA &&
4575       AA->pointsToConstantMemory(
4576           MemoryLocation(BasePtr,
4577                          LocationSize::precise(
4578                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4579                          AAInfo))) {
4580     // Do not serialize (non-volatile) loads of constant memory with anything.
4581     Root = DAG.getEntryNode();
4582     ConstantMemory = true;
4583   }
4584 
4585   MachineMemOperand *MMO =
4586     DAG.getMachineFunction().
4587     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4588                          MachineMemOperand::MOLoad,
4589                          // TODO: Make MachineMemOperands aware of scalable
4590                          // vectors.
4591                          VT.getStoreSize().getKnownMinSize(),
4592                          Alignment, AAInfo, Ranges);
4593 
4594   if (!UniformBase) {
4595     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4596     Index = getValue(Ptr);
4597     IndexType = ISD::SIGNED_SCALED;
4598     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4599   }
4600   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4601   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4602                                        Ops, MMO, IndexType);
4603 
4604   SDValue OutChain = Gather.getValue(1);
4605   if (!ConstantMemory)
4606     PendingLoads.push_back(OutChain);
4607   setValue(&I, Gather);
4608 }
4609 
4610 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4611   SDLoc dl = getCurSDLoc();
4612   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4613   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4614   SyncScope::ID SSID = I.getSyncScopeID();
4615 
4616   SDValue InChain = getRoot();
4617 
4618   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4619   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4620 
4621   auto Alignment = DAG.getEVTAlignment(MemVT);
4622   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4623   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4624 
4625   MachineFunction &MF = DAG.getMachineFunction();
4626   MachineMemOperand *MMO =
4627     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4628                             Flags, MemVT.getStoreSize(), Alignment,
4629                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4630                             FailureOrdering);
4631 
4632   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4633                                    dl, MemVT, VTs, InChain,
4634                                    getValue(I.getPointerOperand()),
4635                                    getValue(I.getCompareOperand()),
4636                                    getValue(I.getNewValOperand()), MMO);
4637 
4638   SDValue OutChain = L.getValue(2);
4639 
4640   setValue(&I, L);
4641   DAG.setRoot(OutChain);
4642 }
4643 
4644 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4645   SDLoc dl = getCurSDLoc();
4646   ISD::NodeType NT;
4647   switch (I.getOperation()) {
4648   default: llvm_unreachable("Unknown atomicrmw operation");
4649   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4650   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4651   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4652   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4653   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4654   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4655   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4656   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4657   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4658   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4659   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4660   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4661   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4662   }
4663   AtomicOrdering Ordering = I.getOrdering();
4664   SyncScope::ID SSID = I.getSyncScopeID();
4665 
4666   SDValue InChain = getRoot();
4667 
4668   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4669   auto Alignment = DAG.getEVTAlignment(MemVT);
4670   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4671   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4672 
4673   MachineFunction &MF = DAG.getMachineFunction();
4674   MachineMemOperand *MMO =
4675     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4676                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4677                             nullptr, SSID, Ordering);
4678 
4679   SDValue L =
4680     DAG.getAtomic(NT, dl, MemVT, InChain,
4681                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4682                   MMO);
4683 
4684   SDValue OutChain = L.getValue(1);
4685 
4686   setValue(&I, L);
4687   DAG.setRoot(OutChain);
4688 }
4689 
4690 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4691   SDLoc dl = getCurSDLoc();
4692   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4693   SDValue Ops[3];
4694   Ops[0] = getRoot();
4695   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4696                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4697   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4698                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4699   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4700 }
4701 
4702 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4703   SDLoc dl = getCurSDLoc();
4704   AtomicOrdering Order = I.getOrdering();
4705   SyncScope::ID SSID = I.getSyncScopeID();
4706 
4707   SDValue InChain = getRoot();
4708 
4709   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4710   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4711   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4712 
4713   if (!TLI.supportsUnalignedAtomics() &&
4714       I.getAlignment() < MemVT.getSizeInBits() / 8)
4715     report_fatal_error("Cannot generate unaligned atomic load");
4716 
4717   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4718 
4719   MachineMemOperand *MMO =
4720       DAG.getMachineFunction().
4721       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4722                            Flags, MemVT.getStoreSize(),
4723                            I.getAlignment() ? I.getAlignment() :
4724                                               DAG.getEVTAlignment(MemVT),
4725                            AAMDNodes(), nullptr, SSID, Order);
4726 
4727   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4728 
4729   SDValue Ptr = getValue(I.getPointerOperand());
4730 
4731   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4732     // TODO: Once this is better exercised by tests, it should be merged with
4733     // the normal path for loads to prevent future divergence.
4734     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4735     if (MemVT != VT)
4736       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4737 
4738     setValue(&I, L);
4739     SDValue OutChain = L.getValue(1);
4740     if (!I.isUnordered())
4741       DAG.setRoot(OutChain);
4742     else
4743       PendingLoads.push_back(OutChain);
4744     return;
4745   }
4746 
4747   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4748                             Ptr, MMO);
4749 
4750   SDValue OutChain = L.getValue(1);
4751   if (MemVT != VT)
4752     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4753 
4754   setValue(&I, L);
4755   DAG.setRoot(OutChain);
4756 }
4757 
4758 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4759   SDLoc dl = getCurSDLoc();
4760 
4761   AtomicOrdering Ordering = I.getOrdering();
4762   SyncScope::ID SSID = I.getSyncScopeID();
4763 
4764   SDValue InChain = getRoot();
4765 
4766   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4767   EVT MemVT =
4768       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4769 
4770   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4771     report_fatal_error("Cannot generate unaligned atomic store");
4772 
4773   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4774 
4775   MachineFunction &MF = DAG.getMachineFunction();
4776   MachineMemOperand *MMO =
4777     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4778                             MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4779                             nullptr, SSID, Ordering);
4780 
4781   SDValue Val = getValue(I.getValueOperand());
4782   if (Val.getValueType() != MemVT)
4783     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4784   SDValue Ptr = getValue(I.getPointerOperand());
4785 
4786   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4787     // TODO: Once this is better exercised by tests, it should be merged with
4788     // the normal path for stores to prevent future divergence.
4789     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4790     DAG.setRoot(S);
4791     return;
4792   }
4793   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4794                                    Ptr, Val, MMO);
4795 
4796 
4797   DAG.setRoot(OutChain);
4798 }
4799 
4800 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4801 /// node.
4802 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4803                                                unsigned Intrinsic) {
4804   // Ignore the callsite's attributes. A specific call site may be marked with
4805   // readnone, but the lowering code will expect the chain based on the
4806   // definition.
4807   const Function *F = I.getCalledFunction();
4808   bool HasChain = !F->doesNotAccessMemory();
4809   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4810 
4811   // Build the operand list.
4812   SmallVector<SDValue, 8> Ops;
4813   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4814     if (OnlyLoad) {
4815       // We don't need to serialize loads against other loads.
4816       Ops.push_back(DAG.getRoot());
4817     } else {
4818       Ops.push_back(getRoot());
4819     }
4820   }
4821 
4822   // Info is set by getTgtMemInstrinsic
4823   TargetLowering::IntrinsicInfo Info;
4824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4825   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4826                                                DAG.getMachineFunction(),
4827                                                Intrinsic);
4828 
4829   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4830   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4831       Info.opc == ISD::INTRINSIC_W_CHAIN)
4832     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4833                                         TLI.getPointerTy(DAG.getDataLayout())));
4834 
4835   // Add all operands of the call to the operand list.
4836   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4837     const Value *Arg = I.getArgOperand(i);
4838     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4839       Ops.push_back(getValue(Arg));
4840       continue;
4841     }
4842 
4843     // Use TargetConstant instead of a regular constant for immarg.
4844     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4845     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4846       assert(CI->getBitWidth() <= 64 &&
4847              "large intrinsic immediates not handled");
4848       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4849     } else {
4850       Ops.push_back(
4851           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4852     }
4853   }
4854 
4855   SmallVector<EVT, 4> ValueVTs;
4856   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4857 
4858   if (HasChain)
4859     ValueVTs.push_back(MVT::Other);
4860 
4861   SDVTList VTs = DAG.getVTList(ValueVTs);
4862 
4863   // Create the node.
4864   SDValue Result;
4865   if (IsTgtIntrinsic) {
4866     // This is target intrinsic that touches memory
4867     AAMDNodes AAInfo;
4868     I.getAAMetadata(AAInfo);
4869     Result = DAG.getMemIntrinsicNode(
4870         Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4871         MachinePointerInfo(Info.ptrVal, Info.offset),
4872         Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
4873   } else if (!HasChain) {
4874     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4875   } else if (!I.getType()->isVoidTy()) {
4876     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4877   } else {
4878     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4879   }
4880 
4881   if (HasChain) {
4882     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4883     if (OnlyLoad)
4884       PendingLoads.push_back(Chain);
4885     else
4886       DAG.setRoot(Chain);
4887   }
4888 
4889   if (!I.getType()->isVoidTy()) {
4890     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4891       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4892       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4893     } else
4894       Result = lowerRangeToAssertZExt(DAG, I, Result);
4895 
4896     setValue(&I, Result);
4897   }
4898 }
4899 
4900 /// GetSignificand - Get the significand and build it into a floating-point
4901 /// number with exponent of 1:
4902 ///
4903 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4904 ///
4905 /// where Op is the hexadecimal representation of floating point value.
4906 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4907   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4908                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4909   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4910                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4911   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4912 }
4913 
4914 /// GetExponent - Get the exponent:
4915 ///
4916 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4917 ///
4918 /// where Op is the hexadecimal representation of floating point value.
4919 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4920                            const TargetLowering &TLI, const SDLoc &dl) {
4921   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4922                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4923   SDValue t1 = DAG.getNode(
4924       ISD::SRL, dl, MVT::i32, t0,
4925       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4926   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4927                            DAG.getConstant(127, dl, MVT::i32));
4928   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4929 }
4930 
4931 /// getF32Constant - Get 32-bit floating point constant.
4932 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4933                               const SDLoc &dl) {
4934   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4935                            MVT::f32);
4936 }
4937 
4938 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4939                                        SelectionDAG &DAG) {
4940   // TODO: What fast-math-flags should be set on the floating-point nodes?
4941 
4942   //   IntegerPartOfX = ((int32_t)(t0);
4943   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4944 
4945   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4946   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4947   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4948 
4949   //   IntegerPartOfX <<= 23;
4950   IntegerPartOfX = DAG.getNode(
4951       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4952       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4953                                   DAG.getDataLayout())));
4954 
4955   SDValue TwoToFractionalPartOfX;
4956   if (LimitFloatPrecision <= 6) {
4957     // For floating-point precision of 6:
4958     //
4959     //   TwoToFractionalPartOfX =
4960     //     0.997535578f +
4961     //       (0.735607626f + 0.252464424f * x) * x;
4962     //
4963     // error 0.0144103317, which is 6 bits
4964     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4965                              getF32Constant(DAG, 0x3e814304, dl));
4966     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4967                              getF32Constant(DAG, 0x3f3c50c8, dl));
4968     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4969     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4970                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4971   } else if (LimitFloatPrecision <= 12) {
4972     // For floating-point precision of 12:
4973     //
4974     //   TwoToFractionalPartOfX =
4975     //     0.999892986f +
4976     //       (0.696457318f +
4977     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4978     //
4979     // error 0.000107046256, which is 13 to 14 bits
4980     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4981                              getF32Constant(DAG, 0x3da235e3, dl));
4982     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4983                              getF32Constant(DAG, 0x3e65b8f3, dl));
4984     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4985     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4986                              getF32Constant(DAG, 0x3f324b07, dl));
4987     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4988     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4989                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4990   } else { // LimitFloatPrecision <= 18
4991     // For floating-point precision of 18:
4992     //
4993     //   TwoToFractionalPartOfX =
4994     //     0.999999982f +
4995     //       (0.693148872f +
4996     //         (0.240227044f +
4997     //           (0.554906021e-1f +
4998     //             (0.961591928e-2f +
4999     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5000     // error 2.47208000*10^(-7), which is better than 18 bits
5001     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5002                              getF32Constant(DAG, 0x3924b03e, dl));
5003     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5004                              getF32Constant(DAG, 0x3ab24b87, dl));
5005     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5006     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5007                              getF32Constant(DAG, 0x3c1d8c17, dl));
5008     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5009     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5010                              getF32Constant(DAG, 0x3d634a1d, dl));
5011     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5012     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5013                              getF32Constant(DAG, 0x3e75fe14, dl));
5014     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5015     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5016                               getF32Constant(DAG, 0x3f317234, dl));
5017     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5018     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5019                                          getF32Constant(DAG, 0x3f800000, dl));
5020   }
5021 
5022   // Add the exponent into the result in integer domain.
5023   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5024   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5025                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5026 }
5027 
5028 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5029 /// limited-precision mode.
5030 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5031                          const TargetLowering &TLI) {
5032   if (Op.getValueType() == MVT::f32 &&
5033       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5034 
5035     // Put the exponent in the right bit position for later addition to the
5036     // final result:
5037     //
5038     // t0 = Op * log2(e)
5039 
5040     // TODO: What fast-math-flags should be set here?
5041     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5042                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5043     return getLimitedPrecisionExp2(t0, dl, DAG);
5044   }
5045 
5046   // No special expansion.
5047   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
5048 }
5049 
5050 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5051 /// limited-precision mode.
5052 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5053                          const TargetLowering &TLI) {
5054   // TODO: What fast-math-flags should be set on the floating-point nodes?
5055 
5056   if (Op.getValueType() == MVT::f32 &&
5057       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5058     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5059 
5060     // Scale the exponent by log(2).
5061     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5062     SDValue LogOfExponent =
5063         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5064                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5065 
5066     // Get the significand and build it into a floating-point number with
5067     // exponent of 1.
5068     SDValue X = GetSignificand(DAG, Op1, dl);
5069 
5070     SDValue LogOfMantissa;
5071     if (LimitFloatPrecision <= 6) {
5072       // For floating-point precision of 6:
5073       //
5074       //   LogofMantissa =
5075       //     -1.1609546f +
5076       //       (1.4034025f - 0.23903021f * x) * x;
5077       //
5078       // error 0.0034276066, which is better than 8 bits
5079       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5080                                getF32Constant(DAG, 0xbe74c456, dl));
5081       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5082                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5083       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5084       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5085                                   getF32Constant(DAG, 0x3f949a29, dl));
5086     } else if (LimitFloatPrecision <= 12) {
5087       // For floating-point precision of 12:
5088       //
5089       //   LogOfMantissa =
5090       //     -1.7417939f +
5091       //       (2.8212026f +
5092       //         (-1.4699568f +
5093       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5094       //
5095       // error 0.000061011436, which is 14 bits
5096       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5097                                getF32Constant(DAG, 0xbd67b6d6, dl));
5098       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5099                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5100       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5101       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5102                                getF32Constant(DAG, 0x3fbc278b, dl));
5103       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5104       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5105                                getF32Constant(DAG, 0x40348e95, dl));
5106       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5107       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5108                                   getF32Constant(DAG, 0x3fdef31a, dl));
5109     } else { // LimitFloatPrecision <= 18
5110       // For floating-point precision of 18:
5111       //
5112       //   LogOfMantissa =
5113       //     -2.1072184f +
5114       //       (4.2372794f +
5115       //         (-3.7029485f +
5116       //           (2.2781945f +
5117       //             (-0.87823314f +
5118       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5119       //
5120       // error 0.0000023660568, which is better than 18 bits
5121       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5122                                getF32Constant(DAG, 0xbc91e5ac, dl));
5123       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5124                                getF32Constant(DAG, 0x3e4350aa, dl));
5125       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5126       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5127                                getF32Constant(DAG, 0x3f60d3e3, dl));
5128       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5129       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5130                                getF32Constant(DAG, 0x4011cdf0, dl));
5131       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5132       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5133                                getF32Constant(DAG, 0x406cfd1c, dl));
5134       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5135       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5136                                getF32Constant(DAG, 0x408797cb, dl));
5137       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5138       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5139                                   getF32Constant(DAG, 0x4006dcab, dl));
5140     }
5141 
5142     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5143   }
5144 
5145   // No special expansion.
5146   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5147 }
5148 
5149 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5150 /// limited-precision mode.
5151 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5152                           const TargetLowering &TLI) {
5153   // TODO: What fast-math-flags should be set on the floating-point nodes?
5154 
5155   if (Op.getValueType() == MVT::f32 &&
5156       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5157     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5158 
5159     // Get the exponent.
5160     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5161 
5162     // Get the significand and build it into a floating-point number with
5163     // exponent of 1.
5164     SDValue X = GetSignificand(DAG, Op1, dl);
5165 
5166     // Different possible minimax approximations of significand in
5167     // floating-point for various degrees of accuracy over [1,2].
5168     SDValue Log2ofMantissa;
5169     if (LimitFloatPrecision <= 6) {
5170       // For floating-point precision of 6:
5171       //
5172       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5173       //
5174       // error 0.0049451742, which is more than 7 bits
5175       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5176                                getF32Constant(DAG, 0xbeb08fe0, dl));
5177       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5178                                getF32Constant(DAG, 0x40019463, dl));
5179       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5180       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5181                                    getF32Constant(DAG, 0x3fd6633d, dl));
5182     } else if (LimitFloatPrecision <= 12) {
5183       // For floating-point precision of 12:
5184       //
5185       //   Log2ofMantissa =
5186       //     -2.51285454f +
5187       //       (4.07009056f +
5188       //         (-2.12067489f +
5189       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5190       //
5191       // error 0.0000876136000, which is better than 13 bits
5192       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5193                                getF32Constant(DAG, 0xbda7262e, dl));
5194       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5195                                getF32Constant(DAG, 0x3f25280b, dl));
5196       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5197       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5198                                getF32Constant(DAG, 0x4007b923, dl));
5199       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5200       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5201                                getF32Constant(DAG, 0x40823e2f, dl));
5202       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5203       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5204                                    getF32Constant(DAG, 0x4020d29c, dl));
5205     } else { // LimitFloatPrecision <= 18
5206       // For floating-point precision of 18:
5207       //
5208       //   Log2ofMantissa =
5209       //     -3.0400495f +
5210       //       (6.1129976f +
5211       //         (-5.3420409f +
5212       //           (3.2865683f +
5213       //             (-1.2669343f +
5214       //               (0.27515199f -
5215       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5216       //
5217       // error 0.0000018516, which is better than 18 bits
5218       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5219                                getF32Constant(DAG, 0xbcd2769e, dl));
5220       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5221                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5222       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5223       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5224                                getF32Constant(DAG, 0x3fa22ae7, dl));
5225       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5226       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5227                                getF32Constant(DAG, 0x40525723, dl));
5228       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5229       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5230                                getF32Constant(DAG, 0x40aaf200, dl));
5231       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5232       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5233                                getF32Constant(DAG, 0x40c39dad, dl));
5234       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5235       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5236                                    getF32Constant(DAG, 0x4042902c, dl));
5237     }
5238 
5239     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5240   }
5241 
5242   // No special expansion.
5243   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5244 }
5245 
5246 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5247 /// limited-precision mode.
5248 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5249                            const TargetLowering &TLI) {
5250   // TODO: What fast-math-flags should be set on the floating-point nodes?
5251 
5252   if (Op.getValueType() == MVT::f32 &&
5253       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5254     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5255 
5256     // Scale the exponent by log10(2) [0.30102999f].
5257     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5258     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5259                                         getF32Constant(DAG, 0x3e9a209a, dl));
5260 
5261     // Get the significand and build it into a floating-point number with
5262     // exponent of 1.
5263     SDValue X = GetSignificand(DAG, Op1, dl);
5264 
5265     SDValue Log10ofMantissa;
5266     if (LimitFloatPrecision <= 6) {
5267       // For floating-point precision of 6:
5268       //
5269       //   Log10ofMantissa =
5270       //     -0.50419619f +
5271       //       (0.60948995f - 0.10380950f * x) * x;
5272       //
5273       // error 0.0014886165, which is 6 bits
5274       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5275                                getF32Constant(DAG, 0xbdd49a13, dl));
5276       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5277                                getF32Constant(DAG, 0x3f1c0789, dl));
5278       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5279       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5280                                     getF32Constant(DAG, 0x3f011300, dl));
5281     } else if (LimitFloatPrecision <= 12) {
5282       // For floating-point precision of 12:
5283       //
5284       //   Log10ofMantissa =
5285       //     -0.64831180f +
5286       //       (0.91751397f +
5287       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5288       //
5289       // error 0.00019228036, which is better than 12 bits
5290       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5291                                getF32Constant(DAG, 0x3d431f31, dl));
5292       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5293                                getF32Constant(DAG, 0x3ea21fb2, dl));
5294       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5295       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5296                                getF32Constant(DAG, 0x3f6ae232, dl));
5297       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5298       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5299                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5300     } else { // LimitFloatPrecision <= 18
5301       // For floating-point precision of 18:
5302       //
5303       //   Log10ofMantissa =
5304       //     -0.84299375f +
5305       //       (1.5327582f +
5306       //         (-1.0688956f +
5307       //           (0.49102474f +
5308       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5309       //
5310       // error 0.0000037995730, which is better than 18 bits
5311       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5312                                getF32Constant(DAG, 0x3c5d51ce, dl));
5313       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5314                                getF32Constant(DAG, 0x3e00685a, dl));
5315       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5316       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5317                                getF32Constant(DAG, 0x3efb6798, dl));
5318       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5319       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5320                                getF32Constant(DAG, 0x3f88d192, dl));
5321       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5322       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5323                                getF32Constant(DAG, 0x3fc4316c, dl));
5324       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5325       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5326                                     getF32Constant(DAG, 0x3f57ce70, dl));
5327     }
5328 
5329     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5330   }
5331 
5332   // No special expansion.
5333   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5334 }
5335 
5336 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5337 /// limited-precision mode.
5338 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5339                           const TargetLowering &TLI) {
5340   if (Op.getValueType() == MVT::f32 &&
5341       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5342     return getLimitedPrecisionExp2(Op, dl, DAG);
5343 
5344   // No special expansion.
5345   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5346 }
5347 
5348 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5349 /// limited-precision mode with x == 10.0f.
5350 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5351                          SelectionDAG &DAG, const TargetLowering &TLI) {
5352   bool IsExp10 = false;
5353   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5354       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5355     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5356       APFloat Ten(10.0f);
5357       IsExp10 = LHSC->isExactlyValue(Ten);
5358     }
5359   }
5360 
5361   // TODO: What fast-math-flags should be set on the FMUL node?
5362   if (IsExp10) {
5363     // Put the exponent in the right bit position for later addition to the
5364     // final result:
5365     //
5366     //   #define LOG2OF10 3.3219281f
5367     //   t0 = Op * LOG2OF10;
5368     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5369                              getF32Constant(DAG, 0x40549a78, dl));
5370     return getLimitedPrecisionExp2(t0, dl, DAG);
5371   }
5372 
5373   // No special expansion.
5374   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5375 }
5376 
5377 /// ExpandPowI - Expand a llvm.powi intrinsic.
5378 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5379                           SelectionDAG &DAG) {
5380   // If RHS is a constant, we can expand this out to a multiplication tree,
5381   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5382   // optimizing for size, we only want to do this if the expansion would produce
5383   // a small number of multiplies, otherwise we do the full expansion.
5384   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5385     // Get the exponent as a positive value.
5386     unsigned Val = RHSC->getSExtValue();
5387     if ((int)Val < 0) Val = -Val;
5388 
5389     // powi(x, 0) -> 1.0
5390     if (Val == 0)
5391       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5392 
5393     bool OptForSize = DAG.shouldOptForSize();
5394     if (!OptForSize ||
5395         // If optimizing for size, don't insert too many multiplies.
5396         // This inserts up to 5 multiplies.
5397         countPopulation(Val) + Log2_32(Val) < 7) {
5398       // We use the simple binary decomposition method to generate the multiply
5399       // sequence.  There are more optimal ways to do this (for example,
5400       // powi(x,15) generates one more multiply than it should), but this has
5401       // the benefit of being both really simple and much better than a libcall.
5402       SDValue Res;  // Logically starts equal to 1.0
5403       SDValue CurSquare = LHS;
5404       // TODO: Intrinsics should have fast-math-flags that propagate to these
5405       // nodes.
5406       while (Val) {
5407         if (Val & 1) {
5408           if (Res.getNode())
5409             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5410           else
5411             Res = CurSquare;  // 1.0*CurSquare.
5412         }
5413 
5414         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5415                                 CurSquare, CurSquare);
5416         Val >>= 1;
5417       }
5418 
5419       // If the original was negative, invert the result, producing 1/(x*x*x).
5420       if (RHSC->getSExtValue() < 0)
5421         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5422                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5423       return Res;
5424     }
5425   }
5426 
5427   // Otherwise, expand to a libcall.
5428   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5429 }
5430 
5431 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5432                             SDValue LHS, SDValue RHS, SDValue Scale,
5433                             SelectionDAG &DAG, const TargetLowering &TLI) {
5434   EVT VT = LHS.getValueType();
5435   bool Signed = Opcode == ISD::SDIVFIX;
5436   LLVMContext &Ctx = *DAG.getContext();
5437 
5438   // If the type is legal but the operation isn't, this node might survive all
5439   // the way to operation legalization. If we end up there and we do not have
5440   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5441   // node.
5442 
5443   // Coax the legalizer into expanding the node during type legalization instead
5444   // by bumping the size by one bit. This will force it to Promote, enabling the
5445   // early expansion and avoiding the need to expand later.
5446 
5447   // We don't have to do this if Scale is 0; that can always be expanded.
5448 
5449   // FIXME: We wouldn't have to do this (or any of the early
5450   // expansion/promotion) if it was possible to expand a libcall of an
5451   // illegal type during operation legalization. But it's not, so things
5452   // get a bit hacky.
5453   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5454   if (ScaleInt > 0 &&
5455       (TLI.isTypeLegal(VT) ||
5456        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5457     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5458         Opcode, VT, ScaleInt);
5459     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5460       EVT PromVT;
5461       if (VT.isScalarInteger())
5462         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5463       else if (VT.isVector()) {
5464         PromVT = VT.getVectorElementType();
5465         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5466         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5467       } else
5468         llvm_unreachable("Wrong VT for DIVFIX?");
5469       if (Signed) {
5470         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5471         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5472       } else {
5473         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5474         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5475       }
5476       // TODO: Saturation.
5477       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5478       return DAG.getZExtOrTrunc(Res, DL, VT);
5479     }
5480   }
5481 
5482   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5483 }
5484 
5485 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5486 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5487 static void
5488 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5489                      const SDValue &N) {
5490   switch (N.getOpcode()) {
5491   case ISD::CopyFromReg: {
5492     SDValue Op = N.getOperand(1);
5493     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5494                       Op.getValueType().getSizeInBits());
5495     return;
5496   }
5497   case ISD::BITCAST:
5498   case ISD::AssertZext:
5499   case ISD::AssertSext:
5500   case ISD::TRUNCATE:
5501     getUnderlyingArgRegs(Regs, N.getOperand(0));
5502     return;
5503   case ISD::BUILD_PAIR:
5504   case ISD::BUILD_VECTOR:
5505   case ISD::CONCAT_VECTORS:
5506     for (SDValue Op : N->op_values())
5507       getUnderlyingArgRegs(Regs, Op);
5508     return;
5509   default:
5510     return;
5511   }
5512 }
5513 
5514 /// If the DbgValueInst is a dbg_value of a function argument, create the
5515 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5516 /// instruction selection, they will be inserted to the entry BB.
5517 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5518     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5519     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5520   const Argument *Arg = dyn_cast<Argument>(V);
5521   if (!Arg)
5522     return false;
5523 
5524   if (!IsDbgDeclare) {
5525     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5526     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5527     // the entry block.
5528     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5529     if (!IsInEntryBlock)
5530       return false;
5531 
5532     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5533     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5534     // variable that also is a param.
5535     //
5536     // Although, if we are at the top of the entry block already, we can still
5537     // emit using ArgDbgValue. This might catch some situations when the
5538     // dbg.value refers to an argument that isn't used in the entry block, so
5539     // any CopyToReg node would be optimized out and the only way to express
5540     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5541     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5542     // we should only emit as ArgDbgValue if the Variable is an argument to the
5543     // current function, and the dbg.value intrinsic is found in the entry
5544     // block.
5545     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5546         !DL->getInlinedAt();
5547     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5548     if (!IsInPrologue && !VariableIsFunctionInputArg)
5549       return false;
5550 
5551     // Here we assume that a function argument on IR level only can be used to
5552     // describe one input parameter on source level. If we for example have
5553     // source code like this
5554     //
5555     //    struct A { long x, y; };
5556     //    void foo(struct A a, long b) {
5557     //      ...
5558     //      b = a.x;
5559     //      ...
5560     //    }
5561     //
5562     // and IR like this
5563     //
5564     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5565     //  entry:
5566     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5567     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5568     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5569     //    ...
5570     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5571     //    ...
5572     //
5573     // then the last dbg.value is describing a parameter "b" using a value that
5574     // is an argument. But since we already has used %a1 to describe a parameter
5575     // we should not handle that last dbg.value here (that would result in an
5576     // incorrect hoisting of the DBG_VALUE to the function entry).
5577     // Notice that we allow one dbg.value per IR level argument, to accommodate
5578     // for the situation with fragments above.
5579     if (VariableIsFunctionInputArg) {
5580       unsigned ArgNo = Arg->getArgNo();
5581       if (ArgNo >= FuncInfo.DescribedArgs.size())
5582         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5583       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5584         return false;
5585       FuncInfo.DescribedArgs.set(ArgNo);
5586     }
5587   }
5588 
5589   MachineFunction &MF = DAG.getMachineFunction();
5590   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5591 
5592   Optional<MachineOperand> Op;
5593   // Some arguments' frame index is recorded during argument lowering.
5594   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5595   if (FI != std::numeric_limits<int>::max())
5596     Op = MachineOperand::CreateFI(FI);
5597 
5598   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5599   if (!Op && N.getNode()) {
5600     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5601     Register Reg;
5602     if (ArgRegsAndSizes.size() == 1)
5603       Reg = ArgRegsAndSizes.front().first;
5604 
5605     if (Reg && Reg.isVirtual()) {
5606       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5607       Register PR = RegInfo.getLiveInPhysReg(Reg);
5608       if (PR)
5609         Reg = PR;
5610     }
5611     if (Reg) {
5612       Op = MachineOperand::CreateReg(Reg, false);
5613     }
5614   }
5615 
5616   if (!Op && N.getNode()) {
5617     // Check if frame index is available.
5618     SDValue LCandidate = peekThroughBitcasts(N);
5619     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5620       if (FrameIndexSDNode *FINode =
5621           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5622         Op = MachineOperand::CreateFI(FINode->getIndex());
5623   }
5624 
5625   if (!Op) {
5626     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5627     auto splitMultiRegDbgValue
5628       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5629       unsigned Offset = 0;
5630       for (auto RegAndSize : SplitRegs) {
5631         // If the expression is already a fragment, the current register
5632         // offset+size might extend beyond the fragment. In this case, only
5633         // the register bits that are inside the fragment are relevant.
5634         int RegFragmentSizeInBits = RegAndSize.second;
5635         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5636           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5637           // The register is entirely outside the expression fragment,
5638           // so is irrelevant for debug info.
5639           if (Offset >= ExprFragmentSizeInBits)
5640             break;
5641           // The register is partially outside the expression fragment, only
5642           // the low bits within the fragment are relevant for debug info.
5643           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5644             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5645           }
5646         }
5647 
5648         auto FragmentExpr = DIExpression::createFragmentExpression(
5649             Expr, Offset, RegFragmentSizeInBits);
5650         Offset += RegAndSize.second;
5651         // If a valid fragment expression cannot be created, the variable's
5652         // correct value cannot be determined and so it is set as Undef.
5653         if (!FragmentExpr) {
5654           SDDbgValue *SDV = DAG.getConstantDbgValue(
5655               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5656           DAG.AddDbgValue(SDV, nullptr, false);
5657           continue;
5658         }
5659         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5660         FuncInfo.ArgDbgValues.push_back(
5661           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5662                   RegAndSize.first, Variable, *FragmentExpr));
5663       }
5664     };
5665 
5666     // Check if ValueMap has reg number.
5667     DenseMap<const Value *, unsigned>::const_iterator
5668       VMI = FuncInfo.ValueMap.find(V);
5669     if (VMI != FuncInfo.ValueMap.end()) {
5670       const auto &TLI = DAG.getTargetLoweringInfo();
5671       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5672                        V->getType(), getABIRegCopyCC(V));
5673       if (RFV.occupiesMultipleRegs()) {
5674         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5675         return true;
5676       }
5677 
5678       Op = MachineOperand::CreateReg(VMI->second, false);
5679     } else if (ArgRegsAndSizes.size() > 1) {
5680       // This was split due to the calling convention, and no virtual register
5681       // mapping exists for the value.
5682       splitMultiRegDbgValue(ArgRegsAndSizes);
5683       return true;
5684     }
5685   }
5686 
5687   if (!Op)
5688     return false;
5689 
5690   assert(Variable->isValidLocationForIntrinsic(DL) &&
5691          "Expected inlined-at fields to agree");
5692 
5693   // If the argument arrives in a stack slot, then what the IR thought was a
5694   // normal Value is actually in memory, and we must add a deref to load it.
5695   if (Op->isFI()) {
5696     int FI = Op->getIndex();
5697     unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI);
5698     if (Expr->isImplicit()) {
5699       SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
5700       Expr = DIExpression::prependOpcodes(Expr, Ops);
5701     } else {
5702       Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
5703     }
5704   }
5705 
5706   // If this location was specified with a dbg.declare, then it and its
5707   // expression calculate the address of the variable. Append a deref to
5708   // force it to be a memory location.
5709   if (IsDbgDeclare)
5710     Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref});
5711 
5712   FuncInfo.ArgDbgValues.push_back(
5713       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5714               *Op, Variable, Expr));
5715 
5716   return true;
5717 }
5718 
5719 /// Return the appropriate SDDbgValue based on N.
5720 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5721                                              DILocalVariable *Variable,
5722                                              DIExpression *Expr,
5723                                              const DebugLoc &dl,
5724                                              unsigned DbgSDNodeOrder) {
5725   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5726     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5727     // stack slot locations.
5728     //
5729     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5730     // debug values here after optimization:
5731     //
5732     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5733     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5734     //
5735     // Both describe the direct values of their associated variables.
5736     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5737                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5738   }
5739   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5740                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5741 }
5742 
5743 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5744   switch (Intrinsic) {
5745   case Intrinsic::smul_fix:
5746     return ISD::SMULFIX;
5747   case Intrinsic::umul_fix:
5748     return ISD::UMULFIX;
5749   case Intrinsic::smul_fix_sat:
5750     return ISD::SMULFIXSAT;
5751   case Intrinsic::umul_fix_sat:
5752     return ISD::UMULFIXSAT;
5753   case Intrinsic::sdiv_fix:
5754     return ISD::SDIVFIX;
5755   case Intrinsic::udiv_fix:
5756     return ISD::UDIVFIX;
5757   default:
5758     llvm_unreachable("Unhandled fixed point intrinsic");
5759   }
5760 }
5761 
5762 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5763                                            const char *FunctionName) {
5764   assert(FunctionName && "FunctionName must not be nullptr");
5765   SDValue Callee = DAG.getExternalSymbol(
5766       FunctionName,
5767       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5768   LowerCallTo(&I, Callee, I.isTailCall());
5769 }
5770 
5771 /// Lower the call to the specified intrinsic function.
5772 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5773                                              unsigned Intrinsic) {
5774   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5775   SDLoc sdl = getCurSDLoc();
5776   DebugLoc dl = getCurDebugLoc();
5777   SDValue Res;
5778 
5779   switch (Intrinsic) {
5780   default:
5781     // By default, turn this into a target intrinsic node.
5782     visitTargetIntrinsic(I, Intrinsic);
5783     return;
5784   case Intrinsic::vastart:  visitVAStart(I); return;
5785   case Intrinsic::vaend:    visitVAEnd(I); return;
5786   case Intrinsic::vacopy:   visitVACopy(I); return;
5787   case Intrinsic::returnaddress:
5788     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5789                              TLI.getPointerTy(DAG.getDataLayout()),
5790                              getValue(I.getArgOperand(0))));
5791     return;
5792   case Intrinsic::addressofreturnaddress:
5793     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5794                              TLI.getPointerTy(DAG.getDataLayout())));
5795     return;
5796   case Intrinsic::sponentry:
5797     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5798                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5799     return;
5800   case Intrinsic::frameaddress:
5801     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5802                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5803                              getValue(I.getArgOperand(0))));
5804     return;
5805   case Intrinsic::read_register: {
5806     Value *Reg = I.getArgOperand(0);
5807     SDValue Chain = getRoot();
5808     SDValue RegName =
5809         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5810     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5811     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5812       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5813     setValue(&I, Res);
5814     DAG.setRoot(Res.getValue(1));
5815     return;
5816   }
5817   case Intrinsic::write_register: {
5818     Value *Reg = I.getArgOperand(0);
5819     Value *RegValue = I.getArgOperand(1);
5820     SDValue Chain = getRoot();
5821     SDValue RegName =
5822         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5823     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5824                             RegName, getValue(RegValue)));
5825     return;
5826   }
5827   case Intrinsic::memcpy: {
5828     const auto &MCI = cast<MemCpyInst>(I);
5829     SDValue Op1 = getValue(I.getArgOperand(0));
5830     SDValue Op2 = getValue(I.getArgOperand(1));
5831     SDValue Op3 = getValue(I.getArgOperand(2));
5832     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5833     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5834     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5835     unsigned Align = MinAlign(DstAlign, SrcAlign);
5836     bool isVol = MCI.isVolatile();
5837     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5838     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5839     // node.
5840     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5841     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Align, isVol,
5842                                false, isTC,
5843                                MachinePointerInfo(I.getArgOperand(0)),
5844                                MachinePointerInfo(I.getArgOperand(1)));
5845     updateDAGForMaybeTailCall(MC);
5846     return;
5847   }
5848   case Intrinsic::memset: {
5849     const auto &MSI = cast<MemSetInst>(I);
5850     SDValue Op1 = getValue(I.getArgOperand(0));
5851     SDValue Op2 = getValue(I.getArgOperand(1));
5852     SDValue Op3 = getValue(I.getArgOperand(2));
5853     // @llvm.memset defines 0 and 1 to both mean no alignment.
5854     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5855     bool isVol = MSI.isVolatile();
5856     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5857     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5858     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Align, isVol,
5859                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5860     updateDAGForMaybeTailCall(MS);
5861     return;
5862   }
5863   case Intrinsic::memmove: {
5864     const auto &MMI = cast<MemMoveInst>(I);
5865     SDValue Op1 = getValue(I.getArgOperand(0));
5866     SDValue Op2 = getValue(I.getArgOperand(1));
5867     SDValue Op3 = getValue(I.getArgOperand(2));
5868     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5869     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5870     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5871     unsigned Align = MinAlign(DstAlign, SrcAlign);
5872     bool isVol = MMI.isVolatile();
5873     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5874     // FIXME: Support passing different dest/src alignments to the memmove DAG
5875     // node.
5876     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5877     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Align, isVol,
5878                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5879                                 MachinePointerInfo(I.getArgOperand(1)));
5880     updateDAGForMaybeTailCall(MM);
5881     return;
5882   }
5883   case Intrinsic::memcpy_element_unordered_atomic: {
5884     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5885     SDValue Dst = getValue(MI.getRawDest());
5886     SDValue Src = getValue(MI.getRawSource());
5887     SDValue Length = getValue(MI.getLength());
5888 
5889     unsigned DstAlign = MI.getDestAlignment();
5890     unsigned SrcAlign = MI.getSourceAlignment();
5891     Type *LengthTy = MI.getLength()->getType();
5892     unsigned ElemSz = MI.getElementSizeInBytes();
5893     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5894     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5895                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5896                                      MachinePointerInfo(MI.getRawDest()),
5897                                      MachinePointerInfo(MI.getRawSource()));
5898     updateDAGForMaybeTailCall(MC);
5899     return;
5900   }
5901   case Intrinsic::memmove_element_unordered_atomic: {
5902     auto &MI = cast<AtomicMemMoveInst>(I);
5903     SDValue Dst = getValue(MI.getRawDest());
5904     SDValue Src = getValue(MI.getRawSource());
5905     SDValue Length = getValue(MI.getLength());
5906 
5907     unsigned DstAlign = MI.getDestAlignment();
5908     unsigned SrcAlign = MI.getSourceAlignment();
5909     Type *LengthTy = MI.getLength()->getType();
5910     unsigned ElemSz = MI.getElementSizeInBytes();
5911     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5912     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5913                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5914                                       MachinePointerInfo(MI.getRawDest()),
5915                                       MachinePointerInfo(MI.getRawSource()));
5916     updateDAGForMaybeTailCall(MC);
5917     return;
5918   }
5919   case Intrinsic::memset_element_unordered_atomic: {
5920     auto &MI = cast<AtomicMemSetInst>(I);
5921     SDValue Dst = getValue(MI.getRawDest());
5922     SDValue Val = getValue(MI.getValue());
5923     SDValue Length = getValue(MI.getLength());
5924 
5925     unsigned DstAlign = MI.getDestAlignment();
5926     Type *LengthTy = MI.getLength()->getType();
5927     unsigned ElemSz = MI.getElementSizeInBytes();
5928     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5929     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5930                                      LengthTy, ElemSz, isTC,
5931                                      MachinePointerInfo(MI.getRawDest()));
5932     updateDAGForMaybeTailCall(MC);
5933     return;
5934   }
5935   case Intrinsic::dbg_addr:
5936   case Intrinsic::dbg_declare: {
5937     const auto &DI = cast<DbgVariableIntrinsic>(I);
5938     DILocalVariable *Variable = DI.getVariable();
5939     DIExpression *Expression = DI.getExpression();
5940     dropDanglingDebugInfo(Variable, Expression);
5941     assert(Variable && "Missing variable");
5942 
5943     // Check if address has undef value.
5944     const Value *Address = DI.getVariableLocation();
5945     if (!Address || isa<UndefValue>(Address) ||
5946         (Address->use_empty() && !isa<Argument>(Address))) {
5947       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5948       return;
5949     }
5950 
5951     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5952 
5953     // Check if this variable can be described by a frame index, typically
5954     // either as a static alloca or a byval parameter.
5955     int FI = std::numeric_limits<int>::max();
5956     if (const auto *AI =
5957             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5958       if (AI->isStaticAlloca()) {
5959         auto I = FuncInfo.StaticAllocaMap.find(AI);
5960         if (I != FuncInfo.StaticAllocaMap.end())
5961           FI = I->second;
5962       }
5963     } else if (const auto *Arg = dyn_cast<Argument>(
5964                    Address->stripInBoundsConstantOffsets())) {
5965       FI = FuncInfo.getArgumentFrameIndex(Arg);
5966     }
5967 
5968     // llvm.dbg.addr is control dependent and always generates indirect
5969     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5970     // the MachineFunction variable table.
5971     if (FI != std::numeric_limits<int>::max()) {
5972       if (Intrinsic == Intrinsic::dbg_addr) {
5973         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5974             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5975         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5976       }
5977       return;
5978     }
5979 
5980     SDValue &N = NodeMap[Address];
5981     if (!N.getNode() && isa<Argument>(Address))
5982       // Check unused arguments map.
5983       N = UnusedArgNodeMap[Address];
5984     SDDbgValue *SDV;
5985     if (N.getNode()) {
5986       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5987         Address = BCI->getOperand(0);
5988       // Parameters are handled specially.
5989       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5990       if (isParameter && FINode) {
5991         // Byval parameter. We have a frame index at this point.
5992         SDV =
5993             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5994                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5995       } else if (isa<Argument>(Address)) {
5996         // Address is an argument, so try to emit its dbg value using
5997         // virtual register info from the FuncInfo.ValueMap.
5998         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5999         return;
6000       } else {
6001         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6002                               true, dl, SDNodeOrder);
6003       }
6004       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
6005     } else {
6006       // If Address is an argument then try to emit its dbg value using
6007       // virtual register info from the FuncInfo.ValueMap.
6008       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6009                                     N)) {
6010         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
6011       }
6012     }
6013     return;
6014   }
6015   case Intrinsic::dbg_label: {
6016     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6017     DILabel *Label = DI.getLabel();
6018     assert(Label && "Missing label");
6019 
6020     SDDbgLabel *SDV;
6021     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6022     DAG.AddDbgLabel(SDV);
6023     return;
6024   }
6025   case Intrinsic::dbg_value: {
6026     const DbgValueInst &DI = cast<DbgValueInst>(I);
6027     assert(DI.getVariable() && "Missing variable");
6028 
6029     DILocalVariable *Variable = DI.getVariable();
6030     DIExpression *Expression = DI.getExpression();
6031     dropDanglingDebugInfo(Variable, Expression);
6032     const Value *V = DI.getValue();
6033     if (!V)
6034       return;
6035 
6036     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
6037         SDNodeOrder))
6038       return;
6039 
6040     // TODO: Dangling debug info will eventually either be resolved or produce
6041     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
6042     // between the original dbg.value location and its resolved DBG_VALUE, which
6043     // we should ideally fill with an extra Undef DBG_VALUE.
6044 
6045     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
6046     return;
6047   }
6048 
6049   case Intrinsic::eh_typeid_for: {
6050     // Find the type id for the given typeinfo.
6051     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6052     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6053     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6054     setValue(&I, Res);
6055     return;
6056   }
6057 
6058   case Intrinsic::eh_return_i32:
6059   case Intrinsic::eh_return_i64:
6060     DAG.getMachineFunction().setCallsEHReturn(true);
6061     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6062                             MVT::Other,
6063                             getControlRoot(),
6064                             getValue(I.getArgOperand(0)),
6065                             getValue(I.getArgOperand(1))));
6066     return;
6067   case Intrinsic::eh_unwind_init:
6068     DAG.getMachineFunction().setCallsUnwindInit(true);
6069     return;
6070   case Intrinsic::eh_dwarf_cfa:
6071     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6072                              TLI.getPointerTy(DAG.getDataLayout()),
6073                              getValue(I.getArgOperand(0))));
6074     return;
6075   case Intrinsic::eh_sjlj_callsite: {
6076     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6077     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6078     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6079     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6080 
6081     MMI.setCurrentCallSite(CI->getZExtValue());
6082     return;
6083   }
6084   case Intrinsic::eh_sjlj_functioncontext: {
6085     // Get and store the index of the function context.
6086     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6087     AllocaInst *FnCtx =
6088       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6089     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6090     MFI.setFunctionContextIndex(FI);
6091     return;
6092   }
6093   case Intrinsic::eh_sjlj_setjmp: {
6094     SDValue Ops[2];
6095     Ops[0] = getRoot();
6096     Ops[1] = getValue(I.getArgOperand(0));
6097     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6098                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6099     setValue(&I, Op.getValue(0));
6100     DAG.setRoot(Op.getValue(1));
6101     return;
6102   }
6103   case Intrinsic::eh_sjlj_longjmp:
6104     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6105                             getRoot(), getValue(I.getArgOperand(0))));
6106     return;
6107   case Intrinsic::eh_sjlj_setup_dispatch:
6108     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6109                             getRoot()));
6110     return;
6111   case Intrinsic::masked_gather:
6112     visitMaskedGather(I);
6113     return;
6114   case Intrinsic::masked_load:
6115     visitMaskedLoad(I);
6116     return;
6117   case Intrinsic::masked_scatter:
6118     visitMaskedScatter(I);
6119     return;
6120   case Intrinsic::masked_store:
6121     visitMaskedStore(I);
6122     return;
6123   case Intrinsic::masked_expandload:
6124     visitMaskedLoad(I, true /* IsExpanding */);
6125     return;
6126   case Intrinsic::masked_compressstore:
6127     visitMaskedStore(I, true /* IsCompressing */);
6128     return;
6129   case Intrinsic::powi:
6130     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6131                             getValue(I.getArgOperand(1)), DAG));
6132     return;
6133   case Intrinsic::log:
6134     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6135     return;
6136   case Intrinsic::log2:
6137     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6138     return;
6139   case Intrinsic::log10:
6140     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6141     return;
6142   case Intrinsic::exp:
6143     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6144     return;
6145   case Intrinsic::exp2:
6146     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6147     return;
6148   case Intrinsic::pow:
6149     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6150                            getValue(I.getArgOperand(1)), DAG, TLI));
6151     return;
6152   case Intrinsic::sqrt:
6153   case Intrinsic::fabs:
6154   case Intrinsic::sin:
6155   case Intrinsic::cos:
6156   case Intrinsic::floor:
6157   case Intrinsic::ceil:
6158   case Intrinsic::trunc:
6159   case Intrinsic::rint:
6160   case Intrinsic::nearbyint:
6161   case Intrinsic::round:
6162   case Intrinsic::canonicalize: {
6163     unsigned Opcode;
6164     switch (Intrinsic) {
6165     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6166     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6167     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6168     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6169     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6170     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6171     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6172     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6173     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6174     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6175     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6176     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6177     }
6178 
6179     setValue(&I, DAG.getNode(Opcode, sdl,
6180                              getValue(I.getArgOperand(0)).getValueType(),
6181                              getValue(I.getArgOperand(0))));
6182     return;
6183   }
6184   case Intrinsic::lround:
6185   case Intrinsic::llround:
6186   case Intrinsic::lrint:
6187   case Intrinsic::llrint: {
6188     unsigned Opcode;
6189     switch (Intrinsic) {
6190     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6191     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6192     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6193     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6194     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6195     }
6196 
6197     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6198     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6199                              getValue(I.getArgOperand(0))));
6200     return;
6201   }
6202   case Intrinsic::minnum:
6203     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6204                              getValue(I.getArgOperand(0)).getValueType(),
6205                              getValue(I.getArgOperand(0)),
6206                              getValue(I.getArgOperand(1))));
6207     return;
6208   case Intrinsic::maxnum:
6209     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6210                              getValue(I.getArgOperand(0)).getValueType(),
6211                              getValue(I.getArgOperand(0)),
6212                              getValue(I.getArgOperand(1))));
6213     return;
6214   case Intrinsic::minimum:
6215     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6216                              getValue(I.getArgOperand(0)).getValueType(),
6217                              getValue(I.getArgOperand(0)),
6218                              getValue(I.getArgOperand(1))));
6219     return;
6220   case Intrinsic::maximum:
6221     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6222                              getValue(I.getArgOperand(0)).getValueType(),
6223                              getValue(I.getArgOperand(0)),
6224                              getValue(I.getArgOperand(1))));
6225     return;
6226   case Intrinsic::copysign:
6227     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6228                              getValue(I.getArgOperand(0)).getValueType(),
6229                              getValue(I.getArgOperand(0)),
6230                              getValue(I.getArgOperand(1))));
6231     return;
6232   case Intrinsic::fma:
6233     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6234                              getValue(I.getArgOperand(0)).getValueType(),
6235                              getValue(I.getArgOperand(0)),
6236                              getValue(I.getArgOperand(1)),
6237                              getValue(I.getArgOperand(2))));
6238     return;
6239 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
6240   case Intrinsic::INTRINSIC:
6241 #include "llvm/IR/ConstrainedOps.def"
6242     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6243     return;
6244   case Intrinsic::fmuladd: {
6245     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6246     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6247         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6248       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6249                                getValue(I.getArgOperand(0)).getValueType(),
6250                                getValue(I.getArgOperand(0)),
6251                                getValue(I.getArgOperand(1)),
6252                                getValue(I.getArgOperand(2))));
6253     } else {
6254       // TODO: Intrinsic calls should have fast-math-flags.
6255       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6256                                 getValue(I.getArgOperand(0)).getValueType(),
6257                                 getValue(I.getArgOperand(0)),
6258                                 getValue(I.getArgOperand(1)));
6259       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6260                                 getValue(I.getArgOperand(0)).getValueType(),
6261                                 Mul,
6262                                 getValue(I.getArgOperand(2)));
6263       setValue(&I, Add);
6264     }
6265     return;
6266   }
6267   case Intrinsic::convert_to_fp16:
6268     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6269                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6270                                          getValue(I.getArgOperand(0)),
6271                                          DAG.getTargetConstant(0, sdl,
6272                                                                MVT::i32))));
6273     return;
6274   case Intrinsic::convert_from_fp16:
6275     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6276                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6277                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6278                                          getValue(I.getArgOperand(0)))));
6279     return;
6280   case Intrinsic::pcmarker: {
6281     SDValue Tmp = getValue(I.getArgOperand(0));
6282     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6283     return;
6284   }
6285   case Intrinsic::readcyclecounter: {
6286     SDValue Op = getRoot();
6287     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6288                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6289     setValue(&I, Res);
6290     DAG.setRoot(Res.getValue(1));
6291     return;
6292   }
6293   case Intrinsic::bitreverse:
6294     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6295                              getValue(I.getArgOperand(0)).getValueType(),
6296                              getValue(I.getArgOperand(0))));
6297     return;
6298   case Intrinsic::bswap:
6299     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6300                              getValue(I.getArgOperand(0)).getValueType(),
6301                              getValue(I.getArgOperand(0))));
6302     return;
6303   case Intrinsic::cttz: {
6304     SDValue Arg = getValue(I.getArgOperand(0));
6305     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6306     EVT Ty = Arg.getValueType();
6307     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6308                              sdl, Ty, Arg));
6309     return;
6310   }
6311   case Intrinsic::ctlz: {
6312     SDValue Arg = getValue(I.getArgOperand(0));
6313     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6314     EVT Ty = Arg.getValueType();
6315     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6316                              sdl, Ty, Arg));
6317     return;
6318   }
6319   case Intrinsic::ctpop: {
6320     SDValue Arg = getValue(I.getArgOperand(0));
6321     EVT Ty = Arg.getValueType();
6322     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6323     return;
6324   }
6325   case Intrinsic::fshl:
6326   case Intrinsic::fshr: {
6327     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6328     SDValue X = getValue(I.getArgOperand(0));
6329     SDValue Y = getValue(I.getArgOperand(1));
6330     SDValue Z = getValue(I.getArgOperand(2));
6331     EVT VT = X.getValueType();
6332     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6333     SDValue Zero = DAG.getConstant(0, sdl, VT);
6334     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6335 
6336     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6337     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6338       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6339       return;
6340     }
6341 
6342     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6343     // avoid the select that is necessary in the general case to filter out
6344     // the 0-shift possibility that leads to UB.
6345     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6346       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6347       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6348         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6349         return;
6350       }
6351 
6352       // Some targets only rotate one way. Try the opposite direction.
6353       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6354       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6355         // Negate the shift amount because it is safe to ignore the high bits.
6356         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6357         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6358         return;
6359       }
6360 
6361       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6362       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6363       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6364       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6365       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6366       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6367       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6368       return;
6369     }
6370 
6371     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6372     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6373     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6374     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6375     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6376     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6377 
6378     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6379     // and that is undefined. We must compare and select to avoid UB.
6380     EVT CCVT = MVT::i1;
6381     if (VT.isVector())
6382       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6383 
6384     // For fshl, 0-shift returns the 1st arg (X).
6385     // For fshr, 0-shift returns the 2nd arg (Y).
6386     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6387     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6388     return;
6389   }
6390   case Intrinsic::sadd_sat: {
6391     SDValue Op1 = getValue(I.getArgOperand(0));
6392     SDValue Op2 = getValue(I.getArgOperand(1));
6393     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6394     return;
6395   }
6396   case Intrinsic::uadd_sat: {
6397     SDValue Op1 = getValue(I.getArgOperand(0));
6398     SDValue Op2 = getValue(I.getArgOperand(1));
6399     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6400     return;
6401   }
6402   case Intrinsic::ssub_sat: {
6403     SDValue Op1 = getValue(I.getArgOperand(0));
6404     SDValue Op2 = getValue(I.getArgOperand(1));
6405     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6406     return;
6407   }
6408   case Intrinsic::usub_sat: {
6409     SDValue Op1 = getValue(I.getArgOperand(0));
6410     SDValue Op2 = getValue(I.getArgOperand(1));
6411     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6412     return;
6413   }
6414   case Intrinsic::smul_fix:
6415   case Intrinsic::umul_fix:
6416   case Intrinsic::smul_fix_sat:
6417   case Intrinsic::umul_fix_sat: {
6418     SDValue Op1 = getValue(I.getArgOperand(0));
6419     SDValue Op2 = getValue(I.getArgOperand(1));
6420     SDValue Op3 = getValue(I.getArgOperand(2));
6421     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6422                              Op1.getValueType(), Op1, Op2, Op3));
6423     return;
6424   }
6425   case Intrinsic::sdiv_fix:
6426   case Intrinsic::udiv_fix: {
6427     SDValue Op1 = getValue(I.getArgOperand(0));
6428     SDValue Op2 = getValue(I.getArgOperand(1));
6429     SDValue Op3 = getValue(I.getArgOperand(2));
6430     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6431                               Op1, Op2, Op3, DAG, TLI));
6432     return;
6433   }
6434   case Intrinsic::stacksave: {
6435     SDValue Op = getRoot();
6436     Res = DAG.getNode(
6437         ISD::STACKSAVE, sdl,
6438         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6439     setValue(&I, Res);
6440     DAG.setRoot(Res.getValue(1));
6441     return;
6442   }
6443   case Intrinsic::stackrestore:
6444     Res = getValue(I.getArgOperand(0));
6445     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6446     return;
6447   case Intrinsic::get_dynamic_area_offset: {
6448     SDValue Op = getRoot();
6449     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6450     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6451     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6452     // target.
6453     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6454       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6455                          " intrinsic!");
6456     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6457                       Op);
6458     DAG.setRoot(Op);
6459     setValue(&I, Res);
6460     return;
6461   }
6462   case Intrinsic::stackguard: {
6463     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6464     MachineFunction &MF = DAG.getMachineFunction();
6465     const Module &M = *MF.getFunction().getParent();
6466     SDValue Chain = getRoot();
6467     if (TLI.useLoadStackGuardNode()) {
6468       Res = getLoadStackGuard(DAG, sdl, Chain);
6469     } else {
6470       const Value *Global = TLI.getSDagStackGuard(M);
6471       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6472       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6473                         MachinePointerInfo(Global, 0), Align,
6474                         MachineMemOperand::MOVolatile);
6475     }
6476     if (TLI.useStackGuardXorFP())
6477       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6478     DAG.setRoot(Chain);
6479     setValue(&I, Res);
6480     return;
6481   }
6482   case Intrinsic::stackprotector: {
6483     // Emit code into the DAG to store the stack guard onto the stack.
6484     MachineFunction &MF = DAG.getMachineFunction();
6485     MachineFrameInfo &MFI = MF.getFrameInfo();
6486     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6487     SDValue Src, Chain = getRoot();
6488 
6489     if (TLI.useLoadStackGuardNode())
6490       Src = getLoadStackGuard(DAG, sdl, Chain);
6491     else
6492       Src = getValue(I.getArgOperand(0));   // The guard's value.
6493 
6494     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6495 
6496     int FI = FuncInfo.StaticAllocaMap[Slot];
6497     MFI.setStackProtectorIndex(FI);
6498 
6499     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6500 
6501     // Store the stack protector onto the stack.
6502     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6503                                                  DAG.getMachineFunction(), FI),
6504                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6505     setValue(&I, Res);
6506     DAG.setRoot(Res);
6507     return;
6508   }
6509   case Intrinsic::objectsize:
6510     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6511 
6512   case Intrinsic::is_constant:
6513     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6514 
6515   case Intrinsic::annotation:
6516   case Intrinsic::ptr_annotation:
6517   case Intrinsic::launder_invariant_group:
6518   case Intrinsic::strip_invariant_group:
6519     // Drop the intrinsic, but forward the value
6520     setValue(&I, getValue(I.getOperand(0)));
6521     return;
6522   case Intrinsic::assume:
6523   case Intrinsic::var_annotation:
6524   case Intrinsic::sideeffect:
6525     // Discard annotate attributes, assumptions, and artificial side-effects.
6526     return;
6527 
6528   case Intrinsic::codeview_annotation: {
6529     // Emit a label associated with this metadata.
6530     MachineFunction &MF = DAG.getMachineFunction();
6531     MCSymbol *Label =
6532         MF.getMMI().getContext().createTempSymbol("annotation", true);
6533     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6534     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6535     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6536     DAG.setRoot(Res);
6537     return;
6538   }
6539 
6540   case Intrinsic::init_trampoline: {
6541     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6542 
6543     SDValue Ops[6];
6544     Ops[0] = getRoot();
6545     Ops[1] = getValue(I.getArgOperand(0));
6546     Ops[2] = getValue(I.getArgOperand(1));
6547     Ops[3] = getValue(I.getArgOperand(2));
6548     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6549     Ops[5] = DAG.getSrcValue(F);
6550 
6551     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6552 
6553     DAG.setRoot(Res);
6554     return;
6555   }
6556   case Intrinsic::adjust_trampoline:
6557     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6558                              TLI.getPointerTy(DAG.getDataLayout()),
6559                              getValue(I.getArgOperand(0))));
6560     return;
6561   case Intrinsic::gcroot: {
6562     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6563            "only valid in functions with gc specified, enforced by Verifier");
6564     assert(GFI && "implied by previous");
6565     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6566     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6567 
6568     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6569     GFI->addStackRoot(FI->getIndex(), TypeMap);
6570     return;
6571   }
6572   case Intrinsic::gcread:
6573   case Intrinsic::gcwrite:
6574     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6575   case Intrinsic::flt_rounds:
6576     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6577     return;
6578 
6579   case Intrinsic::expect:
6580     // Just replace __builtin_expect(exp, c) with EXP.
6581     setValue(&I, getValue(I.getArgOperand(0)));
6582     return;
6583 
6584   case Intrinsic::debugtrap:
6585   case Intrinsic::trap: {
6586     StringRef TrapFuncName =
6587         I.getAttributes()
6588             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6589             .getValueAsString();
6590     if (TrapFuncName.empty()) {
6591       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6592         ISD::TRAP : ISD::DEBUGTRAP;
6593       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6594       return;
6595     }
6596     TargetLowering::ArgListTy Args;
6597 
6598     TargetLowering::CallLoweringInfo CLI(DAG);
6599     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6600         CallingConv::C, I.getType(),
6601         DAG.getExternalSymbol(TrapFuncName.data(),
6602                               TLI.getPointerTy(DAG.getDataLayout())),
6603         std::move(Args));
6604 
6605     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6606     DAG.setRoot(Result.second);
6607     return;
6608   }
6609 
6610   case Intrinsic::uadd_with_overflow:
6611   case Intrinsic::sadd_with_overflow:
6612   case Intrinsic::usub_with_overflow:
6613   case Intrinsic::ssub_with_overflow:
6614   case Intrinsic::umul_with_overflow:
6615   case Intrinsic::smul_with_overflow: {
6616     ISD::NodeType Op;
6617     switch (Intrinsic) {
6618     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6619     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6620     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6621     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6622     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6623     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6624     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6625     }
6626     SDValue Op1 = getValue(I.getArgOperand(0));
6627     SDValue Op2 = getValue(I.getArgOperand(1));
6628 
6629     EVT ResultVT = Op1.getValueType();
6630     EVT OverflowVT = MVT::i1;
6631     if (ResultVT.isVector())
6632       OverflowVT = EVT::getVectorVT(
6633           *Context, OverflowVT, ResultVT.getVectorNumElements());
6634 
6635     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6636     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6637     return;
6638   }
6639   case Intrinsic::prefetch: {
6640     SDValue Ops[5];
6641     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6642     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6643     Ops[0] = DAG.getRoot();
6644     Ops[1] = getValue(I.getArgOperand(0));
6645     Ops[2] = getValue(I.getArgOperand(1));
6646     Ops[3] = getValue(I.getArgOperand(2));
6647     Ops[4] = getValue(I.getArgOperand(3));
6648     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6649                                              DAG.getVTList(MVT::Other), Ops,
6650                                              EVT::getIntegerVT(*Context, 8),
6651                                              MachinePointerInfo(I.getArgOperand(0)),
6652                                              0, /* align */
6653                                              Flags);
6654 
6655     // Chain the prefetch in parallell with any pending loads, to stay out of
6656     // the way of later optimizations.
6657     PendingLoads.push_back(Result);
6658     Result = getRoot();
6659     DAG.setRoot(Result);
6660     return;
6661   }
6662   case Intrinsic::lifetime_start:
6663   case Intrinsic::lifetime_end: {
6664     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6665     // Stack coloring is not enabled in O0, discard region information.
6666     if (TM.getOptLevel() == CodeGenOpt::None)
6667       return;
6668 
6669     const int64_t ObjectSize =
6670         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6671     Value *const ObjectPtr = I.getArgOperand(1);
6672     SmallVector<const Value *, 4> Allocas;
6673     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6674 
6675     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6676            E = Allocas.end(); Object != E; ++Object) {
6677       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6678 
6679       // Could not find an Alloca.
6680       if (!LifetimeObject)
6681         continue;
6682 
6683       // First check that the Alloca is static, otherwise it won't have a
6684       // valid frame index.
6685       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6686       if (SI == FuncInfo.StaticAllocaMap.end())
6687         return;
6688 
6689       const int FrameIndex = SI->second;
6690       int64_t Offset;
6691       if (GetPointerBaseWithConstantOffset(
6692               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6693         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6694       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6695                                 Offset);
6696       DAG.setRoot(Res);
6697     }
6698     return;
6699   }
6700   case Intrinsic::invariant_start:
6701     // Discard region information.
6702     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6703     return;
6704   case Intrinsic::invariant_end:
6705     // Discard region information.
6706     return;
6707   case Intrinsic::clear_cache:
6708     /// FunctionName may be null.
6709     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6710       lowerCallToExternalSymbol(I, FunctionName);
6711     return;
6712   case Intrinsic::donothing:
6713     // ignore
6714     return;
6715   case Intrinsic::experimental_stackmap:
6716     visitStackmap(I);
6717     return;
6718   case Intrinsic::experimental_patchpoint_void:
6719   case Intrinsic::experimental_patchpoint_i64:
6720     visitPatchpoint(&I);
6721     return;
6722   case Intrinsic::experimental_gc_statepoint:
6723     LowerStatepoint(ImmutableStatepoint(&I));
6724     return;
6725   case Intrinsic::experimental_gc_result:
6726     visitGCResult(cast<GCResultInst>(I));
6727     return;
6728   case Intrinsic::experimental_gc_relocate:
6729     visitGCRelocate(cast<GCRelocateInst>(I));
6730     return;
6731   case Intrinsic::instrprof_increment:
6732     llvm_unreachable("instrprof failed to lower an increment");
6733   case Intrinsic::instrprof_value_profile:
6734     llvm_unreachable("instrprof failed to lower a value profiling call");
6735   case Intrinsic::localescape: {
6736     MachineFunction &MF = DAG.getMachineFunction();
6737     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6738 
6739     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6740     // is the same on all targets.
6741     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6742       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6743       if (isa<ConstantPointerNull>(Arg))
6744         continue; // Skip null pointers. They represent a hole in index space.
6745       AllocaInst *Slot = cast<AllocaInst>(Arg);
6746       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6747              "can only escape static allocas");
6748       int FI = FuncInfo.StaticAllocaMap[Slot];
6749       MCSymbol *FrameAllocSym =
6750           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6751               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6752       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6753               TII->get(TargetOpcode::LOCAL_ESCAPE))
6754           .addSym(FrameAllocSym)
6755           .addFrameIndex(FI);
6756     }
6757 
6758     return;
6759   }
6760 
6761   case Intrinsic::localrecover: {
6762     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6763     MachineFunction &MF = DAG.getMachineFunction();
6764     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6765 
6766     // Get the symbol that defines the frame offset.
6767     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6768     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6769     unsigned IdxVal =
6770         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6771     MCSymbol *FrameAllocSym =
6772         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6773             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6774 
6775     // Create a MCSymbol for the label to avoid any target lowering
6776     // that would make this PC relative.
6777     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6778     SDValue OffsetVal =
6779         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6780 
6781     // Add the offset to the FP.
6782     Value *FP = I.getArgOperand(1);
6783     SDValue FPVal = getValue(FP);
6784     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6785     setValue(&I, Add);
6786 
6787     return;
6788   }
6789 
6790   case Intrinsic::eh_exceptionpointer:
6791   case Intrinsic::eh_exceptioncode: {
6792     // Get the exception pointer vreg, copy from it, and resize it to fit.
6793     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6794     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6795     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6796     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6797     SDValue N =
6798         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6799     if (Intrinsic == Intrinsic::eh_exceptioncode)
6800       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6801     setValue(&I, N);
6802     return;
6803   }
6804   case Intrinsic::xray_customevent: {
6805     // Here we want to make sure that the intrinsic behaves as if it has a
6806     // specific calling convention, and only for x86_64.
6807     // FIXME: Support other platforms later.
6808     const auto &Triple = DAG.getTarget().getTargetTriple();
6809     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6810       return;
6811 
6812     SDLoc DL = getCurSDLoc();
6813     SmallVector<SDValue, 8> Ops;
6814 
6815     // We want to say that we always want the arguments in registers.
6816     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6817     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6818     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6819     SDValue Chain = getRoot();
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(TargetOpcode::PATCHABLE_EVENT_CALL,
6829                                            DL, NodeTys, Ops);
6830     SDValue patchableNode = SDValue(MN, 0);
6831     DAG.setRoot(patchableNode);
6832     setValue(&I, patchableNode);
6833     return;
6834   }
6835   case Intrinsic::xray_typedevent: {
6836     // Here we want to make sure that the intrinsic behaves as if it has a
6837     // specific calling convention, and only for x86_64.
6838     // FIXME: Support other platforms later.
6839     const auto &Triple = DAG.getTarget().getTargetTriple();
6840     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6841       return;
6842 
6843     SDLoc DL = getCurSDLoc();
6844     SmallVector<SDValue, 8> Ops;
6845 
6846     // We want to say that we always want the arguments in registers.
6847     // It's unclear to me how manipulating the selection DAG here forces callers
6848     // to provide arguments in registers instead of on the stack.
6849     SDValue LogTypeId = getValue(I.getArgOperand(0));
6850     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6851     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6852     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6853     SDValue Chain = getRoot();
6854     Ops.push_back(LogTypeId);
6855     Ops.push_back(LogEntryVal);
6856     Ops.push_back(StrSizeVal);
6857     Ops.push_back(Chain);
6858 
6859     // We need to enforce the calling convention for the callsite, so that
6860     // argument ordering is enforced correctly, and that register allocation can
6861     // see that some registers may be assumed clobbered and have to preserve
6862     // them across calls to the intrinsic.
6863     MachineSDNode *MN = DAG.getMachineNode(
6864         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6865     SDValue patchableNode = SDValue(MN, 0);
6866     DAG.setRoot(patchableNode);
6867     setValue(&I, patchableNode);
6868     return;
6869   }
6870   case Intrinsic::experimental_deoptimize:
6871     LowerDeoptimizeCall(&I);
6872     return;
6873 
6874   case Intrinsic::experimental_vector_reduce_v2_fadd:
6875   case Intrinsic::experimental_vector_reduce_v2_fmul:
6876   case Intrinsic::experimental_vector_reduce_add:
6877   case Intrinsic::experimental_vector_reduce_mul:
6878   case Intrinsic::experimental_vector_reduce_and:
6879   case Intrinsic::experimental_vector_reduce_or:
6880   case Intrinsic::experimental_vector_reduce_xor:
6881   case Intrinsic::experimental_vector_reduce_smax:
6882   case Intrinsic::experimental_vector_reduce_smin:
6883   case Intrinsic::experimental_vector_reduce_umax:
6884   case Intrinsic::experimental_vector_reduce_umin:
6885   case Intrinsic::experimental_vector_reduce_fmax:
6886   case Intrinsic::experimental_vector_reduce_fmin:
6887     visitVectorReduce(I, Intrinsic);
6888     return;
6889 
6890   case Intrinsic::icall_branch_funnel: {
6891     SmallVector<SDValue, 16> Ops;
6892     Ops.push_back(getValue(I.getArgOperand(0)));
6893 
6894     int64_t Offset;
6895     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6896         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6897     if (!Base)
6898       report_fatal_error(
6899           "llvm.icall.branch.funnel operand must be a GlobalValue");
6900     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6901 
6902     struct BranchFunnelTarget {
6903       int64_t Offset;
6904       SDValue Target;
6905     };
6906     SmallVector<BranchFunnelTarget, 8> Targets;
6907 
6908     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6909       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6910           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6911       if (ElemBase != Base)
6912         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6913                            "to the same GlobalValue");
6914 
6915       SDValue Val = getValue(I.getArgOperand(Op + 1));
6916       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6917       if (!GA)
6918         report_fatal_error(
6919             "llvm.icall.branch.funnel operand must be a GlobalValue");
6920       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6921                                      GA->getGlobal(), getCurSDLoc(),
6922                                      Val.getValueType(), GA->getOffset())});
6923     }
6924     llvm::sort(Targets,
6925                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6926                  return T1.Offset < T2.Offset;
6927                });
6928 
6929     for (auto &T : Targets) {
6930       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6931       Ops.push_back(T.Target);
6932     }
6933 
6934     Ops.push_back(DAG.getRoot()); // Chain
6935     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6936                                  getCurSDLoc(), MVT::Other, Ops),
6937               0);
6938     DAG.setRoot(N);
6939     setValue(&I, N);
6940     HasTailCall = true;
6941     return;
6942   }
6943 
6944   case Intrinsic::wasm_landingpad_index:
6945     // Information this intrinsic contained has been transferred to
6946     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6947     // delete it now.
6948     return;
6949 
6950   case Intrinsic::aarch64_settag:
6951   case Intrinsic::aarch64_settag_zero: {
6952     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6953     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6954     SDValue Val = TSI.EmitTargetCodeForSetTag(
6955         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6956         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6957         ZeroMemory);
6958     DAG.setRoot(Val);
6959     setValue(&I, Val);
6960     return;
6961   }
6962   case Intrinsic::ptrmask: {
6963     SDValue Ptr = getValue(I.getOperand(0));
6964     SDValue Const = getValue(I.getOperand(1));
6965 
6966     EVT DestVT =
6967         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6968 
6969     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
6970                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
6971     return;
6972   }
6973   }
6974 }
6975 
6976 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6977     const ConstrainedFPIntrinsic &FPI) {
6978   SDLoc sdl = getCurSDLoc();
6979 
6980   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6981   SmallVector<EVT, 4> ValueVTs;
6982   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6983   ValueVTs.push_back(MVT::Other); // Out chain
6984 
6985   // We do not need to serialize constrained FP intrinsics against
6986   // each other or against (nonvolatile) loads, so they can be
6987   // chained like loads.
6988   SDValue Chain = DAG.getRoot();
6989   SmallVector<SDValue, 4> Opers;
6990   Opers.push_back(Chain);
6991   if (FPI.isUnaryOp()) {
6992     Opers.push_back(getValue(FPI.getArgOperand(0)));
6993   } else if (FPI.isTernaryOp()) {
6994     Opers.push_back(getValue(FPI.getArgOperand(0)));
6995     Opers.push_back(getValue(FPI.getArgOperand(1)));
6996     Opers.push_back(getValue(FPI.getArgOperand(2)));
6997   } else {
6998     Opers.push_back(getValue(FPI.getArgOperand(0)));
6999     Opers.push_back(getValue(FPI.getArgOperand(1)));
7000   }
7001 
7002   unsigned Opcode;
7003   switch (FPI.getIntrinsicID()) {
7004   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7005 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
7006   case Intrinsic::INTRINSIC:                                                   \
7007     Opcode = ISD::STRICT_##DAGN;                                               \
7008     break;
7009 #include "llvm/IR/ConstrainedOps.def"
7010   }
7011 
7012   // A few strict DAG nodes carry additional operands that are not
7013   // set up by the default code above.
7014   switch (Opcode) {
7015   default: break;
7016   case ISD::STRICT_FP_ROUND:
7017     Opers.push_back(
7018         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7019     break;
7020   case ISD::STRICT_FSETCC:
7021   case ISD::STRICT_FSETCCS: {
7022     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7023     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
7024     break;
7025   }
7026   }
7027 
7028   SDVTList VTs = DAG.getVTList(ValueVTs);
7029   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers);
7030 
7031   assert(Result.getNode()->getNumValues() == 2);
7032 
7033   // Push node to the appropriate list so that future instructions can be
7034   // chained up correctly.
7035   SDValue OutChain = Result.getValue(1);
7036   switch (FPI.getExceptionBehavior().getValue()) {
7037   case fp::ExceptionBehavior::ebIgnore:
7038     // The only reason why ebIgnore nodes still need to be chained is that
7039     // they might depend on the current rounding mode, and therefore must
7040     // not be moved across instruction that may change that mode.
7041     LLVM_FALLTHROUGH;
7042   case fp::ExceptionBehavior::ebMayTrap:
7043     // These must not be moved across calls or instructions that may change
7044     // floating-point exception masks.
7045     PendingConstrainedFP.push_back(OutChain);
7046     break;
7047   case fp::ExceptionBehavior::ebStrict:
7048     // These must not be moved across calls or instructions that may change
7049     // floating-point exception masks or read floating-point exception flags.
7050     // In addition, they cannot be optimized out even if unused.
7051     PendingConstrainedFPStrict.push_back(OutChain);
7052     break;
7053   }
7054 
7055   SDValue FPResult = Result.getValue(0);
7056   setValue(&FPI, FPResult);
7057 }
7058 
7059 std::pair<SDValue, SDValue>
7060 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7061                                     const BasicBlock *EHPadBB) {
7062   MachineFunction &MF = DAG.getMachineFunction();
7063   MachineModuleInfo &MMI = MF.getMMI();
7064   MCSymbol *BeginLabel = nullptr;
7065 
7066   if (EHPadBB) {
7067     // Insert a label before the invoke call to mark the try range.  This can be
7068     // used to detect deletion of the invoke via the MachineModuleInfo.
7069     BeginLabel = MMI.getContext().createTempSymbol();
7070 
7071     // For SjLj, keep track of which landing pads go with which invokes
7072     // so as to maintain the ordering of pads in the LSDA.
7073     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7074     if (CallSiteIndex) {
7075       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7076       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7077 
7078       // Now that the call site is handled, stop tracking it.
7079       MMI.setCurrentCallSite(0);
7080     }
7081 
7082     // Both PendingLoads and PendingExports must be flushed here;
7083     // this call might not return.
7084     (void)getRoot();
7085     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7086 
7087     CLI.setChain(getRoot());
7088   }
7089   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7090   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7091 
7092   assert((CLI.IsTailCall || Result.second.getNode()) &&
7093          "Non-null chain expected with non-tail call!");
7094   assert((Result.second.getNode() || !Result.first.getNode()) &&
7095          "Null value expected with tail call!");
7096 
7097   if (!Result.second.getNode()) {
7098     // As a special case, a null chain means that a tail call has been emitted
7099     // and the DAG root is already updated.
7100     HasTailCall = true;
7101 
7102     // Since there's no actual continuation from this block, nothing can be
7103     // relying on us setting vregs for them.
7104     PendingExports.clear();
7105   } else {
7106     DAG.setRoot(Result.second);
7107   }
7108 
7109   if (EHPadBB) {
7110     // Insert a label at the end of the invoke call to mark the try range.  This
7111     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7112     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7113     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7114 
7115     // Inform MachineModuleInfo of range.
7116     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7117     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7118     // actually use outlined funclets and their LSDA info style.
7119     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7120       assert(CLI.CS);
7121       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7122       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7123                                 BeginLabel, EndLabel);
7124     } else if (!isScopedEHPersonality(Pers)) {
7125       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7126     }
7127   }
7128 
7129   return Result;
7130 }
7131 
7132 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7133                                       bool isTailCall,
7134                                       const BasicBlock *EHPadBB) {
7135   auto &DL = DAG.getDataLayout();
7136   FunctionType *FTy = CS.getFunctionType();
7137   Type *RetTy = CS.getType();
7138 
7139   TargetLowering::ArgListTy Args;
7140   Args.reserve(CS.arg_size());
7141 
7142   const Value *SwiftErrorVal = nullptr;
7143   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7144 
7145   if (isTailCall) {
7146     // Avoid emitting tail calls in functions with the disable-tail-calls
7147     // attribute.
7148     auto *Caller = CS.getInstruction()->getParent()->getParent();
7149     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7150         "true")
7151       isTailCall = false;
7152 
7153     // We can't tail call inside a function with a swifterror argument. Lowering
7154     // does not support this yet. It would have to move into the swifterror
7155     // register before the call.
7156     if (TLI.supportSwiftError() &&
7157         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7158       isTailCall = false;
7159   }
7160 
7161   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7162        i != e; ++i) {
7163     TargetLowering::ArgListEntry Entry;
7164     const Value *V = *i;
7165 
7166     // Skip empty types
7167     if (V->getType()->isEmptyTy())
7168       continue;
7169 
7170     SDValue ArgNode = getValue(V);
7171     Entry.Node = ArgNode; Entry.Ty = V->getType();
7172 
7173     Entry.setAttributes(&CS, i - CS.arg_begin());
7174 
7175     // Use swifterror virtual register as input to the call.
7176     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7177       SwiftErrorVal = V;
7178       // We find the virtual register for the actual swifterror argument.
7179       // Instead of using the Value, we use the virtual register instead.
7180       Entry.Node = DAG.getRegister(
7181           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7182           EVT(TLI.getPointerTy(DL)));
7183     }
7184 
7185     Args.push_back(Entry);
7186 
7187     // If we have an explicit sret argument that is an Instruction, (i.e., it
7188     // might point to function-local memory), we can't meaningfully tail-call.
7189     if (Entry.IsSRet && isa<Instruction>(V))
7190       isTailCall = false;
7191   }
7192 
7193   // If call site has a cfguardtarget operand bundle, create and add an
7194   // additional ArgListEntry.
7195   if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7196     TargetLowering::ArgListEntry Entry;
7197     Value *V = Bundle->Inputs[0];
7198     SDValue ArgNode = getValue(V);
7199     Entry.Node = ArgNode;
7200     Entry.Ty = V->getType();
7201     Entry.IsCFGuardTarget = true;
7202     Args.push_back(Entry);
7203   }
7204 
7205   // Check if target-independent constraints permit a tail call here.
7206   // Target-dependent constraints are checked within TLI->LowerCallTo.
7207   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7208     isTailCall = false;
7209 
7210   // Disable tail calls if there is an swifterror argument. Targets have not
7211   // been updated to support tail calls.
7212   if (TLI.supportSwiftError() && SwiftErrorVal)
7213     isTailCall = false;
7214 
7215   TargetLowering::CallLoweringInfo CLI(DAG);
7216   CLI.setDebugLoc(getCurSDLoc())
7217       .setChain(getRoot())
7218       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7219       .setTailCall(isTailCall)
7220       .setConvergent(CS.isConvergent());
7221   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7222 
7223   if (Result.first.getNode()) {
7224     const Instruction *Inst = CS.getInstruction();
7225     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7226     setValue(Inst, Result.first);
7227   }
7228 
7229   // The last element of CLI.InVals has the SDValue for swifterror return.
7230   // Here we copy it to a virtual register and update SwiftErrorMap for
7231   // book-keeping.
7232   if (SwiftErrorVal && TLI.supportSwiftError()) {
7233     // Get the last element of InVals.
7234     SDValue Src = CLI.InVals.back();
7235     Register VReg = SwiftError.getOrCreateVRegDefAt(
7236         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7237     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7238     DAG.setRoot(CopyNode);
7239   }
7240 }
7241 
7242 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7243                              SelectionDAGBuilder &Builder) {
7244   // Check to see if this load can be trivially constant folded, e.g. if the
7245   // input is from a string literal.
7246   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7247     // Cast pointer to the type we really want to load.
7248     Type *LoadTy =
7249         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7250     if (LoadVT.isVector())
7251       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7252 
7253     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7254                                          PointerType::getUnqual(LoadTy));
7255 
7256     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7257             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7258       return Builder.getValue(LoadCst);
7259   }
7260 
7261   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7262   // still constant memory, the input chain can be the entry node.
7263   SDValue Root;
7264   bool ConstantMemory = false;
7265 
7266   // Do not serialize (non-volatile) loads of constant memory with anything.
7267   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7268     Root = Builder.DAG.getEntryNode();
7269     ConstantMemory = true;
7270   } else {
7271     // Do not serialize non-volatile loads against each other.
7272     Root = Builder.DAG.getRoot();
7273   }
7274 
7275   SDValue Ptr = Builder.getValue(PtrVal);
7276   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7277                                         Ptr, MachinePointerInfo(PtrVal),
7278                                         /* Alignment = */ 1);
7279 
7280   if (!ConstantMemory)
7281     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7282   return LoadVal;
7283 }
7284 
7285 /// Record the value for an instruction that produces an integer result,
7286 /// converting the type where necessary.
7287 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7288                                                   SDValue Value,
7289                                                   bool IsSigned) {
7290   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7291                                                     I.getType(), true);
7292   if (IsSigned)
7293     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7294   else
7295     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7296   setValue(&I, Value);
7297 }
7298 
7299 /// See if we can lower a memcmp call into an optimized form. If so, return
7300 /// true and lower it. Otherwise return false, and it will be lowered like a
7301 /// normal call.
7302 /// The caller already checked that \p I calls the appropriate LibFunc with a
7303 /// correct prototype.
7304 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7305   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7306   const Value *Size = I.getArgOperand(2);
7307   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7308   if (CSize && CSize->getZExtValue() == 0) {
7309     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7310                                                           I.getType(), true);
7311     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7312     return true;
7313   }
7314 
7315   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7316   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7317       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7318       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7319   if (Res.first.getNode()) {
7320     processIntegerCallValue(I, Res.first, true);
7321     PendingLoads.push_back(Res.second);
7322     return true;
7323   }
7324 
7325   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7326   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7327   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7328     return false;
7329 
7330   // If the target has a fast compare for the given size, it will return a
7331   // preferred load type for that size. Require that the load VT is legal and
7332   // that the target supports unaligned loads of that type. Otherwise, return
7333   // INVALID.
7334   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7335     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7336     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7337     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7338       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7339       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7340       // TODO: Check alignment of src and dest ptrs.
7341       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7342       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7343       if (!TLI.isTypeLegal(LVT) ||
7344           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7345           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7346         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7347     }
7348 
7349     return LVT;
7350   };
7351 
7352   // This turns into unaligned loads. We only do this if the target natively
7353   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7354   // we'll only produce a small number of byte loads.
7355   MVT LoadVT;
7356   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7357   switch (NumBitsToCompare) {
7358   default:
7359     return false;
7360   case 16:
7361     LoadVT = MVT::i16;
7362     break;
7363   case 32:
7364     LoadVT = MVT::i32;
7365     break;
7366   case 64:
7367   case 128:
7368   case 256:
7369     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7370     break;
7371   }
7372 
7373   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7374     return false;
7375 
7376   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7377   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7378 
7379   // Bitcast to a wide integer type if the loads are vectors.
7380   if (LoadVT.isVector()) {
7381     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7382     LoadL = DAG.getBitcast(CmpVT, LoadL);
7383     LoadR = DAG.getBitcast(CmpVT, LoadR);
7384   }
7385 
7386   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7387   processIntegerCallValue(I, Cmp, false);
7388   return true;
7389 }
7390 
7391 /// See if we can lower a memchr call into an optimized form. If so, return
7392 /// true and lower it. Otherwise return false, and it will be lowered like a
7393 /// normal call.
7394 /// The caller already checked that \p I calls the appropriate LibFunc with a
7395 /// correct prototype.
7396 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7397   const Value *Src = I.getArgOperand(0);
7398   const Value *Char = I.getArgOperand(1);
7399   const Value *Length = I.getArgOperand(2);
7400 
7401   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7402   std::pair<SDValue, SDValue> Res =
7403     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7404                                 getValue(Src), getValue(Char), getValue(Length),
7405                                 MachinePointerInfo(Src));
7406   if (Res.first.getNode()) {
7407     setValue(&I, Res.first);
7408     PendingLoads.push_back(Res.second);
7409     return true;
7410   }
7411 
7412   return false;
7413 }
7414 
7415 /// See if we can lower a mempcpy 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::visitMemPCpyCall(const CallInst &I) {
7421   SDValue Dst = getValue(I.getArgOperand(0));
7422   SDValue Src = getValue(I.getArgOperand(1));
7423   SDValue Size = getValue(I.getArgOperand(2));
7424 
7425   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7426   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7427   unsigned Align = std::min(DstAlign, SrcAlign);
7428   if (Align == 0) // Alignment of one or both could not be inferred.
7429     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7430 
7431   bool isVol = false;
7432   SDLoc sdl = getCurSDLoc();
7433 
7434   // In the mempcpy context we need to pass in a false value for isTailCall
7435   // because the return pointer needs to be adjusted by the size of
7436   // the copied memory.
7437   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7438   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Align, isVol,
7439                              false, /*isTailCall=*/false,
7440                              MachinePointerInfo(I.getArgOperand(0)),
7441                              MachinePointerInfo(I.getArgOperand(1)));
7442   assert(MC.getNode() != nullptr &&
7443          "** memcpy should not be lowered as TailCall in mempcpy context **");
7444   DAG.setRoot(MC);
7445 
7446   // Check if Size needs to be truncated or extended.
7447   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7448 
7449   // Adjust return pointer to point just past the last dst byte.
7450   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7451                                     Dst, Size);
7452   setValue(&I, DstPlusSize);
7453   return true;
7454 }
7455 
7456 /// See if we can lower a strcpy call into an optimized form.  If so, return
7457 /// true and lower it, otherwise return false and it will be lowered like a
7458 /// normal call.
7459 /// The caller already checked that \p I calls the appropriate LibFunc with a
7460 /// correct prototype.
7461 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7462   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7463 
7464   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7465   std::pair<SDValue, SDValue> Res =
7466     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7467                                 getValue(Arg0), getValue(Arg1),
7468                                 MachinePointerInfo(Arg0),
7469                                 MachinePointerInfo(Arg1), isStpcpy);
7470   if (Res.first.getNode()) {
7471     setValue(&I, Res.first);
7472     DAG.setRoot(Res.second);
7473     return true;
7474   }
7475 
7476   return false;
7477 }
7478 
7479 /// See if we can lower a strcmp 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::visitStrCmpCall(const CallInst &I) {
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.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7490                                 getValue(Arg0), getValue(Arg1),
7491                                 MachinePointerInfo(Arg0),
7492                                 MachinePointerInfo(Arg1));
7493   if (Res.first.getNode()) {
7494     processIntegerCallValue(I, Res.first, true);
7495     PendingLoads.push_back(Res.second);
7496     return true;
7497   }
7498 
7499   return false;
7500 }
7501 
7502 /// See if we can lower a strlen 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::visitStrLenCall(const CallInst &I) {
7508   const Value *Arg0 = I.getArgOperand(0);
7509 
7510   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7511   std::pair<SDValue, SDValue> Res =
7512     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7513                                 getValue(Arg0), MachinePointerInfo(Arg0));
7514   if (Res.first.getNode()) {
7515     processIntegerCallValue(I, Res.first, false);
7516     PendingLoads.push_back(Res.second);
7517     return true;
7518   }
7519 
7520   return false;
7521 }
7522 
7523 /// See if we can lower a strnlen call into an optimized form.  If so, return
7524 /// true and lower it, otherwise return false and it will be lowered like a
7525 /// normal call.
7526 /// The caller already checked that \p I calls the appropriate LibFunc with a
7527 /// correct prototype.
7528 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7529   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7530 
7531   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7532   std::pair<SDValue, SDValue> Res =
7533     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7534                                  getValue(Arg0), getValue(Arg1),
7535                                  MachinePointerInfo(Arg0));
7536   if (Res.first.getNode()) {
7537     processIntegerCallValue(I, Res.first, false);
7538     PendingLoads.push_back(Res.second);
7539     return true;
7540   }
7541 
7542   return false;
7543 }
7544 
7545 /// See if we can lower a unary floating-point operation into an SDNode with
7546 /// the specified Opcode.  If so, return true and lower it, otherwise return
7547 /// false and it will be lowered like a normal call.
7548 /// The caller already checked that \p I calls the appropriate LibFunc with a
7549 /// correct prototype.
7550 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7551                                               unsigned Opcode) {
7552   // We already checked this call's prototype; verify it doesn't modify errno.
7553   if (!I.onlyReadsMemory())
7554     return false;
7555 
7556   SDValue Tmp = getValue(I.getArgOperand(0));
7557   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7558   return true;
7559 }
7560 
7561 /// See if we can lower a binary floating-point operation into an SDNode with
7562 /// the specified Opcode. If so, return true and lower it. Otherwise return
7563 /// false, and it will be lowered like a normal call.
7564 /// The caller already checked that \p I calls the appropriate LibFunc with a
7565 /// correct prototype.
7566 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7567                                                unsigned Opcode) {
7568   // We already checked this call's prototype; verify it doesn't modify errno.
7569   if (!I.onlyReadsMemory())
7570     return false;
7571 
7572   SDValue Tmp0 = getValue(I.getArgOperand(0));
7573   SDValue Tmp1 = getValue(I.getArgOperand(1));
7574   EVT VT = Tmp0.getValueType();
7575   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7576   return true;
7577 }
7578 
7579 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7580   // Handle inline assembly differently.
7581   if (isa<InlineAsm>(I.getCalledValue())) {
7582     visitInlineAsm(&I);
7583     return;
7584   }
7585 
7586   if (Function *F = I.getCalledFunction()) {
7587     if (F->isDeclaration()) {
7588       // Is this an LLVM intrinsic or a target-specific intrinsic?
7589       unsigned IID = F->getIntrinsicID();
7590       if (!IID)
7591         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7592           IID = II->getIntrinsicID(F);
7593 
7594       if (IID) {
7595         visitIntrinsicCall(I, IID);
7596         return;
7597       }
7598     }
7599 
7600     // Check for well-known libc/libm calls.  If the function is internal, it
7601     // can't be a library call.  Don't do the check if marked as nobuiltin for
7602     // some reason or the call site requires strict floating point semantics.
7603     LibFunc Func;
7604     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7605         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7606         LibInfo->hasOptimizedCodeGen(Func)) {
7607       switch (Func) {
7608       default: break;
7609       case LibFunc_copysign:
7610       case LibFunc_copysignf:
7611       case LibFunc_copysignl:
7612         // We already checked this call's prototype; verify it doesn't modify
7613         // errno.
7614         if (I.onlyReadsMemory()) {
7615           SDValue LHS = getValue(I.getArgOperand(0));
7616           SDValue RHS = getValue(I.getArgOperand(1));
7617           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7618                                    LHS.getValueType(), LHS, RHS));
7619           return;
7620         }
7621         break;
7622       case LibFunc_fabs:
7623       case LibFunc_fabsf:
7624       case LibFunc_fabsl:
7625         if (visitUnaryFloatCall(I, ISD::FABS))
7626           return;
7627         break;
7628       case LibFunc_fmin:
7629       case LibFunc_fminf:
7630       case LibFunc_fminl:
7631         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7632           return;
7633         break;
7634       case LibFunc_fmax:
7635       case LibFunc_fmaxf:
7636       case LibFunc_fmaxl:
7637         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7638           return;
7639         break;
7640       case LibFunc_sin:
7641       case LibFunc_sinf:
7642       case LibFunc_sinl:
7643         if (visitUnaryFloatCall(I, ISD::FSIN))
7644           return;
7645         break;
7646       case LibFunc_cos:
7647       case LibFunc_cosf:
7648       case LibFunc_cosl:
7649         if (visitUnaryFloatCall(I, ISD::FCOS))
7650           return;
7651         break;
7652       case LibFunc_sqrt:
7653       case LibFunc_sqrtf:
7654       case LibFunc_sqrtl:
7655       case LibFunc_sqrt_finite:
7656       case LibFunc_sqrtf_finite:
7657       case LibFunc_sqrtl_finite:
7658         if (visitUnaryFloatCall(I, ISD::FSQRT))
7659           return;
7660         break;
7661       case LibFunc_floor:
7662       case LibFunc_floorf:
7663       case LibFunc_floorl:
7664         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7665           return;
7666         break;
7667       case LibFunc_nearbyint:
7668       case LibFunc_nearbyintf:
7669       case LibFunc_nearbyintl:
7670         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7671           return;
7672         break;
7673       case LibFunc_ceil:
7674       case LibFunc_ceilf:
7675       case LibFunc_ceill:
7676         if (visitUnaryFloatCall(I, ISD::FCEIL))
7677           return;
7678         break;
7679       case LibFunc_rint:
7680       case LibFunc_rintf:
7681       case LibFunc_rintl:
7682         if (visitUnaryFloatCall(I, ISD::FRINT))
7683           return;
7684         break;
7685       case LibFunc_round:
7686       case LibFunc_roundf:
7687       case LibFunc_roundl:
7688         if (visitUnaryFloatCall(I, ISD::FROUND))
7689           return;
7690         break;
7691       case LibFunc_trunc:
7692       case LibFunc_truncf:
7693       case LibFunc_truncl:
7694         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7695           return;
7696         break;
7697       case LibFunc_log2:
7698       case LibFunc_log2f:
7699       case LibFunc_log2l:
7700         if (visitUnaryFloatCall(I, ISD::FLOG2))
7701           return;
7702         break;
7703       case LibFunc_exp2:
7704       case LibFunc_exp2f:
7705       case LibFunc_exp2l:
7706         if (visitUnaryFloatCall(I, ISD::FEXP2))
7707           return;
7708         break;
7709       case LibFunc_memcmp:
7710         if (visitMemCmpCall(I))
7711           return;
7712         break;
7713       case LibFunc_mempcpy:
7714         if (visitMemPCpyCall(I))
7715           return;
7716         break;
7717       case LibFunc_memchr:
7718         if (visitMemChrCall(I))
7719           return;
7720         break;
7721       case LibFunc_strcpy:
7722         if (visitStrCpyCall(I, false))
7723           return;
7724         break;
7725       case LibFunc_stpcpy:
7726         if (visitStrCpyCall(I, true))
7727           return;
7728         break;
7729       case LibFunc_strcmp:
7730         if (visitStrCmpCall(I))
7731           return;
7732         break;
7733       case LibFunc_strlen:
7734         if (visitStrLenCall(I))
7735           return;
7736         break;
7737       case LibFunc_strnlen:
7738         if (visitStrNLenCall(I))
7739           return;
7740         break;
7741       }
7742     }
7743   }
7744 
7745   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7746   // have to do anything here to lower funclet bundles.
7747   // CFGuardTarget bundles are lowered in LowerCallTo.
7748   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7749                                         LLVMContext::OB_funclet,
7750                                         LLVMContext::OB_cfguardtarget}) &&
7751          "Cannot lower calls with arbitrary operand bundles!");
7752 
7753   SDValue Callee = getValue(I.getCalledValue());
7754 
7755   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7756     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7757   else
7758     // Check if we can potentially perform a tail call. More detailed checking
7759     // is be done within LowerCallTo, after more information about the call is
7760     // known.
7761     LowerCallTo(&I, Callee, I.isTailCall());
7762 }
7763 
7764 namespace {
7765 
7766 /// AsmOperandInfo - This contains information for each constraint that we are
7767 /// lowering.
7768 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7769 public:
7770   /// CallOperand - If this is the result output operand or a clobber
7771   /// this is null, otherwise it is the incoming operand to the CallInst.
7772   /// This gets modified as the asm is processed.
7773   SDValue CallOperand;
7774 
7775   /// AssignedRegs - If this is a register or register class operand, this
7776   /// contains the set of register corresponding to the operand.
7777   RegsForValue AssignedRegs;
7778 
7779   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7780     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7781   }
7782 
7783   /// Whether or not this operand accesses memory
7784   bool hasMemory(const TargetLowering &TLI) const {
7785     // Indirect operand accesses access memory.
7786     if (isIndirect)
7787       return true;
7788 
7789     for (const auto &Code : Codes)
7790       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7791         return true;
7792 
7793     return false;
7794   }
7795 
7796   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7797   /// corresponds to.  If there is no Value* for this operand, it returns
7798   /// MVT::Other.
7799   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7800                            const DataLayout &DL) const {
7801     if (!CallOperandVal) return MVT::Other;
7802 
7803     if (isa<BasicBlock>(CallOperandVal))
7804       return TLI.getPointerTy(DL);
7805 
7806     llvm::Type *OpTy = CallOperandVal->getType();
7807 
7808     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7809     // If this is an indirect operand, the operand is a pointer to the
7810     // accessed type.
7811     if (isIndirect) {
7812       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7813       if (!PtrTy)
7814         report_fatal_error("Indirect operand for inline asm not a pointer!");
7815       OpTy = PtrTy->getElementType();
7816     }
7817 
7818     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7819     if (StructType *STy = dyn_cast<StructType>(OpTy))
7820       if (STy->getNumElements() == 1)
7821         OpTy = STy->getElementType(0);
7822 
7823     // If OpTy is not a single value, it may be a struct/union that we
7824     // can tile with integers.
7825     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7826       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7827       switch (BitSize) {
7828       default: break;
7829       case 1:
7830       case 8:
7831       case 16:
7832       case 32:
7833       case 64:
7834       case 128:
7835         OpTy = IntegerType::get(Context, BitSize);
7836         break;
7837       }
7838     }
7839 
7840     return TLI.getValueType(DL, OpTy, true);
7841   }
7842 };
7843 
7844 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7845 
7846 } // end anonymous namespace
7847 
7848 /// Make sure that the output operand \p OpInfo and its corresponding input
7849 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7850 /// out).
7851 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7852                                SDISelAsmOperandInfo &MatchingOpInfo,
7853                                SelectionDAG &DAG) {
7854   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7855     return;
7856 
7857   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7858   const auto &TLI = DAG.getTargetLoweringInfo();
7859 
7860   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7861       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7862                                        OpInfo.ConstraintVT);
7863   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7864       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7865                                        MatchingOpInfo.ConstraintVT);
7866   if ((OpInfo.ConstraintVT.isInteger() !=
7867        MatchingOpInfo.ConstraintVT.isInteger()) ||
7868       (MatchRC.second != InputRC.second)) {
7869     // FIXME: error out in a more elegant fashion
7870     report_fatal_error("Unsupported asm: input constraint"
7871                        " with a matching output constraint of"
7872                        " incompatible type!");
7873   }
7874   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7875 }
7876 
7877 /// Get a direct memory input to behave well as an indirect operand.
7878 /// This may introduce stores, hence the need for a \p Chain.
7879 /// \return The (possibly updated) chain.
7880 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7881                                         SDISelAsmOperandInfo &OpInfo,
7882                                         SelectionDAG &DAG) {
7883   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7884 
7885   // If we don't have an indirect input, put it in the constpool if we can,
7886   // otherwise spill it to a stack slot.
7887   // TODO: This isn't quite right. We need to handle these according to
7888   // the addressing mode that the constraint wants. Also, this may take
7889   // an additional register for the computation and we don't want that
7890   // either.
7891 
7892   // If the operand is a float, integer, or vector constant, spill to a
7893   // constant pool entry to get its address.
7894   const Value *OpVal = OpInfo.CallOperandVal;
7895   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7896       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7897     OpInfo.CallOperand = DAG.getConstantPool(
7898         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7899     return Chain;
7900   }
7901 
7902   // Otherwise, create a stack slot and emit a store to it before the asm.
7903   Type *Ty = OpVal->getType();
7904   auto &DL = DAG.getDataLayout();
7905   uint64_t TySize = DL.getTypeAllocSize(Ty);
7906   unsigned Align = DL.getPrefTypeAlignment(Ty);
7907   MachineFunction &MF = DAG.getMachineFunction();
7908   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7909   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7910   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7911                             MachinePointerInfo::getFixedStack(MF, SSFI),
7912                             TLI.getMemValueType(DL, Ty));
7913   OpInfo.CallOperand = StackSlot;
7914 
7915   return Chain;
7916 }
7917 
7918 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7919 /// specified operand.  We prefer to assign virtual registers, to allow the
7920 /// register allocator to handle the assignment process.  However, if the asm
7921 /// uses features that we can't model on machineinstrs, we have SDISel do the
7922 /// allocation.  This produces generally horrible, but correct, code.
7923 ///
7924 ///   OpInfo describes the operand
7925 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7926 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7927                                  SDISelAsmOperandInfo &OpInfo,
7928                                  SDISelAsmOperandInfo &RefOpInfo) {
7929   LLVMContext &Context = *DAG.getContext();
7930   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7931 
7932   MachineFunction &MF = DAG.getMachineFunction();
7933   SmallVector<unsigned, 4> Regs;
7934   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7935 
7936   // No work to do for memory operations.
7937   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7938     return;
7939 
7940   // If this is a constraint for a single physreg, or a constraint for a
7941   // register class, find it.
7942   unsigned AssignedReg;
7943   const TargetRegisterClass *RC;
7944   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7945       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7946   // RC is unset only on failure. Return immediately.
7947   if (!RC)
7948     return;
7949 
7950   // Get the actual register value type.  This is important, because the user
7951   // may have asked for (e.g.) the AX register in i32 type.  We need to
7952   // remember that AX is actually i16 to get the right extension.
7953   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7954 
7955   if (OpInfo.ConstraintVT != MVT::Other) {
7956     // If this is an FP operand in an integer register (or visa versa), or more
7957     // generally if the operand value disagrees with the register class we plan
7958     // to stick it in, fix the operand type.
7959     //
7960     // If this is an input value, the bitcast to the new type is done now.
7961     // Bitcast for output value is done at the end of visitInlineAsm().
7962     if ((OpInfo.Type == InlineAsm::isOutput ||
7963          OpInfo.Type == InlineAsm::isInput) &&
7964         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7965       // Try to convert to the first EVT that the reg class contains.  If the
7966       // types are identical size, use a bitcast to convert (e.g. two differing
7967       // vector types).  Note: output bitcast is done at the end of
7968       // visitInlineAsm().
7969       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7970         // Exclude indirect inputs while they are unsupported because the code
7971         // to perform the load is missing and thus OpInfo.CallOperand still
7972         // refers to the input address rather than the pointed-to value.
7973         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7974           OpInfo.CallOperand =
7975               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7976         OpInfo.ConstraintVT = RegVT;
7977         // If the operand is an FP value and we want it in integer registers,
7978         // use the corresponding integer type. This turns an f64 value into
7979         // i64, which can be passed with two i32 values on a 32-bit machine.
7980       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7981         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7982         if (OpInfo.Type == InlineAsm::isInput)
7983           OpInfo.CallOperand =
7984               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7985         OpInfo.ConstraintVT = VT;
7986       }
7987     }
7988   }
7989 
7990   // No need to allocate a matching input constraint since the constraint it's
7991   // matching to has already been allocated.
7992   if (OpInfo.isMatchingInputConstraint())
7993     return;
7994 
7995   EVT ValueVT = OpInfo.ConstraintVT;
7996   if (OpInfo.ConstraintVT == MVT::Other)
7997     ValueVT = RegVT;
7998 
7999   // Initialize NumRegs.
8000   unsigned NumRegs = 1;
8001   if (OpInfo.ConstraintVT != MVT::Other)
8002     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
8003 
8004   // If this is a constraint for a specific physical register, like {r17},
8005   // assign it now.
8006 
8007   // If this associated to a specific register, initialize iterator to correct
8008   // place. If virtual, make sure we have enough registers
8009 
8010   // Initialize iterator if necessary
8011   TargetRegisterClass::iterator I = RC->begin();
8012   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8013 
8014   // Do not check for single registers.
8015   if (AssignedReg) {
8016       for (; *I != AssignedReg; ++I)
8017         assert(I != RC->end() && "AssignedReg should be member of RC");
8018   }
8019 
8020   for (; NumRegs; --NumRegs, ++I) {
8021     assert(I != RC->end() && "Ran out of registers to allocate!");
8022     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8023     Regs.push_back(R);
8024   }
8025 
8026   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8027 }
8028 
8029 static unsigned
8030 findMatchingInlineAsmOperand(unsigned OperandNo,
8031                              const std::vector<SDValue> &AsmNodeOperands) {
8032   // Scan until we find the definition we already emitted of this operand.
8033   unsigned CurOp = InlineAsm::Op_FirstOperand;
8034   for (; OperandNo; --OperandNo) {
8035     // Advance to the next operand.
8036     unsigned OpFlag =
8037         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8038     assert((InlineAsm::isRegDefKind(OpFlag) ||
8039             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8040             InlineAsm::isMemKind(OpFlag)) &&
8041            "Skipped past definitions?");
8042     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8043   }
8044   return CurOp;
8045 }
8046 
8047 namespace {
8048 
8049 class ExtraFlags {
8050   unsigned Flags = 0;
8051 
8052 public:
8053   explicit ExtraFlags(ImmutableCallSite CS) {
8054     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8055     if (IA->hasSideEffects())
8056       Flags |= InlineAsm::Extra_HasSideEffects;
8057     if (IA->isAlignStack())
8058       Flags |= InlineAsm::Extra_IsAlignStack;
8059     if (CS.isConvergent())
8060       Flags |= InlineAsm::Extra_IsConvergent;
8061     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8062   }
8063 
8064   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8065     // Ideally, we would only check against memory constraints.  However, the
8066     // meaning of an Other constraint can be target-specific and we can't easily
8067     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8068     // for Other constraints as well.
8069     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8070         OpInfo.ConstraintType == TargetLowering::C_Other) {
8071       if (OpInfo.Type == InlineAsm::isInput)
8072         Flags |= InlineAsm::Extra_MayLoad;
8073       else if (OpInfo.Type == InlineAsm::isOutput)
8074         Flags |= InlineAsm::Extra_MayStore;
8075       else if (OpInfo.Type == InlineAsm::isClobber)
8076         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8077     }
8078   }
8079 
8080   unsigned get() const { return Flags; }
8081 };
8082 
8083 } // end anonymous namespace
8084 
8085 /// visitInlineAsm - Handle a call to an InlineAsm object.
8086 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
8087   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8088 
8089   /// ConstraintOperands - Information about all of the constraints.
8090   SDISelAsmOperandInfoVector ConstraintOperands;
8091 
8092   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8093   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8094       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
8095 
8096   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8097   // AsmDialect, MayLoad, MayStore).
8098   bool HasSideEffect = IA->hasSideEffects();
8099   ExtraFlags ExtraInfo(CS);
8100 
8101   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8102   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8103   for (auto &T : TargetConstraints) {
8104     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8105     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8106 
8107     // Compute the value type for each operand.
8108     if (OpInfo.Type == InlineAsm::isInput ||
8109         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8110       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
8111 
8112       // Process the call argument. BasicBlocks are labels, currently appearing
8113       // only in asm's.
8114       const Instruction *I = CS.getInstruction();
8115       if (isa<CallBrInst>(I) &&
8116           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
8117                           cast<CallBrInst>(I)->getNumIndirectDests())) {
8118         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8119         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8120         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8121       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8122         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8123       } else {
8124         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8125       }
8126 
8127       OpInfo.ConstraintVT =
8128           OpInfo
8129               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8130               .getSimpleVT();
8131     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8132       // The return value of the call is this value.  As such, there is no
8133       // corresponding argument.
8134       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8135       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8136         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8137             DAG.getDataLayout(), STy->getElementType(ResNo));
8138       } else {
8139         assert(ResNo == 0 && "Asm only has one result!");
8140         OpInfo.ConstraintVT =
8141             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8142       }
8143       ++ResNo;
8144     } else {
8145       OpInfo.ConstraintVT = MVT::Other;
8146     }
8147 
8148     if (!HasSideEffect)
8149       HasSideEffect = OpInfo.hasMemory(TLI);
8150 
8151     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8152     // FIXME: Could we compute this on OpInfo rather than T?
8153 
8154     // Compute the constraint code and ConstraintType to use.
8155     TLI.ComputeConstraintToUse(T, SDValue());
8156 
8157     if (T.ConstraintType == TargetLowering::C_Immediate &&
8158         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8159       // We've delayed emitting a diagnostic like the "n" constraint because
8160       // inlining could cause an integer showing up.
8161       return emitInlineAsmError(
8162           CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8163                   "integer constant expression");
8164 
8165     ExtraInfo.update(T);
8166   }
8167 
8168 
8169   // We won't need to flush pending loads if this asm doesn't touch
8170   // memory and is nonvolatile.
8171   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8172 
8173   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8174   if (IsCallBr) {
8175     // If this is a callbr we need to flush pending exports since inlineasm_br
8176     // is a terminator. We need to do this before nodes are glued to
8177     // the inlineasm_br node.
8178     Chain = getControlRoot();
8179   }
8180 
8181   // Second pass over the constraints: compute which constraint option to use.
8182   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8183     // If this is an output operand with a matching input operand, look up the
8184     // matching input. If their types mismatch, e.g. one is an integer, the
8185     // other is floating point, or their sizes are different, flag it as an
8186     // error.
8187     if (OpInfo.hasMatchingInput()) {
8188       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8189       patchMatchingInput(OpInfo, Input, DAG);
8190     }
8191 
8192     // Compute the constraint code and ConstraintType to use.
8193     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8194 
8195     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8196         OpInfo.Type == InlineAsm::isClobber)
8197       continue;
8198 
8199     // If this is a memory input, and if the operand is not indirect, do what we
8200     // need to provide an address for the memory input.
8201     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8202         !OpInfo.isIndirect) {
8203       assert((OpInfo.isMultipleAlternative ||
8204               (OpInfo.Type == InlineAsm::isInput)) &&
8205              "Can only indirectify direct input operands!");
8206 
8207       // Memory operands really want the address of the value.
8208       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8209 
8210       // There is no longer a Value* corresponding to this operand.
8211       OpInfo.CallOperandVal = nullptr;
8212 
8213       // It is now an indirect operand.
8214       OpInfo.isIndirect = true;
8215     }
8216 
8217   }
8218 
8219   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8220   std::vector<SDValue> AsmNodeOperands;
8221   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8222   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8223       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8224 
8225   // If we have a !srcloc metadata node associated with it, we want to attach
8226   // this to the ultimately generated inline asm machineinstr.  To do this, we
8227   // pass in the third operand as this (potentially null) inline asm MDNode.
8228   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8229   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8230 
8231   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8232   // bits as operand 3.
8233   AsmNodeOperands.push_back(DAG.getTargetConstant(
8234       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8235 
8236   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8237   // this, assign virtual and physical registers for inputs and otput.
8238   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8239     // Assign Registers.
8240     SDISelAsmOperandInfo &RefOpInfo =
8241         OpInfo.isMatchingInputConstraint()
8242             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8243             : OpInfo;
8244     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8245 
8246     switch (OpInfo.Type) {
8247     case InlineAsm::isOutput:
8248       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8249         unsigned ConstraintID =
8250             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8251         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8252                "Failed to convert memory constraint code to constraint id.");
8253 
8254         // Add information to the INLINEASM node to know about this output.
8255         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8256         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8257         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8258                                                         MVT::i32));
8259         AsmNodeOperands.push_back(OpInfo.CallOperand);
8260       } else {
8261         // Otherwise, this outputs to a register (directly for C_Register /
8262         // C_RegisterClass, and a target-defined fashion for
8263         // C_Immediate/C_Other). Find a register that we can use.
8264         if (OpInfo.AssignedRegs.Regs.empty()) {
8265           emitInlineAsmError(
8266               CS, "couldn't allocate output register for constraint '" +
8267                       Twine(OpInfo.ConstraintCode) + "'");
8268           return;
8269         }
8270 
8271         // Add information to the INLINEASM node to know that this register is
8272         // set.
8273         OpInfo.AssignedRegs.AddInlineAsmOperands(
8274             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8275                                   : InlineAsm::Kind_RegDef,
8276             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8277       }
8278       break;
8279 
8280     case InlineAsm::isInput: {
8281       SDValue InOperandVal = OpInfo.CallOperand;
8282 
8283       if (OpInfo.isMatchingInputConstraint()) {
8284         // If this is required to match an output register we have already set,
8285         // just use its register.
8286         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8287                                                   AsmNodeOperands);
8288         unsigned OpFlag =
8289           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8290         if (InlineAsm::isRegDefKind(OpFlag) ||
8291             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8292           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8293           if (OpInfo.isIndirect) {
8294             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8295             emitInlineAsmError(CS, "inline asm not supported yet:"
8296                                    " don't know how to handle tied "
8297                                    "indirect register inputs");
8298             return;
8299           }
8300 
8301           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8302           SmallVector<unsigned, 4> Regs;
8303 
8304           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8305             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8306             MachineRegisterInfo &RegInfo =
8307                 DAG.getMachineFunction().getRegInfo();
8308             for (unsigned i = 0; i != NumRegs; ++i)
8309               Regs.push_back(RegInfo.createVirtualRegister(RC));
8310           } else {
8311             emitInlineAsmError(CS, "inline asm error: This value type register "
8312                                    "class is not natively supported!");
8313             return;
8314           }
8315 
8316           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8317 
8318           SDLoc dl = getCurSDLoc();
8319           // Use the produced MatchedRegs object to
8320           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8321                                     CS.getInstruction());
8322           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8323                                            true, OpInfo.getMatchedOperand(), dl,
8324                                            DAG, AsmNodeOperands);
8325           break;
8326         }
8327 
8328         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8329         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8330                "Unexpected number of operands");
8331         // Add information to the INLINEASM node to know about this input.
8332         // See InlineAsm.h isUseOperandTiedToDef.
8333         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8334         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8335                                                     OpInfo.getMatchedOperand());
8336         AsmNodeOperands.push_back(DAG.getTargetConstant(
8337             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8338         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8339         break;
8340       }
8341 
8342       // Treat indirect 'X' constraint as memory.
8343       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8344           OpInfo.isIndirect)
8345         OpInfo.ConstraintType = TargetLowering::C_Memory;
8346 
8347       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8348           OpInfo.ConstraintType == TargetLowering::C_Other) {
8349         std::vector<SDValue> Ops;
8350         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8351                                           Ops, DAG);
8352         if (Ops.empty()) {
8353           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8354             if (isa<ConstantSDNode>(InOperandVal)) {
8355               emitInlineAsmError(CS, "value out of range for constraint '" +
8356                                  Twine(OpInfo.ConstraintCode) + "'");
8357               return;
8358             }
8359 
8360           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8361                                      Twine(OpInfo.ConstraintCode) + "'");
8362           return;
8363         }
8364 
8365         // Add information to the INLINEASM node to know about this input.
8366         unsigned ResOpType =
8367           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8368         AsmNodeOperands.push_back(DAG.getTargetConstant(
8369             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8370         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8371         break;
8372       }
8373 
8374       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8375         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8376         assert(InOperandVal.getValueType() ==
8377                    TLI.getPointerTy(DAG.getDataLayout()) &&
8378                "Memory operands expect pointer values");
8379 
8380         unsigned ConstraintID =
8381             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8382         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8383                "Failed to convert memory constraint code to constraint id.");
8384 
8385         // Add information to the INLINEASM node to know about this input.
8386         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8387         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8388         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8389                                                         getCurSDLoc(),
8390                                                         MVT::i32));
8391         AsmNodeOperands.push_back(InOperandVal);
8392         break;
8393       }
8394 
8395       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8396               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8397              "Unknown constraint type!");
8398 
8399       // TODO: Support this.
8400       if (OpInfo.isIndirect) {
8401         emitInlineAsmError(
8402             CS, "Don't know how to handle indirect register inputs yet "
8403                 "for constraint '" +
8404                     Twine(OpInfo.ConstraintCode) + "'");
8405         return;
8406       }
8407 
8408       // Copy the input into the appropriate registers.
8409       if (OpInfo.AssignedRegs.Regs.empty()) {
8410         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8411                                    Twine(OpInfo.ConstraintCode) + "'");
8412         return;
8413       }
8414 
8415       SDLoc dl = getCurSDLoc();
8416 
8417       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8418                                         Chain, &Flag, CS.getInstruction());
8419 
8420       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8421                                                dl, DAG, AsmNodeOperands);
8422       break;
8423     }
8424     case InlineAsm::isClobber:
8425       // Add the clobbered value to the operand list, so that the register
8426       // allocator is aware that the physreg got clobbered.
8427       if (!OpInfo.AssignedRegs.Regs.empty())
8428         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8429                                                  false, 0, getCurSDLoc(), DAG,
8430                                                  AsmNodeOperands);
8431       break;
8432     }
8433   }
8434 
8435   // Finish up input operands.  Set the input chain and add the flag last.
8436   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8437   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8438 
8439   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8440   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8441                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8442   Flag = Chain.getValue(1);
8443 
8444   // Do additional work to generate outputs.
8445 
8446   SmallVector<EVT, 1> ResultVTs;
8447   SmallVector<SDValue, 1> ResultValues;
8448   SmallVector<SDValue, 8> OutChains;
8449 
8450   llvm::Type *CSResultType = CS.getType();
8451   ArrayRef<Type *> ResultTypes;
8452   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8453     ResultTypes = StructResult->elements();
8454   else if (!CSResultType->isVoidTy())
8455     ResultTypes = makeArrayRef(CSResultType);
8456 
8457   auto CurResultType = ResultTypes.begin();
8458   auto handleRegAssign = [&](SDValue V) {
8459     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8460     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8461     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8462     ++CurResultType;
8463     // If the type of the inline asm call site return value is different but has
8464     // same size as the type of the asm output bitcast it.  One example of this
8465     // is for vectors with different width / number of elements.  This can
8466     // happen for register classes that can contain multiple different value
8467     // types.  The preg or vreg allocated may not have the same VT as was
8468     // expected.
8469     //
8470     // This can also happen for a return value that disagrees with the register
8471     // class it is put in, eg. a double in a general-purpose register on a
8472     // 32-bit machine.
8473     if (ResultVT != V.getValueType() &&
8474         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8475       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8476     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8477              V.getValueType().isInteger()) {
8478       // If a result value was tied to an input value, the computed result
8479       // may have a wider width than the expected result.  Extract the
8480       // relevant portion.
8481       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8482     }
8483     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8484     ResultVTs.push_back(ResultVT);
8485     ResultValues.push_back(V);
8486   };
8487 
8488   // Deal with output operands.
8489   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8490     if (OpInfo.Type == InlineAsm::isOutput) {
8491       SDValue Val;
8492       // Skip trivial output operands.
8493       if (OpInfo.AssignedRegs.Regs.empty())
8494         continue;
8495 
8496       switch (OpInfo.ConstraintType) {
8497       case TargetLowering::C_Register:
8498       case TargetLowering::C_RegisterClass:
8499         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8500             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8501         break;
8502       case TargetLowering::C_Immediate:
8503       case TargetLowering::C_Other:
8504         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8505                                               OpInfo, DAG);
8506         break;
8507       case TargetLowering::C_Memory:
8508         break; // Already handled.
8509       case TargetLowering::C_Unknown:
8510         assert(false && "Unexpected unknown constraint");
8511       }
8512 
8513       // Indirect output manifest as stores. Record output chains.
8514       if (OpInfo.isIndirect) {
8515         const Value *Ptr = OpInfo.CallOperandVal;
8516         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8517         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8518                                      MachinePointerInfo(Ptr));
8519         OutChains.push_back(Store);
8520       } else {
8521         // generate CopyFromRegs to associated registers.
8522         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8523         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8524           for (const SDValue &V : Val->op_values())
8525             handleRegAssign(V);
8526         } else
8527           handleRegAssign(Val);
8528       }
8529     }
8530   }
8531 
8532   // Set results.
8533   if (!ResultValues.empty()) {
8534     assert(CurResultType == ResultTypes.end() &&
8535            "Mismatch in number of ResultTypes");
8536     assert(ResultValues.size() == ResultTypes.size() &&
8537            "Mismatch in number of output operands in asm result");
8538 
8539     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8540                             DAG.getVTList(ResultVTs), ResultValues);
8541     setValue(CS.getInstruction(), V);
8542   }
8543 
8544   // Collect store chains.
8545   if (!OutChains.empty())
8546     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8547 
8548   // Only Update Root if inline assembly has a memory effect.
8549   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8550     DAG.setRoot(Chain);
8551 }
8552 
8553 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8554                                              const Twine &Message) {
8555   LLVMContext &Ctx = *DAG.getContext();
8556   Ctx.emitError(CS.getInstruction(), Message);
8557 
8558   // Make sure we leave the DAG in a valid state
8559   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8560   SmallVector<EVT, 1> ValueVTs;
8561   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8562 
8563   if (ValueVTs.empty())
8564     return;
8565 
8566   SmallVector<SDValue, 1> Ops;
8567   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8568     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8569 
8570   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8571 }
8572 
8573 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8574   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8575                           MVT::Other, getRoot(),
8576                           getValue(I.getArgOperand(0)),
8577                           DAG.getSrcValue(I.getArgOperand(0))));
8578 }
8579 
8580 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8581   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8582   const DataLayout &DL = DAG.getDataLayout();
8583   SDValue V = DAG.getVAArg(
8584       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8585       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8586       DL.getABITypeAlignment(I.getType()));
8587   DAG.setRoot(V.getValue(1));
8588 
8589   if (I.getType()->isPointerTy())
8590     V = DAG.getPtrExtOrTrunc(
8591         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8592   setValue(&I, V);
8593 }
8594 
8595 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8596   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8597                           MVT::Other, getRoot(),
8598                           getValue(I.getArgOperand(0)),
8599                           DAG.getSrcValue(I.getArgOperand(0))));
8600 }
8601 
8602 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8603   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8604                           MVT::Other, getRoot(),
8605                           getValue(I.getArgOperand(0)),
8606                           getValue(I.getArgOperand(1)),
8607                           DAG.getSrcValue(I.getArgOperand(0)),
8608                           DAG.getSrcValue(I.getArgOperand(1))));
8609 }
8610 
8611 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8612                                                     const Instruction &I,
8613                                                     SDValue Op) {
8614   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8615   if (!Range)
8616     return Op;
8617 
8618   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8619   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8620     return Op;
8621 
8622   APInt Lo = CR.getUnsignedMin();
8623   if (!Lo.isMinValue())
8624     return Op;
8625 
8626   APInt Hi = CR.getUnsignedMax();
8627   unsigned Bits = std::max(Hi.getActiveBits(),
8628                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8629 
8630   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8631 
8632   SDLoc SL = getCurSDLoc();
8633 
8634   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8635                              DAG.getValueType(SmallVT));
8636   unsigned NumVals = Op.getNode()->getNumValues();
8637   if (NumVals == 1)
8638     return ZExt;
8639 
8640   SmallVector<SDValue, 4> Ops;
8641 
8642   Ops.push_back(ZExt);
8643   for (unsigned I = 1; I != NumVals; ++I)
8644     Ops.push_back(Op.getValue(I));
8645 
8646   return DAG.getMergeValues(Ops, SL);
8647 }
8648 
8649 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8650 /// the call being lowered.
8651 ///
8652 /// This is a helper for lowering intrinsics that follow a target calling
8653 /// convention or require stack pointer adjustment. Only a subset of the
8654 /// intrinsic's operands need to participate in the calling convention.
8655 void SelectionDAGBuilder::populateCallLoweringInfo(
8656     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8657     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8658     bool IsPatchPoint) {
8659   TargetLowering::ArgListTy Args;
8660   Args.reserve(NumArgs);
8661 
8662   // Populate the argument list.
8663   // Attributes for args start at offset 1, after the return attribute.
8664   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8665        ArgI != ArgE; ++ArgI) {
8666     const Value *V = Call->getOperand(ArgI);
8667 
8668     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8669 
8670     TargetLowering::ArgListEntry Entry;
8671     Entry.Node = getValue(V);
8672     Entry.Ty = V->getType();
8673     Entry.setAttributes(Call, ArgI);
8674     Args.push_back(Entry);
8675   }
8676 
8677   CLI.setDebugLoc(getCurSDLoc())
8678       .setChain(getRoot())
8679       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8680       .setDiscardResult(Call->use_empty())
8681       .setIsPatchPoint(IsPatchPoint);
8682 }
8683 
8684 /// Add a stack map intrinsic call's live variable operands to a stackmap
8685 /// or patchpoint target node's operand list.
8686 ///
8687 /// Constants are converted to TargetConstants purely as an optimization to
8688 /// avoid constant materialization and register allocation.
8689 ///
8690 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8691 /// generate addess computation nodes, and so FinalizeISel can convert the
8692 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8693 /// address materialization and register allocation, but may also be required
8694 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8695 /// alloca in the entry block, then the runtime may assume that the alloca's
8696 /// StackMap location can be read immediately after compilation and that the
8697 /// location is valid at any point during execution (this is similar to the
8698 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8699 /// only available in a register, then the runtime would need to trap when
8700 /// execution reaches the StackMap in order to read the alloca's location.
8701 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8702                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8703                                 SelectionDAGBuilder &Builder) {
8704   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8705     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8706     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8707       Ops.push_back(
8708         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8709       Ops.push_back(
8710         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8711     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8712       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8713       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8714           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8715     } else
8716       Ops.push_back(OpVal);
8717   }
8718 }
8719 
8720 /// Lower llvm.experimental.stackmap directly to its target opcode.
8721 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8722   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8723   //                                  [live variables...])
8724 
8725   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8726 
8727   SDValue Chain, InFlag, Callee, NullPtr;
8728   SmallVector<SDValue, 32> Ops;
8729 
8730   SDLoc DL = getCurSDLoc();
8731   Callee = getValue(CI.getCalledValue());
8732   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8733 
8734   // The stackmap intrinsic only records the live variables (the arguments
8735   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8736   // intrinsic, this won't be lowered to a function call. This means we don't
8737   // have to worry about calling conventions and target specific lowering code.
8738   // Instead we perform the call lowering right here.
8739   //
8740   // chain, flag = CALLSEQ_START(chain, 0, 0)
8741   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8742   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8743   //
8744   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8745   InFlag = Chain.getValue(1);
8746 
8747   // Add the <id> and <numBytes> constants.
8748   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8749   Ops.push_back(DAG.getTargetConstant(
8750                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8751   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8752   Ops.push_back(DAG.getTargetConstant(
8753                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8754                   MVT::i32));
8755 
8756   // Push live variables for the stack map.
8757   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8758 
8759   // We are not pushing any register mask info here on the operands list,
8760   // because the stackmap doesn't clobber anything.
8761 
8762   // Push the chain and the glue flag.
8763   Ops.push_back(Chain);
8764   Ops.push_back(InFlag);
8765 
8766   // Create the STACKMAP node.
8767   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8768   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8769   Chain = SDValue(SM, 0);
8770   InFlag = Chain.getValue(1);
8771 
8772   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8773 
8774   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8775 
8776   // Set the root to the target-lowered call chain.
8777   DAG.setRoot(Chain);
8778 
8779   // Inform the Frame Information that we have a stackmap in this function.
8780   FuncInfo.MF->getFrameInfo().setHasStackMap();
8781 }
8782 
8783 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8784 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8785                                           const BasicBlock *EHPadBB) {
8786   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8787   //                                                 i32 <numBytes>,
8788   //                                                 i8* <target>,
8789   //                                                 i32 <numArgs>,
8790   //                                                 [Args...],
8791   //                                                 [live variables...])
8792 
8793   CallingConv::ID CC = CS.getCallingConv();
8794   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8795   bool HasDef = !CS->getType()->isVoidTy();
8796   SDLoc dl = getCurSDLoc();
8797   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8798 
8799   // Handle immediate and symbolic callees.
8800   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8801     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8802                                    /*isTarget=*/true);
8803   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8804     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8805                                          SDLoc(SymbolicCallee),
8806                                          SymbolicCallee->getValueType(0));
8807 
8808   // Get the real number of arguments participating in the call <numArgs>
8809   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8810   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8811 
8812   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8813   // Intrinsics include all meta-operands up to but not including CC.
8814   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8815   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8816          "Not enough arguments provided to the patchpoint intrinsic");
8817 
8818   // For AnyRegCC the arguments are lowered later on manually.
8819   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8820   Type *ReturnTy =
8821     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8822 
8823   TargetLowering::CallLoweringInfo CLI(DAG);
8824   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8825                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8826   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8827 
8828   SDNode *CallEnd = Result.second.getNode();
8829   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8830     CallEnd = CallEnd->getOperand(0).getNode();
8831 
8832   /// Get a call instruction from the call sequence chain.
8833   /// Tail calls are not allowed.
8834   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8835          "Expected a callseq node.");
8836   SDNode *Call = CallEnd->getOperand(0).getNode();
8837   bool HasGlue = Call->getGluedNode();
8838 
8839   // Replace the target specific call node with the patchable intrinsic.
8840   SmallVector<SDValue, 8> Ops;
8841 
8842   // Add the <id> and <numBytes> constants.
8843   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8844   Ops.push_back(DAG.getTargetConstant(
8845                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8846   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8847   Ops.push_back(DAG.getTargetConstant(
8848                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8849                   MVT::i32));
8850 
8851   // Add the callee.
8852   Ops.push_back(Callee);
8853 
8854   // Adjust <numArgs> to account for any arguments that have been passed on the
8855   // stack instead.
8856   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8857   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8858   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8859   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8860 
8861   // Add the calling convention
8862   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8863 
8864   // Add the arguments we omitted previously. The register allocator should
8865   // place these in any free register.
8866   if (IsAnyRegCC)
8867     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8868       Ops.push_back(getValue(CS.getArgument(i)));
8869 
8870   // Push the arguments from the call instruction up to the register mask.
8871   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8872   Ops.append(Call->op_begin() + 2, e);
8873 
8874   // Push live variables for the stack map.
8875   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8876 
8877   // Push the register mask info.
8878   if (HasGlue)
8879     Ops.push_back(*(Call->op_end()-2));
8880   else
8881     Ops.push_back(*(Call->op_end()-1));
8882 
8883   // Push the chain (this is originally the first operand of the call, but
8884   // becomes now the last or second to last operand).
8885   Ops.push_back(*(Call->op_begin()));
8886 
8887   // Push the glue flag (last operand).
8888   if (HasGlue)
8889     Ops.push_back(*(Call->op_end()-1));
8890 
8891   SDVTList NodeTys;
8892   if (IsAnyRegCC && HasDef) {
8893     // Create the return types based on the intrinsic definition
8894     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8895     SmallVector<EVT, 3> ValueVTs;
8896     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8897     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8898 
8899     // There is always a chain and a glue type at the end
8900     ValueVTs.push_back(MVT::Other);
8901     ValueVTs.push_back(MVT::Glue);
8902     NodeTys = DAG.getVTList(ValueVTs);
8903   } else
8904     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8905 
8906   // Replace the target specific call node with a PATCHPOINT node.
8907   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8908                                          dl, NodeTys, Ops);
8909 
8910   // Update the NodeMap.
8911   if (HasDef) {
8912     if (IsAnyRegCC)
8913       setValue(CS.getInstruction(), SDValue(MN, 0));
8914     else
8915       setValue(CS.getInstruction(), Result.first);
8916   }
8917 
8918   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8919   // call sequence. Furthermore the location of the chain and glue can change
8920   // when the AnyReg calling convention is used and the intrinsic returns a
8921   // value.
8922   if (IsAnyRegCC && HasDef) {
8923     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8924     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8925     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8926   } else
8927     DAG.ReplaceAllUsesWith(Call, MN);
8928   DAG.DeleteNode(Call);
8929 
8930   // Inform the Frame Information that we have a patchpoint in this function.
8931   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8932 }
8933 
8934 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8935                                             unsigned Intrinsic) {
8936   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8937   SDValue Op1 = getValue(I.getArgOperand(0));
8938   SDValue Op2;
8939   if (I.getNumArgOperands() > 1)
8940     Op2 = getValue(I.getArgOperand(1));
8941   SDLoc dl = getCurSDLoc();
8942   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8943   SDValue Res;
8944   FastMathFlags FMF;
8945   if (isa<FPMathOperator>(I))
8946     FMF = I.getFastMathFlags();
8947 
8948   switch (Intrinsic) {
8949   case Intrinsic::experimental_vector_reduce_v2_fadd:
8950     if (FMF.allowReassoc())
8951       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8952                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8953     else
8954       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8955     break;
8956   case Intrinsic::experimental_vector_reduce_v2_fmul:
8957     if (FMF.allowReassoc())
8958       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8959                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8960     else
8961       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8962     break;
8963   case Intrinsic::experimental_vector_reduce_add:
8964     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8965     break;
8966   case Intrinsic::experimental_vector_reduce_mul:
8967     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8968     break;
8969   case Intrinsic::experimental_vector_reduce_and:
8970     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8971     break;
8972   case Intrinsic::experimental_vector_reduce_or:
8973     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8974     break;
8975   case Intrinsic::experimental_vector_reduce_xor:
8976     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8977     break;
8978   case Intrinsic::experimental_vector_reduce_smax:
8979     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8980     break;
8981   case Intrinsic::experimental_vector_reduce_smin:
8982     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8983     break;
8984   case Intrinsic::experimental_vector_reduce_umax:
8985     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8986     break;
8987   case Intrinsic::experimental_vector_reduce_umin:
8988     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8989     break;
8990   case Intrinsic::experimental_vector_reduce_fmax:
8991     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8992     break;
8993   case Intrinsic::experimental_vector_reduce_fmin:
8994     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8995     break;
8996   default:
8997     llvm_unreachable("Unhandled vector reduce intrinsic");
8998   }
8999   setValue(&I, Res);
9000 }
9001 
9002 /// Returns an AttributeList representing the attributes applied to the return
9003 /// value of the given call.
9004 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9005   SmallVector<Attribute::AttrKind, 2> Attrs;
9006   if (CLI.RetSExt)
9007     Attrs.push_back(Attribute::SExt);
9008   if (CLI.RetZExt)
9009     Attrs.push_back(Attribute::ZExt);
9010   if (CLI.IsInReg)
9011     Attrs.push_back(Attribute::InReg);
9012 
9013   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9014                             Attrs);
9015 }
9016 
9017 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9018 /// implementation, which just calls LowerCall.
9019 /// FIXME: When all targets are
9020 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9021 std::pair<SDValue, SDValue>
9022 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9023   // Handle the incoming return values from the call.
9024   CLI.Ins.clear();
9025   Type *OrigRetTy = CLI.RetTy;
9026   SmallVector<EVT, 4> RetTys;
9027   SmallVector<uint64_t, 4> Offsets;
9028   auto &DL = CLI.DAG.getDataLayout();
9029   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9030 
9031   if (CLI.IsPostTypeLegalization) {
9032     // If we are lowering a libcall after legalization, split the return type.
9033     SmallVector<EVT, 4> OldRetTys;
9034     SmallVector<uint64_t, 4> OldOffsets;
9035     RetTys.swap(OldRetTys);
9036     Offsets.swap(OldOffsets);
9037 
9038     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9039       EVT RetVT = OldRetTys[i];
9040       uint64_t Offset = OldOffsets[i];
9041       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9042       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9043       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9044       RetTys.append(NumRegs, RegisterVT);
9045       for (unsigned j = 0; j != NumRegs; ++j)
9046         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9047     }
9048   }
9049 
9050   SmallVector<ISD::OutputArg, 4> Outs;
9051   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9052 
9053   bool CanLowerReturn =
9054       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9055                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9056 
9057   SDValue DemoteStackSlot;
9058   int DemoteStackIdx = -100;
9059   if (!CanLowerReturn) {
9060     // FIXME: equivalent assert?
9061     // assert(!CS.hasInAllocaArgument() &&
9062     //        "sret demotion is incompatible with inalloca");
9063     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9064     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
9065     MachineFunction &MF = CLI.DAG.getMachineFunction();
9066     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
9067     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9068                                               DL.getAllocaAddrSpace());
9069 
9070     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9071     ArgListEntry Entry;
9072     Entry.Node = DemoteStackSlot;
9073     Entry.Ty = StackSlotPtrType;
9074     Entry.IsSExt = false;
9075     Entry.IsZExt = false;
9076     Entry.IsInReg = false;
9077     Entry.IsSRet = true;
9078     Entry.IsNest = false;
9079     Entry.IsByVal = false;
9080     Entry.IsReturned = false;
9081     Entry.IsSwiftSelf = false;
9082     Entry.IsSwiftError = false;
9083     Entry.IsCFGuardTarget = false;
9084     Entry.Alignment = Align;
9085     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9086     CLI.NumFixedArgs += 1;
9087     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9088 
9089     // sret demotion isn't compatible with tail-calls, since the sret argument
9090     // points into the callers stack frame.
9091     CLI.IsTailCall = false;
9092   } else {
9093     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9094         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9095     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9096       ISD::ArgFlagsTy Flags;
9097       if (NeedsRegBlock) {
9098         Flags.setInConsecutiveRegs();
9099         if (I == RetTys.size() - 1)
9100           Flags.setInConsecutiveRegsLast();
9101       }
9102       EVT VT = RetTys[I];
9103       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9104                                                      CLI.CallConv, VT);
9105       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9106                                                        CLI.CallConv, VT);
9107       for (unsigned i = 0; i != NumRegs; ++i) {
9108         ISD::InputArg MyFlags;
9109         MyFlags.Flags = Flags;
9110         MyFlags.VT = RegisterVT;
9111         MyFlags.ArgVT = VT;
9112         MyFlags.Used = CLI.IsReturnValueUsed;
9113         if (CLI.RetTy->isPointerTy()) {
9114           MyFlags.Flags.setPointer();
9115           MyFlags.Flags.setPointerAddrSpace(
9116               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9117         }
9118         if (CLI.RetSExt)
9119           MyFlags.Flags.setSExt();
9120         if (CLI.RetZExt)
9121           MyFlags.Flags.setZExt();
9122         if (CLI.IsInReg)
9123           MyFlags.Flags.setInReg();
9124         CLI.Ins.push_back(MyFlags);
9125       }
9126     }
9127   }
9128 
9129   // We push in swifterror return as the last element of CLI.Ins.
9130   ArgListTy &Args = CLI.getArgs();
9131   if (supportSwiftError()) {
9132     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9133       if (Args[i].IsSwiftError) {
9134         ISD::InputArg MyFlags;
9135         MyFlags.VT = getPointerTy(DL);
9136         MyFlags.ArgVT = EVT(getPointerTy(DL));
9137         MyFlags.Flags.setSwiftError();
9138         CLI.Ins.push_back(MyFlags);
9139       }
9140     }
9141   }
9142 
9143   // Handle all of the outgoing arguments.
9144   CLI.Outs.clear();
9145   CLI.OutVals.clear();
9146   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9147     SmallVector<EVT, 4> ValueVTs;
9148     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9149     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9150     Type *FinalType = Args[i].Ty;
9151     if (Args[i].IsByVal)
9152       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9153     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9154         FinalType, CLI.CallConv, CLI.IsVarArg);
9155     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9156          ++Value) {
9157       EVT VT = ValueVTs[Value];
9158       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9159       SDValue Op = SDValue(Args[i].Node.getNode(),
9160                            Args[i].Node.getResNo() + Value);
9161       ISD::ArgFlagsTy Flags;
9162 
9163       // Certain targets (such as MIPS), may have a different ABI alignment
9164       // for a type depending on the context. Give the target a chance to
9165       // specify the alignment it wants.
9166       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9167 
9168       if (Args[i].Ty->isPointerTy()) {
9169         Flags.setPointer();
9170         Flags.setPointerAddrSpace(
9171             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9172       }
9173       if (Args[i].IsZExt)
9174         Flags.setZExt();
9175       if (Args[i].IsSExt)
9176         Flags.setSExt();
9177       if (Args[i].IsInReg) {
9178         // If we are using vectorcall calling convention, a structure that is
9179         // passed InReg - is surely an HVA
9180         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9181             isa<StructType>(FinalType)) {
9182           // The first value of a structure is marked
9183           if (0 == Value)
9184             Flags.setHvaStart();
9185           Flags.setHva();
9186         }
9187         // Set InReg Flag
9188         Flags.setInReg();
9189       }
9190       if (Args[i].IsSRet)
9191         Flags.setSRet();
9192       if (Args[i].IsSwiftSelf)
9193         Flags.setSwiftSelf();
9194       if (Args[i].IsSwiftError)
9195         Flags.setSwiftError();
9196       if (Args[i].IsCFGuardTarget)
9197         Flags.setCFGuardTarget();
9198       if (Args[i].IsByVal)
9199         Flags.setByVal();
9200       if (Args[i].IsInAlloca) {
9201         Flags.setInAlloca();
9202         // Set the byval flag for CCAssignFn callbacks that don't know about
9203         // inalloca.  This way we can know how many bytes we should've allocated
9204         // and how many bytes a callee cleanup function will pop.  If we port
9205         // inalloca to more targets, we'll have to add custom inalloca handling
9206         // in the various CC lowering callbacks.
9207         Flags.setByVal();
9208       }
9209       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9210         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9211         Type *ElementTy = Ty->getElementType();
9212 
9213         unsigned FrameSize = DL.getTypeAllocSize(
9214             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9215         Flags.setByValSize(FrameSize);
9216 
9217         // info is not there but there are cases it cannot get right.
9218         unsigned FrameAlign;
9219         if (Args[i].Alignment)
9220           FrameAlign = Args[i].Alignment;
9221         else
9222           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9223         Flags.setByValAlign(Align(FrameAlign));
9224       }
9225       if (Args[i].IsNest)
9226         Flags.setNest();
9227       if (NeedsRegBlock)
9228         Flags.setInConsecutiveRegs();
9229       Flags.setOrigAlign(OriginalAlignment);
9230 
9231       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9232                                                  CLI.CallConv, VT);
9233       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9234                                                         CLI.CallConv, VT);
9235       SmallVector<SDValue, 4> Parts(NumParts);
9236       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9237 
9238       if (Args[i].IsSExt)
9239         ExtendKind = ISD::SIGN_EXTEND;
9240       else if (Args[i].IsZExt)
9241         ExtendKind = ISD::ZERO_EXTEND;
9242 
9243       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9244       // for now.
9245       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9246           CanLowerReturn) {
9247         assert((CLI.RetTy == Args[i].Ty ||
9248                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9249                  CLI.RetTy->getPointerAddressSpace() ==
9250                      Args[i].Ty->getPointerAddressSpace())) &&
9251                RetTys.size() == NumValues && "unexpected use of 'returned'");
9252         // Before passing 'returned' to the target lowering code, ensure that
9253         // either the register MVT and the actual EVT are the same size or that
9254         // the return value and argument are extended in the same way; in these
9255         // cases it's safe to pass the argument register value unchanged as the
9256         // return register value (although it's at the target's option whether
9257         // to do so)
9258         // TODO: allow code generation to take advantage of partially preserved
9259         // registers rather than clobbering the entire register when the
9260         // parameter extension method is not compatible with the return
9261         // extension method
9262         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9263             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9264              CLI.RetZExt == Args[i].IsZExt))
9265           Flags.setReturned();
9266       }
9267 
9268       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9269                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9270 
9271       for (unsigned j = 0; j != NumParts; ++j) {
9272         // if it isn't first piece, alignment must be 1
9273         // For scalable vectors the scalable part is currently handled
9274         // by individual targets, so we just use the known minimum size here.
9275         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9276                     i < CLI.NumFixedArgs, i,
9277                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9278         if (NumParts > 1 && j == 0)
9279           MyFlags.Flags.setSplit();
9280         else if (j != 0) {
9281           MyFlags.Flags.setOrigAlign(Align::None());
9282           if (j == NumParts - 1)
9283             MyFlags.Flags.setSplitEnd();
9284         }
9285 
9286         CLI.Outs.push_back(MyFlags);
9287         CLI.OutVals.push_back(Parts[j]);
9288       }
9289 
9290       if (NeedsRegBlock && Value == NumValues - 1)
9291         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9292     }
9293   }
9294 
9295   SmallVector<SDValue, 4> InVals;
9296   CLI.Chain = LowerCall(CLI, InVals);
9297 
9298   // Update CLI.InVals to use outside of this function.
9299   CLI.InVals = InVals;
9300 
9301   // Verify that the target's LowerCall behaved as expected.
9302   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9303          "LowerCall didn't return a valid chain!");
9304   assert((!CLI.IsTailCall || InVals.empty()) &&
9305          "LowerCall emitted a return value for a tail call!");
9306   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9307          "LowerCall didn't emit the correct number of values!");
9308 
9309   // For a tail call, the return value is merely live-out and there aren't
9310   // any nodes in the DAG representing it. Return a special value to
9311   // indicate that a tail call has been emitted and no more Instructions
9312   // should be processed in the current block.
9313   if (CLI.IsTailCall) {
9314     CLI.DAG.setRoot(CLI.Chain);
9315     return std::make_pair(SDValue(), SDValue());
9316   }
9317 
9318 #ifndef NDEBUG
9319   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9320     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9321     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9322            "LowerCall emitted a value with the wrong type!");
9323   }
9324 #endif
9325 
9326   SmallVector<SDValue, 4> ReturnValues;
9327   if (!CanLowerReturn) {
9328     // The instruction result is the result of loading from the
9329     // hidden sret parameter.
9330     SmallVector<EVT, 1> PVTs;
9331     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9332 
9333     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9334     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9335     EVT PtrVT = PVTs[0];
9336 
9337     unsigned NumValues = RetTys.size();
9338     ReturnValues.resize(NumValues);
9339     SmallVector<SDValue, 4> Chains(NumValues);
9340 
9341     // An aggregate return value cannot wrap around the address space, so
9342     // offsets to its parts don't wrap either.
9343     SDNodeFlags Flags;
9344     Flags.setNoUnsignedWrap(true);
9345 
9346     for (unsigned i = 0; i < NumValues; ++i) {
9347       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9348                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9349                                                         PtrVT), Flags);
9350       SDValue L = CLI.DAG.getLoad(
9351           RetTys[i], CLI.DL, CLI.Chain, Add,
9352           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9353                                             DemoteStackIdx, Offsets[i]),
9354           /* Alignment = */ 1);
9355       ReturnValues[i] = L;
9356       Chains[i] = L.getValue(1);
9357     }
9358 
9359     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9360   } else {
9361     // Collect the legal value parts into potentially illegal values
9362     // that correspond to the original function's return values.
9363     Optional<ISD::NodeType> AssertOp;
9364     if (CLI.RetSExt)
9365       AssertOp = ISD::AssertSext;
9366     else if (CLI.RetZExt)
9367       AssertOp = ISD::AssertZext;
9368     unsigned CurReg = 0;
9369     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9370       EVT VT = RetTys[I];
9371       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9372                                                      CLI.CallConv, VT);
9373       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9374                                                        CLI.CallConv, VT);
9375 
9376       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9377                                               NumRegs, RegisterVT, VT, nullptr,
9378                                               CLI.CallConv, AssertOp));
9379       CurReg += NumRegs;
9380     }
9381 
9382     // For a function returning void, there is no return value. We can't create
9383     // such a node, so we just return a null return value in that case. In
9384     // that case, nothing will actually look at the value.
9385     if (ReturnValues.empty())
9386       return std::make_pair(SDValue(), CLI.Chain);
9387   }
9388 
9389   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9390                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9391   return std::make_pair(Res, CLI.Chain);
9392 }
9393 
9394 void TargetLowering::LowerOperationWrapper(SDNode *N,
9395                                            SmallVectorImpl<SDValue> &Results,
9396                                            SelectionDAG &DAG) const {
9397   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9398     Results.push_back(Res);
9399 }
9400 
9401 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9402   llvm_unreachable("LowerOperation not implemented for this target!");
9403 }
9404 
9405 void
9406 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9407   SDValue Op = getNonRegisterValue(V);
9408   assert((Op.getOpcode() != ISD::CopyFromReg ||
9409           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9410          "Copy from a reg to the same reg!");
9411   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9412 
9413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9414   // If this is an InlineAsm we have to match the registers required, not the
9415   // notional registers required by the type.
9416 
9417   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9418                    None); // This is not an ABI copy.
9419   SDValue Chain = DAG.getEntryNode();
9420 
9421   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9422                               FuncInfo.PreferredExtendType.end())
9423                                  ? ISD::ANY_EXTEND
9424                                  : FuncInfo.PreferredExtendType[V];
9425   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9426   PendingExports.push_back(Chain);
9427 }
9428 
9429 #include "llvm/CodeGen/SelectionDAGISel.h"
9430 
9431 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9432 /// entry block, return true.  This includes arguments used by switches, since
9433 /// the switch may expand into multiple basic blocks.
9434 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9435   // With FastISel active, we may be splitting blocks, so force creation
9436   // of virtual registers for all non-dead arguments.
9437   if (FastISel)
9438     return A->use_empty();
9439 
9440   const BasicBlock &Entry = A->getParent()->front();
9441   for (const User *U : A->users())
9442     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9443       return false;  // Use not in entry block.
9444 
9445   return true;
9446 }
9447 
9448 using ArgCopyElisionMapTy =
9449     DenseMap<const Argument *,
9450              std::pair<const AllocaInst *, const StoreInst *>>;
9451 
9452 /// Scan the entry block of the function in FuncInfo for arguments that look
9453 /// like copies into a local alloca. Record any copied arguments in
9454 /// ArgCopyElisionCandidates.
9455 static void
9456 findArgumentCopyElisionCandidates(const DataLayout &DL,
9457                                   FunctionLoweringInfo *FuncInfo,
9458                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9459   // Record the state of every static alloca used in the entry block. Argument
9460   // allocas are all used in the entry block, so we need approximately as many
9461   // entries as we have arguments.
9462   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9463   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9464   unsigned NumArgs = FuncInfo->Fn->arg_size();
9465   StaticAllocas.reserve(NumArgs * 2);
9466 
9467   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9468     if (!V)
9469       return nullptr;
9470     V = V->stripPointerCasts();
9471     const auto *AI = dyn_cast<AllocaInst>(V);
9472     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9473       return nullptr;
9474     auto Iter = StaticAllocas.insert({AI, Unknown});
9475     return &Iter.first->second;
9476   };
9477 
9478   // Look for stores of arguments to static allocas. Look through bitcasts and
9479   // GEPs to handle type coercions, as long as the alloca is fully initialized
9480   // by the store. Any non-store use of an alloca escapes it and any subsequent
9481   // unanalyzed store might write it.
9482   // FIXME: Handle structs initialized with multiple stores.
9483   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9484     // Look for stores, and handle non-store uses conservatively.
9485     const auto *SI = dyn_cast<StoreInst>(&I);
9486     if (!SI) {
9487       // We will look through cast uses, so ignore them completely.
9488       if (I.isCast())
9489         continue;
9490       // Ignore debug info intrinsics, they don't escape or store to allocas.
9491       if (isa<DbgInfoIntrinsic>(I))
9492         continue;
9493       // This is an unknown instruction. Assume it escapes or writes to all
9494       // static alloca operands.
9495       for (const Use &U : I.operands()) {
9496         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9497           *Info = StaticAllocaInfo::Clobbered;
9498       }
9499       continue;
9500     }
9501 
9502     // If the stored value is a static alloca, mark it as escaped.
9503     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9504       *Info = StaticAllocaInfo::Clobbered;
9505 
9506     // Check if the destination is a static alloca.
9507     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9508     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9509     if (!Info)
9510       continue;
9511     const AllocaInst *AI = cast<AllocaInst>(Dst);
9512 
9513     // Skip allocas that have been initialized or clobbered.
9514     if (*Info != StaticAllocaInfo::Unknown)
9515       continue;
9516 
9517     // Check if the stored value is an argument, and that this store fully
9518     // initializes the alloca. Don't elide copies from the same argument twice.
9519     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9520     const auto *Arg = dyn_cast<Argument>(Val);
9521     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9522         Arg->getType()->isEmptyTy() ||
9523         DL.getTypeStoreSize(Arg->getType()) !=
9524             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9525         ArgCopyElisionCandidates.count(Arg)) {
9526       *Info = StaticAllocaInfo::Clobbered;
9527       continue;
9528     }
9529 
9530     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9531                       << '\n');
9532 
9533     // Mark this alloca and store for argument copy elision.
9534     *Info = StaticAllocaInfo::Elidable;
9535     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9536 
9537     // Stop scanning if we've seen all arguments. This will happen early in -O0
9538     // builds, which is useful, because -O0 builds have large entry blocks and
9539     // many allocas.
9540     if (ArgCopyElisionCandidates.size() == NumArgs)
9541       break;
9542   }
9543 }
9544 
9545 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9546 /// ArgVal is a load from a suitable fixed stack object.
9547 static void tryToElideArgumentCopy(
9548     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9549     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9550     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9551     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9552     SDValue ArgVal, bool &ArgHasUses) {
9553   // Check if this is a load from a fixed stack object.
9554   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9555   if (!LNode)
9556     return;
9557   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9558   if (!FINode)
9559     return;
9560 
9561   // Check that the fixed stack object is the right size and alignment.
9562   // Look at the alignment that the user wrote on the alloca instead of looking
9563   // at the stack object.
9564   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9565   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9566   const AllocaInst *AI = ArgCopyIter->second.first;
9567   int FixedIndex = FINode->getIndex();
9568   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9569   int OldIndex = AllocaIndex;
9570   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9571   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9572     LLVM_DEBUG(
9573         dbgs() << "  argument copy elision failed due to bad fixed stack "
9574                   "object size\n");
9575     return;
9576   }
9577   unsigned RequiredAlignment = AI->getAlignment();
9578   if (!RequiredAlignment) {
9579     RequiredAlignment = FuncInfo.MF->getDataLayout().getABITypeAlignment(
9580         AI->getAllocatedType());
9581   }
9582   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9583     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9584                          "greater than stack argument alignment ("
9585                       << RequiredAlignment << " vs "
9586                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9587     return;
9588   }
9589 
9590   // Perform the elision. Delete the old stack object and replace its only use
9591   // in the variable info map. Mark the stack object as mutable.
9592   LLVM_DEBUG({
9593     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9594            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9595            << '\n';
9596   });
9597   MFI.RemoveStackObject(OldIndex);
9598   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9599   AllocaIndex = FixedIndex;
9600   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9601   Chains.push_back(ArgVal.getValue(1));
9602 
9603   // Avoid emitting code for the store implementing the copy.
9604   const StoreInst *SI = ArgCopyIter->second.second;
9605   ElidedArgCopyInstrs.insert(SI);
9606 
9607   // Check for uses of the argument again so that we can avoid exporting ArgVal
9608   // if it is't used by anything other than the store.
9609   for (const Value *U : Arg.users()) {
9610     if (U != SI) {
9611       ArgHasUses = true;
9612       break;
9613     }
9614   }
9615 }
9616 
9617 void SelectionDAGISel::LowerArguments(const Function &F) {
9618   SelectionDAG &DAG = SDB->DAG;
9619   SDLoc dl = SDB->getCurSDLoc();
9620   const DataLayout &DL = DAG.getDataLayout();
9621   SmallVector<ISD::InputArg, 16> Ins;
9622 
9623   if (!FuncInfo->CanLowerReturn) {
9624     // Put in an sret pointer parameter before all the other parameters.
9625     SmallVector<EVT, 1> ValueVTs;
9626     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9627                     F.getReturnType()->getPointerTo(
9628                         DAG.getDataLayout().getAllocaAddrSpace()),
9629                     ValueVTs);
9630 
9631     // NOTE: Assuming that a pointer will never break down to more than one VT
9632     // or one register.
9633     ISD::ArgFlagsTy Flags;
9634     Flags.setSRet();
9635     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9636     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9637                          ISD::InputArg::NoArgIndex, 0);
9638     Ins.push_back(RetArg);
9639   }
9640 
9641   // Look for stores of arguments to static allocas. Mark such arguments with a
9642   // flag to ask the target to give us the memory location of that argument if
9643   // available.
9644   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9645   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9646                                     ArgCopyElisionCandidates);
9647 
9648   // Set up the incoming argument description vector.
9649   for (const Argument &Arg : F.args()) {
9650     unsigned ArgNo = Arg.getArgNo();
9651     SmallVector<EVT, 4> ValueVTs;
9652     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9653     bool isArgValueUsed = !Arg.use_empty();
9654     unsigned PartBase = 0;
9655     Type *FinalType = Arg.getType();
9656     if (Arg.hasAttribute(Attribute::ByVal))
9657       FinalType = Arg.getParamByValType();
9658     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9659         FinalType, F.getCallingConv(), F.isVarArg());
9660     for (unsigned Value = 0, NumValues = ValueVTs.size();
9661          Value != NumValues; ++Value) {
9662       EVT VT = ValueVTs[Value];
9663       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9664       ISD::ArgFlagsTy Flags;
9665 
9666       // Certain targets (such as MIPS), may have a different ABI alignment
9667       // for a type depending on the context. Give the target a chance to
9668       // specify the alignment it wants.
9669       const Align OriginalAlignment(
9670           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9671 
9672       if (Arg.getType()->isPointerTy()) {
9673         Flags.setPointer();
9674         Flags.setPointerAddrSpace(
9675             cast<PointerType>(Arg.getType())->getAddressSpace());
9676       }
9677       if (Arg.hasAttribute(Attribute::ZExt))
9678         Flags.setZExt();
9679       if (Arg.hasAttribute(Attribute::SExt))
9680         Flags.setSExt();
9681       if (Arg.hasAttribute(Attribute::InReg)) {
9682         // If we are using vectorcall calling convention, a structure that is
9683         // passed InReg - is surely an HVA
9684         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9685             isa<StructType>(Arg.getType())) {
9686           // The first value of a structure is marked
9687           if (0 == Value)
9688             Flags.setHvaStart();
9689           Flags.setHva();
9690         }
9691         // Set InReg Flag
9692         Flags.setInReg();
9693       }
9694       if (Arg.hasAttribute(Attribute::StructRet))
9695         Flags.setSRet();
9696       if (Arg.hasAttribute(Attribute::SwiftSelf))
9697         Flags.setSwiftSelf();
9698       if (Arg.hasAttribute(Attribute::SwiftError))
9699         Flags.setSwiftError();
9700       if (Arg.hasAttribute(Attribute::ByVal))
9701         Flags.setByVal();
9702       if (Arg.hasAttribute(Attribute::InAlloca)) {
9703         Flags.setInAlloca();
9704         // Set the byval flag for CCAssignFn callbacks that don't know about
9705         // inalloca.  This way we can know how many bytes we should've allocated
9706         // and how many bytes a callee cleanup function will pop.  If we port
9707         // inalloca to more targets, we'll have to add custom inalloca handling
9708         // in the various CC lowering callbacks.
9709         Flags.setByVal();
9710       }
9711       if (F.getCallingConv() == CallingConv::X86_INTR) {
9712         // IA Interrupt passes frame (1st parameter) by value in the stack.
9713         if (ArgNo == 0)
9714           Flags.setByVal();
9715       }
9716       if (Flags.isByVal() || Flags.isInAlloca()) {
9717         Type *ElementTy = Arg.getParamByValType();
9718 
9719         // For ByVal, size and alignment should be passed from FE.  BE will
9720         // guess if this info is not there but there are cases it cannot get
9721         // right.
9722         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9723         Flags.setByValSize(FrameSize);
9724 
9725         unsigned FrameAlign;
9726         if (Arg.getParamAlignment())
9727           FrameAlign = Arg.getParamAlignment();
9728         else
9729           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9730         Flags.setByValAlign(Align(FrameAlign));
9731       }
9732       if (Arg.hasAttribute(Attribute::Nest))
9733         Flags.setNest();
9734       if (NeedsRegBlock)
9735         Flags.setInConsecutiveRegs();
9736       Flags.setOrigAlign(OriginalAlignment);
9737       if (ArgCopyElisionCandidates.count(&Arg))
9738         Flags.setCopyElisionCandidate();
9739       if (Arg.hasAttribute(Attribute::Returned))
9740         Flags.setReturned();
9741 
9742       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9743           *CurDAG->getContext(), F.getCallingConv(), VT);
9744       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9745           *CurDAG->getContext(), F.getCallingConv(), VT);
9746       for (unsigned i = 0; i != NumRegs; ++i) {
9747         // For scalable vectors, use the minimum size; individual targets
9748         // are responsible for handling scalable vector arguments and
9749         // return values.
9750         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9751                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9752         if (NumRegs > 1 && i == 0)
9753           MyFlags.Flags.setSplit();
9754         // if it isn't first piece, alignment must be 1
9755         else if (i > 0) {
9756           MyFlags.Flags.setOrigAlign(Align::None());
9757           if (i == NumRegs - 1)
9758             MyFlags.Flags.setSplitEnd();
9759         }
9760         Ins.push_back(MyFlags);
9761       }
9762       if (NeedsRegBlock && Value == NumValues - 1)
9763         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9764       PartBase += VT.getStoreSize().getKnownMinSize();
9765     }
9766   }
9767 
9768   // Call the target to set up the argument values.
9769   SmallVector<SDValue, 8> InVals;
9770   SDValue NewRoot = TLI->LowerFormalArguments(
9771       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9772 
9773   // Verify that the target's LowerFormalArguments behaved as expected.
9774   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9775          "LowerFormalArguments didn't return a valid chain!");
9776   assert(InVals.size() == Ins.size() &&
9777          "LowerFormalArguments didn't emit the correct number of values!");
9778   LLVM_DEBUG({
9779     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9780       assert(InVals[i].getNode() &&
9781              "LowerFormalArguments emitted a null value!");
9782       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9783              "LowerFormalArguments emitted a value with the wrong type!");
9784     }
9785   });
9786 
9787   // Update the DAG with the new chain value resulting from argument lowering.
9788   DAG.setRoot(NewRoot);
9789 
9790   // Set up the argument values.
9791   unsigned i = 0;
9792   if (!FuncInfo->CanLowerReturn) {
9793     // Create a virtual register for the sret pointer, and put in a copy
9794     // from the sret argument into it.
9795     SmallVector<EVT, 1> ValueVTs;
9796     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9797                     F.getReturnType()->getPointerTo(
9798                         DAG.getDataLayout().getAllocaAddrSpace()),
9799                     ValueVTs);
9800     MVT VT = ValueVTs[0].getSimpleVT();
9801     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9802     Optional<ISD::NodeType> AssertOp = None;
9803     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9804                                         nullptr, F.getCallingConv(), AssertOp);
9805 
9806     MachineFunction& MF = SDB->DAG.getMachineFunction();
9807     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9808     Register SRetReg =
9809         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9810     FuncInfo->DemoteRegister = SRetReg;
9811     NewRoot =
9812         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9813     DAG.setRoot(NewRoot);
9814 
9815     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9816     ++i;
9817   }
9818 
9819   SmallVector<SDValue, 4> Chains;
9820   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9821   for (const Argument &Arg : F.args()) {
9822     SmallVector<SDValue, 4> ArgValues;
9823     SmallVector<EVT, 4> ValueVTs;
9824     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9825     unsigned NumValues = ValueVTs.size();
9826     if (NumValues == 0)
9827       continue;
9828 
9829     bool ArgHasUses = !Arg.use_empty();
9830 
9831     // Elide the copying store if the target loaded this argument from a
9832     // suitable fixed stack object.
9833     if (Ins[i].Flags.isCopyElisionCandidate()) {
9834       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9835                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9836                              InVals[i], ArgHasUses);
9837     }
9838 
9839     // If this argument is unused then remember its value. It is used to generate
9840     // debugging information.
9841     bool isSwiftErrorArg =
9842         TLI->supportSwiftError() &&
9843         Arg.hasAttribute(Attribute::SwiftError);
9844     if (!ArgHasUses && !isSwiftErrorArg) {
9845       SDB->setUnusedArgValue(&Arg, InVals[i]);
9846 
9847       // Also remember any frame index for use in FastISel.
9848       if (FrameIndexSDNode *FI =
9849           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9850         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9851     }
9852 
9853     for (unsigned Val = 0; Val != NumValues; ++Val) {
9854       EVT VT = ValueVTs[Val];
9855       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9856                                                       F.getCallingConv(), VT);
9857       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9858           *CurDAG->getContext(), F.getCallingConv(), VT);
9859 
9860       // Even an apparent 'unused' swifterror argument needs to be returned. So
9861       // we do generate a copy for it that can be used on return from the
9862       // function.
9863       if (ArgHasUses || isSwiftErrorArg) {
9864         Optional<ISD::NodeType> AssertOp;
9865         if (Arg.hasAttribute(Attribute::SExt))
9866           AssertOp = ISD::AssertSext;
9867         else if (Arg.hasAttribute(Attribute::ZExt))
9868           AssertOp = ISD::AssertZext;
9869 
9870         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9871                                              PartVT, VT, nullptr,
9872                                              F.getCallingConv(), AssertOp));
9873       }
9874 
9875       i += NumParts;
9876     }
9877 
9878     // We don't need to do anything else for unused arguments.
9879     if (ArgValues.empty())
9880       continue;
9881 
9882     // Note down frame index.
9883     if (FrameIndexSDNode *FI =
9884         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9885       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9886 
9887     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9888                                      SDB->getCurSDLoc());
9889 
9890     SDB->setValue(&Arg, Res);
9891     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9892       // We want to associate the argument with the frame index, among
9893       // involved operands, that correspond to the lowest address. The
9894       // getCopyFromParts function, called earlier, is swapping the order of
9895       // the operands to BUILD_PAIR depending on endianness. The result of
9896       // that swapping is that the least significant bits of the argument will
9897       // be in the first operand of the BUILD_PAIR node, and the most
9898       // significant bits will be in the second operand.
9899       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9900       if (LoadSDNode *LNode =
9901           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9902         if (FrameIndexSDNode *FI =
9903             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9904           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9905     }
9906 
9907     // Analyses past this point are naive and don't expect an assertion.
9908     if (Res.getOpcode() == ISD::AssertZext)
9909       Res = Res.getOperand(0);
9910 
9911     // Update the SwiftErrorVRegDefMap.
9912     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9913       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9914       if (Register::isVirtualRegister(Reg))
9915         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9916                                    Reg);
9917     }
9918 
9919     // If this argument is live outside of the entry block, insert a copy from
9920     // wherever we got it to the vreg that other BB's will reference it as.
9921     if (Res.getOpcode() == ISD::CopyFromReg) {
9922       // If we can, though, try to skip creating an unnecessary vreg.
9923       // FIXME: This isn't very clean... it would be nice to make this more
9924       // general.
9925       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9926       if (Register::isVirtualRegister(Reg)) {
9927         FuncInfo->ValueMap[&Arg] = Reg;
9928         continue;
9929       }
9930     }
9931     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9932       FuncInfo->InitializeRegForValue(&Arg);
9933       SDB->CopyToExportRegsIfNeeded(&Arg);
9934     }
9935   }
9936 
9937   if (!Chains.empty()) {
9938     Chains.push_back(NewRoot);
9939     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9940   }
9941 
9942   DAG.setRoot(NewRoot);
9943 
9944   assert(i == InVals.size() && "Argument register count mismatch!");
9945 
9946   // If any argument copy elisions occurred and we have debug info, update the
9947   // stale frame indices used in the dbg.declare variable info table.
9948   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9949   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9950     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9951       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9952       if (I != ArgCopyElisionFrameIndexMap.end())
9953         VI.Slot = I->second;
9954     }
9955   }
9956 
9957   // Finally, if the target has anything special to do, allow it to do so.
9958   EmitFunctionEntryCode();
9959 }
9960 
9961 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9962 /// ensure constants are generated when needed.  Remember the virtual registers
9963 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9964 /// directly add them, because expansion might result in multiple MBB's for one
9965 /// BB.  As such, the start of the BB might correspond to a different MBB than
9966 /// the end.
9967 void
9968 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9969   const Instruction *TI = LLVMBB->getTerminator();
9970 
9971   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9972 
9973   // Check PHI nodes in successors that expect a value to be available from this
9974   // block.
9975   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9976     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9977     if (!isa<PHINode>(SuccBB->begin())) continue;
9978     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9979 
9980     // If this terminator has multiple identical successors (common for
9981     // switches), only handle each succ once.
9982     if (!SuccsHandled.insert(SuccMBB).second)
9983       continue;
9984 
9985     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9986 
9987     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9988     // nodes and Machine PHI nodes, but the incoming operands have not been
9989     // emitted yet.
9990     for (const PHINode &PN : SuccBB->phis()) {
9991       // Ignore dead phi's.
9992       if (PN.use_empty())
9993         continue;
9994 
9995       // Skip empty types
9996       if (PN.getType()->isEmptyTy())
9997         continue;
9998 
9999       unsigned Reg;
10000       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10001 
10002       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10003         unsigned &RegOut = ConstantsOut[C];
10004         if (RegOut == 0) {
10005           RegOut = FuncInfo.CreateRegs(C);
10006           CopyValueToVirtualRegister(C, RegOut);
10007         }
10008         Reg = RegOut;
10009       } else {
10010         DenseMap<const Value *, unsigned>::iterator I =
10011           FuncInfo.ValueMap.find(PHIOp);
10012         if (I != FuncInfo.ValueMap.end())
10013           Reg = I->second;
10014         else {
10015           assert(isa<AllocaInst>(PHIOp) &&
10016                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10017                  "Didn't codegen value into a register!??");
10018           Reg = FuncInfo.CreateRegs(PHIOp);
10019           CopyValueToVirtualRegister(PHIOp, Reg);
10020         }
10021       }
10022 
10023       // Remember that this register needs to added to the machine PHI node as
10024       // the input for this MBB.
10025       SmallVector<EVT, 4> ValueVTs;
10026       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10027       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10028       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10029         EVT VT = ValueVTs[vti];
10030         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10031         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10032           FuncInfo.PHINodesToUpdate.push_back(
10033               std::make_pair(&*MBBI++, Reg + i));
10034         Reg += NumRegisters;
10035       }
10036     }
10037   }
10038 
10039   ConstantsOut.clear();
10040 }
10041 
10042 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10043 /// is 0.
10044 MachineBasicBlock *
10045 SelectionDAGBuilder::StackProtectorDescriptor::
10046 AddSuccessorMBB(const BasicBlock *BB,
10047                 MachineBasicBlock *ParentMBB,
10048                 bool IsLikely,
10049                 MachineBasicBlock *SuccMBB) {
10050   // If SuccBB has not been created yet, create it.
10051   if (!SuccMBB) {
10052     MachineFunction *MF = ParentMBB->getParent();
10053     MachineFunction::iterator BBI(ParentMBB);
10054     SuccMBB = MF->CreateMachineBasicBlock(BB);
10055     MF->insert(++BBI, SuccMBB);
10056   }
10057   // Add it as a successor of ParentMBB.
10058   ParentMBB->addSuccessor(
10059       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10060   return SuccMBB;
10061 }
10062 
10063 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10064   MachineFunction::iterator I(MBB);
10065   if (++I == FuncInfo.MF->end())
10066     return nullptr;
10067   return &*I;
10068 }
10069 
10070 /// During lowering new call nodes can be created (such as memset, etc.).
10071 /// Those will become new roots of the current DAG, but complications arise
10072 /// when they are tail calls. In such cases, the call lowering will update
10073 /// the root, but the builder still needs to know that a tail call has been
10074 /// lowered in order to avoid generating an additional return.
10075 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10076   // If the node is null, we do have a tail call.
10077   if (MaybeTC.getNode() != nullptr)
10078     DAG.setRoot(MaybeTC);
10079   else
10080     HasTailCall = true;
10081 }
10082 
10083 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10084                                         MachineBasicBlock *SwitchMBB,
10085                                         MachineBasicBlock *DefaultMBB) {
10086   MachineFunction *CurMF = FuncInfo.MF;
10087   MachineBasicBlock *NextMBB = nullptr;
10088   MachineFunction::iterator BBI(W.MBB);
10089   if (++BBI != FuncInfo.MF->end())
10090     NextMBB = &*BBI;
10091 
10092   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10093 
10094   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10095 
10096   if (Size == 2 && W.MBB == SwitchMBB) {
10097     // If any two of the cases has the same destination, and if one value
10098     // is the same as the other, but has one bit unset that the other has set,
10099     // use bit manipulation to do two compares at once.  For example:
10100     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10101     // TODO: This could be extended to merge any 2 cases in switches with 3
10102     // cases.
10103     // TODO: Handle cases where W.CaseBB != SwitchBB.
10104     CaseCluster &Small = *W.FirstCluster;
10105     CaseCluster &Big = *W.LastCluster;
10106 
10107     if (Small.Low == Small.High && Big.Low == Big.High &&
10108         Small.MBB == Big.MBB) {
10109       const APInt &SmallValue = Small.Low->getValue();
10110       const APInt &BigValue = Big.Low->getValue();
10111 
10112       // Check that there is only one bit different.
10113       APInt CommonBit = BigValue ^ SmallValue;
10114       if (CommonBit.isPowerOf2()) {
10115         SDValue CondLHS = getValue(Cond);
10116         EVT VT = CondLHS.getValueType();
10117         SDLoc DL = getCurSDLoc();
10118 
10119         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10120                                  DAG.getConstant(CommonBit, DL, VT));
10121         SDValue Cond = DAG.getSetCC(
10122             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10123             ISD::SETEQ);
10124 
10125         // Update successor info.
10126         // Both Small and Big will jump to Small.BB, so we sum up the
10127         // probabilities.
10128         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10129         if (BPI)
10130           addSuccessorWithProb(
10131               SwitchMBB, DefaultMBB,
10132               // The default destination is the first successor in IR.
10133               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10134         else
10135           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10136 
10137         // Insert the true branch.
10138         SDValue BrCond =
10139             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10140                         DAG.getBasicBlock(Small.MBB));
10141         // Insert the false branch.
10142         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10143                              DAG.getBasicBlock(DefaultMBB));
10144 
10145         DAG.setRoot(BrCond);
10146         return;
10147       }
10148     }
10149   }
10150 
10151   if (TM.getOptLevel() != CodeGenOpt::None) {
10152     // Here, we order cases by probability so the most likely case will be
10153     // checked first. However, two clusters can have the same probability in
10154     // which case their relative ordering is non-deterministic. So we use Low
10155     // as a tie-breaker as clusters are guaranteed to never overlap.
10156     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10157                [](const CaseCluster &a, const CaseCluster &b) {
10158       return a.Prob != b.Prob ?
10159              a.Prob > b.Prob :
10160              a.Low->getValue().slt(b.Low->getValue());
10161     });
10162 
10163     // Rearrange the case blocks so that the last one falls through if possible
10164     // without changing the order of probabilities.
10165     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10166       --I;
10167       if (I->Prob > W.LastCluster->Prob)
10168         break;
10169       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10170         std::swap(*I, *W.LastCluster);
10171         break;
10172       }
10173     }
10174   }
10175 
10176   // Compute total probability.
10177   BranchProbability DefaultProb = W.DefaultProb;
10178   BranchProbability UnhandledProbs = DefaultProb;
10179   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10180     UnhandledProbs += I->Prob;
10181 
10182   MachineBasicBlock *CurMBB = W.MBB;
10183   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10184     bool FallthroughUnreachable = false;
10185     MachineBasicBlock *Fallthrough;
10186     if (I == W.LastCluster) {
10187       // For the last cluster, fall through to the default destination.
10188       Fallthrough = DefaultMBB;
10189       FallthroughUnreachable = isa<UnreachableInst>(
10190           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10191     } else {
10192       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10193       CurMF->insert(BBI, Fallthrough);
10194       // Put Cond in a virtual register to make it available from the new blocks.
10195       ExportFromCurrentBlock(Cond);
10196     }
10197     UnhandledProbs -= I->Prob;
10198 
10199     switch (I->Kind) {
10200       case CC_JumpTable: {
10201         // FIXME: Optimize away range check based on pivot comparisons.
10202         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10203         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10204 
10205         // The jump block hasn't been inserted yet; insert it here.
10206         MachineBasicBlock *JumpMBB = JT->MBB;
10207         CurMF->insert(BBI, JumpMBB);
10208 
10209         auto JumpProb = I->Prob;
10210         auto FallthroughProb = UnhandledProbs;
10211 
10212         // If the default statement is a target of the jump table, we evenly
10213         // distribute the default probability to successors of CurMBB. Also
10214         // update the probability on the edge from JumpMBB to Fallthrough.
10215         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10216                                               SE = JumpMBB->succ_end();
10217              SI != SE; ++SI) {
10218           if (*SI == DefaultMBB) {
10219             JumpProb += DefaultProb / 2;
10220             FallthroughProb -= DefaultProb / 2;
10221             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10222             JumpMBB->normalizeSuccProbs();
10223             break;
10224           }
10225         }
10226 
10227         if (FallthroughUnreachable) {
10228           // Skip the range check if the fallthrough block is unreachable.
10229           JTH->OmitRangeCheck = true;
10230         }
10231 
10232         if (!JTH->OmitRangeCheck)
10233           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10234         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10235         CurMBB->normalizeSuccProbs();
10236 
10237         // The jump table header will be inserted in our current block, do the
10238         // range check, and fall through to our fallthrough block.
10239         JTH->HeaderBB = CurMBB;
10240         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10241 
10242         // If we're in the right place, emit the jump table header right now.
10243         if (CurMBB == SwitchMBB) {
10244           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10245           JTH->Emitted = true;
10246         }
10247         break;
10248       }
10249       case CC_BitTests: {
10250         // FIXME: Optimize away range check based on pivot comparisons.
10251         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10252 
10253         // The bit test blocks haven't been inserted yet; insert them here.
10254         for (BitTestCase &BTC : BTB->Cases)
10255           CurMF->insert(BBI, BTC.ThisBB);
10256 
10257         // Fill in fields of the BitTestBlock.
10258         BTB->Parent = CurMBB;
10259         BTB->Default = Fallthrough;
10260 
10261         BTB->DefaultProb = UnhandledProbs;
10262         // If the cases in bit test don't form a contiguous range, we evenly
10263         // distribute the probability on the edge to Fallthrough to two
10264         // successors of CurMBB.
10265         if (!BTB->ContiguousRange) {
10266           BTB->Prob += DefaultProb / 2;
10267           BTB->DefaultProb -= DefaultProb / 2;
10268         }
10269 
10270         if (FallthroughUnreachable) {
10271           // Skip the range check if the fallthrough block is unreachable.
10272           BTB->OmitRangeCheck = true;
10273         }
10274 
10275         // If we're in the right place, emit the bit test header right now.
10276         if (CurMBB == SwitchMBB) {
10277           visitBitTestHeader(*BTB, SwitchMBB);
10278           BTB->Emitted = true;
10279         }
10280         break;
10281       }
10282       case CC_Range: {
10283         const Value *RHS, *LHS, *MHS;
10284         ISD::CondCode CC;
10285         if (I->Low == I->High) {
10286           // Check Cond == I->Low.
10287           CC = ISD::SETEQ;
10288           LHS = Cond;
10289           RHS=I->Low;
10290           MHS = nullptr;
10291         } else {
10292           // Check I->Low <= Cond <= I->High.
10293           CC = ISD::SETLE;
10294           LHS = I->Low;
10295           MHS = Cond;
10296           RHS = I->High;
10297         }
10298 
10299         // If Fallthrough is unreachable, fold away the comparison.
10300         if (FallthroughUnreachable)
10301           CC = ISD::SETTRUE;
10302 
10303         // The false probability is the sum of all unhandled cases.
10304         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10305                      getCurSDLoc(), I->Prob, UnhandledProbs);
10306 
10307         if (CurMBB == SwitchMBB)
10308           visitSwitchCase(CB, SwitchMBB);
10309         else
10310           SL->SwitchCases.push_back(CB);
10311 
10312         break;
10313       }
10314     }
10315     CurMBB = Fallthrough;
10316   }
10317 }
10318 
10319 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10320                                               CaseClusterIt First,
10321                                               CaseClusterIt Last) {
10322   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10323     if (X.Prob != CC.Prob)
10324       return X.Prob > CC.Prob;
10325 
10326     // Ties are broken by comparing the case value.
10327     return X.Low->getValue().slt(CC.Low->getValue());
10328   });
10329 }
10330 
10331 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10332                                         const SwitchWorkListItem &W,
10333                                         Value *Cond,
10334                                         MachineBasicBlock *SwitchMBB) {
10335   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10336          "Clusters not sorted?");
10337 
10338   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10339 
10340   // Balance the tree based on branch probabilities to create a near-optimal (in
10341   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10342   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10343   CaseClusterIt LastLeft = W.FirstCluster;
10344   CaseClusterIt FirstRight = W.LastCluster;
10345   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10346   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10347 
10348   // Move LastLeft and FirstRight towards each other from opposite directions to
10349   // find a partitioning of the clusters which balances the probability on both
10350   // sides. If LeftProb and RightProb are equal, alternate which side is
10351   // taken to ensure 0-probability nodes are distributed evenly.
10352   unsigned I = 0;
10353   while (LastLeft + 1 < FirstRight) {
10354     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10355       LeftProb += (++LastLeft)->Prob;
10356     else
10357       RightProb += (--FirstRight)->Prob;
10358     I++;
10359   }
10360 
10361   while (true) {
10362     // Our binary search tree differs from a typical BST in that ours can have up
10363     // to three values in each leaf. The pivot selection above doesn't take that
10364     // into account, which means the tree might require more nodes and be less
10365     // efficient. We compensate for this here.
10366 
10367     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10368     unsigned NumRight = W.LastCluster - FirstRight + 1;
10369 
10370     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10371       // If one side has less than 3 clusters, and the other has more than 3,
10372       // consider taking a cluster from the other side.
10373 
10374       if (NumLeft < NumRight) {
10375         // Consider moving the first cluster on the right to the left side.
10376         CaseCluster &CC = *FirstRight;
10377         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10378         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10379         if (LeftSideRank <= RightSideRank) {
10380           // Moving the cluster to the left does not demote it.
10381           ++LastLeft;
10382           ++FirstRight;
10383           continue;
10384         }
10385       } else {
10386         assert(NumRight < NumLeft);
10387         // Consider moving the last element on the left to the right side.
10388         CaseCluster &CC = *LastLeft;
10389         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10390         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10391         if (RightSideRank <= LeftSideRank) {
10392           // Moving the cluster to the right does not demot it.
10393           --LastLeft;
10394           --FirstRight;
10395           continue;
10396         }
10397       }
10398     }
10399     break;
10400   }
10401 
10402   assert(LastLeft + 1 == FirstRight);
10403   assert(LastLeft >= W.FirstCluster);
10404   assert(FirstRight <= W.LastCluster);
10405 
10406   // Use the first element on the right as pivot since we will make less-than
10407   // comparisons against it.
10408   CaseClusterIt PivotCluster = FirstRight;
10409   assert(PivotCluster > W.FirstCluster);
10410   assert(PivotCluster <= W.LastCluster);
10411 
10412   CaseClusterIt FirstLeft = W.FirstCluster;
10413   CaseClusterIt LastRight = W.LastCluster;
10414 
10415   const ConstantInt *Pivot = PivotCluster->Low;
10416 
10417   // New blocks will be inserted immediately after the current one.
10418   MachineFunction::iterator BBI(W.MBB);
10419   ++BBI;
10420 
10421   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10422   // we can branch to its destination directly if it's squeezed exactly in
10423   // between the known lower bound and Pivot - 1.
10424   MachineBasicBlock *LeftMBB;
10425   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10426       FirstLeft->Low == W.GE &&
10427       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10428     LeftMBB = FirstLeft->MBB;
10429   } else {
10430     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10431     FuncInfo.MF->insert(BBI, LeftMBB);
10432     WorkList.push_back(
10433         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10434     // Put Cond in a virtual register to make it available from the new blocks.
10435     ExportFromCurrentBlock(Cond);
10436   }
10437 
10438   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10439   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10440   // directly if RHS.High equals the current upper bound.
10441   MachineBasicBlock *RightMBB;
10442   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10443       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10444     RightMBB = FirstRight->MBB;
10445   } else {
10446     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10447     FuncInfo.MF->insert(BBI, RightMBB);
10448     WorkList.push_back(
10449         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10450     // Put Cond in a virtual register to make it available from the new blocks.
10451     ExportFromCurrentBlock(Cond);
10452   }
10453 
10454   // Create the CaseBlock record that will be used to lower the branch.
10455   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10456                getCurSDLoc(), LeftProb, RightProb);
10457 
10458   if (W.MBB == SwitchMBB)
10459     visitSwitchCase(CB, SwitchMBB);
10460   else
10461     SL->SwitchCases.push_back(CB);
10462 }
10463 
10464 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10465 // from the swith statement.
10466 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10467                                             BranchProbability PeeledCaseProb) {
10468   if (PeeledCaseProb == BranchProbability::getOne())
10469     return BranchProbability::getZero();
10470   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10471 
10472   uint32_t Numerator = CaseProb.getNumerator();
10473   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10474   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10475 }
10476 
10477 // Try to peel the top probability case if it exceeds the threshold.
10478 // Return current MachineBasicBlock for the switch statement if the peeling
10479 // does not occur.
10480 // If the peeling is performed, return the newly created MachineBasicBlock
10481 // for the peeled switch statement. Also update Clusters to remove the peeled
10482 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10483 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10484     const SwitchInst &SI, CaseClusterVector &Clusters,
10485     BranchProbability &PeeledCaseProb) {
10486   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10487   // Don't perform if there is only one cluster or optimizing for size.
10488   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10489       TM.getOptLevel() == CodeGenOpt::None ||
10490       SwitchMBB->getParent()->getFunction().hasMinSize())
10491     return SwitchMBB;
10492 
10493   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10494   unsigned PeeledCaseIndex = 0;
10495   bool SwitchPeeled = false;
10496   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10497     CaseCluster &CC = Clusters[Index];
10498     if (CC.Prob < TopCaseProb)
10499       continue;
10500     TopCaseProb = CC.Prob;
10501     PeeledCaseIndex = Index;
10502     SwitchPeeled = true;
10503   }
10504   if (!SwitchPeeled)
10505     return SwitchMBB;
10506 
10507   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10508                     << TopCaseProb << "\n");
10509 
10510   // Record the MBB for the peeled switch statement.
10511   MachineFunction::iterator BBI(SwitchMBB);
10512   ++BBI;
10513   MachineBasicBlock *PeeledSwitchMBB =
10514       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10515   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10516 
10517   ExportFromCurrentBlock(SI.getCondition());
10518   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10519   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10520                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10521   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10522 
10523   Clusters.erase(PeeledCaseIt);
10524   for (CaseCluster &CC : Clusters) {
10525     LLVM_DEBUG(
10526         dbgs() << "Scale the probablity for one cluster, before scaling: "
10527                << CC.Prob << "\n");
10528     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10529     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10530   }
10531   PeeledCaseProb = TopCaseProb;
10532   return PeeledSwitchMBB;
10533 }
10534 
10535 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10536   // Extract cases from the switch.
10537   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10538   CaseClusterVector Clusters;
10539   Clusters.reserve(SI.getNumCases());
10540   for (auto I : SI.cases()) {
10541     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10542     const ConstantInt *CaseVal = I.getCaseValue();
10543     BranchProbability Prob =
10544         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10545             : BranchProbability(1, SI.getNumCases() + 1);
10546     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10547   }
10548 
10549   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10550 
10551   // Cluster adjacent cases with the same destination. We do this at all
10552   // optimization levels because it's cheap to do and will make codegen faster
10553   // if there are many clusters.
10554   sortAndRangeify(Clusters);
10555 
10556   // The branch probablity of the peeled case.
10557   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10558   MachineBasicBlock *PeeledSwitchMBB =
10559       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10560 
10561   // If there is only the default destination, jump there directly.
10562   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10563   if (Clusters.empty()) {
10564     assert(PeeledSwitchMBB == SwitchMBB);
10565     SwitchMBB->addSuccessor(DefaultMBB);
10566     if (DefaultMBB != NextBlock(SwitchMBB)) {
10567       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10568                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10569     }
10570     return;
10571   }
10572 
10573   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10574   SL->findBitTestClusters(Clusters, &SI);
10575 
10576   LLVM_DEBUG({
10577     dbgs() << "Case clusters: ";
10578     for (const CaseCluster &C : Clusters) {
10579       if (C.Kind == CC_JumpTable)
10580         dbgs() << "JT:";
10581       if (C.Kind == CC_BitTests)
10582         dbgs() << "BT:";
10583 
10584       C.Low->getValue().print(dbgs(), true);
10585       if (C.Low != C.High) {
10586         dbgs() << '-';
10587         C.High->getValue().print(dbgs(), true);
10588       }
10589       dbgs() << ' ';
10590     }
10591     dbgs() << '\n';
10592   });
10593 
10594   assert(!Clusters.empty());
10595   SwitchWorkList WorkList;
10596   CaseClusterIt First = Clusters.begin();
10597   CaseClusterIt Last = Clusters.end() - 1;
10598   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10599   // Scale the branchprobability for DefaultMBB if the peel occurs and
10600   // DefaultMBB is not replaced.
10601   if (PeeledCaseProb != BranchProbability::getZero() &&
10602       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10603     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10604   WorkList.push_back(
10605       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10606 
10607   while (!WorkList.empty()) {
10608     SwitchWorkListItem W = WorkList.back();
10609     WorkList.pop_back();
10610     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10611 
10612     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10613         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10614       // For optimized builds, lower large range as a balanced binary tree.
10615       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10616       continue;
10617     }
10618 
10619     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10620   }
10621 }
10622 
10623 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10624   SDValue N = getValue(I.getOperand(0));
10625   setValue(&I, N);
10626 }
10627