xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 80c79035ef06b4429c4bb6aa5504fff08ace4b05)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/BranchProbabilityInfo.h"
29 #include "llvm/Analysis/ConstantFolding.h"
30 #include "llvm/Analysis/EHPersonalities.h"
31 #include "llvm/Analysis/Loads.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/ProfileSummaryInfo.h"
34 #include "llvm/Analysis/TargetLibraryInfo.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/Analysis/VectorUtils.h"
37 #include "llvm/CodeGen/Analysis.h"
38 #include "llvm/CodeGen/FunctionLoweringInfo.h"
39 #include "llvm/CodeGen/GCMetadata.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineJumpTableInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
53 #include "llvm/CodeGen/StackMaps.h"
54 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
55 #include "llvm/CodeGen/TargetFrameLowering.h"
56 #include "llvm/CodeGen/TargetInstrInfo.h"
57 #include "llvm/CodeGen/TargetOpcodes.h"
58 #include "llvm/CodeGen/TargetRegisterInfo.h"
59 #include "llvm/CodeGen/TargetSubtargetInfo.h"
60 #include "llvm/CodeGen/WinEHFuncInfo.h"
61 #include "llvm/IR/Argument.h"
62 #include "llvm/IR/Attributes.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/CFG.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/ConstantRange.h"
68 #include "llvm/IR/Constants.h"
69 #include "llvm/IR/DataLayout.h"
70 #include "llvm/IR/DebugInfoMetadata.h"
71 #include "llvm/IR/DerivedTypes.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/GetElementPtrTypeIterator.h"
74 #include "llvm/IR/InlineAsm.h"
75 #include "llvm/IR/InstrTypes.h"
76 #include "llvm/IR/Instructions.h"
77 #include "llvm/IR/IntrinsicInst.h"
78 #include "llvm/IR/Intrinsics.h"
79 #include "llvm/IR/IntrinsicsAArch64.h"
80 #include "llvm/IR/IntrinsicsWebAssembly.h"
81 #include "llvm/IR/LLVMContext.h"
82 #include "llvm/IR/Metadata.h"
83 #include "llvm/IR/Module.h"
84 #include "llvm/IR/Operator.h"
85 #include "llvm/IR/PatternMatch.h"
86 #include "llvm/IR/Statepoint.h"
87 #include "llvm/IR/Type.h"
88 #include "llvm/IR/User.h"
89 #include "llvm/IR/Value.h"
90 #include "llvm/MC/MCContext.h"
91 #include "llvm/MC/MCSymbol.h"
92 #include "llvm/Support/AtomicOrdering.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/MathExtras.h"
98 #include "llvm/Support/raw_ostream.h"
99 #include "llvm/Target/TargetIntrinsicInfo.h"
100 #include "llvm/Target/TargetMachine.h"
101 #include "llvm/Target/TargetOptions.h"
102 #include "llvm/Transforms/Utils/Local.h"
103 #include <cstddef>
104 #include <cstring>
105 #include <iterator>
106 #include <limits>
107 #include <numeric>
108 #include <tuple>
109 
110 using namespace llvm;
111 using namespace PatternMatch;
112 using namespace SwitchCG;
113 
114 #define DEBUG_TYPE "isel"
115 
116 /// LimitFloatPrecision - Generate low-precision inline sequences for
117 /// some float libcalls (6, 8 or 12 bits).
118 static unsigned LimitFloatPrecision;
119 
120 static cl::opt<bool>
121     InsertAssertAlign("insert-assert-align", cl::init(true),
122                       cl::desc("Insert the experimental `assertalign` node."),
123                       cl::ReallyHidden);
124 
125 static cl::opt<unsigned, true>
126     LimitFPPrecision("limit-float-precision",
127                      cl::desc("Generate low-precision inline sequences "
128                               "for some float libcalls"),
129                      cl::location(LimitFloatPrecision), cl::Hidden,
130                      cl::init(0));
131 
132 static cl::opt<unsigned> SwitchPeelThreshold(
133     "switch-peel-threshold", cl::Hidden, cl::init(66),
134     cl::desc("Set the case probability threshold for peeling the case from a "
135              "switch statement. A value greater than 100 will void this "
136              "optimization"));
137 
138 // Limit the width of DAG chains. This is important in general to prevent
139 // DAG-based analysis from blowing up. For example, alias analysis and
140 // load clustering may not complete in reasonable time. It is difficult to
141 // recognize and avoid this situation within each individual analysis, and
142 // future analyses are likely to have the same behavior. Limiting DAG width is
143 // the safe approach and will be especially important with global DAGs.
144 //
145 // MaxParallelChains default is arbitrarily high to avoid affecting
146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
147 // sequence over this should have been converted to llvm.memcpy by the
148 // frontend. It is easy to induce this behavior with .ll code such as:
149 // %buffer = alloca [4096 x i8]
150 // %data = load [4096 x i8]* %argPtr
151 // store [4096 x i8] %data, [4096 x i8]* %buffer
152 static const unsigned MaxParallelChains = 64;
153 
154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
155                                       const SDValue *Parts, unsigned NumParts,
156                                       MVT PartVT, EVT ValueVT, const Value *V,
157                                       Optional<CallingConv::ID> CC);
158 
159 /// getCopyFromParts - Create a value that contains the specified legal parts
160 /// combined into the value they represent.  If the parts combine to a type
161 /// larger than ValueVT then AssertOp can be used to specify whether the extra
162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
163 /// (ISD::AssertSext).
164 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
165                                 const SDValue *Parts, unsigned NumParts,
166                                 MVT PartVT, EVT ValueVT, const Value *V,
167                                 Optional<CallingConv::ID> CC = None,
168                                 Optional<ISD::NodeType> AssertOp = None) {
169   // Let the target assemble the parts if it wants to
170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
171   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
172                                                    PartVT, ValueVT, CC))
173     return Val;
174 
175   if (ValueVT.isVector())
176     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
177                                   CC);
178 
179   assert(NumParts > 0 && "No parts to assemble!");
180   SDValue Val = Parts[0];
181 
182   if (NumParts > 1) {
183     // Assemble the value from multiple parts.
184     if (ValueVT.isInteger()) {
185       unsigned PartBits = PartVT.getSizeInBits();
186       unsigned ValueBits = ValueVT.getSizeInBits();
187 
188       // Assemble the power of 2 part.
189       unsigned RoundParts =
190           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
191       unsigned RoundBits = PartBits * RoundParts;
192       EVT RoundVT = RoundBits == ValueBits ?
193         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
194       SDValue Lo, Hi;
195 
196       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
197 
198       if (RoundParts > 2) {
199         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
200                               PartVT, HalfVT, V);
201         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
202                               RoundParts / 2, PartVT, HalfVT, V);
203       } else {
204         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
205         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
206       }
207 
208       if (DAG.getDataLayout().isBigEndian())
209         std::swap(Lo, Hi);
210 
211       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
212 
213       if (RoundParts < NumParts) {
214         // Assemble the trailing non-power-of-2 part.
215         unsigned OddParts = NumParts - RoundParts;
216         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
217         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
218                               OddVT, V, CC);
219 
220         // Combine the round and odd parts.
221         Lo = Val;
222         if (DAG.getDataLayout().isBigEndian())
223           std::swap(Lo, Hi);
224         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
225         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
226         Hi =
227             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
228                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
229                                         TLI.getPointerTy(DAG.getDataLayout())));
230         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
231         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
232       }
233     } else if (PartVT.isFloatingPoint()) {
234       // FP split into multiple FP parts (for ppcf128)
235       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
236              "Unexpected split");
237       SDValue Lo, Hi;
238       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
239       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
240       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
241         std::swap(Lo, Hi);
242       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
243     } else {
244       // FP split into integer parts (soft fp)
245       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
246              !PartVT.isVector() && "Unexpected split");
247       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
248       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
249     }
250   }
251 
252   // There is now one part, held in Val.  Correct it to match ValueVT.
253   // PartEVT is the type of the register class that holds the value.
254   // ValueVT is the type of the inline asm operation.
255   EVT PartEVT = Val.getValueType();
256 
257   if (PartEVT == ValueVT)
258     return Val;
259 
260   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
261       ValueVT.bitsLT(PartEVT)) {
262     // For an FP value in an integer part, we need to truncate to the right
263     // width first.
264     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
265     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
266   }
267 
268   // Handle types that have the same size.
269   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
270     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
271 
272   // Handle types with different sizes.
273   if (PartEVT.isInteger() && ValueVT.isInteger()) {
274     if (ValueVT.bitsLT(PartEVT)) {
275       // For a truncate, see if we have any information to
276       // indicate whether the truncated bits will always be
277       // zero or sign-extension.
278       if (AssertOp.hasValue())
279         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
280                           DAG.getValueType(ValueVT));
281       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
282     }
283     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
284   }
285 
286   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
287     // FP_ROUND's are always exact here.
288     if (ValueVT.bitsLT(Val.getValueType()))
289       return DAG.getNode(
290           ISD::FP_ROUND, DL, ValueVT, Val,
291           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
292 
293     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
294   }
295 
296   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
297   // then truncating.
298   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
299       ValueVT.bitsLT(PartEVT)) {
300     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
301     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
302   }
303 
304   report_fatal_error("Unknown mismatch in getCopyFromParts!");
305 }
306 
307 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
308                                               const Twine &ErrMsg) {
309   const Instruction *I = dyn_cast_or_null<Instruction>(V);
310   if (!V)
311     return Ctx.emitError(ErrMsg);
312 
313   const char *AsmError = ", possible invalid constraint for vector type";
314   if (const CallInst *CI = dyn_cast<CallInst>(I))
315     if (CI->isInlineAsm())
316       return Ctx.emitError(I, ErrMsg + AsmError);
317 
318   return Ctx.emitError(I, ErrMsg);
319 }
320 
321 /// getCopyFromPartsVector - Create a value that contains the specified legal
322 /// parts combined into the value they represent.  If the parts combine to a
323 /// type larger than ValueVT then AssertOp can be used to specify whether the
324 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
325 /// ValueVT (ISD::AssertSext).
326 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
327                                       const SDValue *Parts, unsigned NumParts,
328                                       MVT PartVT, EVT ValueVT, const Value *V,
329                                       Optional<CallingConv::ID> CallConv) {
330   assert(ValueVT.isVector() && "Not a vector value");
331   assert(NumParts > 0 && "No parts to assemble!");
332   const bool IsABIRegCopy = CallConv.hasValue();
333 
334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
335   SDValue Val = Parts[0];
336 
337   // Handle a multi-element vector.
338   if (NumParts > 1) {
339     EVT IntermediateVT;
340     MVT RegisterVT;
341     unsigned NumIntermediates;
342     unsigned NumRegs;
343 
344     if (IsABIRegCopy) {
345       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
346           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
347           NumIntermediates, RegisterVT);
348     } else {
349       NumRegs =
350           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
351                                      NumIntermediates, RegisterVT);
352     }
353 
354     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
355     NumParts = NumRegs; // Silence a compiler warning.
356     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
357     assert(RegisterVT.getSizeInBits() ==
358            Parts[0].getSimpleValueType().getSizeInBits() &&
359            "Part type sizes don't match!");
360 
361     // Assemble the parts into intermediate operands.
362     SmallVector<SDValue, 8> Ops(NumIntermediates);
363     if (NumIntermediates == NumParts) {
364       // If the register was not expanded, truncate or copy the value,
365       // as appropriate.
366       for (unsigned i = 0; i != NumParts; ++i)
367         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
368                                   PartVT, IntermediateVT, V, CallConv);
369     } else if (NumParts > 0) {
370       // If the intermediate type was expanded, build the intermediate
371       // operands from the parts.
372       assert(NumParts % NumIntermediates == 0 &&
373              "Must expand into a divisible number of parts!");
374       unsigned Factor = NumParts / NumIntermediates;
375       for (unsigned i = 0; i != NumIntermediates; ++i)
376         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
377                                   PartVT, IntermediateVT, V, CallConv);
378     }
379 
380     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
381     // intermediate operands.
382     EVT BuiltVectorTy =
383         IntermediateVT.isVector()
384             ? EVT::getVectorVT(
385                   *DAG.getContext(), IntermediateVT.getScalarType(),
386                   IntermediateVT.getVectorElementCount() * NumParts)
387             : EVT::getVectorVT(*DAG.getContext(),
388                                IntermediateVT.getScalarType(),
389                                NumIntermediates);
390     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
391                                                 : ISD::BUILD_VECTOR,
392                       DL, BuiltVectorTy, Ops);
393   }
394 
395   // There is now one part, held in Val.  Correct it to match ValueVT.
396   EVT PartEVT = Val.getValueType();
397 
398   if (PartEVT == ValueVT)
399     return Val;
400 
401   if (PartEVT.isVector()) {
402     // If the element type of the source/dest vectors are the same, but the
403     // parts vector has more elements than the value vector, then we have a
404     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
405     // elements we want.
406     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
407       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
408               ValueVT.getVectorElementCount().getKnownMinValue()) &&
409              (PartEVT.getVectorElementCount().isScalable() ==
410               ValueVT.getVectorElementCount().isScalable()) &&
411              "Cannot narrow, it would be a lossy transformation");
412       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
413                          DAG.getVectorIdxConstant(0, DL));
414     }
415 
416     // Vector/Vector bitcast.
417     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
418       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
419 
420     assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() &&
421       "Cannot handle this kind of promotion");
422     // Promoted vector extract
423     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
424 
425   }
426 
427   // Trivial bitcast if the types are the same size and the destination
428   // vector type is legal.
429   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
430       TLI.isTypeLegal(ValueVT))
431     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
432 
433   if (ValueVT.getVectorNumElements() != 1) {
434      // Certain ABIs require that vectors are passed as integers. For vectors
435      // are the same size, this is an obvious bitcast.
436      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
437        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
438      } else if (ValueVT.bitsLT(PartEVT)) {
439        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
440        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
441        // Drop the extra bits.
442        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
443        return DAG.getBitcast(ValueVT, Val);
444      }
445 
446      diagnosePossiblyInvalidConstraint(
447          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
448      return DAG.getUNDEF(ValueVT);
449   }
450 
451   // Handle cases such as i8 -> <1 x i1>
452   EVT ValueSVT = ValueVT.getVectorElementType();
453   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
454     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
455       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
456     else
457       Val = ValueVT.isFloatingPoint()
458                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
459                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
460   }
461 
462   return DAG.getBuildVector(ValueVT, DL, Val);
463 }
464 
465 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
466                                  SDValue Val, SDValue *Parts, unsigned NumParts,
467                                  MVT PartVT, const Value *V,
468                                  Optional<CallingConv::ID> CallConv);
469 
470 /// getCopyToParts - Create a series of nodes that contain the specified value
471 /// split into legal parts.  If the parts contain more bits than Val, then, for
472 /// integers, ExtendKind can be used to specify how to generate the extra bits.
473 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
474                            SDValue *Parts, unsigned NumParts, MVT PartVT,
475                            const Value *V,
476                            Optional<CallingConv::ID> CallConv = None,
477                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
478   // Let the target split the parts if it wants to
479   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
480   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
481                                       CallConv))
482     return;
483   EVT ValueVT = Val.getValueType();
484 
485   // Handle the vector case separately.
486   if (ValueVT.isVector())
487     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
488                                 CallConv);
489 
490   unsigned PartBits = PartVT.getSizeInBits();
491   unsigned OrigNumParts = NumParts;
492   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
493          "Copying to an illegal type!");
494 
495   if (NumParts == 0)
496     return;
497 
498   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
499   EVT PartEVT = PartVT;
500   if (PartEVT == ValueVT) {
501     assert(NumParts == 1 && "No-op copy with multiple parts!");
502     Parts[0] = Val;
503     return;
504   }
505 
506   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
507     // If the parts cover more bits than the value has, promote the value.
508     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
509       assert(NumParts == 1 && "Do not know what to promote to!");
510       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
511     } else {
512       if (ValueVT.isFloatingPoint()) {
513         // FP values need to be bitcast, then extended if they are being put
514         // into a larger container.
515         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
516         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
517       }
518       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
519              ValueVT.isInteger() &&
520              "Unknown mismatch!");
521       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
522       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
523       if (PartVT == MVT::x86mmx)
524         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
525     }
526   } else if (PartBits == ValueVT.getSizeInBits()) {
527     // Different types of the same size.
528     assert(NumParts == 1 && PartEVT != ValueVT);
529     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
530   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
531     // If the parts cover less bits than value has, truncate the value.
532     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
533            ValueVT.isInteger() &&
534            "Unknown mismatch!");
535     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
536     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
537     if (PartVT == MVT::x86mmx)
538       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539   }
540 
541   // The value may have changed - recompute ValueVT.
542   ValueVT = Val.getValueType();
543   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
544          "Failed to tile the value with PartVT!");
545 
546   if (NumParts == 1) {
547     if (PartEVT != ValueVT) {
548       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
549                                         "scalar-to-vector conversion failed");
550       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
551     }
552 
553     Parts[0] = Val;
554     return;
555   }
556 
557   // Expand the value into multiple parts.
558   if (NumParts & (NumParts - 1)) {
559     // The number of parts is not a power of 2.  Split off and copy the tail.
560     assert(PartVT.isInteger() && ValueVT.isInteger() &&
561            "Do not know what to expand to!");
562     unsigned RoundParts = 1 << Log2_32(NumParts);
563     unsigned RoundBits = RoundParts * PartBits;
564     unsigned OddParts = NumParts - RoundParts;
565     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
566       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
567 
568     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
569                    CallConv);
570 
571     if (DAG.getDataLayout().isBigEndian())
572       // The odd parts were reversed by getCopyToParts - unreverse them.
573       std::reverse(Parts + RoundParts, Parts + NumParts);
574 
575     NumParts = RoundParts;
576     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
577     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
578   }
579 
580   // The number of parts is a power of 2.  Repeatedly bisect the value using
581   // EXTRACT_ELEMENT.
582   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
583                          EVT::getIntegerVT(*DAG.getContext(),
584                                            ValueVT.getSizeInBits()),
585                          Val);
586 
587   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
588     for (unsigned i = 0; i < NumParts; i += StepSize) {
589       unsigned ThisBits = StepSize * PartBits / 2;
590       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
591       SDValue &Part0 = Parts[i];
592       SDValue &Part1 = Parts[i+StepSize/2];
593 
594       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
595                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
596       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
597                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
598 
599       if (ThisBits == PartBits && ThisVT != PartVT) {
600         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
601         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
602       }
603     }
604   }
605 
606   if (DAG.getDataLayout().isBigEndian())
607     std::reverse(Parts, Parts + OrigNumParts);
608 }
609 
610 static SDValue widenVectorToPartType(SelectionDAG &DAG,
611                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
612   if (!PartVT.isFixedLengthVector())
613     return SDValue();
614 
615   EVT ValueVT = Val.getValueType();
616   unsigned PartNumElts = PartVT.getVectorNumElements();
617   unsigned ValueNumElts = ValueVT.getVectorNumElements();
618   if (PartNumElts > ValueNumElts &&
619       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
620     EVT ElementVT = PartVT.getVectorElementType();
621     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
622     // undef elements.
623     SmallVector<SDValue, 16> Ops;
624     DAG.ExtractVectorElements(Val, Ops);
625     SDValue EltUndef = DAG.getUNDEF(ElementVT);
626     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
627       Ops.push_back(EltUndef);
628 
629     // FIXME: Use CONCAT for 2x -> 4x.
630     return DAG.getBuildVector(PartVT, DL, Ops);
631   }
632 
633   return SDValue();
634 }
635 
636 /// getCopyToPartsVector - Create a series of nodes that contain the specified
637 /// value split into legal parts.
638 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
639                                  SDValue Val, SDValue *Parts, unsigned NumParts,
640                                  MVT PartVT, const Value *V,
641                                  Optional<CallingConv::ID> CallConv) {
642   EVT ValueVT = Val.getValueType();
643   assert(ValueVT.isVector() && "Not a vector");
644   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
645   const bool IsABIRegCopy = CallConv.hasValue();
646 
647   if (NumParts == 1) {
648     EVT PartEVT = PartVT;
649     if (PartEVT == ValueVT) {
650       // Nothing to do.
651     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
652       // Bitconvert vector->vector case.
653       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
654     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
655       Val = Widened;
656     } else if (PartVT.isVector() &&
657                PartEVT.getVectorElementType().bitsGE(
658                    ValueVT.getVectorElementType()) &&
659                PartEVT.getVectorElementCount() ==
660                    ValueVT.getVectorElementCount()) {
661 
662       // Promoted vector extract
663       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
664     } else {
665       if (ValueVT.getVectorElementCount().isScalar()) {
666         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
667                           DAG.getVectorIdxConstant(0, DL));
668       } else {
669         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
670         assert(PartVT.getFixedSizeInBits() > ValueSize &&
671                "lossy conversion of vector to scalar type");
672         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
673         Val = DAG.getBitcast(IntermediateType, Val);
674         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
675       }
676     }
677 
678     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
679     Parts[0] = Val;
680     return;
681   }
682 
683   // Handle a multi-element vector.
684   EVT IntermediateVT;
685   MVT RegisterVT;
686   unsigned NumIntermediates;
687   unsigned NumRegs;
688   if (IsABIRegCopy) {
689     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
690         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
691         NumIntermediates, RegisterVT);
692   } else {
693     NumRegs =
694         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
695                                    NumIntermediates, RegisterVT);
696   }
697 
698   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
699   NumParts = NumRegs; // Silence a compiler warning.
700   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
701 
702   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
703          "Mixing scalable and fixed vectors when copying in parts");
704 
705   Optional<ElementCount> DestEltCnt;
706 
707   if (IntermediateVT.isVector())
708     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
709   else
710     DestEltCnt = ElementCount::getFixed(NumIntermediates);
711 
712   EVT BuiltVectorTy = EVT::getVectorVT(
713       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
714 
715   if (ValueVT == BuiltVectorTy) {
716     // Nothing to do.
717   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
718     // Bitconvert vector->vector case.
719     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
720   } else if (SDValue Widened =
721                  widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
722     Val = Widened;
723   } else if (BuiltVectorTy.getVectorElementType().bitsGE(
724                  ValueVT.getVectorElementType()) &&
725              BuiltVectorTy.getVectorElementCount() ==
726                  ValueVT.getVectorElementCount()) {
727     // Promoted vector extract
728     Val = DAG.getAnyExtOrTrunc(Val, DL, BuiltVectorTy);
729   }
730 
731   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
732 
733   // Split the vector into intermediate operands.
734   SmallVector<SDValue, 8> Ops(NumIntermediates);
735   for (unsigned i = 0; i != NumIntermediates; ++i) {
736     if (IntermediateVT.isVector()) {
737       // This does something sensible for scalable vectors - see the
738       // definition of EXTRACT_SUBVECTOR for further details.
739       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
740       Ops[i] =
741           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
742                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
743     } else {
744       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
745                            DAG.getVectorIdxConstant(i, DL));
746     }
747   }
748 
749   // Split the intermediate operands into legal parts.
750   if (NumParts == NumIntermediates) {
751     // If the register was not expanded, promote or copy the value,
752     // as appropriate.
753     for (unsigned i = 0; i != NumParts; ++i)
754       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
755   } else if (NumParts > 0) {
756     // If the intermediate type was expanded, split each the value into
757     // legal parts.
758     assert(NumIntermediates != 0 && "division by zero");
759     assert(NumParts % NumIntermediates == 0 &&
760            "Must expand into a divisible number of parts!");
761     unsigned Factor = NumParts / NumIntermediates;
762     for (unsigned i = 0; i != NumIntermediates; ++i)
763       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
764                      CallConv);
765   }
766 }
767 
768 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
769                            EVT valuevt, Optional<CallingConv::ID> CC)
770     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
771       RegCount(1, regs.size()), CallConv(CC) {}
772 
773 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
774                            const DataLayout &DL, unsigned Reg, Type *Ty,
775                            Optional<CallingConv::ID> CC) {
776   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
777 
778   CallConv = CC;
779 
780   for (EVT ValueVT : ValueVTs) {
781     unsigned NumRegs =
782         isABIMangled()
783             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
784             : TLI.getNumRegisters(Context, ValueVT);
785     MVT RegisterVT =
786         isABIMangled()
787             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
788             : TLI.getRegisterType(Context, ValueVT);
789     for (unsigned i = 0; i != NumRegs; ++i)
790       Regs.push_back(Reg + i);
791     RegVTs.push_back(RegisterVT);
792     RegCount.push_back(NumRegs);
793     Reg += NumRegs;
794   }
795 }
796 
797 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
798                                       FunctionLoweringInfo &FuncInfo,
799                                       const SDLoc &dl, SDValue &Chain,
800                                       SDValue *Flag, const Value *V) const {
801   // A Value with type {} or [0 x %t] needs no registers.
802   if (ValueVTs.empty())
803     return SDValue();
804 
805   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
806 
807   // Assemble the legal parts into the final values.
808   SmallVector<SDValue, 4> Values(ValueVTs.size());
809   SmallVector<SDValue, 8> Parts;
810   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
811     // Copy the legal parts from the registers.
812     EVT ValueVT = ValueVTs[Value];
813     unsigned NumRegs = RegCount[Value];
814     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
815                                           *DAG.getContext(),
816                                           CallConv.getValue(), RegVTs[Value])
817                                     : RegVTs[Value];
818 
819     Parts.resize(NumRegs);
820     for (unsigned i = 0; i != NumRegs; ++i) {
821       SDValue P;
822       if (!Flag) {
823         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
824       } else {
825         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
826         *Flag = P.getValue(2);
827       }
828 
829       Chain = P.getValue(1);
830       Parts[i] = P;
831 
832       // If the source register was virtual and if we know something about it,
833       // add an assert node.
834       if (!Register::isVirtualRegister(Regs[Part + i]) ||
835           !RegisterVT.isInteger())
836         continue;
837 
838       const FunctionLoweringInfo::LiveOutInfo *LOI =
839         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
840       if (!LOI)
841         continue;
842 
843       unsigned RegSize = RegisterVT.getScalarSizeInBits();
844       unsigned NumSignBits = LOI->NumSignBits;
845       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
846 
847       if (NumZeroBits == RegSize) {
848         // The current value is a zero.
849         // Explicitly express that as it would be easier for
850         // optimizations to kick in.
851         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
852         continue;
853       }
854 
855       // FIXME: We capture more information than the dag can represent.  For
856       // now, just use the tightest assertzext/assertsext possible.
857       bool isSExt;
858       EVT FromVT(MVT::Other);
859       if (NumZeroBits) {
860         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
861         isSExt = false;
862       } else if (NumSignBits > 1) {
863         FromVT =
864             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
865         isSExt = true;
866       } else {
867         continue;
868       }
869       // Add an assertion node.
870       assert(FromVT != MVT::Other);
871       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
872                              RegisterVT, P, DAG.getValueType(FromVT));
873     }
874 
875     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
876                                      RegisterVT, ValueVT, V, CallConv);
877     Part += NumRegs;
878     Parts.clear();
879   }
880 
881   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
882 }
883 
884 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
885                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
886                                  const Value *V,
887                                  ISD::NodeType PreferredExtendType) const {
888   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
889   ISD::NodeType ExtendKind = PreferredExtendType;
890 
891   // Get the list of the values's legal parts.
892   unsigned NumRegs = Regs.size();
893   SmallVector<SDValue, 8> Parts(NumRegs);
894   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
895     unsigned NumParts = RegCount[Value];
896 
897     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
898                                           *DAG.getContext(),
899                                           CallConv.getValue(), RegVTs[Value])
900                                     : RegVTs[Value];
901 
902     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
903       ExtendKind = ISD::ZERO_EXTEND;
904 
905     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
906                    NumParts, RegisterVT, V, CallConv, ExtendKind);
907     Part += NumParts;
908   }
909 
910   // Copy the parts into the registers.
911   SmallVector<SDValue, 8> Chains(NumRegs);
912   for (unsigned i = 0; i != NumRegs; ++i) {
913     SDValue Part;
914     if (!Flag) {
915       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
916     } else {
917       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
918       *Flag = Part.getValue(1);
919     }
920 
921     Chains[i] = Part.getValue(0);
922   }
923 
924   if (NumRegs == 1 || Flag)
925     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
926     // flagged to it. That is the CopyToReg nodes and the user are considered
927     // a single scheduling unit. If we create a TokenFactor and return it as
928     // chain, then the TokenFactor is both a predecessor (operand) of the
929     // user as well as a successor (the TF operands are flagged to the user).
930     // c1, f1 = CopyToReg
931     // c2, f2 = CopyToReg
932     // c3     = TokenFactor c1, c2
933     // ...
934     //        = op c3, ..., f2
935     Chain = Chains[NumRegs-1];
936   else
937     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
938 }
939 
940 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
941                                         unsigned MatchingIdx, const SDLoc &dl,
942                                         SelectionDAG &DAG,
943                                         std::vector<SDValue> &Ops) const {
944   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
945 
946   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
947   if (HasMatching)
948     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
949   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
950     // Put the register class of the virtual registers in the flag word.  That
951     // way, later passes can recompute register class constraints for inline
952     // assembly as well as normal instructions.
953     // Don't do this for tied operands that can use the regclass information
954     // from the def.
955     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
956     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
957     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
958   }
959 
960   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
961   Ops.push_back(Res);
962 
963   if (Code == InlineAsm::Kind_Clobber) {
964     // Clobbers should always have a 1:1 mapping with registers, and may
965     // reference registers that have illegal (e.g. vector) types. Hence, we
966     // shouldn't try to apply any sort of splitting logic to them.
967     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
968            "No 1:1 mapping from clobbers to regs?");
969     Register SP = TLI.getStackPointerRegisterToSaveRestore();
970     (void)SP;
971     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
972       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
973       assert(
974           (Regs[I] != SP ||
975            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
976           "If we clobbered the stack pointer, MFI should know about it.");
977     }
978     return;
979   }
980 
981   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
982     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
983     MVT RegisterVT = RegVTs[Value];
984     for (unsigned i = 0; i != NumRegs; ++i) {
985       assert(Reg < Regs.size() && "Mismatch in # registers expected");
986       unsigned TheReg = Regs[Reg++];
987       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
988     }
989   }
990 }
991 
992 SmallVector<std::pair<unsigned, TypeSize>, 4>
993 RegsForValue::getRegsAndSizes() const {
994   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
995   unsigned I = 0;
996   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
997     unsigned RegCount = std::get<0>(CountAndVT);
998     MVT RegisterVT = std::get<1>(CountAndVT);
999     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1000     for (unsigned E = I + RegCount; I != E; ++I)
1001       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1002   }
1003   return OutVec;
1004 }
1005 
1006 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1007                                const TargetLibraryInfo *li) {
1008   AA = aa;
1009   GFI = gfi;
1010   LibInfo = li;
1011   DL = &DAG.getDataLayout();
1012   Context = DAG.getContext();
1013   LPadToCallSiteMap.clear();
1014   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1015 }
1016 
1017 void SelectionDAGBuilder::clear() {
1018   NodeMap.clear();
1019   UnusedArgNodeMap.clear();
1020   PendingLoads.clear();
1021   PendingExports.clear();
1022   PendingConstrainedFP.clear();
1023   PendingConstrainedFPStrict.clear();
1024   CurInst = nullptr;
1025   HasTailCall = false;
1026   SDNodeOrder = LowestSDNodeOrder;
1027   StatepointLowering.clear();
1028 }
1029 
1030 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1031   DanglingDebugInfoMap.clear();
1032 }
1033 
1034 // Update DAG root to include dependencies on Pending chains.
1035 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1036   SDValue Root = DAG.getRoot();
1037 
1038   if (Pending.empty())
1039     return Root;
1040 
1041   // Add current root to PendingChains, unless we already indirectly
1042   // depend on it.
1043   if (Root.getOpcode() != ISD::EntryToken) {
1044     unsigned i = 0, e = Pending.size();
1045     for (; i != e; ++i) {
1046       assert(Pending[i].getNode()->getNumOperands() > 1);
1047       if (Pending[i].getNode()->getOperand(0) == Root)
1048         break;  // Don't add the root if we already indirectly depend on it.
1049     }
1050 
1051     if (i == e)
1052       Pending.push_back(Root);
1053   }
1054 
1055   if (Pending.size() == 1)
1056     Root = Pending[0];
1057   else
1058     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1059 
1060   DAG.setRoot(Root);
1061   Pending.clear();
1062   return Root;
1063 }
1064 
1065 SDValue SelectionDAGBuilder::getMemoryRoot() {
1066   return updateRoot(PendingLoads);
1067 }
1068 
1069 SDValue SelectionDAGBuilder::getRoot() {
1070   // Chain up all pending constrained intrinsics together with all
1071   // pending loads, by simply appending them to PendingLoads and
1072   // then calling getMemoryRoot().
1073   PendingLoads.reserve(PendingLoads.size() +
1074                        PendingConstrainedFP.size() +
1075                        PendingConstrainedFPStrict.size());
1076   PendingLoads.append(PendingConstrainedFP.begin(),
1077                       PendingConstrainedFP.end());
1078   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1079                       PendingConstrainedFPStrict.end());
1080   PendingConstrainedFP.clear();
1081   PendingConstrainedFPStrict.clear();
1082   return getMemoryRoot();
1083 }
1084 
1085 SDValue SelectionDAGBuilder::getControlRoot() {
1086   // We need to emit pending fpexcept.strict constrained intrinsics,
1087   // so append them to the PendingExports list.
1088   PendingExports.append(PendingConstrainedFPStrict.begin(),
1089                         PendingConstrainedFPStrict.end());
1090   PendingConstrainedFPStrict.clear();
1091   return updateRoot(PendingExports);
1092 }
1093 
1094 void SelectionDAGBuilder::visit(const Instruction &I) {
1095   // Set up outgoing PHI node register values before emitting the terminator.
1096   if (I.isTerminator()) {
1097     HandlePHINodesInSuccessorBlocks(I.getParent());
1098   }
1099 
1100   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1101   if (!isa<DbgInfoIntrinsic>(I))
1102     ++SDNodeOrder;
1103 
1104   CurInst = &I;
1105 
1106   visit(I.getOpcode(), I);
1107 
1108   if (!I.isTerminator() && !HasTailCall &&
1109       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1110     CopyToExportRegsIfNeeded(&I);
1111 
1112   CurInst = nullptr;
1113 }
1114 
1115 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1116   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1117 }
1118 
1119 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1120   // Note: this doesn't use InstVisitor, because it has to work with
1121   // ConstantExpr's in addition to instructions.
1122   switch (Opcode) {
1123   default: llvm_unreachable("Unknown instruction type encountered!");
1124     // Build the switch statement using the Instruction.def file.
1125 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1126     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1127 #include "llvm/IR/Instruction.def"
1128   }
1129 }
1130 
1131 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1132                                                DebugLoc DL, unsigned Order) {
1133   // We treat variadic dbg_values differently at this stage.
1134   if (DI->hasArgList()) {
1135     // For variadic dbg_values we will now insert an undef.
1136     // FIXME: We can potentially recover these!
1137     SmallVector<SDDbgOperand, 2> Locs;
1138     for (const Value *V : DI->getValues()) {
1139       auto Undef = UndefValue::get(V->getType());
1140       Locs.push_back(SDDbgOperand::fromConst(Undef));
1141     }
1142     SDDbgValue *SDV = DAG.getDbgValueList(
1143         DI->getVariable(), DI->getExpression(), Locs, {},
1144         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1145     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1146   } else {
1147     // TODO: Dangling debug info will eventually either be resolved or produce
1148     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1149     // between the original dbg.value location and its resolved DBG_VALUE,
1150     // which we should ideally fill with an extra Undef DBG_VALUE.
1151     assert(DI->getNumVariableLocationOps() == 1 &&
1152            "DbgValueInst without an ArgList should have a single location "
1153            "operand.");
1154     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1155   }
1156 }
1157 
1158 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1159                                                 const DIExpression *Expr) {
1160   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1161     const DbgValueInst *DI = DDI.getDI();
1162     DIVariable *DanglingVariable = DI->getVariable();
1163     DIExpression *DanglingExpr = DI->getExpression();
1164     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1165       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1166       return true;
1167     }
1168     return false;
1169   };
1170 
1171   for (auto &DDIMI : DanglingDebugInfoMap) {
1172     DanglingDebugInfoVector &DDIV = DDIMI.second;
1173 
1174     // If debug info is to be dropped, run it through final checks to see
1175     // whether it can be salvaged.
1176     for (auto &DDI : DDIV)
1177       if (isMatchingDbgValue(DDI))
1178         salvageUnresolvedDbgValue(DDI);
1179 
1180     erase_if(DDIV, isMatchingDbgValue);
1181   }
1182 }
1183 
1184 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1185 // generate the debug data structures now that we've seen its definition.
1186 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1187                                                    SDValue Val) {
1188   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1189   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1190     return;
1191 
1192   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1193   for (auto &DDI : DDIV) {
1194     const DbgValueInst *DI = DDI.getDI();
1195     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1196     assert(DI && "Ill-formed DanglingDebugInfo");
1197     DebugLoc dl = DDI.getdl();
1198     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1199     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1200     DILocalVariable *Variable = DI->getVariable();
1201     DIExpression *Expr = DI->getExpression();
1202     assert(Variable->isValidLocationForIntrinsic(dl) &&
1203            "Expected inlined-at fields to agree");
1204     SDDbgValue *SDV;
1205     if (Val.getNode()) {
1206       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1207       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1208       // we couldn't resolve it directly when examining the DbgValue intrinsic
1209       // in the first place we should not be more successful here). Unless we
1210       // have some test case that prove this to be correct we should avoid
1211       // calling EmitFuncArgumentDbgValue here.
1212       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1213         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1214                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1215         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1216         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1217         // inserted after the definition of Val when emitting the instructions
1218         // after ISel. An alternative could be to teach
1219         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1220         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1221                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1222                    << ValSDNodeOrder << "\n");
1223         SDV = getDbgValue(Val, Variable, Expr, dl,
1224                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1225         DAG.AddDbgValue(SDV, false);
1226       } else
1227         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1228                           << "in EmitFuncArgumentDbgValue\n");
1229     } else {
1230       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1231       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1232       auto SDV =
1233           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1234       DAG.AddDbgValue(SDV, false);
1235     }
1236   }
1237   DDIV.clear();
1238 }
1239 
1240 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1241   assert(!DDI.getDI()->hasArgList() &&
1242          "Not implemented for variadic dbg_values");
1243   Value *V = DDI.getDI()->getValue(0);
1244   DILocalVariable *Var = DDI.getDI()->getVariable();
1245   DIExpression *Expr = DDI.getDI()->getExpression();
1246   DebugLoc DL = DDI.getdl();
1247   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1248   unsigned SDOrder = DDI.getSDNodeOrder();
1249   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1250   // that DW_OP_stack_value is desired.
1251   assert(isa<DbgValueInst>(DDI.getDI()));
1252   bool StackValue = true;
1253 
1254   // Can this Value can be encoded without any further work?
1255   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
1256     return;
1257 
1258   // Attempt to salvage back through as many instructions as possible. Bail if
1259   // a non-instruction is seen, such as a constant expression or global
1260   // variable. FIXME: Further work could recover those too.
1261   while (isa<Instruction>(V)) {
1262     Instruction &VAsInst = *cast<Instruction>(V);
1263     // Temporary "0", awaiting real implementation.
1264     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue, 0);
1265 
1266     // If we cannot salvage any further, and haven't yet found a suitable debug
1267     // expression, bail out.
1268     if (!NewExpr)
1269       break;
1270 
1271     // New value and expr now represent this debuginfo.
1272     V = VAsInst.getOperand(0);
1273     Expr = NewExpr;
1274 
1275     // Some kind of simplification occurred: check whether the operand of the
1276     // salvaged debug expression can be encoded in this DAG.
1277     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1278                          /*IsVariadic=*/false)) {
1279       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1280                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1281       return;
1282     }
1283   }
1284 
1285   // This was the final opportunity to salvage this debug information, and it
1286   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1287   // any earlier variable location.
1288   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1289   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1290   DAG.AddDbgValue(SDV, false);
1291 
1292   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1293                     << "\n");
1294   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1295                     << "\n");
1296 }
1297 
1298 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1299                                            DILocalVariable *Var,
1300                                            DIExpression *Expr, DebugLoc dl,
1301                                            DebugLoc InstDL, unsigned Order,
1302                                            bool IsVariadic) {
1303   if (Values.empty())
1304     return true;
1305   SmallVector<SDDbgOperand> LocationOps;
1306   SmallVector<SDNode *> Dependencies;
1307   for (const Value *V : Values) {
1308     // Constant value.
1309     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1310         isa<ConstantPointerNull>(V)) {
1311       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1312       continue;
1313     }
1314 
1315     // If the Value is a frame index, we can create a FrameIndex debug value
1316     // without relying on the DAG at all.
1317     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1318       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1319       if (SI != FuncInfo.StaticAllocaMap.end()) {
1320         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1321         continue;
1322       }
1323     }
1324 
1325     // Do not use getValue() in here; we don't want to generate code at
1326     // this point if it hasn't been done yet.
1327     SDValue N = NodeMap[V];
1328     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1329       N = UnusedArgNodeMap[V];
1330     if (N.getNode()) {
1331       // Only emit func arg dbg value for non-variadic dbg.values for now.
1332       if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1333         return true;
1334       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1335         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1336         // describe stack slot locations.
1337         //
1338         // Consider "int x = 0; int *px = &x;". There are two kinds of
1339         // interesting debug values here after optimization:
1340         //
1341         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1342         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1343         //
1344         // Both describe the direct values of their associated variables.
1345         Dependencies.push_back(N.getNode());
1346         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1347         continue;
1348       }
1349       LocationOps.emplace_back(
1350           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1351       continue;
1352     }
1353 
1354     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1355     // Special rules apply for the first dbg.values of parameter variables in a
1356     // function. Identify them by the fact they reference Argument Values, that
1357     // they're parameters, and they are parameters of the current function. We
1358     // need to let them dangle until they get an SDNode.
1359     bool IsParamOfFunc =
1360         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1361     if (IsParamOfFunc)
1362       return false;
1363 
1364     // The value is not used in this block yet (or it would have an SDNode).
1365     // We still want the value to appear for the user if possible -- if it has
1366     // an associated VReg, we can refer to that instead.
1367     auto VMI = FuncInfo.ValueMap.find(V);
1368     if (VMI != FuncInfo.ValueMap.end()) {
1369       unsigned Reg = VMI->second;
1370       // If this is a PHI node, it may be split up into several MI PHI nodes
1371       // (in FunctionLoweringInfo::set).
1372       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1373                        V->getType(), None);
1374       if (RFV.occupiesMultipleRegs()) {
1375         // FIXME: We could potentially support variadic dbg_values here.
1376         if (IsVariadic)
1377           return false;
1378         unsigned Offset = 0;
1379         unsigned BitsToDescribe = 0;
1380         if (auto VarSize = Var->getSizeInBits())
1381           BitsToDescribe = *VarSize;
1382         if (auto Fragment = Expr->getFragmentInfo())
1383           BitsToDescribe = Fragment->SizeInBits;
1384         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1385           // Bail out if all bits are described already.
1386           if (Offset >= BitsToDescribe)
1387             break;
1388           // TODO: handle scalable vectors.
1389           unsigned RegisterSize = RegAndSize.second;
1390           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1391                                       ? BitsToDescribe - Offset
1392                                       : RegisterSize;
1393           auto FragmentExpr = DIExpression::createFragmentExpression(
1394               Expr, Offset, FragmentSize);
1395           if (!FragmentExpr)
1396             continue;
1397           SDDbgValue *SDV = DAG.getVRegDbgValue(
1398               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1399           DAG.AddDbgValue(SDV, false);
1400           Offset += RegisterSize;
1401         }
1402         return true;
1403       }
1404       // We can use simple vreg locations for variadic dbg_values as well.
1405       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1406       continue;
1407     }
1408     // We failed to create a SDDbgOperand for V.
1409     return false;
1410   }
1411 
1412   // We have created a SDDbgOperand for each Value in Values.
1413   // Should use Order instead of SDNodeOrder?
1414   assert(!LocationOps.empty());
1415   SDDbgValue *SDV =
1416       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1417                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1418   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1419   return true;
1420 }
1421 
1422 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1423   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1424   for (auto &Pair : DanglingDebugInfoMap)
1425     for (auto &DDI : Pair.second)
1426       salvageUnresolvedDbgValue(DDI);
1427   clearDanglingDebugInfo();
1428 }
1429 
1430 /// getCopyFromRegs - If there was virtual register allocated for the value V
1431 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1432 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1433   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1434   SDValue Result;
1435 
1436   if (It != FuncInfo.ValueMap.end()) {
1437     Register InReg = It->second;
1438 
1439     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1440                      DAG.getDataLayout(), InReg, Ty,
1441                      None); // This is not an ABI copy.
1442     SDValue Chain = DAG.getEntryNode();
1443     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1444                                  V);
1445     resolveDanglingDebugInfo(V, Result);
1446   }
1447 
1448   return Result;
1449 }
1450 
1451 /// getValue - Return an SDValue for the given Value.
1452 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1453   // If we already have an SDValue for this value, use it. It's important
1454   // to do this first, so that we don't create a CopyFromReg if we already
1455   // have a regular SDValue.
1456   SDValue &N = NodeMap[V];
1457   if (N.getNode()) return N;
1458 
1459   // If there's a virtual register allocated and initialized for this
1460   // value, use it.
1461   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1462     return copyFromReg;
1463 
1464   // Otherwise create a new SDValue and remember it.
1465   SDValue Val = getValueImpl(V);
1466   NodeMap[V] = Val;
1467   resolveDanglingDebugInfo(V, Val);
1468   return Val;
1469 }
1470 
1471 /// getNonRegisterValue - Return an SDValue for the given Value, but
1472 /// don't look in FuncInfo.ValueMap for a virtual register.
1473 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1474   // If we already have an SDValue for this value, use it.
1475   SDValue &N = NodeMap[V];
1476   if (N.getNode()) {
1477     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1478       // Remove the debug location from the node as the node is about to be used
1479       // in a location which may differ from the original debug location.  This
1480       // is relevant to Constant and ConstantFP nodes because they can appear
1481       // as constant expressions inside PHI nodes.
1482       N->setDebugLoc(DebugLoc());
1483     }
1484     return N;
1485   }
1486 
1487   // Otherwise create a new SDValue and remember it.
1488   SDValue Val = getValueImpl(V);
1489   NodeMap[V] = Val;
1490   resolveDanglingDebugInfo(V, Val);
1491   return Val;
1492 }
1493 
1494 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1495 /// Create an SDValue for the given value.
1496 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1497   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1498 
1499   if (const Constant *C = dyn_cast<Constant>(V)) {
1500     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1501 
1502     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1503       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1504 
1505     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1506       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1507 
1508     if (isa<ConstantPointerNull>(C)) {
1509       unsigned AS = V->getType()->getPointerAddressSpace();
1510       return DAG.getConstant(0, getCurSDLoc(),
1511                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1512     }
1513 
1514     if (match(C, m_VScale(DAG.getDataLayout())))
1515       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1516 
1517     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1518       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1519 
1520     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1521       return DAG.getUNDEF(VT);
1522 
1523     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1524       visit(CE->getOpcode(), *CE);
1525       SDValue N1 = NodeMap[V];
1526       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1527       return N1;
1528     }
1529 
1530     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1531       SmallVector<SDValue, 4> Constants;
1532       for (const Use &U : C->operands()) {
1533         SDNode *Val = getValue(U).getNode();
1534         // If the operand is an empty aggregate, there are no values.
1535         if (!Val) continue;
1536         // Add each leaf value from the operand to the Constants list
1537         // to form a flattened list of all the values.
1538         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1539           Constants.push_back(SDValue(Val, i));
1540       }
1541 
1542       return DAG.getMergeValues(Constants, getCurSDLoc());
1543     }
1544 
1545     if (const ConstantDataSequential *CDS =
1546           dyn_cast<ConstantDataSequential>(C)) {
1547       SmallVector<SDValue, 4> Ops;
1548       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1549         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1550         // Add each leaf value from the operand to the Constants list
1551         // to form a flattened list of all the values.
1552         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1553           Ops.push_back(SDValue(Val, i));
1554       }
1555 
1556       if (isa<ArrayType>(CDS->getType()))
1557         return DAG.getMergeValues(Ops, getCurSDLoc());
1558       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1559     }
1560 
1561     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1562       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1563              "Unknown struct or array constant!");
1564 
1565       SmallVector<EVT, 4> ValueVTs;
1566       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1567       unsigned NumElts = ValueVTs.size();
1568       if (NumElts == 0)
1569         return SDValue(); // empty struct
1570       SmallVector<SDValue, 4> Constants(NumElts);
1571       for (unsigned i = 0; i != NumElts; ++i) {
1572         EVT EltVT = ValueVTs[i];
1573         if (isa<UndefValue>(C))
1574           Constants[i] = DAG.getUNDEF(EltVT);
1575         else if (EltVT.isFloatingPoint())
1576           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1577         else
1578           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1579       }
1580 
1581       return DAG.getMergeValues(Constants, getCurSDLoc());
1582     }
1583 
1584     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1585       return DAG.getBlockAddress(BA, VT);
1586 
1587     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1588       return getValue(Equiv->getGlobalValue());
1589 
1590     VectorType *VecTy = cast<VectorType>(V->getType());
1591 
1592     // Now that we know the number and type of the elements, get that number of
1593     // elements into the Ops array based on what kind of constant it is.
1594     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1595       SmallVector<SDValue, 16> Ops;
1596       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1597       for (unsigned i = 0; i != NumElements; ++i)
1598         Ops.push_back(getValue(CV->getOperand(i)));
1599 
1600       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1601     } else if (isa<ConstantAggregateZero>(C)) {
1602       EVT EltVT =
1603           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1604 
1605       SDValue Op;
1606       if (EltVT.isFloatingPoint())
1607         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1608       else
1609         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1610 
1611       if (isa<ScalableVectorType>(VecTy))
1612         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1613       else {
1614         SmallVector<SDValue, 16> Ops;
1615         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1616         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1617       }
1618     }
1619     llvm_unreachable("Unknown vector constant");
1620   }
1621 
1622   // If this is a static alloca, generate it as the frameindex instead of
1623   // computation.
1624   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1625     DenseMap<const AllocaInst*, int>::iterator SI =
1626       FuncInfo.StaticAllocaMap.find(AI);
1627     if (SI != FuncInfo.StaticAllocaMap.end())
1628       return DAG.getFrameIndex(SI->second,
1629                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1630   }
1631 
1632   // If this is an instruction which fast-isel has deferred, select it now.
1633   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1634     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1635 
1636     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1637                      Inst->getType(), None);
1638     SDValue Chain = DAG.getEntryNode();
1639     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1640   }
1641 
1642   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1643     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1644   }
1645   llvm_unreachable("Can't get register for value!");
1646 }
1647 
1648 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1649   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1650   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1651   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1652   bool IsSEH = isAsynchronousEHPersonality(Pers);
1653   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1654   if (!IsSEH)
1655     CatchPadMBB->setIsEHScopeEntry();
1656   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1657   if (IsMSVCCXX || IsCoreCLR)
1658     CatchPadMBB->setIsEHFuncletEntry();
1659 }
1660 
1661 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1662   // Update machine-CFG edge.
1663   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1664   FuncInfo.MBB->addSuccessor(TargetMBB);
1665   TargetMBB->setIsEHCatchretTarget(true);
1666   DAG.getMachineFunction().setHasEHCatchret(true);
1667 
1668   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1669   bool IsSEH = isAsynchronousEHPersonality(Pers);
1670   if (IsSEH) {
1671     // If this is not a fall-through branch or optimizations are switched off,
1672     // emit the branch.
1673     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1674         TM.getOptLevel() == CodeGenOpt::None)
1675       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1676                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1677     return;
1678   }
1679 
1680   // Figure out the funclet membership for the catchret's successor.
1681   // This will be used by the FuncletLayout pass to determine how to order the
1682   // BB's.
1683   // A 'catchret' returns to the outer scope's color.
1684   Value *ParentPad = I.getCatchSwitchParentPad();
1685   const BasicBlock *SuccessorColor;
1686   if (isa<ConstantTokenNone>(ParentPad))
1687     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1688   else
1689     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1690   assert(SuccessorColor && "No parent funclet for catchret!");
1691   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1692   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1693 
1694   // Create the terminator node.
1695   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1696                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1697                             DAG.getBasicBlock(SuccessorColorMBB));
1698   DAG.setRoot(Ret);
1699 }
1700 
1701 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1702   // Don't emit any special code for the cleanuppad instruction. It just marks
1703   // the start of an EH scope/funclet.
1704   FuncInfo.MBB->setIsEHScopeEntry();
1705   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1706   if (Pers != EHPersonality::Wasm_CXX) {
1707     FuncInfo.MBB->setIsEHFuncletEntry();
1708     FuncInfo.MBB->setIsCleanupFuncletEntry();
1709   }
1710 }
1711 
1712 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1713 // not match, it is OK to add only the first unwind destination catchpad to the
1714 // successors, because there will be at least one invoke instruction within the
1715 // catch scope that points to the next unwind destination, if one exists, so
1716 // CFGSort cannot mess up with BB sorting order.
1717 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1718 // call within them, and catchpads only consisting of 'catch (...)' have a
1719 // '__cxa_end_catch' call within them, both of which generate invokes in case
1720 // the next unwind destination exists, i.e., the next unwind destination is not
1721 // the caller.)
1722 //
1723 // Having at most one EH pad successor is also simpler and helps later
1724 // transformations.
1725 //
1726 // For example,
1727 // current:
1728 //   invoke void @foo to ... unwind label %catch.dispatch
1729 // catch.dispatch:
1730 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1731 // catch.start:
1732 //   ...
1733 //   ... in this BB or some other child BB dominated by this BB there will be an
1734 //   invoke that points to 'next' BB as an unwind destination
1735 //
1736 // next: ; We don't need to add this to 'current' BB's successor
1737 //   ...
1738 static void findWasmUnwindDestinations(
1739     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1740     BranchProbability Prob,
1741     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1742         &UnwindDests) {
1743   while (EHPadBB) {
1744     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1745     if (isa<CleanupPadInst>(Pad)) {
1746       // Stop on cleanup pads.
1747       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1748       UnwindDests.back().first->setIsEHScopeEntry();
1749       break;
1750     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1751       // Add the catchpad handlers to the possible destinations. We don't
1752       // continue to the unwind destination of the catchswitch for wasm.
1753       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1754         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1755         UnwindDests.back().first->setIsEHScopeEntry();
1756       }
1757       break;
1758     } else {
1759       continue;
1760     }
1761   }
1762 }
1763 
1764 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1765 /// many places it could ultimately go. In the IR, we have a single unwind
1766 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1767 /// This function skips over imaginary basic blocks that hold catchswitch
1768 /// instructions, and finds all the "real" machine
1769 /// basic block destinations. As those destinations may not be successors of
1770 /// EHPadBB, here we also calculate the edge probability to those destinations.
1771 /// The passed-in Prob is the edge probability to EHPadBB.
1772 static void findUnwindDestinations(
1773     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1774     BranchProbability Prob,
1775     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1776         &UnwindDests) {
1777   EHPersonality Personality =
1778     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1779   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1780   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1781   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1782   bool IsSEH = isAsynchronousEHPersonality(Personality);
1783 
1784   if (IsWasmCXX) {
1785     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1786     assert(UnwindDests.size() <= 1 &&
1787            "There should be at most one unwind destination for wasm");
1788     return;
1789   }
1790 
1791   while (EHPadBB) {
1792     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1793     BasicBlock *NewEHPadBB = nullptr;
1794     if (isa<LandingPadInst>(Pad)) {
1795       // Stop on landingpads. They are not funclets.
1796       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1797       break;
1798     } else if (isa<CleanupPadInst>(Pad)) {
1799       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1800       // personalities.
1801       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1802       UnwindDests.back().first->setIsEHScopeEntry();
1803       UnwindDests.back().first->setIsEHFuncletEntry();
1804       break;
1805     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1806       // Add the catchpad handlers to the possible destinations.
1807       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1808         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1809         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1810         if (IsMSVCCXX || IsCoreCLR)
1811           UnwindDests.back().first->setIsEHFuncletEntry();
1812         if (!IsSEH)
1813           UnwindDests.back().first->setIsEHScopeEntry();
1814       }
1815       NewEHPadBB = CatchSwitch->getUnwindDest();
1816     } else {
1817       continue;
1818     }
1819 
1820     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1821     if (BPI && NewEHPadBB)
1822       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1823     EHPadBB = NewEHPadBB;
1824   }
1825 }
1826 
1827 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1828   // Update successor info.
1829   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1830   auto UnwindDest = I.getUnwindDest();
1831   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1832   BranchProbability UnwindDestProb =
1833       (BPI && UnwindDest)
1834           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1835           : BranchProbability::getZero();
1836   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1837   for (auto &UnwindDest : UnwindDests) {
1838     UnwindDest.first->setIsEHPad();
1839     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1840   }
1841   FuncInfo.MBB->normalizeSuccProbs();
1842 
1843   // Create the terminator node.
1844   SDValue Ret =
1845       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1846   DAG.setRoot(Ret);
1847 }
1848 
1849 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1850   report_fatal_error("visitCatchSwitch not yet implemented!");
1851 }
1852 
1853 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1854   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1855   auto &DL = DAG.getDataLayout();
1856   SDValue Chain = getControlRoot();
1857   SmallVector<ISD::OutputArg, 8> Outs;
1858   SmallVector<SDValue, 8> OutVals;
1859 
1860   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1861   // lower
1862   //
1863   //   %val = call <ty> @llvm.experimental.deoptimize()
1864   //   ret <ty> %val
1865   //
1866   // differently.
1867   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1868     LowerDeoptimizingReturn();
1869     return;
1870   }
1871 
1872   if (!FuncInfo.CanLowerReturn) {
1873     unsigned DemoteReg = FuncInfo.DemoteRegister;
1874     const Function *F = I.getParent()->getParent();
1875 
1876     // Emit a store of the return value through the virtual register.
1877     // Leave Outs empty so that LowerReturn won't try to load return
1878     // registers the usual way.
1879     SmallVector<EVT, 1> PtrValueVTs;
1880     ComputeValueVTs(TLI, DL,
1881                     F->getReturnType()->getPointerTo(
1882                         DAG.getDataLayout().getAllocaAddrSpace()),
1883                     PtrValueVTs);
1884 
1885     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1886                                         DemoteReg, PtrValueVTs[0]);
1887     SDValue RetOp = getValue(I.getOperand(0));
1888 
1889     SmallVector<EVT, 4> ValueVTs, MemVTs;
1890     SmallVector<uint64_t, 4> Offsets;
1891     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1892                     &Offsets);
1893     unsigned NumValues = ValueVTs.size();
1894 
1895     SmallVector<SDValue, 4> Chains(NumValues);
1896     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1897     for (unsigned i = 0; i != NumValues; ++i) {
1898       // An aggregate return value cannot wrap around the address space, so
1899       // offsets to its parts don't wrap either.
1900       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1901                                            TypeSize::Fixed(Offsets[i]));
1902 
1903       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1904       if (MemVTs[i] != ValueVTs[i])
1905         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1906       Chains[i] = DAG.getStore(
1907           Chain, getCurSDLoc(), Val,
1908           // FIXME: better loc info would be nice.
1909           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1910           commonAlignment(BaseAlign, Offsets[i]));
1911     }
1912 
1913     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1914                         MVT::Other, Chains);
1915   } else if (I.getNumOperands() != 0) {
1916     SmallVector<EVT, 4> ValueVTs;
1917     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1918     unsigned NumValues = ValueVTs.size();
1919     if (NumValues) {
1920       SDValue RetOp = getValue(I.getOperand(0));
1921 
1922       const Function *F = I.getParent()->getParent();
1923 
1924       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1925           I.getOperand(0)->getType(), F->getCallingConv(),
1926           /*IsVarArg*/ false);
1927 
1928       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1929       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1930                                           Attribute::SExt))
1931         ExtendKind = ISD::SIGN_EXTEND;
1932       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1933                                                Attribute::ZExt))
1934         ExtendKind = ISD::ZERO_EXTEND;
1935 
1936       LLVMContext &Context = F->getContext();
1937       bool RetInReg = F->getAttributes().hasAttribute(
1938           AttributeList::ReturnIndex, Attribute::InReg);
1939 
1940       for (unsigned j = 0; j != NumValues; ++j) {
1941         EVT VT = ValueVTs[j];
1942 
1943         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1944           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1945 
1946         CallingConv::ID CC = F->getCallingConv();
1947 
1948         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1949         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1950         SmallVector<SDValue, 4> Parts(NumParts);
1951         getCopyToParts(DAG, getCurSDLoc(),
1952                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1953                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1954 
1955         // 'inreg' on function refers to return value
1956         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1957         if (RetInReg)
1958           Flags.setInReg();
1959 
1960         if (I.getOperand(0)->getType()->isPointerTy()) {
1961           Flags.setPointer();
1962           Flags.setPointerAddrSpace(
1963               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1964         }
1965 
1966         if (NeedsRegBlock) {
1967           Flags.setInConsecutiveRegs();
1968           if (j == NumValues - 1)
1969             Flags.setInConsecutiveRegsLast();
1970         }
1971 
1972         // Propagate extension type if any
1973         if (ExtendKind == ISD::SIGN_EXTEND)
1974           Flags.setSExt();
1975         else if (ExtendKind == ISD::ZERO_EXTEND)
1976           Flags.setZExt();
1977 
1978         for (unsigned i = 0; i < NumParts; ++i) {
1979           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1980                                         VT, /*isfixed=*/true, 0, 0));
1981           OutVals.push_back(Parts[i]);
1982         }
1983       }
1984     }
1985   }
1986 
1987   // Push in swifterror virtual register as the last element of Outs. This makes
1988   // sure swifterror virtual register will be returned in the swifterror
1989   // physical register.
1990   const Function *F = I.getParent()->getParent();
1991   if (TLI.supportSwiftError() &&
1992       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1993     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1994     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1995     Flags.setSwiftError();
1996     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1997                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1998                                   true /*isfixed*/, 1 /*origidx*/,
1999                                   0 /*partOffs*/));
2000     // Create SDNode for the swifterror virtual register.
2001     OutVals.push_back(
2002         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2003                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2004                         EVT(TLI.getPointerTy(DL))));
2005   }
2006 
2007   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2008   CallingConv::ID CallConv =
2009     DAG.getMachineFunction().getFunction().getCallingConv();
2010   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2011       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2012 
2013   // Verify that the target's LowerReturn behaved as expected.
2014   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2015          "LowerReturn didn't return a valid chain!");
2016 
2017   // Update the DAG with the new chain value resulting from return lowering.
2018   DAG.setRoot(Chain);
2019 }
2020 
2021 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2022 /// created for it, emit nodes to copy the value into the virtual
2023 /// registers.
2024 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2025   // Skip empty types
2026   if (V->getType()->isEmptyTy())
2027     return;
2028 
2029   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2030   if (VMI != FuncInfo.ValueMap.end()) {
2031     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2032     CopyValueToVirtualRegister(V, VMI->second);
2033   }
2034 }
2035 
2036 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2037 /// the current basic block, add it to ValueMap now so that we'll get a
2038 /// CopyTo/FromReg.
2039 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2040   // No need to export constants.
2041   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2042 
2043   // Already exported?
2044   if (FuncInfo.isExportedInst(V)) return;
2045 
2046   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2047   CopyValueToVirtualRegister(V, Reg);
2048 }
2049 
2050 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2051                                                      const BasicBlock *FromBB) {
2052   // The operands of the setcc have to be in this block.  We don't know
2053   // how to export them from some other block.
2054   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2055     // Can export from current BB.
2056     if (VI->getParent() == FromBB)
2057       return true;
2058 
2059     // Is already exported, noop.
2060     return FuncInfo.isExportedInst(V);
2061   }
2062 
2063   // If this is an argument, we can export it if the BB is the entry block or
2064   // if it is already exported.
2065   if (isa<Argument>(V)) {
2066     if (FromBB == &FromBB->getParent()->getEntryBlock())
2067       return true;
2068 
2069     // Otherwise, can only export this if it is already exported.
2070     return FuncInfo.isExportedInst(V);
2071   }
2072 
2073   // Otherwise, constants can always be exported.
2074   return true;
2075 }
2076 
2077 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2078 BranchProbability
2079 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2080                                         const MachineBasicBlock *Dst) const {
2081   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2082   const BasicBlock *SrcBB = Src->getBasicBlock();
2083   const BasicBlock *DstBB = Dst->getBasicBlock();
2084   if (!BPI) {
2085     // If BPI is not available, set the default probability as 1 / N, where N is
2086     // the number of successors.
2087     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2088     return BranchProbability(1, SuccSize);
2089   }
2090   return BPI->getEdgeProbability(SrcBB, DstBB);
2091 }
2092 
2093 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2094                                                MachineBasicBlock *Dst,
2095                                                BranchProbability Prob) {
2096   if (!FuncInfo.BPI)
2097     Src->addSuccessorWithoutProb(Dst);
2098   else {
2099     if (Prob.isUnknown())
2100       Prob = getEdgeProbability(Src, Dst);
2101     Src->addSuccessor(Dst, Prob);
2102   }
2103 }
2104 
2105 static bool InBlock(const Value *V, const BasicBlock *BB) {
2106   if (const Instruction *I = dyn_cast<Instruction>(V))
2107     return I->getParent() == BB;
2108   return true;
2109 }
2110 
2111 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2112 /// This function emits a branch and is used at the leaves of an OR or an
2113 /// AND operator tree.
2114 void
2115 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2116                                                   MachineBasicBlock *TBB,
2117                                                   MachineBasicBlock *FBB,
2118                                                   MachineBasicBlock *CurBB,
2119                                                   MachineBasicBlock *SwitchBB,
2120                                                   BranchProbability TProb,
2121                                                   BranchProbability FProb,
2122                                                   bool InvertCond) {
2123   const BasicBlock *BB = CurBB->getBasicBlock();
2124 
2125   // If the leaf of the tree is a comparison, merge the condition into
2126   // the caseblock.
2127   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2128     // The operands of the cmp have to be in this block.  We don't know
2129     // how to export them from some other block.  If this is the first block
2130     // of the sequence, no exporting is needed.
2131     if (CurBB == SwitchBB ||
2132         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2133          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2134       ISD::CondCode Condition;
2135       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2136         ICmpInst::Predicate Pred =
2137             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2138         Condition = getICmpCondCode(Pred);
2139       } else {
2140         const FCmpInst *FC = cast<FCmpInst>(Cond);
2141         FCmpInst::Predicate Pred =
2142             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2143         Condition = getFCmpCondCode(Pred);
2144         if (TM.Options.NoNaNsFPMath)
2145           Condition = getFCmpCodeWithoutNaN(Condition);
2146       }
2147 
2148       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2149                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2150       SL->SwitchCases.push_back(CB);
2151       return;
2152     }
2153   }
2154 
2155   // Create a CaseBlock record representing this branch.
2156   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2157   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2158                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2159   SL->SwitchCases.push_back(CB);
2160 }
2161 
2162 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2163                                                MachineBasicBlock *TBB,
2164                                                MachineBasicBlock *FBB,
2165                                                MachineBasicBlock *CurBB,
2166                                                MachineBasicBlock *SwitchBB,
2167                                                Instruction::BinaryOps Opc,
2168                                                BranchProbability TProb,
2169                                                BranchProbability FProb,
2170                                                bool InvertCond) {
2171   // Skip over not part of the tree and remember to invert op and operands at
2172   // next level.
2173   Value *NotCond;
2174   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2175       InBlock(NotCond, CurBB->getBasicBlock())) {
2176     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2177                          !InvertCond);
2178     return;
2179   }
2180 
2181   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2182   const Value *BOpOp0, *BOpOp1;
2183   // Compute the effective opcode for Cond, taking into account whether it needs
2184   // to be inverted, e.g.
2185   //   and (not (or A, B)), C
2186   // gets lowered as
2187   //   and (and (not A, not B), C)
2188   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2189   if (BOp) {
2190     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2191                ? Instruction::And
2192                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2193                       ? Instruction::Or
2194                       : (Instruction::BinaryOps)0);
2195     if (InvertCond) {
2196       if (BOpc == Instruction::And)
2197         BOpc = Instruction::Or;
2198       else if (BOpc == Instruction::Or)
2199         BOpc = Instruction::And;
2200     }
2201   }
2202 
2203   // If this node is not part of the or/and tree, emit it as a branch.
2204   // Note that all nodes in the tree should have same opcode.
2205   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2206   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2207       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2208       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2209     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2210                                  TProb, FProb, InvertCond);
2211     return;
2212   }
2213 
2214   //  Create TmpBB after CurBB.
2215   MachineFunction::iterator BBI(CurBB);
2216   MachineFunction &MF = DAG.getMachineFunction();
2217   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2218   CurBB->getParent()->insert(++BBI, TmpBB);
2219 
2220   if (Opc == Instruction::Or) {
2221     // Codegen X | Y as:
2222     // BB1:
2223     //   jmp_if_X TBB
2224     //   jmp TmpBB
2225     // TmpBB:
2226     //   jmp_if_Y TBB
2227     //   jmp FBB
2228     //
2229 
2230     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2231     // The requirement is that
2232     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2233     //     = TrueProb for original BB.
2234     // Assuming the original probabilities are A and B, one choice is to set
2235     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2236     // A/(1+B) and 2B/(1+B). This choice assumes that
2237     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2238     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2239     // TmpBB, but the math is more complicated.
2240 
2241     auto NewTrueProb = TProb / 2;
2242     auto NewFalseProb = TProb / 2 + FProb;
2243     // Emit the LHS condition.
2244     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2245                          NewFalseProb, InvertCond);
2246 
2247     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2248     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2249     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2250     // Emit the RHS condition into TmpBB.
2251     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2252                          Probs[1], InvertCond);
2253   } else {
2254     assert(Opc == Instruction::And && "Unknown merge op!");
2255     // Codegen X & Y as:
2256     // BB1:
2257     //   jmp_if_X TmpBB
2258     //   jmp FBB
2259     // TmpBB:
2260     //   jmp_if_Y TBB
2261     //   jmp FBB
2262     //
2263     //  This requires creation of TmpBB after CurBB.
2264 
2265     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2266     // The requirement is that
2267     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2268     //     = FalseProb for original BB.
2269     // Assuming the original probabilities are A and B, one choice is to set
2270     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2271     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2272     // TrueProb for BB1 * FalseProb for TmpBB.
2273 
2274     auto NewTrueProb = TProb + FProb / 2;
2275     auto NewFalseProb = FProb / 2;
2276     // Emit the LHS condition.
2277     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2278                          NewFalseProb, InvertCond);
2279 
2280     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2281     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2282     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2283     // Emit the RHS condition into TmpBB.
2284     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2285                          Probs[1], InvertCond);
2286   }
2287 }
2288 
2289 /// If the set of cases should be emitted as a series of branches, return true.
2290 /// If we should emit this as a bunch of and/or'd together conditions, return
2291 /// false.
2292 bool
2293 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2294   if (Cases.size() != 2) return true;
2295 
2296   // If this is two comparisons of the same values or'd or and'd together, they
2297   // will get folded into a single comparison, so don't emit two blocks.
2298   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2299        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2300       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2301        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2302     return false;
2303   }
2304 
2305   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2306   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2307   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2308       Cases[0].CC == Cases[1].CC &&
2309       isa<Constant>(Cases[0].CmpRHS) &&
2310       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2311     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2312       return false;
2313     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2314       return false;
2315   }
2316 
2317   return true;
2318 }
2319 
2320 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2321   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2322 
2323   // Update machine-CFG edges.
2324   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2325 
2326   if (I.isUnconditional()) {
2327     // Update machine-CFG edges.
2328     BrMBB->addSuccessor(Succ0MBB);
2329 
2330     // If this is not a fall-through branch or optimizations are switched off,
2331     // emit the branch.
2332     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2333       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2334                               MVT::Other, getControlRoot(),
2335                               DAG.getBasicBlock(Succ0MBB)));
2336 
2337     return;
2338   }
2339 
2340   // If this condition is one of the special cases we handle, do special stuff
2341   // now.
2342   const Value *CondVal = I.getCondition();
2343   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2344 
2345   // If this is a series of conditions that are or'd or and'd together, emit
2346   // this as a sequence of branches instead of setcc's with and/or operations.
2347   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2348   // unpredictable branches, and vector extracts because those jumps are likely
2349   // expensive for any target), this should improve performance.
2350   // For example, instead of something like:
2351   //     cmp A, B
2352   //     C = seteq
2353   //     cmp D, E
2354   //     F = setle
2355   //     or C, F
2356   //     jnz foo
2357   // Emit:
2358   //     cmp A, B
2359   //     je foo
2360   //     cmp D, E
2361   //     jle foo
2362   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2363   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2364       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2365     Value *Vec;
2366     const Value *BOp0, *BOp1;
2367     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2368     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2369       Opcode = Instruction::And;
2370     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2371       Opcode = Instruction::Or;
2372 
2373     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2374                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2375       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2376                            getEdgeProbability(BrMBB, Succ0MBB),
2377                            getEdgeProbability(BrMBB, Succ1MBB),
2378                            /*InvertCond=*/false);
2379       // If the compares in later blocks need to use values not currently
2380       // exported from this block, export them now.  This block should always
2381       // be the first entry.
2382       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2383 
2384       // Allow some cases to be rejected.
2385       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2386         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2387           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2388           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2389         }
2390 
2391         // Emit the branch for this block.
2392         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2393         SL->SwitchCases.erase(SL->SwitchCases.begin());
2394         return;
2395       }
2396 
2397       // Okay, we decided not to do this, remove any inserted MBB's and clear
2398       // SwitchCases.
2399       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2400         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2401 
2402       SL->SwitchCases.clear();
2403     }
2404   }
2405 
2406   // Create a CaseBlock record representing this branch.
2407   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2408                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2409 
2410   // Use visitSwitchCase to actually insert the fast branch sequence for this
2411   // cond branch.
2412   visitSwitchCase(CB, BrMBB);
2413 }
2414 
2415 /// visitSwitchCase - Emits the necessary code to represent a single node in
2416 /// the binary search tree resulting from lowering a switch instruction.
2417 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2418                                           MachineBasicBlock *SwitchBB) {
2419   SDValue Cond;
2420   SDValue CondLHS = getValue(CB.CmpLHS);
2421   SDLoc dl = CB.DL;
2422 
2423   if (CB.CC == ISD::SETTRUE) {
2424     // Branch or fall through to TrueBB.
2425     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2426     SwitchBB->normalizeSuccProbs();
2427     if (CB.TrueBB != NextBlock(SwitchBB)) {
2428       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2429                               DAG.getBasicBlock(CB.TrueBB)));
2430     }
2431     return;
2432   }
2433 
2434   auto &TLI = DAG.getTargetLoweringInfo();
2435   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2436 
2437   // Build the setcc now.
2438   if (!CB.CmpMHS) {
2439     // Fold "(X == true)" to X and "(X == false)" to !X to
2440     // handle common cases produced by branch lowering.
2441     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2442         CB.CC == ISD::SETEQ)
2443       Cond = CondLHS;
2444     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2445              CB.CC == ISD::SETEQ) {
2446       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2447       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2448     } else {
2449       SDValue CondRHS = getValue(CB.CmpRHS);
2450 
2451       // If a pointer's DAG type is larger than its memory type then the DAG
2452       // values are zero-extended. This breaks signed comparisons so truncate
2453       // back to the underlying type before doing the compare.
2454       if (CondLHS.getValueType() != MemVT) {
2455         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2456         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2457       }
2458       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2459     }
2460   } else {
2461     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2462 
2463     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2464     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2465 
2466     SDValue CmpOp = getValue(CB.CmpMHS);
2467     EVT VT = CmpOp.getValueType();
2468 
2469     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2470       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2471                           ISD::SETLE);
2472     } else {
2473       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2474                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2475       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2476                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2477     }
2478   }
2479 
2480   // Update successor info
2481   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2482   // TrueBB and FalseBB are always different unless the incoming IR is
2483   // degenerate. This only happens when running llc on weird IR.
2484   if (CB.TrueBB != CB.FalseBB)
2485     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2486   SwitchBB->normalizeSuccProbs();
2487 
2488   // If the lhs block is the next block, invert the condition so that we can
2489   // fall through to the lhs instead of the rhs block.
2490   if (CB.TrueBB == NextBlock(SwitchBB)) {
2491     std::swap(CB.TrueBB, CB.FalseBB);
2492     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2493     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2494   }
2495 
2496   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2497                                MVT::Other, getControlRoot(), Cond,
2498                                DAG.getBasicBlock(CB.TrueBB));
2499 
2500   // Insert the false branch. Do this even if it's a fall through branch,
2501   // this makes it easier to do DAG optimizations which require inverting
2502   // the branch condition.
2503   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2504                        DAG.getBasicBlock(CB.FalseBB));
2505 
2506   DAG.setRoot(BrCond);
2507 }
2508 
2509 /// visitJumpTable - Emit JumpTable node in the current MBB
2510 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2511   // Emit the code for the jump table
2512   assert(JT.Reg != -1U && "Should lower JT Header first!");
2513   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2514   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2515                                      JT.Reg, PTy);
2516   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2517   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2518                                     MVT::Other, Index.getValue(1),
2519                                     Table, Index);
2520   DAG.setRoot(BrJumpTable);
2521 }
2522 
2523 /// visitJumpTableHeader - This function emits necessary code to produce index
2524 /// in the JumpTable from switch case.
2525 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2526                                                JumpTableHeader &JTH,
2527                                                MachineBasicBlock *SwitchBB) {
2528   SDLoc dl = getCurSDLoc();
2529 
2530   // Subtract the lowest switch case value from the value being switched on.
2531   SDValue SwitchOp = getValue(JTH.SValue);
2532   EVT VT = SwitchOp.getValueType();
2533   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2534                             DAG.getConstant(JTH.First, dl, VT));
2535 
2536   // The SDNode we just created, which holds the value being switched on minus
2537   // the smallest case value, needs to be copied to a virtual register so it
2538   // can be used as an index into the jump table in a subsequent basic block.
2539   // This value may be smaller or larger than the target's pointer type, and
2540   // therefore require extension or truncating.
2541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2542   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2543 
2544   unsigned JumpTableReg =
2545       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2546   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2547                                     JumpTableReg, SwitchOp);
2548   JT.Reg = JumpTableReg;
2549 
2550   if (!JTH.OmitRangeCheck) {
2551     // Emit the range check for the jump table, and branch to the default block
2552     // for the switch statement if the value being switched on exceeds the
2553     // largest case in the switch.
2554     SDValue CMP = DAG.getSetCC(
2555         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2556                                    Sub.getValueType()),
2557         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2558 
2559     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2560                                  MVT::Other, CopyTo, CMP,
2561                                  DAG.getBasicBlock(JT.Default));
2562 
2563     // Avoid emitting unnecessary branches to the next block.
2564     if (JT.MBB != NextBlock(SwitchBB))
2565       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2566                            DAG.getBasicBlock(JT.MBB));
2567 
2568     DAG.setRoot(BrCond);
2569   } else {
2570     // Avoid emitting unnecessary branches to the next block.
2571     if (JT.MBB != NextBlock(SwitchBB))
2572       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2573                               DAG.getBasicBlock(JT.MBB)));
2574     else
2575       DAG.setRoot(CopyTo);
2576   }
2577 }
2578 
2579 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2580 /// variable if there exists one.
2581 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2582                                  SDValue &Chain) {
2583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2584   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2585   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2586   MachineFunction &MF = DAG.getMachineFunction();
2587   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2588   MachineSDNode *Node =
2589       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2590   if (Global) {
2591     MachinePointerInfo MPInfo(Global);
2592     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2593                  MachineMemOperand::MODereferenceable;
2594     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2595         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2596     DAG.setNodeMemRefs(Node, {MemRef});
2597   }
2598   if (PtrTy != PtrMemTy)
2599     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2600   return SDValue(Node, 0);
2601 }
2602 
2603 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2604 /// tail spliced into a stack protector check success bb.
2605 ///
2606 /// For a high level explanation of how this fits into the stack protector
2607 /// generation see the comment on the declaration of class
2608 /// StackProtectorDescriptor.
2609 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2610                                                   MachineBasicBlock *ParentBB) {
2611 
2612   // First create the loads to the guard/stack slot for the comparison.
2613   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2614   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2615   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2616 
2617   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2618   int FI = MFI.getStackProtectorIndex();
2619 
2620   SDValue Guard;
2621   SDLoc dl = getCurSDLoc();
2622   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2623   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2624   Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2625 
2626   // Generate code to load the content of the guard slot.
2627   SDValue GuardVal = DAG.getLoad(
2628       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2629       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2630       MachineMemOperand::MOVolatile);
2631 
2632   if (TLI.useStackGuardXorFP())
2633     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2634 
2635   // Retrieve guard check function, nullptr if instrumentation is inlined.
2636   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2637     // The target provides a guard check function to validate the guard value.
2638     // Generate a call to that function with the content of the guard slot as
2639     // argument.
2640     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2641     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2642 
2643     TargetLowering::ArgListTy Args;
2644     TargetLowering::ArgListEntry Entry;
2645     Entry.Node = GuardVal;
2646     Entry.Ty = FnTy->getParamType(0);
2647     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2648       Entry.IsInReg = true;
2649     Args.push_back(Entry);
2650 
2651     TargetLowering::CallLoweringInfo CLI(DAG);
2652     CLI.setDebugLoc(getCurSDLoc())
2653         .setChain(DAG.getEntryNode())
2654         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2655                    getValue(GuardCheckFn), std::move(Args));
2656 
2657     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2658     DAG.setRoot(Result.second);
2659     return;
2660   }
2661 
2662   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2663   // Otherwise, emit a volatile load to retrieve the stack guard value.
2664   SDValue Chain = DAG.getEntryNode();
2665   if (TLI.useLoadStackGuardNode()) {
2666     Guard = getLoadStackGuard(DAG, dl, Chain);
2667   } else {
2668     const Value *IRGuard = TLI.getSDagStackGuard(M);
2669     SDValue GuardPtr = getValue(IRGuard);
2670 
2671     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2672                         MachinePointerInfo(IRGuard, 0), Align,
2673                         MachineMemOperand::MOVolatile);
2674   }
2675 
2676   // Perform the comparison via a getsetcc.
2677   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2678                                                         *DAG.getContext(),
2679                                                         Guard.getValueType()),
2680                              Guard, GuardVal, ISD::SETNE);
2681 
2682   // If the guard/stackslot do not equal, branch to failure MBB.
2683   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2684                                MVT::Other, GuardVal.getOperand(0),
2685                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2686   // Otherwise branch to success MBB.
2687   SDValue Br = DAG.getNode(ISD::BR, dl,
2688                            MVT::Other, BrCond,
2689                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2690 
2691   DAG.setRoot(Br);
2692 }
2693 
2694 /// Codegen the failure basic block for a stack protector check.
2695 ///
2696 /// A failure stack protector machine basic block consists simply of a call to
2697 /// __stack_chk_fail().
2698 ///
2699 /// For a high level explanation of how this fits into the stack protector
2700 /// generation see the comment on the declaration of class
2701 /// StackProtectorDescriptor.
2702 void
2703 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2704   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2705   TargetLowering::MakeLibCallOptions CallOptions;
2706   CallOptions.setDiscardResult(true);
2707   SDValue Chain =
2708       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2709                       None, CallOptions, getCurSDLoc()).second;
2710   // On PS4, the "return address" must still be within the calling function,
2711   // even if it's at the very end, so emit an explicit TRAP here.
2712   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2713   if (TM.getTargetTriple().isPS4CPU())
2714     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2715   // WebAssembly needs an unreachable instruction after a non-returning call,
2716   // because the function return type can be different from __stack_chk_fail's
2717   // return type (void).
2718   if (TM.getTargetTriple().isWasm())
2719     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2720 
2721   DAG.setRoot(Chain);
2722 }
2723 
2724 /// visitBitTestHeader - This function emits necessary code to produce value
2725 /// suitable for "bit tests"
2726 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2727                                              MachineBasicBlock *SwitchBB) {
2728   SDLoc dl = getCurSDLoc();
2729 
2730   // Subtract the minimum value.
2731   SDValue SwitchOp = getValue(B.SValue);
2732   EVT VT = SwitchOp.getValueType();
2733   SDValue RangeSub =
2734       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2735 
2736   // Determine the type of the test operands.
2737   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2738   bool UsePtrType = false;
2739   if (!TLI.isTypeLegal(VT)) {
2740     UsePtrType = true;
2741   } else {
2742     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2743       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2744         // Switch table case range are encoded into series of masks.
2745         // Just use pointer type, it's guaranteed to fit.
2746         UsePtrType = true;
2747         break;
2748       }
2749   }
2750   SDValue Sub = RangeSub;
2751   if (UsePtrType) {
2752     VT = TLI.getPointerTy(DAG.getDataLayout());
2753     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2754   }
2755 
2756   B.RegVT = VT.getSimpleVT();
2757   B.Reg = FuncInfo.CreateReg(B.RegVT);
2758   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2759 
2760   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2761 
2762   if (!B.OmitRangeCheck)
2763     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2764   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2765   SwitchBB->normalizeSuccProbs();
2766 
2767   SDValue Root = CopyTo;
2768   if (!B.OmitRangeCheck) {
2769     // Conditional branch to the default block.
2770     SDValue RangeCmp = DAG.getSetCC(dl,
2771         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2772                                RangeSub.getValueType()),
2773         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2774         ISD::SETUGT);
2775 
2776     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2777                        DAG.getBasicBlock(B.Default));
2778   }
2779 
2780   // Avoid emitting unnecessary branches to the next block.
2781   if (MBB != NextBlock(SwitchBB))
2782     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2783 
2784   DAG.setRoot(Root);
2785 }
2786 
2787 /// visitBitTestCase - this function produces one "bit test"
2788 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2789                                            MachineBasicBlock* NextMBB,
2790                                            BranchProbability BranchProbToNext,
2791                                            unsigned Reg,
2792                                            BitTestCase &B,
2793                                            MachineBasicBlock *SwitchBB) {
2794   SDLoc dl = getCurSDLoc();
2795   MVT VT = BB.RegVT;
2796   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2797   SDValue Cmp;
2798   unsigned PopCount = countPopulation(B.Mask);
2799   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2800   if (PopCount == 1) {
2801     // Testing for a single bit; just compare the shift count with what it
2802     // would need to be to shift a 1 bit in that position.
2803     Cmp = DAG.getSetCC(
2804         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2805         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2806         ISD::SETEQ);
2807   } else if (PopCount == BB.Range) {
2808     // There is only one zero bit in the range, test for it directly.
2809     Cmp = DAG.getSetCC(
2810         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2811         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2812         ISD::SETNE);
2813   } else {
2814     // Make desired shift
2815     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2816                                     DAG.getConstant(1, dl, VT), ShiftOp);
2817 
2818     // Emit bit tests and jumps
2819     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2820                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2821     Cmp = DAG.getSetCC(
2822         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2823         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2824   }
2825 
2826   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2827   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2828   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2829   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2830   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2831   // one as they are relative probabilities (and thus work more like weights),
2832   // and hence we need to normalize them to let the sum of them become one.
2833   SwitchBB->normalizeSuccProbs();
2834 
2835   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2836                               MVT::Other, getControlRoot(),
2837                               Cmp, DAG.getBasicBlock(B.TargetBB));
2838 
2839   // Avoid emitting unnecessary branches to the next block.
2840   if (NextMBB != NextBlock(SwitchBB))
2841     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2842                         DAG.getBasicBlock(NextMBB));
2843 
2844   DAG.setRoot(BrAnd);
2845 }
2846 
2847 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2848   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2849 
2850   // Retrieve successors. Look through artificial IR level blocks like
2851   // catchswitch for successors.
2852   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2853   const BasicBlock *EHPadBB = I.getSuccessor(1);
2854 
2855   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2856   // have to do anything here to lower funclet bundles.
2857   assert(!I.hasOperandBundlesOtherThan(
2858              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2859               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2860               LLVMContext::OB_cfguardtarget,
2861               LLVMContext::OB_clang_arc_attachedcall}) &&
2862          "Cannot lower invokes with arbitrary operand bundles yet!");
2863 
2864   const Value *Callee(I.getCalledOperand());
2865   const Function *Fn = dyn_cast<Function>(Callee);
2866   if (isa<InlineAsm>(Callee))
2867     visitInlineAsm(I);
2868   else if (Fn && Fn->isIntrinsic()) {
2869     switch (Fn->getIntrinsicID()) {
2870     default:
2871       llvm_unreachable("Cannot invoke this intrinsic");
2872     case Intrinsic::donothing:
2873       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2874       break;
2875     case Intrinsic::experimental_patchpoint_void:
2876     case Intrinsic::experimental_patchpoint_i64:
2877       visitPatchpoint(I, EHPadBB);
2878       break;
2879     case Intrinsic::experimental_gc_statepoint:
2880       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2881       break;
2882     case Intrinsic::wasm_rethrow: {
2883       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2884       // special because it can be invoked, so we manually lower it to a DAG
2885       // node here.
2886       SmallVector<SDValue, 8> Ops;
2887       Ops.push_back(getRoot()); // inchain
2888       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2889       Ops.push_back(
2890           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2891                                 TLI.getPointerTy(DAG.getDataLayout())));
2892       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2893       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2894       break;
2895     }
2896     }
2897   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2898     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2899     // Eventually we will support lowering the @llvm.experimental.deoptimize
2900     // intrinsic, and right now there are no plans to support other intrinsics
2901     // with deopt state.
2902     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2903   } else {
2904     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2905   }
2906 
2907   // If the value of the invoke is used outside of its defining block, make it
2908   // available as a virtual register.
2909   // We already took care of the exported value for the statepoint instruction
2910   // during call to the LowerStatepoint.
2911   if (!isa<GCStatepointInst>(I)) {
2912     CopyToExportRegsIfNeeded(&I);
2913   }
2914 
2915   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2916   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2917   BranchProbability EHPadBBProb =
2918       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2919           : BranchProbability::getZero();
2920   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2921 
2922   // Update successor info.
2923   addSuccessorWithProb(InvokeMBB, Return);
2924   for (auto &UnwindDest : UnwindDests) {
2925     UnwindDest.first->setIsEHPad();
2926     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2927   }
2928   InvokeMBB->normalizeSuccProbs();
2929 
2930   // Drop into normal successor.
2931   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2932                           DAG.getBasicBlock(Return)));
2933 }
2934 
2935 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2936   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2937 
2938   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2939   // have to do anything here to lower funclet bundles.
2940   assert(!I.hasOperandBundlesOtherThan(
2941              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2942          "Cannot lower callbrs with arbitrary operand bundles yet!");
2943 
2944   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2945   visitInlineAsm(I);
2946   CopyToExportRegsIfNeeded(&I);
2947 
2948   // Retrieve successors.
2949   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2950 
2951   // Update successor info.
2952   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2953   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2954     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2955     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2956     Target->setIsInlineAsmBrIndirectTarget();
2957   }
2958   CallBrMBB->normalizeSuccProbs();
2959 
2960   // Drop into default successor.
2961   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2962                           MVT::Other, getControlRoot(),
2963                           DAG.getBasicBlock(Return)));
2964 }
2965 
2966 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2967   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2968 }
2969 
2970 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2971   assert(FuncInfo.MBB->isEHPad() &&
2972          "Call to landingpad not in landing pad!");
2973 
2974   // If there aren't registers to copy the values into (e.g., during SjLj
2975   // exceptions), then don't bother to create these DAG nodes.
2976   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2977   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2978   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2979       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2980     return;
2981 
2982   // If landingpad's return type is token type, we don't create DAG nodes
2983   // for its exception pointer and selector value. The extraction of exception
2984   // pointer or selector value from token type landingpads is not currently
2985   // supported.
2986   if (LP.getType()->isTokenTy())
2987     return;
2988 
2989   SmallVector<EVT, 2> ValueVTs;
2990   SDLoc dl = getCurSDLoc();
2991   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2992   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2993 
2994   // Get the two live-in registers as SDValues. The physregs have already been
2995   // copied into virtual registers.
2996   SDValue Ops[2];
2997   if (FuncInfo.ExceptionPointerVirtReg) {
2998     Ops[0] = DAG.getZExtOrTrunc(
2999         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3000                            FuncInfo.ExceptionPointerVirtReg,
3001                            TLI.getPointerTy(DAG.getDataLayout())),
3002         dl, ValueVTs[0]);
3003   } else {
3004     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3005   }
3006   Ops[1] = DAG.getZExtOrTrunc(
3007       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3008                          FuncInfo.ExceptionSelectorVirtReg,
3009                          TLI.getPointerTy(DAG.getDataLayout())),
3010       dl, ValueVTs[1]);
3011 
3012   // Merge into one.
3013   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3014                             DAG.getVTList(ValueVTs), Ops);
3015   setValue(&LP, Res);
3016 }
3017 
3018 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3019                                            MachineBasicBlock *Last) {
3020   // Update JTCases.
3021   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
3022     if (SL->JTCases[i].first.HeaderBB == First)
3023       SL->JTCases[i].first.HeaderBB = Last;
3024 
3025   // Update BitTestCases.
3026   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
3027     if (SL->BitTestCases[i].Parent == First)
3028       SL->BitTestCases[i].Parent = Last;
3029 }
3030 
3031 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3032   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3033 
3034   // Update machine-CFG edges with unique successors.
3035   SmallSet<BasicBlock*, 32> Done;
3036   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3037     BasicBlock *BB = I.getSuccessor(i);
3038     bool Inserted = Done.insert(BB).second;
3039     if (!Inserted)
3040         continue;
3041 
3042     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3043     addSuccessorWithProb(IndirectBrMBB, Succ);
3044   }
3045   IndirectBrMBB->normalizeSuccProbs();
3046 
3047   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3048                           MVT::Other, getControlRoot(),
3049                           getValue(I.getAddress())));
3050 }
3051 
3052 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3053   if (!DAG.getTarget().Options.TrapUnreachable)
3054     return;
3055 
3056   // We may be able to ignore unreachable behind a noreturn call.
3057   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3058     const BasicBlock &BB = *I.getParent();
3059     if (&I != &BB.front()) {
3060       BasicBlock::const_iterator PredI =
3061         std::prev(BasicBlock::const_iterator(&I));
3062       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3063         if (Call->doesNotReturn())
3064           return;
3065       }
3066     }
3067   }
3068 
3069   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3070 }
3071 
3072 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3073   SDNodeFlags Flags;
3074 
3075   SDValue Op = getValue(I.getOperand(0));
3076   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3077                                     Op, Flags);
3078   setValue(&I, UnNodeValue);
3079 }
3080 
3081 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3082   SDNodeFlags Flags;
3083   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3084     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3085     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3086   }
3087   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3088     Flags.setExact(ExactOp->isExact());
3089   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3090     Flags.copyFMF(*FPOp);
3091 
3092   SDValue Op1 = getValue(I.getOperand(0));
3093   SDValue Op2 = getValue(I.getOperand(1));
3094   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3095                                      Op1, Op2, Flags);
3096   setValue(&I, BinNodeValue);
3097 }
3098 
3099 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3100   SDValue Op1 = getValue(I.getOperand(0));
3101   SDValue Op2 = getValue(I.getOperand(1));
3102 
3103   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3104       Op1.getValueType(), DAG.getDataLayout());
3105 
3106   // Coerce the shift amount to the right type if we can.
3107   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3108     unsigned ShiftSize = ShiftTy.getSizeInBits();
3109     unsigned Op2Size = Op2.getValueSizeInBits();
3110     SDLoc DL = getCurSDLoc();
3111 
3112     // If the operand is smaller than the shift count type, promote it.
3113     if (ShiftSize > Op2Size)
3114       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3115 
3116     // If the operand is larger than the shift count type but the shift
3117     // count type has enough bits to represent any shift value, truncate
3118     // it now. This is a common case and it exposes the truncate to
3119     // optimization early.
3120     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3121       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3122     // Otherwise we'll need to temporarily settle for some other convenient
3123     // type.  Type legalization will make adjustments once the shiftee is split.
3124     else
3125       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3126   }
3127 
3128   bool nuw = false;
3129   bool nsw = false;
3130   bool exact = false;
3131 
3132   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3133 
3134     if (const OverflowingBinaryOperator *OFBinOp =
3135             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3136       nuw = OFBinOp->hasNoUnsignedWrap();
3137       nsw = OFBinOp->hasNoSignedWrap();
3138     }
3139     if (const PossiblyExactOperator *ExactOp =
3140             dyn_cast<const PossiblyExactOperator>(&I))
3141       exact = ExactOp->isExact();
3142   }
3143   SDNodeFlags Flags;
3144   Flags.setExact(exact);
3145   Flags.setNoSignedWrap(nsw);
3146   Flags.setNoUnsignedWrap(nuw);
3147   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3148                             Flags);
3149   setValue(&I, Res);
3150 }
3151 
3152 void SelectionDAGBuilder::visitSDiv(const User &I) {
3153   SDValue Op1 = getValue(I.getOperand(0));
3154   SDValue Op2 = getValue(I.getOperand(1));
3155 
3156   SDNodeFlags Flags;
3157   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3158                  cast<PossiblyExactOperator>(&I)->isExact());
3159   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3160                            Op2, Flags));
3161 }
3162 
3163 void SelectionDAGBuilder::visitICmp(const User &I) {
3164   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3165   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3166     predicate = IC->getPredicate();
3167   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3168     predicate = ICmpInst::Predicate(IC->getPredicate());
3169   SDValue Op1 = getValue(I.getOperand(0));
3170   SDValue Op2 = getValue(I.getOperand(1));
3171   ISD::CondCode Opcode = getICmpCondCode(predicate);
3172 
3173   auto &TLI = DAG.getTargetLoweringInfo();
3174   EVT MemVT =
3175       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3176 
3177   // If a pointer's DAG type is larger than its memory type then the DAG values
3178   // are zero-extended. This breaks signed comparisons so truncate back to the
3179   // underlying type before doing the compare.
3180   if (Op1.getValueType() != MemVT) {
3181     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3182     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3183   }
3184 
3185   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3186                                                         I.getType());
3187   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3188 }
3189 
3190 void SelectionDAGBuilder::visitFCmp(const User &I) {
3191   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3192   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3193     predicate = FC->getPredicate();
3194   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3195     predicate = FCmpInst::Predicate(FC->getPredicate());
3196   SDValue Op1 = getValue(I.getOperand(0));
3197   SDValue Op2 = getValue(I.getOperand(1));
3198 
3199   ISD::CondCode Condition = getFCmpCondCode(predicate);
3200   auto *FPMO = cast<FPMathOperator>(&I);
3201   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3202     Condition = getFCmpCodeWithoutNaN(Condition);
3203 
3204   SDNodeFlags Flags;
3205   Flags.copyFMF(*FPMO);
3206   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3207 
3208   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3209                                                         I.getType());
3210   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3211 }
3212 
3213 // Check if the condition of the select has one use or two users that are both
3214 // selects with the same condition.
3215 static bool hasOnlySelectUsers(const Value *Cond) {
3216   return llvm::all_of(Cond->users(), [](const Value *V) {
3217     return isa<SelectInst>(V);
3218   });
3219 }
3220 
3221 void SelectionDAGBuilder::visitSelect(const User &I) {
3222   SmallVector<EVT, 4> ValueVTs;
3223   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3224                   ValueVTs);
3225   unsigned NumValues = ValueVTs.size();
3226   if (NumValues == 0) return;
3227 
3228   SmallVector<SDValue, 4> Values(NumValues);
3229   SDValue Cond     = getValue(I.getOperand(0));
3230   SDValue LHSVal   = getValue(I.getOperand(1));
3231   SDValue RHSVal   = getValue(I.getOperand(2));
3232   SmallVector<SDValue, 1> BaseOps(1, Cond);
3233   ISD::NodeType OpCode =
3234       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3235 
3236   bool IsUnaryAbs = false;
3237   bool Negate = false;
3238 
3239   SDNodeFlags Flags;
3240   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3241     Flags.copyFMF(*FPOp);
3242 
3243   // Min/max matching is only viable if all output VTs are the same.
3244   if (is_splat(ValueVTs)) {
3245     EVT VT = ValueVTs[0];
3246     LLVMContext &Ctx = *DAG.getContext();
3247     auto &TLI = DAG.getTargetLoweringInfo();
3248 
3249     // We care about the legality of the operation after it has been type
3250     // legalized.
3251     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3252       VT = TLI.getTypeToTransformTo(Ctx, VT);
3253 
3254     // If the vselect is legal, assume we want to leave this as a vector setcc +
3255     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3256     // min/max is legal on the scalar type.
3257     bool UseScalarMinMax = VT.isVector() &&
3258       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3259 
3260     Value *LHS, *RHS;
3261     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3262     ISD::NodeType Opc = ISD::DELETED_NODE;
3263     switch (SPR.Flavor) {
3264     case SPF_UMAX:    Opc = ISD::UMAX; break;
3265     case SPF_UMIN:    Opc = ISD::UMIN; break;
3266     case SPF_SMAX:    Opc = ISD::SMAX; break;
3267     case SPF_SMIN:    Opc = ISD::SMIN; break;
3268     case SPF_FMINNUM:
3269       switch (SPR.NaNBehavior) {
3270       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3271       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3272       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3273       case SPNB_RETURNS_ANY: {
3274         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3275           Opc = ISD::FMINNUM;
3276         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3277           Opc = ISD::FMINIMUM;
3278         else if (UseScalarMinMax)
3279           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3280             ISD::FMINNUM : ISD::FMINIMUM;
3281         break;
3282       }
3283       }
3284       break;
3285     case SPF_FMAXNUM:
3286       switch (SPR.NaNBehavior) {
3287       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3288       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3289       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3290       case SPNB_RETURNS_ANY:
3291 
3292         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3293           Opc = ISD::FMAXNUM;
3294         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3295           Opc = ISD::FMAXIMUM;
3296         else if (UseScalarMinMax)
3297           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3298             ISD::FMAXNUM : ISD::FMAXIMUM;
3299         break;
3300       }
3301       break;
3302     case SPF_NABS:
3303       Negate = true;
3304       LLVM_FALLTHROUGH;
3305     case SPF_ABS:
3306       IsUnaryAbs = true;
3307       Opc = ISD::ABS;
3308       break;
3309     default: break;
3310     }
3311 
3312     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3313         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3314          (UseScalarMinMax &&
3315           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3316         // If the underlying comparison instruction is used by any other
3317         // instruction, the consumed instructions won't be destroyed, so it is
3318         // not profitable to convert to a min/max.
3319         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3320       OpCode = Opc;
3321       LHSVal = getValue(LHS);
3322       RHSVal = getValue(RHS);
3323       BaseOps.clear();
3324     }
3325 
3326     if (IsUnaryAbs) {
3327       OpCode = Opc;
3328       LHSVal = getValue(LHS);
3329       BaseOps.clear();
3330     }
3331   }
3332 
3333   if (IsUnaryAbs) {
3334     for (unsigned i = 0; i != NumValues; ++i) {
3335       SDLoc dl = getCurSDLoc();
3336       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3337       Values[i] =
3338           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3339       if (Negate)
3340         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3341                                 Values[i]);
3342     }
3343   } else {
3344     for (unsigned i = 0; i != NumValues; ++i) {
3345       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3346       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3347       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3348       Values[i] = DAG.getNode(
3349           OpCode, getCurSDLoc(),
3350           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3351     }
3352   }
3353 
3354   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3355                            DAG.getVTList(ValueVTs), Values));
3356 }
3357 
3358 void SelectionDAGBuilder::visitTrunc(const User &I) {
3359   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3360   SDValue N = getValue(I.getOperand(0));
3361   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3362                                                         I.getType());
3363   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3364 }
3365 
3366 void SelectionDAGBuilder::visitZExt(const User &I) {
3367   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3368   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3369   SDValue N = getValue(I.getOperand(0));
3370   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3371                                                         I.getType());
3372   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3373 }
3374 
3375 void SelectionDAGBuilder::visitSExt(const User &I) {
3376   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3377   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3378   SDValue N = getValue(I.getOperand(0));
3379   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3380                                                         I.getType());
3381   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3382 }
3383 
3384 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3385   // FPTrunc is never a no-op cast, no need to check
3386   SDValue N = getValue(I.getOperand(0));
3387   SDLoc dl = getCurSDLoc();
3388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3389   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3390   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3391                            DAG.getTargetConstant(
3392                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3393 }
3394 
3395 void SelectionDAGBuilder::visitFPExt(const User &I) {
3396   // FPExt is never a no-op cast, no need to check
3397   SDValue N = getValue(I.getOperand(0));
3398   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3399                                                         I.getType());
3400   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3401 }
3402 
3403 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3404   // FPToUI is never a no-op cast, no need to check
3405   SDValue N = getValue(I.getOperand(0));
3406   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3407                                                         I.getType());
3408   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3409 }
3410 
3411 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3412   // FPToSI is never a no-op cast, no need to check
3413   SDValue N = getValue(I.getOperand(0));
3414   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3415                                                         I.getType());
3416   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3417 }
3418 
3419 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3420   // UIToFP is never a no-op cast, no need to check
3421   SDValue N = getValue(I.getOperand(0));
3422   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3423                                                         I.getType());
3424   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3425 }
3426 
3427 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3428   // SIToFP is never a no-op cast, no need to check
3429   SDValue N = getValue(I.getOperand(0));
3430   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3431                                                         I.getType());
3432   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3433 }
3434 
3435 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3436   // What to do depends on the size of the integer and the size of the pointer.
3437   // We can either truncate, zero extend, or no-op, accordingly.
3438   SDValue N = getValue(I.getOperand(0));
3439   auto &TLI = DAG.getTargetLoweringInfo();
3440   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3441                                                         I.getType());
3442   EVT PtrMemVT =
3443       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3444   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3445   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3446   setValue(&I, N);
3447 }
3448 
3449 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3450   // What to do depends on the size of the integer and the size of the pointer.
3451   // We can either truncate, zero extend, or no-op, accordingly.
3452   SDValue N = getValue(I.getOperand(0));
3453   auto &TLI = DAG.getTargetLoweringInfo();
3454   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3455   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3456   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3457   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3458   setValue(&I, N);
3459 }
3460 
3461 void SelectionDAGBuilder::visitBitCast(const User &I) {
3462   SDValue N = getValue(I.getOperand(0));
3463   SDLoc dl = getCurSDLoc();
3464   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3465                                                         I.getType());
3466 
3467   // BitCast assures us that source and destination are the same size so this is
3468   // either a BITCAST or a no-op.
3469   if (DestVT != N.getValueType())
3470     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3471                              DestVT, N)); // convert types.
3472   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3473   // might fold any kind of constant expression to an integer constant and that
3474   // is not what we are looking for. Only recognize a bitcast of a genuine
3475   // constant integer as an opaque constant.
3476   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3477     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3478                                  /*isOpaque*/true));
3479   else
3480     setValue(&I, N);            // noop cast.
3481 }
3482 
3483 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3484   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3485   const Value *SV = I.getOperand(0);
3486   SDValue N = getValue(SV);
3487   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3488 
3489   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3490   unsigned DestAS = I.getType()->getPointerAddressSpace();
3491 
3492   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3493     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3494 
3495   setValue(&I, N);
3496 }
3497 
3498 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3499   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3500   SDValue InVec = getValue(I.getOperand(0));
3501   SDValue InVal = getValue(I.getOperand(1));
3502   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3503                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3504   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3505                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3506                            InVec, InVal, InIdx));
3507 }
3508 
3509 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3510   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3511   SDValue InVec = getValue(I.getOperand(0));
3512   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3513                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3514   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3515                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3516                            InVec, InIdx));
3517 }
3518 
3519 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3520   SDValue Src1 = getValue(I.getOperand(0));
3521   SDValue Src2 = getValue(I.getOperand(1));
3522   ArrayRef<int> Mask;
3523   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3524     Mask = SVI->getShuffleMask();
3525   else
3526     Mask = cast<ConstantExpr>(I).getShuffleMask();
3527   SDLoc DL = getCurSDLoc();
3528   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3529   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3530   EVT SrcVT = Src1.getValueType();
3531 
3532   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3533       VT.isScalableVector()) {
3534     // Canonical splat form of first element of first input vector.
3535     SDValue FirstElt =
3536         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3537                     DAG.getVectorIdxConstant(0, DL));
3538     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3539     return;
3540   }
3541 
3542   // For now, we only handle splats for scalable vectors.
3543   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3544   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3545   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3546 
3547   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3548   unsigned MaskNumElts = Mask.size();
3549 
3550   if (SrcNumElts == MaskNumElts) {
3551     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3552     return;
3553   }
3554 
3555   // Normalize the shuffle vector since mask and vector length don't match.
3556   if (SrcNumElts < MaskNumElts) {
3557     // Mask is longer than the source vectors. We can use concatenate vector to
3558     // make the mask and vectors lengths match.
3559 
3560     if (MaskNumElts % SrcNumElts == 0) {
3561       // Mask length is a multiple of the source vector length.
3562       // Check if the shuffle is some kind of concatenation of the input
3563       // vectors.
3564       unsigned NumConcat = MaskNumElts / SrcNumElts;
3565       bool IsConcat = true;
3566       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3567       for (unsigned i = 0; i != MaskNumElts; ++i) {
3568         int Idx = Mask[i];
3569         if (Idx < 0)
3570           continue;
3571         // Ensure the indices in each SrcVT sized piece are sequential and that
3572         // the same source is used for the whole piece.
3573         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3574             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3575              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3576           IsConcat = false;
3577           break;
3578         }
3579         // Remember which source this index came from.
3580         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3581       }
3582 
3583       // The shuffle is concatenating multiple vectors together. Just emit
3584       // a CONCAT_VECTORS operation.
3585       if (IsConcat) {
3586         SmallVector<SDValue, 8> ConcatOps;
3587         for (auto Src : ConcatSrcs) {
3588           if (Src < 0)
3589             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3590           else if (Src == 0)
3591             ConcatOps.push_back(Src1);
3592           else
3593             ConcatOps.push_back(Src2);
3594         }
3595         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3596         return;
3597       }
3598     }
3599 
3600     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3601     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3602     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3603                                     PaddedMaskNumElts);
3604 
3605     // Pad both vectors with undefs to make them the same length as the mask.
3606     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3607 
3608     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3609     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3610     MOps1[0] = Src1;
3611     MOps2[0] = Src2;
3612 
3613     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3614     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3615 
3616     // Readjust mask for new input vector length.
3617     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3618     for (unsigned i = 0; i != MaskNumElts; ++i) {
3619       int Idx = Mask[i];
3620       if (Idx >= (int)SrcNumElts)
3621         Idx -= SrcNumElts - PaddedMaskNumElts;
3622       MappedOps[i] = Idx;
3623     }
3624 
3625     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3626 
3627     // If the concatenated vector was padded, extract a subvector with the
3628     // correct number of elements.
3629     if (MaskNumElts != PaddedMaskNumElts)
3630       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3631                            DAG.getVectorIdxConstant(0, DL));
3632 
3633     setValue(&I, Result);
3634     return;
3635   }
3636 
3637   if (SrcNumElts > MaskNumElts) {
3638     // Analyze the access pattern of the vector to see if we can extract
3639     // two subvectors and do the shuffle.
3640     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3641     bool CanExtract = true;
3642     for (int Idx : Mask) {
3643       unsigned Input = 0;
3644       if (Idx < 0)
3645         continue;
3646 
3647       if (Idx >= (int)SrcNumElts) {
3648         Input = 1;
3649         Idx -= SrcNumElts;
3650       }
3651 
3652       // If all the indices come from the same MaskNumElts sized portion of
3653       // the sources we can use extract. Also make sure the extract wouldn't
3654       // extract past the end of the source.
3655       int NewStartIdx = alignDown(Idx, MaskNumElts);
3656       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3657           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3658         CanExtract = false;
3659       // Make sure we always update StartIdx as we use it to track if all
3660       // elements are undef.
3661       StartIdx[Input] = NewStartIdx;
3662     }
3663 
3664     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3665       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3666       return;
3667     }
3668     if (CanExtract) {
3669       // Extract appropriate subvector and generate a vector shuffle
3670       for (unsigned Input = 0; Input < 2; ++Input) {
3671         SDValue &Src = Input == 0 ? Src1 : Src2;
3672         if (StartIdx[Input] < 0)
3673           Src = DAG.getUNDEF(VT);
3674         else {
3675           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3676                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3677         }
3678       }
3679 
3680       // Calculate new mask.
3681       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3682       for (int &Idx : MappedOps) {
3683         if (Idx >= (int)SrcNumElts)
3684           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3685         else if (Idx >= 0)
3686           Idx -= StartIdx[0];
3687       }
3688 
3689       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3690       return;
3691     }
3692   }
3693 
3694   // We can't use either concat vectors or extract subvectors so fall back to
3695   // replacing the shuffle with extract and build vector.
3696   // to insert and build vector.
3697   EVT EltVT = VT.getVectorElementType();
3698   SmallVector<SDValue,8> Ops;
3699   for (int Idx : Mask) {
3700     SDValue Res;
3701 
3702     if (Idx < 0) {
3703       Res = DAG.getUNDEF(EltVT);
3704     } else {
3705       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3706       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3707 
3708       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3709                         DAG.getVectorIdxConstant(Idx, DL));
3710     }
3711 
3712     Ops.push_back(Res);
3713   }
3714 
3715   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3716 }
3717 
3718 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3719   ArrayRef<unsigned> Indices;
3720   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3721     Indices = IV->getIndices();
3722   else
3723     Indices = cast<ConstantExpr>(&I)->getIndices();
3724 
3725   const Value *Op0 = I.getOperand(0);
3726   const Value *Op1 = I.getOperand(1);
3727   Type *AggTy = I.getType();
3728   Type *ValTy = Op1->getType();
3729   bool IntoUndef = isa<UndefValue>(Op0);
3730   bool FromUndef = isa<UndefValue>(Op1);
3731 
3732   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3733 
3734   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3735   SmallVector<EVT, 4> AggValueVTs;
3736   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3737   SmallVector<EVT, 4> ValValueVTs;
3738   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3739 
3740   unsigned NumAggValues = AggValueVTs.size();
3741   unsigned NumValValues = ValValueVTs.size();
3742   SmallVector<SDValue, 4> Values(NumAggValues);
3743 
3744   // Ignore an insertvalue that produces an empty object
3745   if (!NumAggValues) {
3746     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3747     return;
3748   }
3749 
3750   SDValue Agg = getValue(Op0);
3751   unsigned i = 0;
3752   // Copy the beginning value(s) from the original aggregate.
3753   for (; i != LinearIndex; ++i)
3754     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3755                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3756   // Copy values from the inserted value(s).
3757   if (NumValValues) {
3758     SDValue Val = getValue(Op1);
3759     for (; i != LinearIndex + NumValValues; ++i)
3760       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3761                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3762   }
3763   // Copy remaining value(s) from the original aggregate.
3764   for (; i != NumAggValues; ++i)
3765     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3766                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3767 
3768   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3769                            DAG.getVTList(AggValueVTs), Values));
3770 }
3771 
3772 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3773   ArrayRef<unsigned> Indices;
3774   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3775     Indices = EV->getIndices();
3776   else
3777     Indices = cast<ConstantExpr>(&I)->getIndices();
3778 
3779   const Value *Op0 = I.getOperand(0);
3780   Type *AggTy = Op0->getType();
3781   Type *ValTy = I.getType();
3782   bool OutOfUndef = isa<UndefValue>(Op0);
3783 
3784   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3785 
3786   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3787   SmallVector<EVT, 4> ValValueVTs;
3788   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3789 
3790   unsigned NumValValues = ValValueVTs.size();
3791 
3792   // Ignore a extractvalue that produces an empty object
3793   if (!NumValValues) {
3794     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3795     return;
3796   }
3797 
3798   SmallVector<SDValue, 4> Values(NumValValues);
3799 
3800   SDValue Agg = getValue(Op0);
3801   // Copy out the selected value(s).
3802   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3803     Values[i - LinearIndex] =
3804       OutOfUndef ?
3805         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3806         SDValue(Agg.getNode(), Agg.getResNo() + i);
3807 
3808   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3809                            DAG.getVTList(ValValueVTs), Values));
3810 }
3811 
3812 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3813   Value *Op0 = I.getOperand(0);
3814   // Note that the pointer operand may be a vector of pointers. Take the scalar
3815   // element which holds a pointer.
3816   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3817   SDValue N = getValue(Op0);
3818   SDLoc dl = getCurSDLoc();
3819   auto &TLI = DAG.getTargetLoweringInfo();
3820 
3821   // Normalize Vector GEP - all scalar operands should be converted to the
3822   // splat vector.
3823   bool IsVectorGEP = I.getType()->isVectorTy();
3824   ElementCount VectorElementCount =
3825       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3826                   : ElementCount::getFixed(0);
3827 
3828   if (IsVectorGEP && !N.getValueType().isVector()) {
3829     LLVMContext &Context = *DAG.getContext();
3830     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3831     if (VectorElementCount.isScalable())
3832       N = DAG.getSplatVector(VT, dl, N);
3833     else
3834       N = DAG.getSplatBuildVector(VT, dl, N);
3835   }
3836 
3837   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3838        GTI != E; ++GTI) {
3839     const Value *Idx = GTI.getOperand();
3840     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3841       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3842       if (Field) {
3843         // N = N + Offset
3844         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3845 
3846         // In an inbounds GEP with an offset that is nonnegative even when
3847         // interpreted as signed, assume there is no unsigned overflow.
3848         SDNodeFlags Flags;
3849         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3850           Flags.setNoUnsignedWrap(true);
3851 
3852         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3853                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3854       }
3855     } else {
3856       // IdxSize is the width of the arithmetic according to IR semantics.
3857       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3858       // (and fix up the result later).
3859       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3860       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3861       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3862       // We intentionally mask away the high bits here; ElementSize may not
3863       // fit in IdxTy.
3864       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3865       bool ElementScalable = ElementSize.isScalable();
3866 
3867       // If this is a scalar constant or a splat vector of constants,
3868       // handle it quickly.
3869       const auto *C = dyn_cast<Constant>(Idx);
3870       if (C && isa<VectorType>(C->getType()))
3871         C = C->getSplatValue();
3872 
3873       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3874       if (CI && CI->isZero())
3875         continue;
3876       if (CI && !ElementScalable) {
3877         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3878         LLVMContext &Context = *DAG.getContext();
3879         SDValue OffsVal;
3880         if (IsVectorGEP)
3881           OffsVal = DAG.getConstant(
3882               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3883         else
3884           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3885 
3886         // In an inbounds GEP with an offset that is nonnegative even when
3887         // interpreted as signed, assume there is no unsigned overflow.
3888         SDNodeFlags Flags;
3889         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3890           Flags.setNoUnsignedWrap(true);
3891 
3892         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3893 
3894         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3895         continue;
3896       }
3897 
3898       // N = N + Idx * ElementMul;
3899       SDValue IdxN = getValue(Idx);
3900 
3901       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3902         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3903                                   VectorElementCount);
3904         if (VectorElementCount.isScalable())
3905           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3906         else
3907           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3908       }
3909 
3910       // If the index is smaller or larger than intptr_t, truncate or extend
3911       // it.
3912       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3913 
3914       if (ElementScalable) {
3915         EVT VScaleTy = N.getValueType().getScalarType();
3916         SDValue VScale = DAG.getNode(
3917             ISD::VSCALE, dl, VScaleTy,
3918             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3919         if (IsVectorGEP)
3920           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3921         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3922       } else {
3923         // If this is a multiply by a power of two, turn it into a shl
3924         // immediately.  This is a very common case.
3925         if (ElementMul != 1) {
3926           if (ElementMul.isPowerOf2()) {
3927             unsigned Amt = ElementMul.logBase2();
3928             IdxN = DAG.getNode(ISD::SHL, dl,
3929                                N.getValueType(), IdxN,
3930                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3931           } else {
3932             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3933                                             IdxN.getValueType());
3934             IdxN = DAG.getNode(ISD::MUL, dl,
3935                                N.getValueType(), IdxN, Scale);
3936           }
3937         }
3938       }
3939 
3940       N = DAG.getNode(ISD::ADD, dl,
3941                       N.getValueType(), N, IdxN);
3942     }
3943   }
3944 
3945   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3946   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3947   if (IsVectorGEP) {
3948     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3949     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3950   }
3951 
3952   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3953     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3954 
3955   setValue(&I, N);
3956 }
3957 
3958 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3959   // If this is a fixed sized alloca in the entry block of the function,
3960   // allocate it statically on the stack.
3961   if (FuncInfo.StaticAllocaMap.count(&I))
3962     return;   // getValue will auto-populate this.
3963 
3964   SDLoc dl = getCurSDLoc();
3965   Type *Ty = I.getAllocatedType();
3966   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3967   auto &DL = DAG.getDataLayout();
3968   uint64_t TySize = DL.getTypeAllocSize(Ty);
3969   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3970 
3971   SDValue AllocSize = getValue(I.getArraySize());
3972 
3973   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3974   if (AllocSize.getValueType() != IntPtr)
3975     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3976 
3977   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3978                           AllocSize,
3979                           DAG.getConstant(TySize, dl, IntPtr));
3980 
3981   // Handle alignment.  If the requested alignment is less than or equal to
3982   // the stack alignment, ignore it.  If the size is greater than or equal to
3983   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3984   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3985   if (*Alignment <= StackAlign)
3986     Alignment = None;
3987 
3988   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3989   // Round the size of the allocation up to the stack alignment size
3990   // by add SA-1 to the size. This doesn't overflow because we're computing
3991   // an address inside an alloca.
3992   SDNodeFlags Flags;
3993   Flags.setNoUnsignedWrap(true);
3994   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3995                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3996 
3997   // Mask out the low bits for alignment purposes.
3998   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3999                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4000 
4001   SDValue Ops[] = {
4002       getRoot(), AllocSize,
4003       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4004   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4005   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4006   setValue(&I, DSA);
4007   DAG.setRoot(DSA.getValue(1));
4008 
4009   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4010 }
4011 
4012 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4013   if (I.isAtomic())
4014     return visitAtomicLoad(I);
4015 
4016   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4017   const Value *SV = I.getOperand(0);
4018   if (TLI.supportSwiftError()) {
4019     // Swifterror values can come from either a function parameter with
4020     // swifterror attribute or an alloca with swifterror attribute.
4021     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4022       if (Arg->hasSwiftErrorAttr())
4023         return visitLoadFromSwiftError(I);
4024     }
4025 
4026     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4027       if (Alloca->isSwiftError())
4028         return visitLoadFromSwiftError(I);
4029     }
4030   }
4031 
4032   SDValue Ptr = getValue(SV);
4033 
4034   Type *Ty = I.getType();
4035   Align Alignment = I.getAlign();
4036 
4037   AAMDNodes AAInfo;
4038   I.getAAMetadata(AAInfo);
4039   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4040 
4041   SmallVector<EVT, 4> ValueVTs, MemVTs;
4042   SmallVector<uint64_t, 4> Offsets;
4043   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4044   unsigned NumValues = ValueVTs.size();
4045   if (NumValues == 0)
4046     return;
4047 
4048   bool isVolatile = I.isVolatile();
4049 
4050   SDValue Root;
4051   bool ConstantMemory = false;
4052   if (isVolatile)
4053     // Serialize volatile loads with other side effects.
4054     Root = getRoot();
4055   else if (NumValues > MaxParallelChains)
4056     Root = getMemoryRoot();
4057   else if (AA &&
4058            AA->pointsToConstantMemory(MemoryLocation(
4059                SV,
4060                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4061                AAInfo))) {
4062     // Do not serialize (non-volatile) loads of constant memory with anything.
4063     Root = DAG.getEntryNode();
4064     ConstantMemory = true;
4065   } else {
4066     // Do not serialize non-volatile loads against each other.
4067     Root = DAG.getRoot();
4068   }
4069 
4070   SDLoc dl = getCurSDLoc();
4071 
4072   if (isVolatile)
4073     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4074 
4075   // An aggregate load cannot wrap around the address space, so offsets to its
4076   // parts don't wrap either.
4077   SDNodeFlags Flags;
4078   Flags.setNoUnsignedWrap(true);
4079 
4080   SmallVector<SDValue, 4> Values(NumValues);
4081   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4082   EVT PtrVT = Ptr.getValueType();
4083 
4084   MachineMemOperand::Flags MMOFlags
4085     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4086 
4087   unsigned ChainI = 0;
4088   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4089     // Serializing loads here may result in excessive register pressure, and
4090     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4091     // could recover a bit by hoisting nodes upward in the chain by recognizing
4092     // they are side-effect free or do not alias. The optimizer should really
4093     // avoid this case by converting large object/array copies to llvm.memcpy
4094     // (MaxParallelChains should always remain as failsafe).
4095     if (ChainI == MaxParallelChains) {
4096       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4097       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4098                                   makeArrayRef(Chains.data(), ChainI));
4099       Root = Chain;
4100       ChainI = 0;
4101     }
4102     SDValue A = DAG.getNode(ISD::ADD, dl,
4103                             PtrVT, Ptr,
4104                             DAG.getConstant(Offsets[i], dl, PtrVT),
4105                             Flags);
4106 
4107     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4108                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4109                             MMOFlags, AAInfo, Ranges);
4110     Chains[ChainI] = L.getValue(1);
4111 
4112     if (MemVTs[i] != ValueVTs[i])
4113       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4114 
4115     Values[i] = L;
4116   }
4117 
4118   if (!ConstantMemory) {
4119     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4120                                 makeArrayRef(Chains.data(), ChainI));
4121     if (isVolatile)
4122       DAG.setRoot(Chain);
4123     else
4124       PendingLoads.push_back(Chain);
4125   }
4126 
4127   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4128                            DAG.getVTList(ValueVTs), Values));
4129 }
4130 
4131 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4132   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4133          "call visitStoreToSwiftError when backend supports swifterror");
4134 
4135   SmallVector<EVT, 4> ValueVTs;
4136   SmallVector<uint64_t, 4> Offsets;
4137   const Value *SrcV = I.getOperand(0);
4138   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4139                   SrcV->getType(), ValueVTs, &Offsets);
4140   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4141          "expect a single EVT for swifterror");
4142 
4143   SDValue Src = getValue(SrcV);
4144   // Create a virtual register, then update the virtual register.
4145   Register VReg =
4146       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4147   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4148   // Chain can be getRoot or getControlRoot.
4149   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4150                                       SDValue(Src.getNode(), Src.getResNo()));
4151   DAG.setRoot(CopyNode);
4152 }
4153 
4154 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4155   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4156          "call visitLoadFromSwiftError when backend supports swifterror");
4157 
4158   assert(!I.isVolatile() &&
4159          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4160          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4161          "Support volatile, non temporal, invariant for load_from_swift_error");
4162 
4163   const Value *SV = I.getOperand(0);
4164   Type *Ty = I.getType();
4165   AAMDNodes AAInfo;
4166   I.getAAMetadata(AAInfo);
4167   assert(
4168       (!AA ||
4169        !AA->pointsToConstantMemory(MemoryLocation(
4170            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4171            AAInfo))) &&
4172       "load_from_swift_error should not be constant memory");
4173 
4174   SmallVector<EVT, 4> ValueVTs;
4175   SmallVector<uint64_t, 4> Offsets;
4176   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4177                   ValueVTs, &Offsets);
4178   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4179          "expect a single EVT for swifterror");
4180 
4181   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4182   SDValue L = DAG.getCopyFromReg(
4183       getRoot(), getCurSDLoc(),
4184       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4185 
4186   setValue(&I, L);
4187 }
4188 
4189 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4190   if (I.isAtomic())
4191     return visitAtomicStore(I);
4192 
4193   const Value *SrcV = I.getOperand(0);
4194   const Value *PtrV = I.getOperand(1);
4195 
4196   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4197   if (TLI.supportSwiftError()) {
4198     // Swifterror values can come from either a function parameter with
4199     // swifterror attribute or an alloca with swifterror attribute.
4200     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4201       if (Arg->hasSwiftErrorAttr())
4202         return visitStoreToSwiftError(I);
4203     }
4204 
4205     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4206       if (Alloca->isSwiftError())
4207         return visitStoreToSwiftError(I);
4208     }
4209   }
4210 
4211   SmallVector<EVT, 4> ValueVTs, MemVTs;
4212   SmallVector<uint64_t, 4> Offsets;
4213   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4214                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4215   unsigned NumValues = ValueVTs.size();
4216   if (NumValues == 0)
4217     return;
4218 
4219   // Get the lowered operands. Note that we do this after
4220   // checking if NumResults is zero, because with zero results
4221   // the operands won't have values in the map.
4222   SDValue Src = getValue(SrcV);
4223   SDValue Ptr = getValue(PtrV);
4224 
4225   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4226   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4227   SDLoc dl = getCurSDLoc();
4228   Align Alignment = I.getAlign();
4229   AAMDNodes AAInfo;
4230   I.getAAMetadata(AAInfo);
4231 
4232   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4233 
4234   // An aggregate load cannot wrap around the address space, so offsets to its
4235   // parts don't wrap either.
4236   SDNodeFlags Flags;
4237   Flags.setNoUnsignedWrap(true);
4238 
4239   unsigned ChainI = 0;
4240   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4241     // See visitLoad comments.
4242     if (ChainI == MaxParallelChains) {
4243       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4244                                   makeArrayRef(Chains.data(), ChainI));
4245       Root = Chain;
4246       ChainI = 0;
4247     }
4248     SDValue Add =
4249         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4250     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4251     if (MemVTs[i] != ValueVTs[i])
4252       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4253     SDValue St =
4254         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4255                      Alignment, MMOFlags, AAInfo);
4256     Chains[ChainI] = St;
4257   }
4258 
4259   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4260                                   makeArrayRef(Chains.data(), ChainI));
4261   DAG.setRoot(StoreNode);
4262 }
4263 
4264 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4265                                            bool IsCompressing) {
4266   SDLoc sdl = getCurSDLoc();
4267 
4268   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4269                                MaybeAlign &Alignment) {
4270     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4271     Src0 = I.getArgOperand(0);
4272     Ptr = I.getArgOperand(1);
4273     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4274     Mask = I.getArgOperand(3);
4275   };
4276   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4277                                     MaybeAlign &Alignment) {
4278     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4279     Src0 = I.getArgOperand(0);
4280     Ptr = I.getArgOperand(1);
4281     Mask = I.getArgOperand(2);
4282     Alignment = None;
4283   };
4284 
4285   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4286   MaybeAlign Alignment;
4287   if (IsCompressing)
4288     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4289   else
4290     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4291 
4292   SDValue Ptr = getValue(PtrOperand);
4293   SDValue Src0 = getValue(Src0Operand);
4294   SDValue Mask = getValue(MaskOperand);
4295   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4296 
4297   EVT VT = Src0.getValueType();
4298   if (!Alignment)
4299     Alignment = DAG.getEVTAlign(VT);
4300 
4301   AAMDNodes AAInfo;
4302   I.getAAMetadata(AAInfo);
4303 
4304   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4305       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4306       // TODO: Make MachineMemOperands aware of scalable
4307       // vectors.
4308       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4309   SDValue StoreNode =
4310       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4311                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4312   DAG.setRoot(StoreNode);
4313   setValue(&I, StoreNode);
4314 }
4315 
4316 // Get a uniform base for the Gather/Scatter intrinsic.
4317 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4318 // We try to represent it as a base pointer + vector of indices.
4319 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4320 // The first operand of the GEP may be a single pointer or a vector of pointers
4321 // Example:
4322 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4323 //  or
4324 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4325 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4326 //
4327 // When the first GEP operand is a single pointer - it is the uniform base we
4328 // are looking for. If first operand of the GEP is a splat vector - we
4329 // extract the splat value and use it as a uniform base.
4330 // In all other cases the function returns 'false'.
4331 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4332                            ISD::MemIndexType &IndexType, SDValue &Scale,
4333                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4334   SelectionDAG& DAG = SDB->DAG;
4335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4336   const DataLayout &DL = DAG.getDataLayout();
4337 
4338   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4339 
4340   // Handle splat constant pointer.
4341   if (auto *C = dyn_cast<Constant>(Ptr)) {
4342     C = C->getSplatValue();
4343     if (!C)
4344       return false;
4345 
4346     Base = SDB->getValue(C);
4347 
4348     unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements();
4349     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4350     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4351     IndexType = ISD::SIGNED_SCALED;
4352     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4353     return true;
4354   }
4355 
4356   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4357   if (!GEP || GEP->getParent() != CurBB)
4358     return false;
4359 
4360   if (GEP->getNumOperands() != 2)
4361     return false;
4362 
4363   const Value *BasePtr = GEP->getPointerOperand();
4364   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4365 
4366   // Make sure the base is scalar and the index is a vector.
4367   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4368     return false;
4369 
4370   Base = SDB->getValue(BasePtr);
4371   Index = SDB->getValue(IndexVal);
4372   IndexType = ISD::SIGNED_SCALED;
4373   Scale = DAG.getTargetConstant(
4374               DL.getTypeAllocSize(GEP->getResultElementType()),
4375               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4376   return true;
4377 }
4378 
4379 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4380   SDLoc sdl = getCurSDLoc();
4381 
4382   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4383   const Value *Ptr = I.getArgOperand(1);
4384   SDValue Src0 = getValue(I.getArgOperand(0));
4385   SDValue Mask = getValue(I.getArgOperand(3));
4386   EVT VT = Src0.getValueType();
4387   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4388                         ->getMaybeAlignValue()
4389                         .getValueOr(DAG.getEVTAlign(VT));
4390   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4391 
4392   AAMDNodes AAInfo;
4393   I.getAAMetadata(AAInfo);
4394 
4395   SDValue Base;
4396   SDValue Index;
4397   ISD::MemIndexType IndexType;
4398   SDValue Scale;
4399   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4400                                     I.getParent());
4401 
4402   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4403   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4404       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4405       // TODO: Make MachineMemOperands aware of scalable
4406       // vectors.
4407       MemoryLocation::UnknownSize, Alignment, AAInfo);
4408   if (!UniformBase) {
4409     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4410     Index = getValue(Ptr);
4411     IndexType = ISD::SIGNED_UNSCALED;
4412     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4413   }
4414 
4415   EVT IdxVT = Index.getValueType();
4416   EVT EltTy = IdxVT.getVectorElementType();
4417   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4418     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4419     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4420   }
4421 
4422   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4423   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4424                                          Ops, MMO, IndexType, false);
4425   DAG.setRoot(Scatter);
4426   setValue(&I, Scatter);
4427 }
4428 
4429 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4430   SDLoc sdl = getCurSDLoc();
4431 
4432   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4433                               MaybeAlign &Alignment) {
4434     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4435     Ptr = I.getArgOperand(0);
4436     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4437     Mask = I.getArgOperand(2);
4438     Src0 = I.getArgOperand(3);
4439   };
4440   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4441                                  MaybeAlign &Alignment) {
4442     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4443     Ptr = I.getArgOperand(0);
4444     Alignment = None;
4445     Mask = I.getArgOperand(1);
4446     Src0 = I.getArgOperand(2);
4447   };
4448 
4449   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4450   MaybeAlign Alignment;
4451   if (IsExpanding)
4452     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4453   else
4454     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4455 
4456   SDValue Ptr = getValue(PtrOperand);
4457   SDValue Src0 = getValue(Src0Operand);
4458   SDValue Mask = getValue(MaskOperand);
4459   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4460 
4461   EVT VT = Src0.getValueType();
4462   if (!Alignment)
4463     Alignment = DAG.getEVTAlign(VT);
4464 
4465   AAMDNodes AAInfo;
4466   I.getAAMetadata(AAInfo);
4467   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4468 
4469   // Do not serialize masked loads of constant memory with anything.
4470   MemoryLocation ML;
4471   if (VT.isScalableVector())
4472     ML = MemoryLocation::getAfter(PtrOperand);
4473   else
4474     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4475                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4476                            AAInfo);
4477   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4478 
4479   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4480 
4481   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4482       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4483       // TODO: Make MachineMemOperands aware of scalable
4484       // vectors.
4485       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4486 
4487   SDValue Load =
4488       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4489                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4490   if (AddToChain)
4491     PendingLoads.push_back(Load.getValue(1));
4492   setValue(&I, Load);
4493 }
4494 
4495 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4496   SDLoc sdl = getCurSDLoc();
4497 
4498   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4499   const Value *Ptr = I.getArgOperand(0);
4500   SDValue Src0 = getValue(I.getArgOperand(3));
4501   SDValue Mask = getValue(I.getArgOperand(2));
4502 
4503   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4504   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4505   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4506                         ->getMaybeAlignValue()
4507                         .getValueOr(DAG.getEVTAlign(VT));
4508 
4509   AAMDNodes AAInfo;
4510   I.getAAMetadata(AAInfo);
4511   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4512 
4513   SDValue Root = DAG.getRoot();
4514   SDValue Base;
4515   SDValue Index;
4516   ISD::MemIndexType IndexType;
4517   SDValue Scale;
4518   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4519                                     I.getParent());
4520   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4521   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4522       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4523       // TODO: Make MachineMemOperands aware of scalable
4524       // vectors.
4525       MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges);
4526 
4527   if (!UniformBase) {
4528     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4529     Index = getValue(Ptr);
4530     IndexType = ISD::SIGNED_UNSCALED;
4531     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4532   }
4533 
4534   EVT IdxVT = Index.getValueType();
4535   EVT EltTy = IdxVT.getVectorElementType();
4536   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4537     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4538     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4539   }
4540 
4541   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4542   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4543                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4544 
4545   PendingLoads.push_back(Gather.getValue(1));
4546   setValue(&I, Gather);
4547 }
4548 
4549 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4550   SDLoc dl = getCurSDLoc();
4551   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4552   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4553   SyncScope::ID SSID = I.getSyncScopeID();
4554 
4555   SDValue InChain = getRoot();
4556 
4557   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4558   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4559 
4560   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4561   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4562 
4563   MachineFunction &MF = DAG.getMachineFunction();
4564   MachineMemOperand *MMO = MF.getMachineMemOperand(
4565       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4566       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4567       FailureOrdering);
4568 
4569   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4570                                    dl, MemVT, VTs, InChain,
4571                                    getValue(I.getPointerOperand()),
4572                                    getValue(I.getCompareOperand()),
4573                                    getValue(I.getNewValOperand()), MMO);
4574 
4575   SDValue OutChain = L.getValue(2);
4576 
4577   setValue(&I, L);
4578   DAG.setRoot(OutChain);
4579 }
4580 
4581 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4582   SDLoc dl = getCurSDLoc();
4583   ISD::NodeType NT;
4584   switch (I.getOperation()) {
4585   default: llvm_unreachable("Unknown atomicrmw operation");
4586   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4587   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4588   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4589   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4590   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4591   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4592   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4593   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4594   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4595   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4596   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4597   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4598   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4599   }
4600   AtomicOrdering Ordering = I.getOrdering();
4601   SyncScope::ID SSID = I.getSyncScopeID();
4602 
4603   SDValue InChain = getRoot();
4604 
4605   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4606   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4607   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4608 
4609   MachineFunction &MF = DAG.getMachineFunction();
4610   MachineMemOperand *MMO = MF.getMachineMemOperand(
4611       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4612       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4613 
4614   SDValue L =
4615     DAG.getAtomic(NT, dl, MemVT, InChain,
4616                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4617                   MMO);
4618 
4619   SDValue OutChain = L.getValue(1);
4620 
4621   setValue(&I, L);
4622   DAG.setRoot(OutChain);
4623 }
4624 
4625 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4626   SDLoc dl = getCurSDLoc();
4627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4628   SDValue Ops[3];
4629   Ops[0] = getRoot();
4630   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4631                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4632   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4633                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4634   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4635 }
4636 
4637 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4638   SDLoc dl = getCurSDLoc();
4639   AtomicOrdering Order = I.getOrdering();
4640   SyncScope::ID SSID = I.getSyncScopeID();
4641 
4642   SDValue InChain = getRoot();
4643 
4644   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4645   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4646   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4647 
4648   if (!TLI.supportsUnalignedAtomics() &&
4649       I.getAlignment() < MemVT.getSizeInBits() / 8)
4650     report_fatal_error("Cannot generate unaligned atomic load");
4651 
4652   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4653 
4654   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4655       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4656       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4657 
4658   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4659 
4660   SDValue Ptr = getValue(I.getPointerOperand());
4661 
4662   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4663     // TODO: Once this is better exercised by tests, it should be merged with
4664     // the normal path for loads to prevent future divergence.
4665     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4666     if (MemVT != VT)
4667       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4668 
4669     setValue(&I, L);
4670     SDValue OutChain = L.getValue(1);
4671     if (!I.isUnordered())
4672       DAG.setRoot(OutChain);
4673     else
4674       PendingLoads.push_back(OutChain);
4675     return;
4676   }
4677 
4678   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4679                             Ptr, MMO);
4680 
4681   SDValue OutChain = L.getValue(1);
4682   if (MemVT != VT)
4683     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4684 
4685   setValue(&I, L);
4686   DAG.setRoot(OutChain);
4687 }
4688 
4689 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4690   SDLoc dl = getCurSDLoc();
4691 
4692   AtomicOrdering Ordering = I.getOrdering();
4693   SyncScope::ID SSID = I.getSyncScopeID();
4694 
4695   SDValue InChain = getRoot();
4696 
4697   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4698   EVT MemVT =
4699       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4700 
4701   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4702     report_fatal_error("Cannot generate unaligned atomic store");
4703 
4704   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4705 
4706   MachineFunction &MF = DAG.getMachineFunction();
4707   MachineMemOperand *MMO = MF.getMachineMemOperand(
4708       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4709       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4710 
4711   SDValue Val = getValue(I.getValueOperand());
4712   if (Val.getValueType() != MemVT)
4713     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4714   SDValue Ptr = getValue(I.getPointerOperand());
4715 
4716   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4717     // TODO: Once this is better exercised by tests, it should be merged with
4718     // the normal path for stores to prevent future divergence.
4719     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4720     DAG.setRoot(S);
4721     return;
4722   }
4723   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4724                                    Ptr, Val, MMO);
4725 
4726 
4727   DAG.setRoot(OutChain);
4728 }
4729 
4730 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4731 /// node.
4732 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4733                                                unsigned Intrinsic) {
4734   // Ignore the callsite's attributes. A specific call site may be marked with
4735   // readnone, but the lowering code will expect the chain based on the
4736   // definition.
4737   const Function *F = I.getCalledFunction();
4738   bool HasChain = !F->doesNotAccessMemory();
4739   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4740 
4741   // Build the operand list.
4742   SmallVector<SDValue, 8> Ops;
4743   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4744     if (OnlyLoad) {
4745       // We don't need to serialize loads against other loads.
4746       Ops.push_back(DAG.getRoot());
4747     } else {
4748       Ops.push_back(getRoot());
4749     }
4750   }
4751 
4752   // Info is set by getTgtMemInstrinsic
4753   TargetLowering::IntrinsicInfo Info;
4754   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4755   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4756                                                DAG.getMachineFunction(),
4757                                                Intrinsic);
4758 
4759   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4760   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4761       Info.opc == ISD::INTRINSIC_W_CHAIN)
4762     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4763                                         TLI.getPointerTy(DAG.getDataLayout())));
4764 
4765   // Add all operands of the call to the operand list.
4766   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4767     const Value *Arg = I.getArgOperand(i);
4768     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4769       Ops.push_back(getValue(Arg));
4770       continue;
4771     }
4772 
4773     // Use TargetConstant instead of a regular constant for immarg.
4774     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4775     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4776       assert(CI->getBitWidth() <= 64 &&
4777              "large intrinsic immediates not handled");
4778       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4779     } else {
4780       Ops.push_back(
4781           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4782     }
4783   }
4784 
4785   SmallVector<EVT, 4> ValueVTs;
4786   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4787 
4788   if (HasChain)
4789     ValueVTs.push_back(MVT::Other);
4790 
4791   SDVTList VTs = DAG.getVTList(ValueVTs);
4792 
4793   // Create the node.
4794   SDValue Result;
4795   if (IsTgtIntrinsic) {
4796     // This is target intrinsic that touches memory
4797     AAMDNodes AAInfo;
4798     I.getAAMetadata(AAInfo);
4799     Result =
4800         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4801                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4802                                 Info.align, Info.flags, Info.size, AAInfo);
4803   } else if (!HasChain) {
4804     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4805   } else if (!I.getType()->isVoidTy()) {
4806     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4807   } else {
4808     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4809   }
4810 
4811   if (HasChain) {
4812     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4813     if (OnlyLoad)
4814       PendingLoads.push_back(Chain);
4815     else
4816       DAG.setRoot(Chain);
4817   }
4818 
4819   if (!I.getType()->isVoidTy()) {
4820     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4821       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4822       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4823     } else
4824       Result = lowerRangeToAssertZExt(DAG, I, Result);
4825 
4826     MaybeAlign Alignment = I.getRetAlign();
4827     if (!Alignment)
4828       Alignment = F->getAttributes().getRetAlignment();
4829     // Insert `assertalign` node if there's an alignment.
4830     if (InsertAssertAlign && Alignment) {
4831       Result =
4832           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4833     }
4834 
4835     setValue(&I, Result);
4836   }
4837 }
4838 
4839 /// GetSignificand - Get the significand and build it into a floating-point
4840 /// number with exponent of 1:
4841 ///
4842 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4843 ///
4844 /// where Op is the hexadecimal representation of floating point value.
4845 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4846   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4847                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4848   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4849                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4850   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4851 }
4852 
4853 /// GetExponent - Get the exponent:
4854 ///
4855 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4856 ///
4857 /// where Op is the hexadecimal representation of floating point value.
4858 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4859                            const TargetLowering &TLI, const SDLoc &dl) {
4860   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4861                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4862   SDValue t1 = DAG.getNode(
4863       ISD::SRL, dl, MVT::i32, t0,
4864       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4865   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4866                            DAG.getConstant(127, dl, MVT::i32));
4867   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4868 }
4869 
4870 /// getF32Constant - Get 32-bit floating point constant.
4871 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4872                               const SDLoc &dl) {
4873   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4874                            MVT::f32);
4875 }
4876 
4877 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4878                                        SelectionDAG &DAG) {
4879   // TODO: What fast-math-flags should be set on the floating-point nodes?
4880 
4881   //   IntegerPartOfX = ((int32_t)(t0);
4882   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4883 
4884   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4885   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4886   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4887 
4888   //   IntegerPartOfX <<= 23;
4889   IntegerPartOfX = DAG.getNode(
4890       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4891       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4892                                   DAG.getDataLayout())));
4893 
4894   SDValue TwoToFractionalPartOfX;
4895   if (LimitFloatPrecision <= 6) {
4896     // For floating-point precision of 6:
4897     //
4898     //   TwoToFractionalPartOfX =
4899     //     0.997535578f +
4900     //       (0.735607626f + 0.252464424f * x) * x;
4901     //
4902     // error 0.0144103317, which is 6 bits
4903     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4904                              getF32Constant(DAG, 0x3e814304, dl));
4905     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4906                              getF32Constant(DAG, 0x3f3c50c8, dl));
4907     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4908     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4909                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4910   } else if (LimitFloatPrecision <= 12) {
4911     // For floating-point precision of 12:
4912     //
4913     //   TwoToFractionalPartOfX =
4914     //     0.999892986f +
4915     //       (0.696457318f +
4916     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4917     //
4918     // error 0.000107046256, which is 13 to 14 bits
4919     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4920                              getF32Constant(DAG, 0x3da235e3, dl));
4921     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4922                              getF32Constant(DAG, 0x3e65b8f3, dl));
4923     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4924     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4925                              getF32Constant(DAG, 0x3f324b07, dl));
4926     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4927     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4928                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4929   } else { // LimitFloatPrecision <= 18
4930     // For floating-point precision of 18:
4931     //
4932     //   TwoToFractionalPartOfX =
4933     //     0.999999982f +
4934     //       (0.693148872f +
4935     //         (0.240227044f +
4936     //           (0.554906021e-1f +
4937     //             (0.961591928e-2f +
4938     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4939     // error 2.47208000*10^(-7), which is better than 18 bits
4940     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4941                              getF32Constant(DAG, 0x3924b03e, dl));
4942     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4943                              getF32Constant(DAG, 0x3ab24b87, dl));
4944     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4945     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4946                              getF32Constant(DAG, 0x3c1d8c17, dl));
4947     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4948     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4949                              getF32Constant(DAG, 0x3d634a1d, dl));
4950     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4951     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4952                              getF32Constant(DAG, 0x3e75fe14, dl));
4953     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4954     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4955                               getF32Constant(DAG, 0x3f317234, dl));
4956     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4957     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4958                                          getF32Constant(DAG, 0x3f800000, dl));
4959   }
4960 
4961   // Add the exponent into the result in integer domain.
4962   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4963   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4964                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4965 }
4966 
4967 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4968 /// limited-precision mode.
4969 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4970                          const TargetLowering &TLI, SDNodeFlags Flags) {
4971   if (Op.getValueType() == MVT::f32 &&
4972       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4973 
4974     // Put the exponent in the right bit position for later addition to the
4975     // final result:
4976     //
4977     // t0 = Op * log2(e)
4978 
4979     // TODO: What fast-math-flags should be set here?
4980     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4981                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4982     return getLimitedPrecisionExp2(t0, dl, DAG);
4983   }
4984 
4985   // No special expansion.
4986   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
4987 }
4988 
4989 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4990 /// limited-precision mode.
4991 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4992                          const TargetLowering &TLI, SDNodeFlags Flags) {
4993   // TODO: What fast-math-flags should be set on the floating-point nodes?
4994 
4995   if (Op.getValueType() == MVT::f32 &&
4996       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4997     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4998 
4999     // Scale the exponent by log(2).
5000     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5001     SDValue LogOfExponent =
5002         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5003                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5004 
5005     // Get the significand and build it into a floating-point number with
5006     // exponent of 1.
5007     SDValue X = GetSignificand(DAG, Op1, dl);
5008 
5009     SDValue LogOfMantissa;
5010     if (LimitFloatPrecision <= 6) {
5011       // For floating-point precision of 6:
5012       //
5013       //   LogofMantissa =
5014       //     -1.1609546f +
5015       //       (1.4034025f - 0.23903021f * x) * x;
5016       //
5017       // error 0.0034276066, which is better than 8 bits
5018       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5019                                getF32Constant(DAG, 0xbe74c456, dl));
5020       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5021                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5022       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5023       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5024                                   getF32Constant(DAG, 0x3f949a29, dl));
5025     } else if (LimitFloatPrecision <= 12) {
5026       // For floating-point precision of 12:
5027       //
5028       //   LogOfMantissa =
5029       //     -1.7417939f +
5030       //       (2.8212026f +
5031       //         (-1.4699568f +
5032       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5033       //
5034       // error 0.000061011436, which is 14 bits
5035       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5036                                getF32Constant(DAG, 0xbd67b6d6, dl));
5037       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5038                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5039       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5040       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5041                                getF32Constant(DAG, 0x3fbc278b, dl));
5042       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5043       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5044                                getF32Constant(DAG, 0x40348e95, dl));
5045       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5046       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5047                                   getF32Constant(DAG, 0x3fdef31a, dl));
5048     } else { // LimitFloatPrecision <= 18
5049       // For floating-point precision of 18:
5050       //
5051       //   LogOfMantissa =
5052       //     -2.1072184f +
5053       //       (4.2372794f +
5054       //         (-3.7029485f +
5055       //           (2.2781945f +
5056       //             (-0.87823314f +
5057       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5058       //
5059       // error 0.0000023660568, which is better than 18 bits
5060       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5061                                getF32Constant(DAG, 0xbc91e5ac, dl));
5062       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5063                                getF32Constant(DAG, 0x3e4350aa, dl));
5064       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5065       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5066                                getF32Constant(DAG, 0x3f60d3e3, dl));
5067       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5068       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5069                                getF32Constant(DAG, 0x4011cdf0, dl));
5070       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5071       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5072                                getF32Constant(DAG, 0x406cfd1c, dl));
5073       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5074       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5075                                getF32Constant(DAG, 0x408797cb, dl));
5076       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5077       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5078                                   getF32Constant(DAG, 0x4006dcab, dl));
5079     }
5080 
5081     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5082   }
5083 
5084   // No special expansion.
5085   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5086 }
5087 
5088 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5089 /// limited-precision mode.
5090 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5091                           const TargetLowering &TLI, SDNodeFlags Flags) {
5092   // TODO: What fast-math-flags should be set on the floating-point nodes?
5093 
5094   if (Op.getValueType() == MVT::f32 &&
5095       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5096     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5097 
5098     // Get the exponent.
5099     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5100 
5101     // Get the significand and build it into a floating-point number with
5102     // exponent of 1.
5103     SDValue X = GetSignificand(DAG, Op1, dl);
5104 
5105     // Different possible minimax approximations of significand in
5106     // floating-point for various degrees of accuracy over [1,2].
5107     SDValue Log2ofMantissa;
5108     if (LimitFloatPrecision <= 6) {
5109       // For floating-point precision of 6:
5110       //
5111       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5112       //
5113       // error 0.0049451742, which is more than 7 bits
5114       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5115                                getF32Constant(DAG, 0xbeb08fe0, dl));
5116       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5117                                getF32Constant(DAG, 0x40019463, dl));
5118       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5119       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5120                                    getF32Constant(DAG, 0x3fd6633d, dl));
5121     } else if (LimitFloatPrecision <= 12) {
5122       // For floating-point precision of 12:
5123       //
5124       //   Log2ofMantissa =
5125       //     -2.51285454f +
5126       //       (4.07009056f +
5127       //         (-2.12067489f +
5128       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5129       //
5130       // error 0.0000876136000, which is better than 13 bits
5131       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5132                                getF32Constant(DAG, 0xbda7262e, dl));
5133       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5134                                getF32Constant(DAG, 0x3f25280b, dl));
5135       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5136       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5137                                getF32Constant(DAG, 0x4007b923, dl));
5138       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5139       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5140                                getF32Constant(DAG, 0x40823e2f, dl));
5141       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5142       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5143                                    getF32Constant(DAG, 0x4020d29c, dl));
5144     } else { // LimitFloatPrecision <= 18
5145       // For floating-point precision of 18:
5146       //
5147       //   Log2ofMantissa =
5148       //     -3.0400495f +
5149       //       (6.1129976f +
5150       //         (-5.3420409f +
5151       //           (3.2865683f +
5152       //             (-1.2669343f +
5153       //               (0.27515199f -
5154       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5155       //
5156       // error 0.0000018516, which is better than 18 bits
5157       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5158                                getF32Constant(DAG, 0xbcd2769e, dl));
5159       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5160                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5161       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5162       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5163                                getF32Constant(DAG, 0x3fa22ae7, dl));
5164       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5165       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5166                                getF32Constant(DAG, 0x40525723, dl));
5167       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5168       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5169                                getF32Constant(DAG, 0x40aaf200, dl));
5170       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5171       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5172                                getF32Constant(DAG, 0x40c39dad, dl));
5173       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5174       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5175                                    getF32Constant(DAG, 0x4042902c, dl));
5176     }
5177 
5178     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5179   }
5180 
5181   // No special expansion.
5182   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5183 }
5184 
5185 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5186 /// limited-precision mode.
5187 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5188                            const TargetLowering &TLI, SDNodeFlags Flags) {
5189   // TODO: What fast-math-flags should be set on the floating-point nodes?
5190 
5191   if (Op.getValueType() == MVT::f32 &&
5192       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5193     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5194 
5195     // Scale the exponent by log10(2) [0.30102999f].
5196     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5197     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5198                                         getF32Constant(DAG, 0x3e9a209a, dl));
5199 
5200     // Get the significand and build it into a floating-point number with
5201     // exponent of 1.
5202     SDValue X = GetSignificand(DAG, Op1, dl);
5203 
5204     SDValue Log10ofMantissa;
5205     if (LimitFloatPrecision <= 6) {
5206       // For floating-point precision of 6:
5207       //
5208       //   Log10ofMantissa =
5209       //     -0.50419619f +
5210       //       (0.60948995f - 0.10380950f * x) * x;
5211       //
5212       // error 0.0014886165, which is 6 bits
5213       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5214                                getF32Constant(DAG, 0xbdd49a13, dl));
5215       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5216                                getF32Constant(DAG, 0x3f1c0789, dl));
5217       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5218       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5219                                     getF32Constant(DAG, 0x3f011300, dl));
5220     } else if (LimitFloatPrecision <= 12) {
5221       // For floating-point precision of 12:
5222       //
5223       //   Log10ofMantissa =
5224       //     -0.64831180f +
5225       //       (0.91751397f +
5226       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5227       //
5228       // error 0.00019228036, which is better than 12 bits
5229       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5230                                getF32Constant(DAG, 0x3d431f31, dl));
5231       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5232                                getF32Constant(DAG, 0x3ea21fb2, dl));
5233       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5234       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5235                                getF32Constant(DAG, 0x3f6ae232, dl));
5236       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5237       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5238                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5239     } else { // LimitFloatPrecision <= 18
5240       // For floating-point precision of 18:
5241       //
5242       //   Log10ofMantissa =
5243       //     -0.84299375f +
5244       //       (1.5327582f +
5245       //         (-1.0688956f +
5246       //           (0.49102474f +
5247       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5248       //
5249       // error 0.0000037995730, which is better than 18 bits
5250       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5251                                getF32Constant(DAG, 0x3c5d51ce, dl));
5252       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5253                                getF32Constant(DAG, 0x3e00685a, dl));
5254       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5255       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5256                                getF32Constant(DAG, 0x3efb6798, dl));
5257       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5258       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5259                                getF32Constant(DAG, 0x3f88d192, dl));
5260       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5261       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5262                                getF32Constant(DAG, 0x3fc4316c, dl));
5263       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5264       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5265                                     getF32Constant(DAG, 0x3f57ce70, dl));
5266     }
5267 
5268     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5269   }
5270 
5271   // No special expansion.
5272   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5273 }
5274 
5275 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5276 /// limited-precision mode.
5277 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5278                           const TargetLowering &TLI, SDNodeFlags Flags) {
5279   if (Op.getValueType() == MVT::f32 &&
5280       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5281     return getLimitedPrecisionExp2(Op, dl, DAG);
5282 
5283   // No special expansion.
5284   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5285 }
5286 
5287 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5288 /// limited-precision mode with x == 10.0f.
5289 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5290                          SelectionDAG &DAG, const TargetLowering &TLI,
5291                          SDNodeFlags Flags) {
5292   bool IsExp10 = false;
5293   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5294       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5295     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5296       APFloat Ten(10.0f);
5297       IsExp10 = LHSC->isExactlyValue(Ten);
5298     }
5299   }
5300 
5301   // TODO: What fast-math-flags should be set on the FMUL node?
5302   if (IsExp10) {
5303     // Put the exponent in the right bit position for later addition to the
5304     // final result:
5305     //
5306     //   #define LOG2OF10 3.3219281f
5307     //   t0 = Op * LOG2OF10;
5308     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5309                              getF32Constant(DAG, 0x40549a78, dl));
5310     return getLimitedPrecisionExp2(t0, dl, DAG);
5311   }
5312 
5313   // No special expansion.
5314   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5315 }
5316 
5317 /// ExpandPowI - Expand a llvm.powi intrinsic.
5318 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5319                           SelectionDAG &DAG) {
5320   // If RHS is a constant, we can expand this out to a multiplication tree,
5321   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5322   // optimizing for size, we only want to do this if the expansion would produce
5323   // a small number of multiplies, otherwise we do the full expansion.
5324   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5325     // Get the exponent as a positive value.
5326     unsigned Val = RHSC->getSExtValue();
5327     if ((int)Val < 0) Val = -Val;
5328 
5329     // powi(x, 0) -> 1.0
5330     if (Val == 0)
5331       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5332 
5333     bool OptForSize = DAG.shouldOptForSize();
5334     if (!OptForSize ||
5335         // If optimizing for size, don't insert too many multiplies.
5336         // This inserts up to 5 multiplies.
5337         countPopulation(Val) + Log2_32(Val) < 7) {
5338       // We use the simple binary decomposition method to generate the multiply
5339       // sequence.  There are more optimal ways to do this (for example,
5340       // powi(x,15) generates one more multiply than it should), but this has
5341       // the benefit of being both really simple and much better than a libcall.
5342       SDValue Res;  // Logically starts equal to 1.0
5343       SDValue CurSquare = LHS;
5344       // TODO: Intrinsics should have fast-math-flags that propagate to these
5345       // nodes.
5346       while (Val) {
5347         if (Val & 1) {
5348           if (Res.getNode())
5349             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5350           else
5351             Res = CurSquare;  // 1.0*CurSquare.
5352         }
5353 
5354         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5355                                 CurSquare, CurSquare);
5356         Val >>= 1;
5357       }
5358 
5359       // If the original was negative, invert the result, producing 1/(x*x*x).
5360       if (RHSC->getSExtValue() < 0)
5361         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5362                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5363       return Res;
5364     }
5365   }
5366 
5367   // Otherwise, expand to a libcall.
5368   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5369 }
5370 
5371 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5372                             SDValue LHS, SDValue RHS, SDValue Scale,
5373                             SelectionDAG &DAG, const TargetLowering &TLI) {
5374   EVT VT = LHS.getValueType();
5375   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5376   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5377   LLVMContext &Ctx = *DAG.getContext();
5378 
5379   // If the type is legal but the operation isn't, this node might survive all
5380   // the way to operation legalization. If we end up there and we do not have
5381   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5382   // node.
5383 
5384   // Coax the legalizer into expanding the node during type legalization instead
5385   // by bumping the size by one bit. This will force it to Promote, enabling the
5386   // early expansion and avoiding the need to expand later.
5387 
5388   // We don't have to do this if Scale is 0; that can always be expanded, unless
5389   // it's a saturating signed operation. Those can experience true integer
5390   // division overflow, a case which we must avoid.
5391 
5392   // FIXME: We wouldn't have to do this (or any of the early
5393   // expansion/promotion) if it was possible to expand a libcall of an
5394   // illegal type during operation legalization. But it's not, so things
5395   // get a bit hacky.
5396   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5397   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5398       (TLI.isTypeLegal(VT) ||
5399        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5400     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5401         Opcode, VT, ScaleInt);
5402     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5403       EVT PromVT;
5404       if (VT.isScalarInteger())
5405         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5406       else if (VT.isVector()) {
5407         PromVT = VT.getVectorElementType();
5408         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5409         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5410       } else
5411         llvm_unreachable("Wrong VT for DIVFIX?");
5412       if (Signed) {
5413         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5414         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5415       } else {
5416         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5417         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5418       }
5419       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5420       // For saturating operations, we need to shift up the LHS to get the
5421       // proper saturation width, and then shift down again afterwards.
5422       if (Saturating)
5423         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5424                           DAG.getConstant(1, DL, ShiftTy));
5425       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5426       if (Saturating)
5427         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5428                           DAG.getConstant(1, DL, ShiftTy));
5429       return DAG.getZExtOrTrunc(Res, DL, VT);
5430     }
5431   }
5432 
5433   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5434 }
5435 
5436 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5437 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5438 static void
5439 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5440                      const SDValue &N) {
5441   switch (N.getOpcode()) {
5442   case ISD::CopyFromReg: {
5443     SDValue Op = N.getOperand(1);
5444     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5445                       Op.getValueType().getSizeInBits());
5446     return;
5447   }
5448   case ISD::BITCAST:
5449   case ISD::AssertZext:
5450   case ISD::AssertSext:
5451   case ISD::TRUNCATE:
5452     getUnderlyingArgRegs(Regs, N.getOperand(0));
5453     return;
5454   case ISD::BUILD_PAIR:
5455   case ISD::BUILD_VECTOR:
5456   case ISD::CONCAT_VECTORS:
5457     for (SDValue Op : N->op_values())
5458       getUnderlyingArgRegs(Regs, Op);
5459     return;
5460   default:
5461     return;
5462   }
5463 }
5464 
5465 /// If the DbgValueInst is a dbg_value of a function argument, create the
5466 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5467 /// instruction selection, they will be inserted to the entry BB.
5468 /// We don't currently support this for variadic dbg_values, as they shouldn't
5469 /// appear for function arguments or in the prologue.
5470 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5471     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5472     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5473   const Argument *Arg = dyn_cast<Argument>(V);
5474   if (!Arg)
5475     return false;
5476 
5477   if (!IsDbgDeclare) {
5478     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5479     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5480     // the entry block.
5481     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5482     if (!IsInEntryBlock)
5483       return false;
5484 
5485     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5486     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5487     // variable that also is a param.
5488     //
5489     // Although, if we are at the top of the entry block already, we can still
5490     // emit using ArgDbgValue. This might catch some situations when the
5491     // dbg.value refers to an argument that isn't used in the entry block, so
5492     // any CopyToReg node would be optimized out and the only way to express
5493     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5494     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5495     // we should only emit as ArgDbgValue if the Variable is an argument to the
5496     // current function, and the dbg.value intrinsic is found in the entry
5497     // block.
5498     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5499         !DL->getInlinedAt();
5500     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5501     if (!IsInPrologue && !VariableIsFunctionInputArg)
5502       return false;
5503 
5504     // Here we assume that a function argument on IR level only can be used to
5505     // describe one input parameter on source level. If we for example have
5506     // source code like this
5507     //
5508     //    struct A { long x, y; };
5509     //    void foo(struct A a, long b) {
5510     //      ...
5511     //      b = a.x;
5512     //      ...
5513     //    }
5514     //
5515     // and IR like this
5516     //
5517     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5518     //  entry:
5519     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5520     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5521     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5522     //    ...
5523     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5524     //    ...
5525     //
5526     // then the last dbg.value is describing a parameter "b" using a value that
5527     // is an argument. But since we already has used %a1 to describe a parameter
5528     // we should not handle that last dbg.value here (that would result in an
5529     // incorrect hoisting of the DBG_VALUE to the function entry).
5530     // Notice that we allow one dbg.value per IR level argument, to accommodate
5531     // for the situation with fragments above.
5532     if (VariableIsFunctionInputArg) {
5533       unsigned ArgNo = Arg->getArgNo();
5534       if (ArgNo >= FuncInfo.DescribedArgs.size())
5535         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5536       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5537         return false;
5538       FuncInfo.DescribedArgs.set(ArgNo);
5539     }
5540   }
5541 
5542   MachineFunction &MF = DAG.getMachineFunction();
5543   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5544 
5545   bool IsIndirect = false;
5546   Optional<MachineOperand> Op;
5547   // Some arguments' frame index is recorded during argument lowering.
5548   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5549   if (FI != std::numeric_limits<int>::max())
5550     Op = MachineOperand::CreateFI(FI);
5551 
5552   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5553   if (!Op && N.getNode()) {
5554     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5555     Register Reg;
5556     if (ArgRegsAndSizes.size() == 1)
5557       Reg = ArgRegsAndSizes.front().first;
5558 
5559     if (Reg && Reg.isVirtual()) {
5560       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5561       Register PR = RegInfo.getLiveInPhysReg(Reg);
5562       if (PR)
5563         Reg = PR;
5564     }
5565     if (Reg) {
5566       Op = MachineOperand::CreateReg(Reg, false);
5567       IsIndirect = IsDbgDeclare;
5568     }
5569   }
5570 
5571   if (!Op && N.getNode()) {
5572     // Check if frame index is available.
5573     SDValue LCandidate = peekThroughBitcasts(N);
5574     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5575       if (FrameIndexSDNode *FINode =
5576           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5577         Op = MachineOperand::CreateFI(FINode->getIndex());
5578   }
5579 
5580   if (!Op) {
5581     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5582     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5583                                          SplitRegs) {
5584       unsigned Offset = 0;
5585       for (auto RegAndSize : SplitRegs) {
5586         // If the expression is already a fragment, the current register
5587         // offset+size might extend beyond the fragment. In this case, only
5588         // the register bits that are inside the fragment are relevant.
5589         int RegFragmentSizeInBits = RegAndSize.second;
5590         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5591           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5592           // The register is entirely outside the expression fragment,
5593           // so is irrelevant for debug info.
5594           if (Offset >= ExprFragmentSizeInBits)
5595             break;
5596           // The register is partially outside the expression fragment, only
5597           // the low bits within the fragment are relevant for debug info.
5598           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5599             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5600           }
5601         }
5602 
5603         auto FragmentExpr = DIExpression::createFragmentExpression(
5604             Expr, Offset, RegFragmentSizeInBits);
5605         Offset += RegAndSize.second;
5606         // If a valid fragment expression cannot be created, the variable's
5607         // correct value cannot be determined and so it is set as Undef.
5608         if (!FragmentExpr) {
5609           SDDbgValue *SDV = DAG.getConstantDbgValue(
5610               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5611           DAG.AddDbgValue(SDV, false);
5612           continue;
5613         }
5614         FuncInfo.ArgDbgValues.push_back(
5615           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5616                   RegAndSize.first, Variable, *FragmentExpr));
5617       }
5618     };
5619 
5620     // Check if ValueMap has reg number.
5621     DenseMap<const Value *, Register>::const_iterator
5622       VMI = FuncInfo.ValueMap.find(V);
5623     if (VMI != FuncInfo.ValueMap.end()) {
5624       const auto &TLI = DAG.getTargetLoweringInfo();
5625       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5626                        V->getType(), None);
5627       if (RFV.occupiesMultipleRegs()) {
5628         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5629         return true;
5630       }
5631 
5632       Op = MachineOperand::CreateReg(VMI->second, false);
5633       IsIndirect = IsDbgDeclare;
5634     } else if (ArgRegsAndSizes.size() > 1) {
5635       // This was split due to the calling convention, and no virtual register
5636       // mapping exists for the value.
5637       splitMultiRegDbgValue(ArgRegsAndSizes);
5638       return true;
5639     }
5640   }
5641 
5642   if (!Op)
5643     return false;
5644 
5645   assert(Variable->isValidLocationForIntrinsic(DL) &&
5646          "Expected inlined-at fields to agree");
5647   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5648   FuncInfo.ArgDbgValues.push_back(
5649       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5650               *Op, Variable, Expr));
5651 
5652   return true;
5653 }
5654 
5655 /// Return the appropriate SDDbgValue based on N.
5656 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5657                                              DILocalVariable *Variable,
5658                                              DIExpression *Expr,
5659                                              const DebugLoc &dl,
5660                                              unsigned DbgSDNodeOrder) {
5661   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5662     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5663     // stack slot locations.
5664     //
5665     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5666     // debug values here after optimization:
5667     //
5668     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5669     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5670     //
5671     // Both describe the direct values of their associated variables.
5672     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5673                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5674   }
5675   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5676                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5677 }
5678 
5679 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5680   switch (Intrinsic) {
5681   case Intrinsic::smul_fix:
5682     return ISD::SMULFIX;
5683   case Intrinsic::umul_fix:
5684     return ISD::UMULFIX;
5685   case Intrinsic::smul_fix_sat:
5686     return ISD::SMULFIXSAT;
5687   case Intrinsic::umul_fix_sat:
5688     return ISD::UMULFIXSAT;
5689   case Intrinsic::sdiv_fix:
5690     return ISD::SDIVFIX;
5691   case Intrinsic::udiv_fix:
5692     return ISD::UDIVFIX;
5693   case Intrinsic::sdiv_fix_sat:
5694     return ISD::SDIVFIXSAT;
5695   case Intrinsic::udiv_fix_sat:
5696     return ISD::UDIVFIXSAT;
5697   default:
5698     llvm_unreachable("Unhandled fixed point intrinsic");
5699   }
5700 }
5701 
5702 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5703                                            const char *FunctionName) {
5704   assert(FunctionName && "FunctionName must not be nullptr");
5705   SDValue Callee = DAG.getExternalSymbol(
5706       FunctionName,
5707       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5708   LowerCallTo(I, Callee, I.isTailCall());
5709 }
5710 
5711 /// Given a @llvm.call.preallocated.setup, return the corresponding
5712 /// preallocated call.
5713 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5714   assert(cast<CallBase>(PreallocatedSetup)
5715                  ->getCalledFunction()
5716                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5717          "expected call_preallocated_setup Value");
5718   for (auto *U : PreallocatedSetup->users()) {
5719     auto *UseCall = cast<CallBase>(U);
5720     const Function *Fn = UseCall->getCalledFunction();
5721     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5722       return UseCall;
5723     }
5724   }
5725   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5726 }
5727 
5728 /// Lower the call to the specified intrinsic function.
5729 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5730                                              unsigned Intrinsic) {
5731   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5732   SDLoc sdl = getCurSDLoc();
5733   DebugLoc dl = getCurDebugLoc();
5734   SDValue Res;
5735 
5736   SDNodeFlags Flags;
5737   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5738     Flags.copyFMF(*FPOp);
5739 
5740   switch (Intrinsic) {
5741   default:
5742     // By default, turn this into a target intrinsic node.
5743     visitTargetIntrinsic(I, Intrinsic);
5744     return;
5745   case Intrinsic::vscale: {
5746     match(&I, m_VScale(DAG.getDataLayout()));
5747     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5748     setValue(&I,
5749              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5750     return;
5751   }
5752   case Intrinsic::vastart:  visitVAStart(I); return;
5753   case Intrinsic::vaend:    visitVAEnd(I); return;
5754   case Intrinsic::vacopy:   visitVACopy(I); return;
5755   case Intrinsic::returnaddress:
5756     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5757                              TLI.getPointerTy(DAG.getDataLayout()),
5758                              getValue(I.getArgOperand(0))));
5759     return;
5760   case Intrinsic::addressofreturnaddress:
5761     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5762                              TLI.getPointerTy(DAG.getDataLayout())));
5763     return;
5764   case Intrinsic::sponentry:
5765     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5766                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5767     return;
5768   case Intrinsic::frameaddress:
5769     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5770                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5771                              getValue(I.getArgOperand(0))));
5772     return;
5773   case Intrinsic::read_volatile_register:
5774   case Intrinsic::read_register: {
5775     Value *Reg = I.getArgOperand(0);
5776     SDValue Chain = getRoot();
5777     SDValue RegName =
5778         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5779     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5780     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5781       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5782     setValue(&I, Res);
5783     DAG.setRoot(Res.getValue(1));
5784     return;
5785   }
5786   case Intrinsic::write_register: {
5787     Value *Reg = I.getArgOperand(0);
5788     Value *RegValue = I.getArgOperand(1);
5789     SDValue Chain = getRoot();
5790     SDValue RegName =
5791         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5792     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5793                             RegName, getValue(RegValue)));
5794     return;
5795   }
5796   case Intrinsic::memcpy: {
5797     const auto &MCI = cast<MemCpyInst>(I);
5798     SDValue Op1 = getValue(I.getArgOperand(0));
5799     SDValue Op2 = getValue(I.getArgOperand(1));
5800     SDValue Op3 = getValue(I.getArgOperand(2));
5801     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5802     Align DstAlign = MCI.getDestAlign().valueOrOne();
5803     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5804     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5805     bool isVol = MCI.isVolatile();
5806     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5807     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5808     // node.
5809     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5810     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5811                                /* AlwaysInline */ false, isTC,
5812                                MachinePointerInfo(I.getArgOperand(0)),
5813                                MachinePointerInfo(I.getArgOperand(1)));
5814     updateDAGForMaybeTailCall(MC);
5815     return;
5816   }
5817   case Intrinsic::memcpy_inline: {
5818     const auto &MCI = cast<MemCpyInlineInst>(I);
5819     SDValue Dst = getValue(I.getArgOperand(0));
5820     SDValue Src = getValue(I.getArgOperand(1));
5821     SDValue Size = getValue(I.getArgOperand(2));
5822     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5823     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5824     Align DstAlign = MCI.getDestAlign().valueOrOne();
5825     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5826     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5827     bool isVol = MCI.isVolatile();
5828     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5829     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5830     // node.
5831     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5832                                /* AlwaysInline */ true, isTC,
5833                                MachinePointerInfo(I.getArgOperand(0)),
5834                                MachinePointerInfo(I.getArgOperand(1)));
5835     updateDAGForMaybeTailCall(MC);
5836     return;
5837   }
5838   case Intrinsic::memset: {
5839     const auto &MSI = cast<MemSetInst>(I);
5840     SDValue Op1 = getValue(I.getArgOperand(0));
5841     SDValue Op2 = getValue(I.getArgOperand(1));
5842     SDValue Op3 = getValue(I.getArgOperand(2));
5843     // @llvm.memset defines 0 and 1 to both mean no alignment.
5844     Align Alignment = MSI.getDestAlign().valueOrOne();
5845     bool isVol = MSI.isVolatile();
5846     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5847     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5848     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5849                                MachinePointerInfo(I.getArgOperand(0)));
5850     updateDAGForMaybeTailCall(MS);
5851     return;
5852   }
5853   case Intrinsic::memmove: {
5854     const auto &MMI = cast<MemMoveInst>(I);
5855     SDValue Op1 = getValue(I.getArgOperand(0));
5856     SDValue Op2 = getValue(I.getArgOperand(1));
5857     SDValue Op3 = getValue(I.getArgOperand(2));
5858     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5859     Align DstAlign = MMI.getDestAlign().valueOrOne();
5860     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5861     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5862     bool isVol = MMI.isVolatile();
5863     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5864     // FIXME: Support passing different dest/src alignments to the memmove DAG
5865     // node.
5866     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5867     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5868                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5869                                 MachinePointerInfo(I.getArgOperand(1)));
5870     updateDAGForMaybeTailCall(MM);
5871     return;
5872   }
5873   case Intrinsic::memcpy_element_unordered_atomic: {
5874     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5875     SDValue Dst = getValue(MI.getRawDest());
5876     SDValue Src = getValue(MI.getRawSource());
5877     SDValue Length = getValue(MI.getLength());
5878 
5879     unsigned DstAlign = MI.getDestAlignment();
5880     unsigned SrcAlign = MI.getSourceAlignment();
5881     Type *LengthTy = MI.getLength()->getType();
5882     unsigned ElemSz = MI.getElementSizeInBytes();
5883     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5884     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5885                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5886                                      MachinePointerInfo(MI.getRawDest()),
5887                                      MachinePointerInfo(MI.getRawSource()));
5888     updateDAGForMaybeTailCall(MC);
5889     return;
5890   }
5891   case Intrinsic::memmove_element_unordered_atomic: {
5892     auto &MI = cast<AtomicMemMoveInst>(I);
5893     SDValue Dst = getValue(MI.getRawDest());
5894     SDValue Src = getValue(MI.getRawSource());
5895     SDValue Length = getValue(MI.getLength());
5896 
5897     unsigned DstAlign = MI.getDestAlignment();
5898     unsigned SrcAlign = MI.getSourceAlignment();
5899     Type *LengthTy = MI.getLength()->getType();
5900     unsigned ElemSz = MI.getElementSizeInBytes();
5901     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5902     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5903                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5904                                       MachinePointerInfo(MI.getRawDest()),
5905                                       MachinePointerInfo(MI.getRawSource()));
5906     updateDAGForMaybeTailCall(MC);
5907     return;
5908   }
5909   case Intrinsic::memset_element_unordered_atomic: {
5910     auto &MI = cast<AtomicMemSetInst>(I);
5911     SDValue Dst = getValue(MI.getRawDest());
5912     SDValue Val = getValue(MI.getValue());
5913     SDValue Length = getValue(MI.getLength());
5914 
5915     unsigned DstAlign = MI.getDestAlignment();
5916     Type *LengthTy = MI.getLength()->getType();
5917     unsigned ElemSz = MI.getElementSizeInBytes();
5918     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5919     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5920                                      LengthTy, ElemSz, isTC,
5921                                      MachinePointerInfo(MI.getRawDest()));
5922     updateDAGForMaybeTailCall(MC);
5923     return;
5924   }
5925   case Intrinsic::call_preallocated_setup: {
5926     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5927     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5928     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5929                               getRoot(), SrcValue);
5930     setValue(&I, Res);
5931     DAG.setRoot(Res);
5932     return;
5933   }
5934   case Intrinsic::call_preallocated_arg: {
5935     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5936     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5937     SDValue Ops[3];
5938     Ops[0] = getRoot();
5939     Ops[1] = SrcValue;
5940     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5941                                    MVT::i32); // arg index
5942     SDValue Res = DAG.getNode(
5943         ISD::PREALLOCATED_ARG, sdl,
5944         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5945     setValue(&I, Res);
5946     DAG.setRoot(Res.getValue(1));
5947     return;
5948   }
5949   case Intrinsic::dbg_addr:
5950   case Intrinsic::dbg_declare: {
5951     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
5952     // they are non-variadic.
5953     const auto &DI = cast<DbgVariableIntrinsic>(I);
5954     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
5955     DILocalVariable *Variable = DI.getVariable();
5956     DIExpression *Expression = DI.getExpression();
5957     dropDanglingDebugInfo(Variable, Expression);
5958     assert(Variable && "Missing variable");
5959     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5960                       << "\n");
5961     // Check if address has undef value.
5962     const Value *Address = DI.getVariableLocationOp(0);
5963     if (!Address || isa<UndefValue>(Address) ||
5964         (Address->use_empty() && !isa<Argument>(Address))) {
5965       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5966                         << " (bad/undef/unused-arg address)\n");
5967       return;
5968     }
5969 
5970     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5971 
5972     // Check if this variable can be described by a frame index, typically
5973     // either as a static alloca or a byval parameter.
5974     int FI = std::numeric_limits<int>::max();
5975     if (const auto *AI =
5976             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5977       if (AI->isStaticAlloca()) {
5978         auto I = FuncInfo.StaticAllocaMap.find(AI);
5979         if (I != FuncInfo.StaticAllocaMap.end())
5980           FI = I->second;
5981       }
5982     } else if (const auto *Arg = dyn_cast<Argument>(
5983                    Address->stripInBoundsConstantOffsets())) {
5984       FI = FuncInfo.getArgumentFrameIndex(Arg);
5985     }
5986 
5987     // llvm.dbg.addr is control dependent and always generates indirect
5988     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5989     // the MachineFunction variable table.
5990     if (FI != std::numeric_limits<int>::max()) {
5991       if (Intrinsic == Intrinsic::dbg_addr) {
5992         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5993             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
5994             dl, SDNodeOrder);
5995         DAG.AddDbgValue(SDV, isParameter);
5996       } else {
5997         LLVM_DEBUG(dbgs() << "Skipping " << DI
5998                           << " (variable info stashed in MF side table)\n");
5999       }
6000       return;
6001     }
6002 
6003     SDValue &N = NodeMap[Address];
6004     if (!N.getNode() && isa<Argument>(Address))
6005       // Check unused arguments map.
6006       N = UnusedArgNodeMap[Address];
6007     SDDbgValue *SDV;
6008     if (N.getNode()) {
6009       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6010         Address = BCI->getOperand(0);
6011       // Parameters are handled specially.
6012       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6013       if (isParameter && FINode) {
6014         // Byval parameter. We have a frame index at this point.
6015         SDV =
6016             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6017                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6018       } else if (isa<Argument>(Address)) {
6019         // Address is an argument, so try to emit its dbg value using
6020         // virtual register info from the FuncInfo.ValueMap.
6021         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6022         return;
6023       } else {
6024         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6025                               true, dl, SDNodeOrder);
6026       }
6027       DAG.AddDbgValue(SDV, isParameter);
6028     } else {
6029       // If Address is an argument then try to emit its dbg value using
6030       // virtual register info from the FuncInfo.ValueMap.
6031       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6032                                     N)) {
6033         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6034                           << " (could not emit func-arg dbg_value)\n");
6035       }
6036     }
6037     return;
6038   }
6039   case Intrinsic::dbg_label: {
6040     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6041     DILabel *Label = DI.getLabel();
6042     assert(Label && "Missing label");
6043 
6044     SDDbgLabel *SDV;
6045     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6046     DAG.AddDbgLabel(SDV);
6047     return;
6048   }
6049   case Intrinsic::dbg_value: {
6050     const DbgValueInst &DI = cast<DbgValueInst>(I);
6051     assert(DI.getVariable() && "Missing variable");
6052 
6053     DILocalVariable *Variable = DI.getVariable();
6054     DIExpression *Expression = DI.getExpression();
6055     dropDanglingDebugInfo(Variable, Expression);
6056     SmallVector<Value *, 4> Values(DI.getValues());
6057     if (Values.empty())
6058       return;
6059 
6060     if (std::count(Values.begin(), Values.end(), nullptr))
6061       return;
6062 
6063     bool IsVariadic = DI.hasArgList();
6064     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6065                           SDNodeOrder, IsVariadic))
6066       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6067     return;
6068   }
6069 
6070   case Intrinsic::eh_typeid_for: {
6071     // Find the type id for the given typeinfo.
6072     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6073     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6074     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6075     setValue(&I, Res);
6076     return;
6077   }
6078 
6079   case Intrinsic::eh_return_i32:
6080   case Intrinsic::eh_return_i64:
6081     DAG.getMachineFunction().setCallsEHReturn(true);
6082     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6083                             MVT::Other,
6084                             getControlRoot(),
6085                             getValue(I.getArgOperand(0)),
6086                             getValue(I.getArgOperand(1))));
6087     return;
6088   case Intrinsic::eh_unwind_init:
6089     DAG.getMachineFunction().setCallsUnwindInit(true);
6090     return;
6091   case Intrinsic::eh_dwarf_cfa:
6092     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6093                              TLI.getPointerTy(DAG.getDataLayout()),
6094                              getValue(I.getArgOperand(0))));
6095     return;
6096   case Intrinsic::eh_sjlj_callsite: {
6097     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6098     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6099     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6100     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6101 
6102     MMI.setCurrentCallSite(CI->getZExtValue());
6103     return;
6104   }
6105   case Intrinsic::eh_sjlj_functioncontext: {
6106     // Get and store the index of the function context.
6107     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6108     AllocaInst *FnCtx =
6109       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6110     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6111     MFI.setFunctionContextIndex(FI);
6112     return;
6113   }
6114   case Intrinsic::eh_sjlj_setjmp: {
6115     SDValue Ops[2];
6116     Ops[0] = getRoot();
6117     Ops[1] = getValue(I.getArgOperand(0));
6118     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6119                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6120     setValue(&I, Op.getValue(0));
6121     DAG.setRoot(Op.getValue(1));
6122     return;
6123   }
6124   case Intrinsic::eh_sjlj_longjmp:
6125     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6126                             getRoot(), getValue(I.getArgOperand(0))));
6127     return;
6128   case Intrinsic::eh_sjlj_setup_dispatch:
6129     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6130                             getRoot()));
6131     return;
6132   case Intrinsic::masked_gather:
6133     visitMaskedGather(I);
6134     return;
6135   case Intrinsic::masked_load:
6136     visitMaskedLoad(I);
6137     return;
6138   case Intrinsic::masked_scatter:
6139     visitMaskedScatter(I);
6140     return;
6141   case Intrinsic::masked_store:
6142     visitMaskedStore(I);
6143     return;
6144   case Intrinsic::masked_expandload:
6145     visitMaskedLoad(I, true /* IsExpanding */);
6146     return;
6147   case Intrinsic::masked_compressstore:
6148     visitMaskedStore(I, true /* IsCompressing */);
6149     return;
6150   case Intrinsic::powi:
6151     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6152                             getValue(I.getArgOperand(1)), DAG));
6153     return;
6154   case Intrinsic::log:
6155     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6156     return;
6157   case Intrinsic::log2:
6158     setValue(&I,
6159              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6160     return;
6161   case Intrinsic::log10:
6162     setValue(&I,
6163              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6164     return;
6165   case Intrinsic::exp:
6166     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6167     return;
6168   case Intrinsic::exp2:
6169     setValue(&I,
6170              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6171     return;
6172   case Intrinsic::pow:
6173     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6174                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6175     return;
6176   case Intrinsic::sqrt:
6177   case Intrinsic::fabs:
6178   case Intrinsic::sin:
6179   case Intrinsic::cos:
6180   case Intrinsic::floor:
6181   case Intrinsic::ceil:
6182   case Intrinsic::trunc:
6183   case Intrinsic::rint:
6184   case Intrinsic::nearbyint:
6185   case Intrinsic::round:
6186   case Intrinsic::roundeven:
6187   case Intrinsic::canonicalize: {
6188     unsigned Opcode;
6189     switch (Intrinsic) {
6190     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6191     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6192     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6193     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6194     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6195     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6196     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6197     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6198     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6199     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6200     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6201     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6202     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6203     }
6204 
6205     setValue(&I, DAG.getNode(Opcode, sdl,
6206                              getValue(I.getArgOperand(0)).getValueType(),
6207                              getValue(I.getArgOperand(0)), Flags));
6208     return;
6209   }
6210   case Intrinsic::lround:
6211   case Intrinsic::llround:
6212   case Intrinsic::lrint:
6213   case Intrinsic::llrint: {
6214     unsigned Opcode;
6215     switch (Intrinsic) {
6216     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6217     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6218     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6219     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6220     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6221     }
6222 
6223     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6224     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6225                              getValue(I.getArgOperand(0))));
6226     return;
6227   }
6228   case Intrinsic::minnum:
6229     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6230                              getValue(I.getArgOperand(0)).getValueType(),
6231                              getValue(I.getArgOperand(0)),
6232                              getValue(I.getArgOperand(1)), Flags));
6233     return;
6234   case Intrinsic::maxnum:
6235     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6236                              getValue(I.getArgOperand(0)).getValueType(),
6237                              getValue(I.getArgOperand(0)),
6238                              getValue(I.getArgOperand(1)), Flags));
6239     return;
6240   case Intrinsic::minimum:
6241     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6242                              getValue(I.getArgOperand(0)).getValueType(),
6243                              getValue(I.getArgOperand(0)),
6244                              getValue(I.getArgOperand(1)), Flags));
6245     return;
6246   case Intrinsic::maximum:
6247     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6248                              getValue(I.getArgOperand(0)).getValueType(),
6249                              getValue(I.getArgOperand(0)),
6250                              getValue(I.getArgOperand(1)), Flags));
6251     return;
6252   case Intrinsic::copysign:
6253     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6254                              getValue(I.getArgOperand(0)).getValueType(),
6255                              getValue(I.getArgOperand(0)),
6256                              getValue(I.getArgOperand(1)), Flags));
6257     return;
6258   case Intrinsic::fma:
6259     setValue(&I, DAG.getNode(
6260                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6261                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6262                      getValue(I.getArgOperand(2)), Flags));
6263     return;
6264 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6265   case Intrinsic::INTRINSIC:
6266 #include "llvm/IR/ConstrainedOps.def"
6267     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6268     return;
6269 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6270 #include "llvm/IR/VPIntrinsics.def"
6271     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6272     return;
6273   case Intrinsic::fmuladd: {
6274     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6275     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6276         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6277       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6278                                getValue(I.getArgOperand(0)).getValueType(),
6279                                getValue(I.getArgOperand(0)),
6280                                getValue(I.getArgOperand(1)),
6281                                getValue(I.getArgOperand(2)), Flags));
6282     } else {
6283       // TODO: Intrinsic calls should have fast-math-flags.
6284       SDValue Mul = DAG.getNode(
6285           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6286           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6287       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6288                                 getValue(I.getArgOperand(0)).getValueType(),
6289                                 Mul, getValue(I.getArgOperand(2)), Flags);
6290       setValue(&I, Add);
6291     }
6292     return;
6293   }
6294   case Intrinsic::convert_to_fp16:
6295     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6296                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6297                                          getValue(I.getArgOperand(0)),
6298                                          DAG.getTargetConstant(0, sdl,
6299                                                                MVT::i32))));
6300     return;
6301   case Intrinsic::convert_from_fp16:
6302     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6303                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6304                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6305                                          getValue(I.getArgOperand(0)))));
6306     return;
6307   case Intrinsic::fptosi_sat: {
6308     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6309     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6310                              getValue(I.getArgOperand(0)),
6311                              DAG.getValueType(VT.getScalarType())));
6312     return;
6313   }
6314   case Intrinsic::fptoui_sat: {
6315     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6316     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6317                              getValue(I.getArgOperand(0)),
6318                              DAG.getValueType(VT.getScalarType())));
6319     return;
6320   }
6321   case Intrinsic::set_rounding:
6322     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6323                       {getRoot(), getValue(I.getArgOperand(0))});
6324     setValue(&I, Res);
6325     DAG.setRoot(Res.getValue(0));
6326     return;
6327   case Intrinsic::pcmarker: {
6328     SDValue Tmp = getValue(I.getArgOperand(0));
6329     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6330     return;
6331   }
6332   case Intrinsic::readcyclecounter: {
6333     SDValue Op = getRoot();
6334     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6335                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6336     setValue(&I, Res);
6337     DAG.setRoot(Res.getValue(1));
6338     return;
6339   }
6340   case Intrinsic::bitreverse:
6341     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6342                              getValue(I.getArgOperand(0)).getValueType(),
6343                              getValue(I.getArgOperand(0))));
6344     return;
6345   case Intrinsic::bswap:
6346     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6347                              getValue(I.getArgOperand(0)).getValueType(),
6348                              getValue(I.getArgOperand(0))));
6349     return;
6350   case Intrinsic::cttz: {
6351     SDValue Arg = getValue(I.getArgOperand(0));
6352     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6353     EVT Ty = Arg.getValueType();
6354     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6355                              sdl, Ty, Arg));
6356     return;
6357   }
6358   case Intrinsic::ctlz: {
6359     SDValue Arg = getValue(I.getArgOperand(0));
6360     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6361     EVT Ty = Arg.getValueType();
6362     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6363                              sdl, Ty, Arg));
6364     return;
6365   }
6366   case Intrinsic::ctpop: {
6367     SDValue Arg = getValue(I.getArgOperand(0));
6368     EVT Ty = Arg.getValueType();
6369     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6370     return;
6371   }
6372   case Intrinsic::fshl:
6373   case Intrinsic::fshr: {
6374     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6375     SDValue X = getValue(I.getArgOperand(0));
6376     SDValue Y = getValue(I.getArgOperand(1));
6377     SDValue Z = getValue(I.getArgOperand(2));
6378     EVT VT = X.getValueType();
6379 
6380     if (X == Y) {
6381       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6382       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6383     } else {
6384       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6385       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6386     }
6387     return;
6388   }
6389   case Intrinsic::sadd_sat: {
6390     SDValue Op1 = getValue(I.getArgOperand(0));
6391     SDValue Op2 = getValue(I.getArgOperand(1));
6392     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6393     return;
6394   }
6395   case Intrinsic::uadd_sat: {
6396     SDValue Op1 = getValue(I.getArgOperand(0));
6397     SDValue Op2 = getValue(I.getArgOperand(1));
6398     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6399     return;
6400   }
6401   case Intrinsic::ssub_sat: {
6402     SDValue Op1 = getValue(I.getArgOperand(0));
6403     SDValue Op2 = getValue(I.getArgOperand(1));
6404     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6405     return;
6406   }
6407   case Intrinsic::usub_sat: {
6408     SDValue Op1 = getValue(I.getArgOperand(0));
6409     SDValue Op2 = getValue(I.getArgOperand(1));
6410     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6411     return;
6412   }
6413   case Intrinsic::sshl_sat: {
6414     SDValue Op1 = getValue(I.getArgOperand(0));
6415     SDValue Op2 = getValue(I.getArgOperand(1));
6416     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6417     return;
6418   }
6419   case Intrinsic::ushl_sat: {
6420     SDValue Op1 = getValue(I.getArgOperand(0));
6421     SDValue Op2 = getValue(I.getArgOperand(1));
6422     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6423     return;
6424   }
6425   case Intrinsic::smul_fix:
6426   case Intrinsic::umul_fix:
6427   case Intrinsic::smul_fix_sat:
6428   case Intrinsic::umul_fix_sat: {
6429     SDValue Op1 = getValue(I.getArgOperand(0));
6430     SDValue Op2 = getValue(I.getArgOperand(1));
6431     SDValue Op3 = getValue(I.getArgOperand(2));
6432     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6433                              Op1.getValueType(), Op1, Op2, Op3));
6434     return;
6435   }
6436   case Intrinsic::sdiv_fix:
6437   case Intrinsic::udiv_fix:
6438   case Intrinsic::sdiv_fix_sat:
6439   case Intrinsic::udiv_fix_sat: {
6440     SDValue Op1 = getValue(I.getArgOperand(0));
6441     SDValue Op2 = getValue(I.getArgOperand(1));
6442     SDValue Op3 = getValue(I.getArgOperand(2));
6443     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6444                               Op1, Op2, Op3, DAG, TLI));
6445     return;
6446   }
6447   case Intrinsic::smax: {
6448     SDValue Op1 = getValue(I.getArgOperand(0));
6449     SDValue Op2 = getValue(I.getArgOperand(1));
6450     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6451     return;
6452   }
6453   case Intrinsic::smin: {
6454     SDValue Op1 = getValue(I.getArgOperand(0));
6455     SDValue Op2 = getValue(I.getArgOperand(1));
6456     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6457     return;
6458   }
6459   case Intrinsic::umax: {
6460     SDValue Op1 = getValue(I.getArgOperand(0));
6461     SDValue Op2 = getValue(I.getArgOperand(1));
6462     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6463     return;
6464   }
6465   case Intrinsic::umin: {
6466     SDValue Op1 = getValue(I.getArgOperand(0));
6467     SDValue Op2 = getValue(I.getArgOperand(1));
6468     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6469     return;
6470   }
6471   case Intrinsic::abs: {
6472     // TODO: Preserve "int min is poison" arg in SDAG?
6473     SDValue Op1 = getValue(I.getArgOperand(0));
6474     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6475     return;
6476   }
6477   case Intrinsic::stacksave: {
6478     SDValue Op = getRoot();
6479     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6480     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6481     setValue(&I, Res);
6482     DAG.setRoot(Res.getValue(1));
6483     return;
6484   }
6485   case Intrinsic::stackrestore:
6486     Res = getValue(I.getArgOperand(0));
6487     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6488     return;
6489   case Intrinsic::get_dynamic_area_offset: {
6490     SDValue Op = getRoot();
6491     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6492     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6493     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6494     // target.
6495     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6496       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6497                          " intrinsic!");
6498     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6499                       Op);
6500     DAG.setRoot(Op);
6501     setValue(&I, Res);
6502     return;
6503   }
6504   case Intrinsic::stackguard: {
6505     MachineFunction &MF = DAG.getMachineFunction();
6506     const Module &M = *MF.getFunction().getParent();
6507     SDValue Chain = getRoot();
6508     if (TLI.useLoadStackGuardNode()) {
6509       Res = getLoadStackGuard(DAG, sdl, Chain);
6510     } else {
6511       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6512       const Value *Global = TLI.getSDagStackGuard(M);
6513       Align Align = DL->getPrefTypeAlign(Global->getType());
6514       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6515                         MachinePointerInfo(Global, 0), Align,
6516                         MachineMemOperand::MOVolatile);
6517     }
6518     if (TLI.useStackGuardXorFP())
6519       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6520     DAG.setRoot(Chain);
6521     setValue(&I, Res);
6522     return;
6523   }
6524   case Intrinsic::stackprotector: {
6525     // Emit code into the DAG to store the stack guard onto the stack.
6526     MachineFunction &MF = DAG.getMachineFunction();
6527     MachineFrameInfo &MFI = MF.getFrameInfo();
6528     SDValue Src, Chain = getRoot();
6529 
6530     if (TLI.useLoadStackGuardNode())
6531       Src = getLoadStackGuard(DAG, sdl, Chain);
6532     else
6533       Src = getValue(I.getArgOperand(0));   // The guard's value.
6534 
6535     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6536 
6537     int FI = FuncInfo.StaticAllocaMap[Slot];
6538     MFI.setStackProtectorIndex(FI);
6539     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6540 
6541     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6542 
6543     // Store the stack protector onto the stack.
6544     Res = DAG.getStore(
6545         Chain, sdl, Src, FIN,
6546         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6547         MaybeAlign(), MachineMemOperand::MOVolatile);
6548     setValue(&I, Res);
6549     DAG.setRoot(Res);
6550     return;
6551   }
6552   case Intrinsic::objectsize:
6553     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6554 
6555   case Intrinsic::is_constant:
6556     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6557 
6558   case Intrinsic::annotation:
6559   case Intrinsic::ptr_annotation:
6560   case Intrinsic::launder_invariant_group:
6561   case Intrinsic::strip_invariant_group:
6562     // Drop the intrinsic, but forward the value
6563     setValue(&I, getValue(I.getOperand(0)));
6564     return;
6565 
6566   case Intrinsic::assume:
6567   case Intrinsic::experimental_noalias_scope_decl:
6568   case Intrinsic::var_annotation:
6569   case Intrinsic::sideeffect:
6570     // Discard annotate attributes, noalias scope declarations, assumptions, and
6571     // artificial side-effects.
6572     return;
6573 
6574   case Intrinsic::codeview_annotation: {
6575     // Emit a label associated with this metadata.
6576     MachineFunction &MF = DAG.getMachineFunction();
6577     MCSymbol *Label =
6578         MF.getMMI().getContext().createTempSymbol("annotation", true);
6579     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6580     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6581     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6582     DAG.setRoot(Res);
6583     return;
6584   }
6585 
6586   case Intrinsic::init_trampoline: {
6587     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6588 
6589     SDValue Ops[6];
6590     Ops[0] = getRoot();
6591     Ops[1] = getValue(I.getArgOperand(0));
6592     Ops[2] = getValue(I.getArgOperand(1));
6593     Ops[3] = getValue(I.getArgOperand(2));
6594     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6595     Ops[5] = DAG.getSrcValue(F);
6596 
6597     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6598 
6599     DAG.setRoot(Res);
6600     return;
6601   }
6602   case Intrinsic::adjust_trampoline:
6603     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6604                              TLI.getPointerTy(DAG.getDataLayout()),
6605                              getValue(I.getArgOperand(0))));
6606     return;
6607   case Intrinsic::gcroot: {
6608     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6609            "only valid in functions with gc specified, enforced by Verifier");
6610     assert(GFI && "implied by previous");
6611     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6612     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6613 
6614     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6615     GFI->addStackRoot(FI->getIndex(), TypeMap);
6616     return;
6617   }
6618   case Intrinsic::gcread:
6619   case Intrinsic::gcwrite:
6620     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6621   case Intrinsic::flt_rounds:
6622     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6623     setValue(&I, Res);
6624     DAG.setRoot(Res.getValue(1));
6625     return;
6626 
6627   case Intrinsic::expect:
6628     // Just replace __builtin_expect(exp, c) with EXP.
6629     setValue(&I, getValue(I.getArgOperand(0)));
6630     return;
6631 
6632   case Intrinsic::ubsantrap:
6633   case Intrinsic::debugtrap:
6634   case Intrinsic::trap: {
6635     StringRef TrapFuncName =
6636         I.getAttributes()
6637             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6638             .getValueAsString();
6639     if (TrapFuncName.empty()) {
6640       switch (Intrinsic) {
6641       case Intrinsic::trap:
6642         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6643         break;
6644       case Intrinsic::debugtrap:
6645         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6646         break;
6647       case Intrinsic::ubsantrap:
6648         DAG.setRoot(DAG.getNode(
6649             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6650             DAG.getTargetConstant(
6651                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6652                 MVT::i32)));
6653         break;
6654       default: llvm_unreachable("unknown trap intrinsic");
6655       }
6656       return;
6657     }
6658     TargetLowering::ArgListTy Args;
6659     if (Intrinsic == Intrinsic::ubsantrap) {
6660       Args.push_back(TargetLoweringBase::ArgListEntry());
6661       Args[0].Val = I.getArgOperand(0);
6662       Args[0].Node = getValue(Args[0].Val);
6663       Args[0].Ty = Args[0].Val->getType();
6664     }
6665 
6666     TargetLowering::CallLoweringInfo CLI(DAG);
6667     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6668         CallingConv::C, I.getType(),
6669         DAG.getExternalSymbol(TrapFuncName.data(),
6670                               TLI.getPointerTy(DAG.getDataLayout())),
6671         std::move(Args));
6672 
6673     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6674     DAG.setRoot(Result.second);
6675     return;
6676   }
6677 
6678   case Intrinsic::uadd_with_overflow:
6679   case Intrinsic::sadd_with_overflow:
6680   case Intrinsic::usub_with_overflow:
6681   case Intrinsic::ssub_with_overflow:
6682   case Intrinsic::umul_with_overflow:
6683   case Intrinsic::smul_with_overflow: {
6684     ISD::NodeType Op;
6685     switch (Intrinsic) {
6686     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6687     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6688     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6689     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6690     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6691     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6692     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6693     }
6694     SDValue Op1 = getValue(I.getArgOperand(0));
6695     SDValue Op2 = getValue(I.getArgOperand(1));
6696 
6697     EVT ResultVT = Op1.getValueType();
6698     EVT OverflowVT = MVT::i1;
6699     if (ResultVT.isVector())
6700       OverflowVT = EVT::getVectorVT(
6701           *Context, OverflowVT, ResultVT.getVectorElementCount());
6702 
6703     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6704     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6705     return;
6706   }
6707   case Intrinsic::prefetch: {
6708     SDValue Ops[5];
6709     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6710     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6711     Ops[0] = DAG.getRoot();
6712     Ops[1] = getValue(I.getArgOperand(0));
6713     Ops[2] = getValue(I.getArgOperand(1));
6714     Ops[3] = getValue(I.getArgOperand(2));
6715     Ops[4] = getValue(I.getArgOperand(3));
6716     SDValue Result = DAG.getMemIntrinsicNode(
6717         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6718         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6719         /* align */ None, Flags);
6720 
6721     // Chain the prefetch in parallell with any pending loads, to stay out of
6722     // the way of later optimizations.
6723     PendingLoads.push_back(Result);
6724     Result = getRoot();
6725     DAG.setRoot(Result);
6726     return;
6727   }
6728   case Intrinsic::lifetime_start:
6729   case Intrinsic::lifetime_end: {
6730     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6731     // Stack coloring is not enabled in O0, discard region information.
6732     if (TM.getOptLevel() == CodeGenOpt::None)
6733       return;
6734 
6735     const int64_t ObjectSize =
6736         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6737     Value *const ObjectPtr = I.getArgOperand(1);
6738     SmallVector<const Value *, 4> Allocas;
6739     getUnderlyingObjects(ObjectPtr, Allocas);
6740 
6741     for (const Value *Alloca : Allocas) {
6742       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6743 
6744       // Could not find an Alloca.
6745       if (!LifetimeObject)
6746         continue;
6747 
6748       // First check that the Alloca is static, otherwise it won't have a
6749       // valid frame index.
6750       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6751       if (SI == FuncInfo.StaticAllocaMap.end())
6752         return;
6753 
6754       const int FrameIndex = SI->second;
6755       int64_t Offset;
6756       if (GetPointerBaseWithConstantOffset(
6757               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6758         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6759       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6760                                 Offset);
6761       DAG.setRoot(Res);
6762     }
6763     return;
6764   }
6765   case Intrinsic::pseudoprobe: {
6766     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6767     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6768     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6769     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6770     DAG.setRoot(Res);
6771     return;
6772   }
6773   case Intrinsic::invariant_start:
6774     // Discard region information.
6775     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6776     return;
6777   case Intrinsic::invariant_end:
6778     // Discard region information.
6779     return;
6780   case Intrinsic::clear_cache:
6781     /// FunctionName may be null.
6782     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6783       lowerCallToExternalSymbol(I, FunctionName);
6784     return;
6785   case Intrinsic::donothing:
6786     // ignore
6787     return;
6788   case Intrinsic::experimental_stackmap:
6789     visitStackmap(I);
6790     return;
6791   case Intrinsic::experimental_patchpoint_void:
6792   case Intrinsic::experimental_patchpoint_i64:
6793     visitPatchpoint(I);
6794     return;
6795   case Intrinsic::experimental_gc_statepoint:
6796     LowerStatepoint(cast<GCStatepointInst>(I));
6797     return;
6798   case Intrinsic::experimental_gc_result:
6799     visitGCResult(cast<GCResultInst>(I));
6800     return;
6801   case Intrinsic::experimental_gc_relocate:
6802     visitGCRelocate(cast<GCRelocateInst>(I));
6803     return;
6804   case Intrinsic::instrprof_increment:
6805     llvm_unreachable("instrprof failed to lower an increment");
6806   case Intrinsic::instrprof_value_profile:
6807     llvm_unreachable("instrprof failed to lower a value profiling call");
6808   case Intrinsic::localescape: {
6809     MachineFunction &MF = DAG.getMachineFunction();
6810     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6811 
6812     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6813     // is the same on all targets.
6814     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6815       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6816       if (isa<ConstantPointerNull>(Arg))
6817         continue; // Skip null pointers. They represent a hole in index space.
6818       AllocaInst *Slot = cast<AllocaInst>(Arg);
6819       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6820              "can only escape static allocas");
6821       int FI = FuncInfo.StaticAllocaMap[Slot];
6822       MCSymbol *FrameAllocSym =
6823           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6824               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6825       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6826               TII->get(TargetOpcode::LOCAL_ESCAPE))
6827           .addSym(FrameAllocSym)
6828           .addFrameIndex(FI);
6829     }
6830 
6831     return;
6832   }
6833 
6834   case Intrinsic::localrecover: {
6835     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6836     MachineFunction &MF = DAG.getMachineFunction();
6837 
6838     // Get the symbol that defines the frame offset.
6839     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6840     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6841     unsigned IdxVal =
6842         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6843     MCSymbol *FrameAllocSym =
6844         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6845             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6846 
6847     Value *FP = I.getArgOperand(1);
6848     SDValue FPVal = getValue(FP);
6849     EVT PtrVT = FPVal.getValueType();
6850 
6851     // Create a MCSymbol for the label to avoid any target lowering
6852     // that would make this PC relative.
6853     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6854     SDValue OffsetVal =
6855         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6856 
6857     // Add the offset to the FP.
6858     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6859     setValue(&I, Add);
6860 
6861     return;
6862   }
6863 
6864   case Intrinsic::eh_exceptionpointer:
6865   case Intrinsic::eh_exceptioncode: {
6866     // Get the exception pointer vreg, copy from it, and resize it to fit.
6867     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6868     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6869     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6870     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6871     SDValue N =
6872         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6873     if (Intrinsic == Intrinsic::eh_exceptioncode)
6874       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6875     setValue(&I, N);
6876     return;
6877   }
6878   case Intrinsic::xray_customevent: {
6879     // Here we want to make sure that the intrinsic behaves as if it has a
6880     // specific calling convention, and only for x86_64.
6881     // FIXME: Support other platforms later.
6882     const auto &Triple = DAG.getTarget().getTargetTriple();
6883     if (Triple.getArch() != Triple::x86_64)
6884       return;
6885 
6886     SDLoc DL = getCurSDLoc();
6887     SmallVector<SDValue, 8> Ops;
6888 
6889     // We want to say that we always want the arguments in registers.
6890     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6891     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6892     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6893     SDValue Chain = getRoot();
6894     Ops.push_back(LogEntryVal);
6895     Ops.push_back(StrSizeVal);
6896     Ops.push_back(Chain);
6897 
6898     // We need to enforce the calling convention for the callsite, so that
6899     // argument ordering is enforced correctly, and that register allocation can
6900     // see that some registers may be assumed clobbered and have to preserve
6901     // them across calls to the intrinsic.
6902     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6903                                            DL, NodeTys, Ops);
6904     SDValue patchableNode = SDValue(MN, 0);
6905     DAG.setRoot(patchableNode);
6906     setValue(&I, patchableNode);
6907     return;
6908   }
6909   case Intrinsic::xray_typedevent: {
6910     // Here we want to make sure that the intrinsic behaves as if it has a
6911     // specific calling convention, and only for x86_64.
6912     // FIXME: Support other platforms later.
6913     const auto &Triple = DAG.getTarget().getTargetTriple();
6914     if (Triple.getArch() != Triple::x86_64)
6915       return;
6916 
6917     SDLoc DL = getCurSDLoc();
6918     SmallVector<SDValue, 8> Ops;
6919 
6920     // We want to say that we always want the arguments in registers.
6921     // It's unclear to me how manipulating the selection DAG here forces callers
6922     // to provide arguments in registers instead of on the stack.
6923     SDValue LogTypeId = getValue(I.getArgOperand(0));
6924     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6925     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6926     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6927     SDValue Chain = getRoot();
6928     Ops.push_back(LogTypeId);
6929     Ops.push_back(LogEntryVal);
6930     Ops.push_back(StrSizeVal);
6931     Ops.push_back(Chain);
6932 
6933     // We need to enforce the calling convention for the callsite, so that
6934     // argument ordering is enforced correctly, and that register allocation can
6935     // see that some registers may be assumed clobbered and have to preserve
6936     // them across calls to the intrinsic.
6937     MachineSDNode *MN = DAG.getMachineNode(
6938         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6939     SDValue patchableNode = SDValue(MN, 0);
6940     DAG.setRoot(patchableNode);
6941     setValue(&I, patchableNode);
6942     return;
6943   }
6944   case Intrinsic::experimental_deoptimize:
6945     LowerDeoptimizeCall(&I);
6946     return;
6947   case Intrinsic::experimental_stepvector:
6948     visitStepVector(I);
6949     return;
6950   case Intrinsic::vector_reduce_fadd:
6951   case Intrinsic::vector_reduce_fmul:
6952   case Intrinsic::vector_reduce_add:
6953   case Intrinsic::vector_reduce_mul:
6954   case Intrinsic::vector_reduce_and:
6955   case Intrinsic::vector_reduce_or:
6956   case Intrinsic::vector_reduce_xor:
6957   case Intrinsic::vector_reduce_smax:
6958   case Intrinsic::vector_reduce_smin:
6959   case Intrinsic::vector_reduce_umax:
6960   case Intrinsic::vector_reduce_umin:
6961   case Intrinsic::vector_reduce_fmax:
6962   case Intrinsic::vector_reduce_fmin:
6963     visitVectorReduce(I, Intrinsic);
6964     return;
6965 
6966   case Intrinsic::icall_branch_funnel: {
6967     SmallVector<SDValue, 16> Ops;
6968     Ops.push_back(getValue(I.getArgOperand(0)));
6969 
6970     int64_t Offset;
6971     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6972         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6973     if (!Base)
6974       report_fatal_error(
6975           "llvm.icall.branch.funnel operand must be a GlobalValue");
6976     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6977 
6978     struct BranchFunnelTarget {
6979       int64_t Offset;
6980       SDValue Target;
6981     };
6982     SmallVector<BranchFunnelTarget, 8> Targets;
6983 
6984     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6985       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6986           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6987       if (ElemBase != Base)
6988         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6989                            "to the same GlobalValue");
6990 
6991       SDValue Val = getValue(I.getArgOperand(Op + 1));
6992       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6993       if (!GA)
6994         report_fatal_error(
6995             "llvm.icall.branch.funnel operand must be a GlobalValue");
6996       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6997                                      GA->getGlobal(), getCurSDLoc(),
6998                                      Val.getValueType(), GA->getOffset())});
6999     }
7000     llvm::sort(Targets,
7001                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7002                  return T1.Offset < T2.Offset;
7003                });
7004 
7005     for (auto &T : Targets) {
7006       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
7007       Ops.push_back(T.Target);
7008     }
7009 
7010     Ops.push_back(DAG.getRoot()); // Chain
7011     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
7012                                  getCurSDLoc(), MVT::Other, Ops),
7013               0);
7014     DAG.setRoot(N);
7015     setValue(&I, N);
7016     HasTailCall = true;
7017     return;
7018   }
7019 
7020   case Intrinsic::wasm_landingpad_index:
7021     // Information this intrinsic contained has been transferred to
7022     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7023     // delete it now.
7024     return;
7025 
7026   case Intrinsic::aarch64_settag:
7027   case Intrinsic::aarch64_settag_zero: {
7028     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7029     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7030     SDValue Val = TSI.EmitTargetCodeForSetTag(
7031         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
7032         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7033         ZeroMemory);
7034     DAG.setRoot(Val);
7035     setValue(&I, Val);
7036     return;
7037   }
7038   case Intrinsic::ptrmask: {
7039     SDValue Ptr = getValue(I.getOperand(0));
7040     SDValue Const = getValue(I.getOperand(1));
7041 
7042     EVT PtrVT = Ptr.getValueType();
7043     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
7044                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
7045     return;
7046   }
7047   case Intrinsic::get_active_lane_mask: {
7048     auto DL = getCurSDLoc();
7049     SDValue Index = getValue(I.getOperand(0));
7050     SDValue TripCount = getValue(I.getOperand(1));
7051     Type *ElementTy = I.getOperand(0)->getType();
7052     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7053     unsigned VecWidth = VT.getVectorNumElements();
7054 
7055     SmallVector<SDValue, 16> OpsTripCount;
7056     SmallVector<SDValue, 16> OpsIndex;
7057     SmallVector<SDValue, 16> OpsStepConstants;
7058     for (unsigned i = 0; i < VecWidth; i++) {
7059       OpsTripCount.push_back(TripCount);
7060       OpsIndex.push_back(Index);
7061       OpsStepConstants.push_back(
7062           DAG.getConstant(i, DL, EVT::getEVT(ElementTy)));
7063     }
7064 
7065     EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth);
7066 
7067     auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth));
7068     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
7069     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
7070     SDValue VectorInduction = DAG.getNode(
7071        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
7072     SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount);
7073     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
7074                                  VectorTripCount, ISD::CondCode::SETULT);
7075     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
7076                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
7077                              SetCC));
7078     return;
7079   }
7080   case Intrinsic::experimental_vector_insert: {
7081     auto DL = getCurSDLoc();
7082 
7083     SDValue Vec = getValue(I.getOperand(0));
7084     SDValue SubVec = getValue(I.getOperand(1));
7085     SDValue Index = getValue(I.getOperand(2));
7086 
7087     // The intrinsic's index type is i64, but the SDNode requires an index type
7088     // suitable for the target. Convert the index as required.
7089     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7090     if (Index.getValueType() != VectorIdxTy)
7091       Index = DAG.getVectorIdxConstant(
7092           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7093 
7094     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7095     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec,
7096                              Index));
7097     return;
7098   }
7099   case Intrinsic::experimental_vector_extract: {
7100     auto DL = getCurSDLoc();
7101 
7102     SDValue Vec = getValue(I.getOperand(0));
7103     SDValue Index = getValue(I.getOperand(1));
7104     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7105 
7106     // The intrinsic's index type is i64, but the SDNode requires an index type
7107     // suitable for the target. Convert the index as required.
7108     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7109     if (Index.getValueType() != VectorIdxTy)
7110       Index = DAG.getVectorIdxConstant(
7111           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7112 
7113     setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index));
7114     return;
7115   }
7116   case Intrinsic::experimental_vector_reverse:
7117     visitVectorReverse(I);
7118     return;
7119   case Intrinsic::experimental_vector_splice:
7120     visitVectorSplice(I);
7121     return;
7122   }
7123 }
7124 
7125 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7126     const ConstrainedFPIntrinsic &FPI) {
7127   SDLoc sdl = getCurSDLoc();
7128 
7129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7130   SmallVector<EVT, 4> ValueVTs;
7131   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7132   ValueVTs.push_back(MVT::Other); // Out chain
7133 
7134   // We do not need to serialize constrained FP intrinsics against
7135   // each other or against (nonvolatile) loads, so they can be
7136   // chained like loads.
7137   SDValue Chain = DAG.getRoot();
7138   SmallVector<SDValue, 4> Opers;
7139   Opers.push_back(Chain);
7140   if (FPI.isUnaryOp()) {
7141     Opers.push_back(getValue(FPI.getArgOperand(0)));
7142   } else if (FPI.isTernaryOp()) {
7143     Opers.push_back(getValue(FPI.getArgOperand(0)));
7144     Opers.push_back(getValue(FPI.getArgOperand(1)));
7145     Opers.push_back(getValue(FPI.getArgOperand(2)));
7146   } else {
7147     Opers.push_back(getValue(FPI.getArgOperand(0)));
7148     Opers.push_back(getValue(FPI.getArgOperand(1)));
7149   }
7150 
7151   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7152     assert(Result.getNode()->getNumValues() == 2);
7153 
7154     // Push node to the appropriate list so that future instructions can be
7155     // chained up correctly.
7156     SDValue OutChain = Result.getValue(1);
7157     switch (EB) {
7158     case fp::ExceptionBehavior::ebIgnore:
7159       // The only reason why ebIgnore nodes still need to be chained is that
7160       // they might depend on the current rounding mode, and therefore must
7161       // not be moved across instruction that may change that mode.
7162       LLVM_FALLTHROUGH;
7163     case fp::ExceptionBehavior::ebMayTrap:
7164       // These must not be moved across calls or instructions that may change
7165       // floating-point exception masks.
7166       PendingConstrainedFP.push_back(OutChain);
7167       break;
7168     case fp::ExceptionBehavior::ebStrict:
7169       // These must not be moved across calls or instructions that may change
7170       // floating-point exception masks or read floating-point exception flags.
7171       // In addition, they cannot be optimized out even if unused.
7172       PendingConstrainedFPStrict.push_back(OutChain);
7173       break;
7174     }
7175   };
7176 
7177   SDVTList VTs = DAG.getVTList(ValueVTs);
7178   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7179 
7180   SDNodeFlags Flags;
7181   if (EB == fp::ExceptionBehavior::ebIgnore)
7182     Flags.setNoFPExcept(true);
7183 
7184   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7185     Flags.copyFMF(*FPOp);
7186 
7187   unsigned Opcode;
7188   switch (FPI.getIntrinsicID()) {
7189   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7190 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7191   case Intrinsic::INTRINSIC:                                                   \
7192     Opcode = ISD::STRICT_##DAGN;                                               \
7193     break;
7194 #include "llvm/IR/ConstrainedOps.def"
7195   case Intrinsic::experimental_constrained_fmuladd: {
7196     Opcode = ISD::STRICT_FMA;
7197     // Break fmuladd into fmul and fadd.
7198     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7199         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7200                                         ValueVTs[0])) {
7201       Opers.pop_back();
7202       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7203       pushOutChain(Mul, EB);
7204       Opcode = ISD::STRICT_FADD;
7205       Opers.clear();
7206       Opers.push_back(Mul.getValue(1));
7207       Opers.push_back(Mul.getValue(0));
7208       Opers.push_back(getValue(FPI.getArgOperand(2)));
7209     }
7210     break;
7211   }
7212   }
7213 
7214   // A few strict DAG nodes carry additional operands that are not
7215   // set up by the default code above.
7216   switch (Opcode) {
7217   default: break;
7218   case ISD::STRICT_FP_ROUND:
7219     Opers.push_back(
7220         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7221     break;
7222   case ISD::STRICT_FSETCC:
7223   case ISD::STRICT_FSETCCS: {
7224     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7225     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7226     if (TM.Options.NoNaNsFPMath)
7227       Condition = getFCmpCodeWithoutNaN(Condition);
7228     Opers.push_back(DAG.getCondCode(Condition));
7229     break;
7230   }
7231   }
7232 
7233   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7234   pushOutChain(Result, EB);
7235 
7236   SDValue FPResult = Result.getValue(0);
7237   setValue(&FPI, FPResult);
7238 }
7239 
7240 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7241   Optional<unsigned> ResOPC;
7242   switch (VPIntrin.getIntrinsicID()) {
7243 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN:
7244 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID;
7245 #define END_REGISTER_VP_INTRINSIC(...) break;
7246 #include "llvm/IR/VPIntrinsics.def"
7247   }
7248 
7249   if (!ResOPC.hasValue())
7250     llvm_unreachable(
7251         "Inconsistency: no SDNode available for this VPIntrinsic!");
7252 
7253   return ResOPC.getValue();
7254 }
7255 
7256 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7257     const VPIntrinsic &VPIntrin) {
7258   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7259 
7260   SmallVector<EVT, 4> ValueVTs;
7261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7262   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7263   SDVTList VTs = DAG.getVTList(ValueVTs);
7264 
7265   // Request operands.
7266   SmallVector<SDValue, 7> OpValues;
7267   for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i)
7268     OpValues.push_back(getValue(VPIntrin.getArgOperand(i)));
7269 
7270   SDLoc DL = getCurSDLoc();
7271   SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7272   setValue(&VPIntrin, Result);
7273 }
7274 
7275 std::pair<SDValue, SDValue>
7276 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7277                                     const BasicBlock *EHPadBB) {
7278   MachineFunction &MF = DAG.getMachineFunction();
7279   MachineModuleInfo &MMI = MF.getMMI();
7280   MCSymbol *BeginLabel = nullptr;
7281 
7282   if (EHPadBB) {
7283     // Insert a label before the invoke call to mark the try range.  This can be
7284     // used to detect deletion of the invoke via the MachineModuleInfo.
7285     BeginLabel = MMI.getContext().createTempSymbol();
7286 
7287     // For SjLj, keep track of which landing pads go with which invokes
7288     // so as to maintain the ordering of pads in the LSDA.
7289     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7290     if (CallSiteIndex) {
7291       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7292       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7293 
7294       // Now that the call site is handled, stop tracking it.
7295       MMI.setCurrentCallSite(0);
7296     }
7297 
7298     // Both PendingLoads and PendingExports must be flushed here;
7299     // this call might not return.
7300     (void)getRoot();
7301     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7302 
7303     CLI.setChain(getRoot());
7304   }
7305   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7306   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7307 
7308   assert((CLI.IsTailCall || Result.second.getNode()) &&
7309          "Non-null chain expected with non-tail call!");
7310   assert((Result.second.getNode() || !Result.first.getNode()) &&
7311          "Null value expected with tail call!");
7312 
7313   if (!Result.second.getNode()) {
7314     // As a special case, a null chain means that a tail call has been emitted
7315     // and the DAG root is already updated.
7316     HasTailCall = true;
7317 
7318     // Since there's no actual continuation from this block, nothing can be
7319     // relying on us setting vregs for them.
7320     PendingExports.clear();
7321   } else {
7322     DAG.setRoot(Result.second);
7323   }
7324 
7325   if (EHPadBB) {
7326     // Insert a label at the end of the invoke call to mark the try range.  This
7327     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7328     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7329     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7330 
7331     // Inform MachineModuleInfo of range.
7332     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7333     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7334     // actually use outlined funclets and their LSDA info style.
7335     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7336       assert(CLI.CB);
7337       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7338       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7339     } else if (!isScopedEHPersonality(Pers)) {
7340       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7341     }
7342   }
7343 
7344   return Result;
7345 }
7346 
7347 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7348                                       bool isTailCall,
7349                                       const BasicBlock *EHPadBB) {
7350   auto &DL = DAG.getDataLayout();
7351   FunctionType *FTy = CB.getFunctionType();
7352   Type *RetTy = CB.getType();
7353 
7354   TargetLowering::ArgListTy Args;
7355   Args.reserve(CB.arg_size());
7356 
7357   const Value *SwiftErrorVal = nullptr;
7358   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7359 
7360   if (isTailCall) {
7361     // Avoid emitting tail calls in functions with the disable-tail-calls
7362     // attribute.
7363     auto *Caller = CB.getParent()->getParent();
7364     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7365         "true")
7366       isTailCall = false;
7367 
7368     // We can't tail call inside a function with a swifterror argument. Lowering
7369     // does not support this yet. It would have to move into the swifterror
7370     // register before the call.
7371     if (TLI.supportSwiftError() &&
7372         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7373       isTailCall = false;
7374   }
7375 
7376   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7377     TargetLowering::ArgListEntry Entry;
7378     const Value *V = *I;
7379 
7380     // Skip empty types
7381     if (V->getType()->isEmptyTy())
7382       continue;
7383 
7384     SDValue ArgNode = getValue(V);
7385     Entry.Node = ArgNode; Entry.Ty = V->getType();
7386 
7387     Entry.setAttributes(&CB, I - CB.arg_begin());
7388 
7389     // Use swifterror virtual register as input to the call.
7390     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7391       SwiftErrorVal = V;
7392       // We find the virtual register for the actual swifterror argument.
7393       // Instead of using the Value, we use the virtual register instead.
7394       Entry.Node =
7395           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7396                           EVT(TLI.getPointerTy(DL)));
7397     }
7398 
7399     Args.push_back(Entry);
7400 
7401     // If we have an explicit sret argument that is an Instruction, (i.e., it
7402     // might point to function-local memory), we can't meaningfully tail-call.
7403     if (Entry.IsSRet && isa<Instruction>(V))
7404       isTailCall = false;
7405   }
7406 
7407   // If call site has a cfguardtarget operand bundle, create and add an
7408   // additional ArgListEntry.
7409   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7410     TargetLowering::ArgListEntry Entry;
7411     Value *V = Bundle->Inputs[0];
7412     SDValue ArgNode = getValue(V);
7413     Entry.Node = ArgNode;
7414     Entry.Ty = V->getType();
7415     Entry.IsCFGuardTarget = true;
7416     Args.push_back(Entry);
7417   }
7418 
7419   // Check if target-independent constraints permit a tail call here.
7420   // Target-dependent constraints are checked within TLI->LowerCallTo.
7421   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7422     isTailCall = false;
7423 
7424   // Disable tail calls if there is an swifterror argument. Targets have not
7425   // been updated to support tail calls.
7426   if (TLI.supportSwiftError() && SwiftErrorVal)
7427     isTailCall = false;
7428 
7429   TargetLowering::CallLoweringInfo CLI(DAG);
7430   CLI.setDebugLoc(getCurSDLoc())
7431       .setChain(getRoot())
7432       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7433       .setTailCall(isTailCall)
7434       .setConvergent(CB.isConvergent())
7435       .setIsPreallocated(
7436           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7437   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7438 
7439   if (Result.first.getNode()) {
7440     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7441     setValue(&CB, Result.first);
7442   }
7443 
7444   // The last element of CLI.InVals has the SDValue for swifterror return.
7445   // Here we copy it to a virtual register and update SwiftErrorMap for
7446   // book-keeping.
7447   if (SwiftErrorVal && TLI.supportSwiftError()) {
7448     // Get the last element of InVals.
7449     SDValue Src = CLI.InVals.back();
7450     Register VReg =
7451         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7452     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7453     DAG.setRoot(CopyNode);
7454   }
7455 }
7456 
7457 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7458                              SelectionDAGBuilder &Builder) {
7459   // Check to see if this load can be trivially constant folded, e.g. if the
7460   // input is from a string literal.
7461   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7462     // Cast pointer to the type we really want to load.
7463     Type *LoadTy =
7464         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7465     if (LoadVT.isVector())
7466       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7467 
7468     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7469                                          PointerType::getUnqual(LoadTy));
7470 
7471     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7472             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7473       return Builder.getValue(LoadCst);
7474   }
7475 
7476   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7477   // still constant memory, the input chain can be the entry node.
7478   SDValue Root;
7479   bool ConstantMemory = false;
7480 
7481   // Do not serialize (non-volatile) loads of constant memory with anything.
7482   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7483     Root = Builder.DAG.getEntryNode();
7484     ConstantMemory = true;
7485   } else {
7486     // Do not serialize non-volatile loads against each other.
7487     Root = Builder.DAG.getRoot();
7488   }
7489 
7490   SDValue Ptr = Builder.getValue(PtrVal);
7491   SDValue LoadVal =
7492       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7493                           MachinePointerInfo(PtrVal), Align(1));
7494 
7495   if (!ConstantMemory)
7496     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7497   return LoadVal;
7498 }
7499 
7500 /// Record the value for an instruction that produces an integer result,
7501 /// converting the type where necessary.
7502 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7503                                                   SDValue Value,
7504                                                   bool IsSigned) {
7505   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7506                                                     I.getType(), true);
7507   if (IsSigned)
7508     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7509   else
7510     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7511   setValue(&I, Value);
7512 }
7513 
7514 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7515 /// true and lower it. Otherwise return false, and it will be lowered like a
7516 /// normal call.
7517 /// The caller already checked that \p I calls the appropriate LibFunc with a
7518 /// correct prototype.
7519 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7520   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7521   const Value *Size = I.getArgOperand(2);
7522   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7523   if (CSize && CSize->getZExtValue() == 0) {
7524     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7525                                                           I.getType(), true);
7526     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7527     return true;
7528   }
7529 
7530   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7531   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7532       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7533       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7534   if (Res.first.getNode()) {
7535     processIntegerCallValue(I, Res.first, true);
7536     PendingLoads.push_back(Res.second);
7537     return true;
7538   }
7539 
7540   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7541   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7542   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7543     return false;
7544 
7545   // If the target has a fast compare for the given size, it will return a
7546   // preferred load type for that size. Require that the load VT is legal and
7547   // that the target supports unaligned loads of that type. Otherwise, return
7548   // INVALID.
7549   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7550     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7551     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7552     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7553       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7554       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7555       // TODO: Check alignment of src and dest ptrs.
7556       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7557       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7558       if (!TLI.isTypeLegal(LVT) ||
7559           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7560           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7561         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7562     }
7563 
7564     return LVT;
7565   };
7566 
7567   // This turns into unaligned loads. We only do this if the target natively
7568   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7569   // we'll only produce a small number of byte loads.
7570   MVT LoadVT;
7571   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7572   switch (NumBitsToCompare) {
7573   default:
7574     return false;
7575   case 16:
7576     LoadVT = MVT::i16;
7577     break;
7578   case 32:
7579     LoadVT = MVT::i32;
7580     break;
7581   case 64:
7582   case 128:
7583   case 256:
7584     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7585     break;
7586   }
7587 
7588   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7589     return false;
7590 
7591   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7592   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7593 
7594   // Bitcast to a wide integer type if the loads are vectors.
7595   if (LoadVT.isVector()) {
7596     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7597     LoadL = DAG.getBitcast(CmpVT, LoadL);
7598     LoadR = DAG.getBitcast(CmpVT, LoadR);
7599   }
7600 
7601   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7602   processIntegerCallValue(I, Cmp, false);
7603   return true;
7604 }
7605 
7606 /// See if we can lower a memchr call into an optimized form. If so, return
7607 /// true and lower it. Otherwise return false, and it will be lowered like a
7608 /// normal call.
7609 /// The caller already checked that \p I calls the appropriate LibFunc with a
7610 /// correct prototype.
7611 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7612   const Value *Src = I.getArgOperand(0);
7613   const Value *Char = I.getArgOperand(1);
7614   const Value *Length = I.getArgOperand(2);
7615 
7616   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7617   std::pair<SDValue, SDValue> Res =
7618     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7619                                 getValue(Src), getValue(Char), getValue(Length),
7620                                 MachinePointerInfo(Src));
7621   if (Res.first.getNode()) {
7622     setValue(&I, Res.first);
7623     PendingLoads.push_back(Res.second);
7624     return true;
7625   }
7626 
7627   return false;
7628 }
7629 
7630 /// See if we can lower a mempcpy call into an optimized form. If so, return
7631 /// true and lower it. Otherwise return false, and it will be lowered like a
7632 /// normal call.
7633 /// The caller already checked that \p I calls the appropriate LibFunc with a
7634 /// correct prototype.
7635 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7636   SDValue Dst = getValue(I.getArgOperand(0));
7637   SDValue Src = getValue(I.getArgOperand(1));
7638   SDValue Size = getValue(I.getArgOperand(2));
7639 
7640   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7641   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7642   // DAG::getMemcpy needs Alignment to be defined.
7643   Align Alignment = std::min(DstAlign, SrcAlign);
7644 
7645   bool isVol = false;
7646   SDLoc sdl = getCurSDLoc();
7647 
7648   // In the mempcpy context we need to pass in a false value for isTailCall
7649   // because the return pointer needs to be adjusted by the size of
7650   // the copied memory.
7651   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7652   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7653                              /*isTailCall=*/false,
7654                              MachinePointerInfo(I.getArgOperand(0)),
7655                              MachinePointerInfo(I.getArgOperand(1)));
7656   assert(MC.getNode() != nullptr &&
7657          "** memcpy should not be lowered as TailCall in mempcpy context **");
7658   DAG.setRoot(MC);
7659 
7660   // Check if Size needs to be truncated or extended.
7661   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7662 
7663   // Adjust return pointer to point just past the last dst byte.
7664   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7665                                     Dst, Size);
7666   setValue(&I, DstPlusSize);
7667   return true;
7668 }
7669 
7670 /// See if we can lower a strcpy call into an optimized form.  If so, return
7671 /// true and lower it, otherwise return false and it will be lowered like a
7672 /// normal call.
7673 /// The caller already checked that \p I calls the appropriate LibFunc with a
7674 /// correct prototype.
7675 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7676   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7677 
7678   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7679   std::pair<SDValue, SDValue> Res =
7680     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7681                                 getValue(Arg0), getValue(Arg1),
7682                                 MachinePointerInfo(Arg0),
7683                                 MachinePointerInfo(Arg1), isStpcpy);
7684   if (Res.first.getNode()) {
7685     setValue(&I, Res.first);
7686     DAG.setRoot(Res.second);
7687     return true;
7688   }
7689 
7690   return false;
7691 }
7692 
7693 /// See if we can lower a strcmp call into an optimized form.  If so, return
7694 /// true and lower it, otherwise return false and it will be lowered like a
7695 /// normal call.
7696 /// The caller already checked that \p I calls the appropriate LibFunc with a
7697 /// correct prototype.
7698 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7699   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7700 
7701   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7702   std::pair<SDValue, SDValue> Res =
7703     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7704                                 getValue(Arg0), getValue(Arg1),
7705                                 MachinePointerInfo(Arg0),
7706                                 MachinePointerInfo(Arg1));
7707   if (Res.first.getNode()) {
7708     processIntegerCallValue(I, Res.first, true);
7709     PendingLoads.push_back(Res.second);
7710     return true;
7711   }
7712 
7713   return false;
7714 }
7715 
7716 /// See if we can lower a strlen call into an optimized form.  If so, return
7717 /// true and lower it, otherwise return false and it will be lowered like a
7718 /// normal call.
7719 /// The caller already checked that \p I calls the appropriate LibFunc with a
7720 /// correct prototype.
7721 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7722   const Value *Arg0 = I.getArgOperand(0);
7723 
7724   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7725   std::pair<SDValue, SDValue> Res =
7726     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7727                                 getValue(Arg0), MachinePointerInfo(Arg0));
7728   if (Res.first.getNode()) {
7729     processIntegerCallValue(I, Res.first, false);
7730     PendingLoads.push_back(Res.second);
7731     return true;
7732   }
7733 
7734   return false;
7735 }
7736 
7737 /// See if we can lower a strnlen call into an optimized form.  If so, return
7738 /// true and lower it, otherwise return false and it will be lowered like a
7739 /// normal call.
7740 /// The caller already checked that \p I calls the appropriate LibFunc with a
7741 /// correct prototype.
7742 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7743   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7744 
7745   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7746   std::pair<SDValue, SDValue> Res =
7747     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7748                                  getValue(Arg0), getValue(Arg1),
7749                                  MachinePointerInfo(Arg0));
7750   if (Res.first.getNode()) {
7751     processIntegerCallValue(I, Res.first, false);
7752     PendingLoads.push_back(Res.second);
7753     return true;
7754   }
7755 
7756   return false;
7757 }
7758 
7759 /// See if we can lower a unary floating-point operation into an SDNode with
7760 /// the specified Opcode.  If so, return true and lower it, otherwise return
7761 /// false and it will be lowered like a normal call.
7762 /// The caller already checked that \p I calls the appropriate LibFunc with a
7763 /// correct prototype.
7764 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7765                                               unsigned Opcode) {
7766   // We already checked this call's prototype; verify it doesn't modify errno.
7767   if (!I.onlyReadsMemory())
7768     return false;
7769 
7770   SDNodeFlags Flags;
7771   Flags.copyFMF(cast<FPMathOperator>(I));
7772 
7773   SDValue Tmp = getValue(I.getArgOperand(0));
7774   setValue(&I,
7775            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
7776   return true;
7777 }
7778 
7779 /// See if we can lower a binary floating-point operation into an SDNode with
7780 /// the specified Opcode. If so, return true and lower it. Otherwise return
7781 /// false, and it will be lowered like a normal call.
7782 /// The caller already checked that \p I calls the appropriate LibFunc with a
7783 /// correct prototype.
7784 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7785                                                unsigned Opcode) {
7786   // We already checked this call's prototype; verify it doesn't modify errno.
7787   if (!I.onlyReadsMemory())
7788     return false;
7789 
7790   SDNodeFlags Flags;
7791   Flags.copyFMF(cast<FPMathOperator>(I));
7792 
7793   SDValue Tmp0 = getValue(I.getArgOperand(0));
7794   SDValue Tmp1 = getValue(I.getArgOperand(1));
7795   EVT VT = Tmp0.getValueType();
7796   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
7797   return true;
7798 }
7799 
7800 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7801   // Handle inline assembly differently.
7802   if (I.isInlineAsm()) {
7803     visitInlineAsm(I);
7804     return;
7805   }
7806 
7807   if (Function *F = I.getCalledFunction()) {
7808     if (F->isDeclaration()) {
7809       // Is this an LLVM intrinsic or a target-specific intrinsic?
7810       unsigned IID = F->getIntrinsicID();
7811       if (!IID)
7812         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7813           IID = II->getIntrinsicID(F);
7814 
7815       if (IID) {
7816         visitIntrinsicCall(I, IID);
7817         return;
7818       }
7819     }
7820 
7821     // Check for well-known libc/libm calls.  If the function is internal, it
7822     // can't be a library call.  Don't do the check if marked as nobuiltin for
7823     // some reason or the call site requires strict floating point semantics.
7824     LibFunc Func;
7825     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7826         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7827         LibInfo->hasOptimizedCodeGen(Func)) {
7828       switch (Func) {
7829       default: break;
7830       case LibFunc_bcmp:
7831         if (visitMemCmpBCmpCall(I))
7832           return;
7833         break;
7834       case LibFunc_copysign:
7835       case LibFunc_copysignf:
7836       case LibFunc_copysignl:
7837         // We already checked this call's prototype; verify it doesn't modify
7838         // errno.
7839         if (I.onlyReadsMemory()) {
7840           SDValue LHS = getValue(I.getArgOperand(0));
7841           SDValue RHS = getValue(I.getArgOperand(1));
7842           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7843                                    LHS.getValueType(), LHS, RHS));
7844           return;
7845         }
7846         break;
7847       case LibFunc_fabs:
7848       case LibFunc_fabsf:
7849       case LibFunc_fabsl:
7850         if (visitUnaryFloatCall(I, ISD::FABS))
7851           return;
7852         break;
7853       case LibFunc_fmin:
7854       case LibFunc_fminf:
7855       case LibFunc_fminl:
7856         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7857           return;
7858         break;
7859       case LibFunc_fmax:
7860       case LibFunc_fmaxf:
7861       case LibFunc_fmaxl:
7862         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7863           return;
7864         break;
7865       case LibFunc_sin:
7866       case LibFunc_sinf:
7867       case LibFunc_sinl:
7868         if (visitUnaryFloatCall(I, ISD::FSIN))
7869           return;
7870         break;
7871       case LibFunc_cos:
7872       case LibFunc_cosf:
7873       case LibFunc_cosl:
7874         if (visitUnaryFloatCall(I, ISD::FCOS))
7875           return;
7876         break;
7877       case LibFunc_sqrt:
7878       case LibFunc_sqrtf:
7879       case LibFunc_sqrtl:
7880       case LibFunc_sqrt_finite:
7881       case LibFunc_sqrtf_finite:
7882       case LibFunc_sqrtl_finite:
7883         if (visitUnaryFloatCall(I, ISD::FSQRT))
7884           return;
7885         break;
7886       case LibFunc_floor:
7887       case LibFunc_floorf:
7888       case LibFunc_floorl:
7889         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7890           return;
7891         break;
7892       case LibFunc_nearbyint:
7893       case LibFunc_nearbyintf:
7894       case LibFunc_nearbyintl:
7895         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7896           return;
7897         break;
7898       case LibFunc_ceil:
7899       case LibFunc_ceilf:
7900       case LibFunc_ceill:
7901         if (visitUnaryFloatCall(I, ISD::FCEIL))
7902           return;
7903         break;
7904       case LibFunc_rint:
7905       case LibFunc_rintf:
7906       case LibFunc_rintl:
7907         if (visitUnaryFloatCall(I, ISD::FRINT))
7908           return;
7909         break;
7910       case LibFunc_round:
7911       case LibFunc_roundf:
7912       case LibFunc_roundl:
7913         if (visitUnaryFloatCall(I, ISD::FROUND))
7914           return;
7915         break;
7916       case LibFunc_trunc:
7917       case LibFunc_truncf:
7918       case LibFunc_truncl:
7919         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7920           return;
7921         break;
7922       case LibFunc_log2:
7923       case LibFunc_log2f:
7924       case LibFunc_log2l:
7925         if (visitUnaryFloatCall(I, ISD::FLOG2))
7926           return;
7927         break;
7928       case LibFunc_exp2:
7929       case LibFunc_exp2f:
7930       case LibFunc_exp2l:
7931         if (visitUnaryFloatCall(I, ISD::FEXP2))
7932           return;
7933         break;
7934       case LibFunc_memcmp:
7935         if (visitMemCmpBCmpCall(I))
7936           return;
7937         break;
7938       case LibFunc_mempcpy:
7939         if (visitMemPCpyCall(I))
7940           return;
7941         break;
7942       case LibFunc_memchr:
7943         if (visitMemChrCall(I))
7944           return;
7945         break;
7946       case LibFunc_strcpy:
7947         if (visitStrCpyCall(I, false))
7948           return;
7949         break;
7950       case LibFunc_stpcpy:
7951         if (visitStrCpyCall(I, true))
7952           return;
7953         break;
7954       case LibFunc_strcmp:
7955         if (visitStrCmpCall(I))
7956           return;
7957         break;
7958       case LibFunc_strlen:
7959         if (visitStrLenCall(I))
7960           return;
7961         break;
7962       case LibFunc_strnlen:
7963         if (visitStrNLenCall(I))
7964           return;
7965         break;
7966       }
7967     }
7968   }
7969 
7970   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7971   // have to do anything here to lower funclet bundles.
7972   // CFGuardTarget bundles are lowered in LowerCallTo.
7973   assert(!I.hasOperandBundlesOtherThan(
7974              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
7975               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
7976               LLVMContext::OB_clang_arc_attachedcall}) &&
7977          "Cannot lower calls with arbitrary operand bundles!");
7978 
7979   SDValue Callee = getValue(I.getCalledOperand());
7980 
7981   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7982     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7983   else
7984     // Check if we can potentially perform a tail call. More detailed checking
7985     // is be done within LowerCallTo, after more information about the call is
7986     // known.
7987     LowerCallTo(I, Callee, I.isTailCall());
7988 }
7989 
7990 namespace {
7991 
7992 /// AsmOperandInfo - This contains information for each constraint that we are
7993 /// lowering.
7994 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7995 public:
7996   /// CallOperand - If this is the result output operand or a clobber
7997   /// this is null, otherwise it is the incoming operand to the CallInst.
7998   /// This gets modified as the asm is processed.
7999   SDValue CallOperand;
8000 
8001   /// AssignedRegs - If this is a register or register class operand, this
8002   /// contains the set of register corresponding to the operand.
8003   RegsForValue AssignedRegs;
8004 
8005   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8006     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8007   }
8008 
8009   /// Whether or not this operand accesses memory
8010   bool hasMemory(const TargetLowering &TLI) const {
8011     // Indirect operand accesses access memory.
8012     if (isIndirect)
8013       return true;
8014 
8015     for (const auto &Code : Codes)
8016       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8017         return true;
8018 
8019     return false;
8020   }
8021 
8022   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
8023   /// corresponds to.  If there is no Value* for this operand, it returns
8024   /// MVT::Other.
8025   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
8026                            const DataLayout &DL) const {
8027     if (!CallOperandVal) return MVT::Other;
8028 
8029     if (isa<BasicBlock>(CallOperandVal))
8030       return TLI.getProgramPointerTy(DL);
8031 
8032     llvm::Type *OpTy = CallOperandVal->getType();
8033 
8034     // FIXME: code duplicated from TargetLowering::ParseConstraints().
8035     // If this is an indirect operand, the operand is a pointer to the
8036     // accessed type.
8037     if (isIndirect) {
8038       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
8039       if (!PtrTy)
8040         report_fatal_error("Indirect operand for inline asm not a pointer!");
8041       OpTy = PtrTy->getElementType();
8042     }
8043 
8044     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
8045     if (StructType *STy = dyn_cast<StructType>(OpTy))
8046       if (STy->getNumElements() == 1)
8047         OpTy = STy->getElementType(0);
8048 
8049     // If OpTy is not a single value, it may be a struct/union that we
8050     // can tile with integers.
8051     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
8052       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
8053       switch (BitSize) {
8054       default: break;
8055       case 1:
8056       case 8:
8057       case 16:
8058       case 32:
8059       case 64:
8060       case 128:
8061         OpTy = IntegerType::get(Context, BitSize);
8062         break;
8063       }
8064     }
8065 
8066     return TLI.getValueType(DL, OpTy, true);
8067   }
8068 };
8069 
8070 
8071 } // end anonymous namespace
8072 
8073 /// Make sure that the output operand \p OpInfo and its corresponding input
8074 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8075 /// out).
8076 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8077                                SDISelAsmOperandInfo &MatchingOpInfo,
8078                                SelectionDAG &DAG) {
8079   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8080     return;
8081 
8082   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8083   const auto &TLI = DAG.getTargetLoweringInfo();
8084 
8085   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8086       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8087                                        OpInfo.ConstraintVT);
8088   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8089       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8090                                        MatchingOpInfo.ConstraintVT);
8091   if ((OpInfo.ConstraintVT.isInteger() !=
8092        MatchingOpInfo.ConstraintVT.isInteger()) ||
8093       (MatchRC.second != InputRC.second)) {
8094     // FIXME: error out in a more elegant fashion
8095     report_fatal_error("Unsupported asm: input constraint"
8096                        " with a matching output constraint of"
8097                        " incompatible type!");
8098   }
8099   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8100 }
8101 
8102 /// Get a direct memory input to behave well as an indirect operand.
8103 /// This may introduce stores, hence the need for a \p Chain.
8104 /// \return The (possibly updated) chain.
8105 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8106                                         SDISelAsmOperandInfo &OpInfo,
8107                                         SelectionDAG &DAG) {
8108   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8109 
8110   // If we don't have an indirect input, put it in the constpool if we can,
8111   // otherwise spill it to a stack slot.
8112   // TODO: This isn't quite right. We need to handle these according to
8113   // the addressing mode that the constraint wants. Also, this may take
8114   // an additional register for the computation and we don't want that
8115   // either.
8116 
8117   // If the operand is a float, integer, or vector constant, spill to a
8118   // constant pool entry to get its address.
8119   const Value *OpVal = OpInfo.CallOperandVal;
8120   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8121       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8122     OpInfo.CallOperand = DAG.getConstantPool(
8123         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8124     return Chain;
8125   }
8126 
8127   // Otherwise, create a stack slot and emit a store to it before the asm.
8128   Type *Ty = OpVal->getType();
8129   auto &DL = DAG.getDataLayout();
8130   uint64_t TySize = DL.getTypeAllocSize(Ty);
8131   MachineFunction &MF = DAG.getMachineFunction();
8132   int SSFI = MF.getFrameInfo().CreateStackObject(
8133       TySize, DL.getPrefTypeAlign(Ty), false);
8134   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8135   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8136                             MachinePointerInfo::getFixedStack(MF, SSFI),
8137                             TLI.getMemValueType(DL, Ty));
8138   OpInfo.CallOperand = StackSlot;
8139 
8140   return Chain;
8141 }
8142 
8143 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8144 /// specified operand.  We prefer to assign virtual registers, to allow the
8145 /// register allocator to handle the assignment process.  However, if the asm
8146 /// uses features that we can't model on machineinstrs, we have SDISel do the
8147 /// allocation.  This produces generally horrible, but correct, code.
8148 ///
8149 ///   OpInfo describes the operand
8150 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8151 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8152                                  SDISelAsmOperandInfo &OpInfo,
8153                                  SDISelAsmOperandInfo &RefOpInfo) {
8154   LLVMContext &Context = *DAG.getContext();
8155   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8156 
8157   MachineFunction &MF = DAG.getMachineFunction();
8158   SmallVector<unsigned, 4> Regs;
8159   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8160 
8161   // No work to do for memory operations.
8162   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8163     return;
8164 
8165   // If this is a constraint for a single physreg, or a constraint for a
8166   // register class, find it.
8167   unsigned AssignedReg;
8168   const TargetRegisterClass *RC;
8169   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8170       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8171   // RC is unset only on failure. Return immediately.
8172   if (!RC)
8173     return;
8174 
8175   // Get the actual register value type.  This is important, because the user
8176   // may have asked for (e.g.) the AX register in i32 type.  We need to
8177   // remember that AX is actually i16 to get the right extension.
8178   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8179 
8180   if (OpInfo.ConstraintVT != MVT::Other) {
8181     // If this is an FP operand in an integer register (or visa versa), or more
8182     // generally if the operand value disagrees with the register class we plan
8183     // to stick it in, fix the operand type.
8184     //
8185     // If this is an input value, the bitcast to the new type is done now.
8186     // Bitcast for output value is done at the end of visitInlineAsm().
8187     if ((OpInfo.Type == InlineAsm::isOutput ||
8188          OpInfo.Type == InlineAsm::isInput) &&
8189         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8190       // Try to convert to the first EVT that the reg class contains.  If the
8191       // types are identical size, use a bitcast to convert (e.g. two differing
8192       // vector types).  Note: output bitcast is done at the end of
8193       // visitInlineAsm().
8194       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8195         // Exclude indirect inputs while they are unsupported because the code
8196         // to perform the load is missing and thus OpInfo.CallOperand still
8197         // refers to the input address rather than the pointed-to value.
8198         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8199           OpInfo.CallOperand =
8200               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8201         OpInfo.ConstraintVT = RegVT;
8202         // If the operand is an FP value and we want it in integer registers,
8203         // use the corresponding integer type. This turns an f64 value into
8204         // i64, which can be passed with two i32 values on a 32-bit machine.
8205       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8206         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8207         if (OpInfo.Type == InlineAsm::isInput)
8208           OpInfo.CallOperand =
8209               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8210         OpInfo.ConstraintVT = VT;
8211       }
8212     }
8213   }
8214 
8215   // No need to allocate a matching input constraint since the constraint it's
8216   // matching to has already been allocated.
8217   if (OpInfo.isMatchingInputConstraint())
8218     return;
8219 
8220   EVT ValueVT = OpInfo.ConstraintVT;
8221   if (OpInfo.ConstraintVT == MVT::Other)
8222     ValueVT = RegVT;
8223 
8224   // Initialize NumRegs.
8225   unsigned NumRegs = 1;
8226   if (OpInfo.ConstraintVT != MVT::Other)
8227     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
8228 
8229   // If this is a constraint for a specific physical register, like {r17},
8230   // assign it now.
8231 
8232   // If this associated to a specific register, initialize iterator to correct
8233   // place. If virtual, make sure we have enough registers
8234 
8235   // Initialize iterator if necessary
8236   TargetRegisterClass::iterator I = RC->begin();
8237   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8238 
8239   // Do not check for single registers.
8240   if (AssignedReg) {
8241       for (; *I != AssignedReg; ++I)
8242         assert(I != RC->end() && "AssignedReg should be member of RC");
8243   }
8244 
8245   for (; NumRegs; --NumRegs, ++I) {
8246     assert(I != RC->end() && "Ran out of registers to allocate!");
8247     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8248     Regs.push_back(R);
8249   }
8250 
8251   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8252 }
8253 
8254 static unsigned
8255 findMatchingInlineAsmOperand(unsigned OperandNo,
8256                              const std::vector<SDValue> &AsmNodeOperands) {
8257   // Scan until we find the definition we already emitted of this operand.
8258   unsigned CurOp = InlineAsm::Op_FirstOperand;
8259   for (; OperandNo; --OperandNo) {
8260     // Advance to the next operand.
8261     unsigned OpFlag =
8262         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8263     assert((InlineAsm::isRegDefKind(OpFlag) ||
8264             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8265             InlineAsm::isMemKind(OpFlag)) &&
8266            "Skipped past definitions?");
8267     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8268   }
8269   return CurOp;
8270 }
8271 
8272 namespace {
8273 
8274 class ExtraFlags {
8275   unsigned Flags = 0;
8276 
8277 public:
8278   explicit ExtraFlags(const CallBase &Call) {
8279     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8280     if (IA->hasSideEffects())
8281       Flags |= InlineAsm::Extra_HasSideEffects;
8282     if (IA->isAlignStack())
8283       Flags |= InlineAsm::Extra_IsAlignStack;
8284     if (Call.isConvergent())
8285       Flags |= InlineAsm::Extra_IsConvergent;
8286     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8287   }
8288 
8289   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8290     // Ideally, we would only check against memory constraints.  However, the
8291     // meaning of an Other constraint can be target-specific and we can't easily
8292     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8293     // for Other constraints as well.
8294     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8295         OpInfo.ConstraintType == TargetLowering::C_Other) {
8296       if (OpInfo.Type == InlineAsm::isInput)
8297         Flags |= InlineAsm::Extra_MayLoad;
8298       else if (OpInfo.Type == InlineAsm::isOutput)
8299         Flags |= InlineAsm::Extra_MayStore;
8300       else if (OpInfo.Type == InlineAsm::isClobber)
8301         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8302     }
8303   }
8304 
8305   unsigned get() const { return Flags; }
8306 };
8307 
8308 } // end anonymous namespace
8309 
8310 /// visitInlineAsm - Handle a call to an InlineAsm object.
8311 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
8312   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8313 
8314   /// ConstraintOperands - Information about all of the constraints.
8315   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8316 
8317   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8318   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8319       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8320 
8321   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8322   // AsmDialect, MayLoad, MayStore).
8323   bool HasSideEffect = IA->hasSideEffects();
8324   ExtraFlags ExtraInfo(Call);
8325 
8326   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8327   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8328   unsigned NumMatchingOps = 0;
8329   for (auto &T : TargetConstraints) {
8330     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8331     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8332 
8333     // Compute the value type for each operand.
8334     if (OpInfo.Type == InlineAsm::isInput ||
8335         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8336       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8337 
8338       // Process the call argument. BasicBlocks are labels, currently appearing
8339       // only in asm's.
8340       if (isa<CallBrInst>(Call) &&
8341           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8342                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8343                         NumMatchingOps) &&
8344           (NumMatchingOps == 0 ||
8345            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8346                         NumMatchingOps))) {
8347         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8348         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8349         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8350       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8351         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8352       } else {
8353         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8354       }
8355 
8356       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8357                                            DAG.getDataLayout());
8358       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8359     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8360       // The return value of the call is this value.  As such, there is no
8361       // corresponding argument.
8362       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8363       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8364         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8365             DAG.getDataLayout(), STy->getElementType(ResNo));
8366       } else {
8367         assert(ResNo == 0 && "Asm only has one result!");
8368         OpInfo.ConstraintVT =
8369             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8370       }
8371       ++ResNo;
8372     } else {
8373       OpInfo.ConstraintVT = MVT::Other;
8374     }
8375 
8376     if (OpInfo.hasMatchingInput())
8377       ++NumMatchingOps;
8378 
8379     if (!HasSideEffect)
8380       HasSideEffect = OpInfo.hasMemory(TLI);
8381 
8382     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8383     // FIXME: Could we compute this on OpInfo rather than T?
8384 
8385     // Compute the constraint code and ConstraintType to use.
8386     TLI.ComputeConstraintToUse(T, SDValue());
8387 
8388     if (T.ConstraintType == TargetLowering::C_Immediate &&
8389         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8390       // We've delayed emitting a diagnostic like the "n" constraint because
8391       // inlining could cause an integer showing up.
8392       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8393                                           "' expects an integer constant "
8394                                           "expression");
8395 
8396     ExtraInfo.update(T);
8397   }
8398 
8399 
8400   // We won't need to flush pending loads if this asm doesn't touch
8401   // memory and is nonvolatile.
8402   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8403 
8404   bool IsCallBr = isa<CallBrInst>(Call);
8405   if (IsCallBr) {
8406     // If this is a callbr we need to flush pending exports since inlineasm_br
8407     // is a terminator. We need to do this before nodes are glued to
8408     // the inlineasm_br node.
8409     Chain = getControlRoot();
8410   }
8411 
8412   // Second pass over the constraints: compute which constraint option to use.
8413   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8414     // If this is an output operand with a matching input operand, look up the
8415     // matching input. If their types mismatch, e.g. one is an integer, the
8416     // other is floating point, or their sizes are different, flag it as an
8417     // error.
8418     if (OpInfo.hasMatchingInput()) {
8419       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8420       patchMatchingInput(OpInfo, Input, DAG);
8421     }
8422 
8423     // Compute the constraint code and ConstraintType to use.
8424     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8425 
8426     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8427         OpInfo.Type == InlineAsm::isClobber)
8428       continue;
8429 
8430     // If this is a memory input, and if the operand is not indirect, do what we
8431     // need to provide an address for the memory input.
8432     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8433         !OpInfo.isIndirect) {
8434       assert((OpInfo.isMultipleAlternative ||
8435               (OpInfo.Type == InlineAsm::isInput)) &&
8436              "Can only indirectify direct input operands!");
8437 
8438       // Memory operands really want the address of the value.
8439       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8440 
8441       // There is no longer a Value* corresponding to this operand.
8442       OpInfo.CallOperandVal = nullptr;
8443 
8444       // It is now an indirect operand.
8445       OpInfo.isIndirect = true;
8446     }
8447 
8448   }
8449 
8450   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8451   std::vector<SDValue> AsmNodeOperands;
8452   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8453   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8454       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8455 
8456   // If we have a !srcloc metadata node associated with it, we want to attach
8457   // this to the ultimately generated inline asm machineinstr.  To do this, we
8458   // pass in the third operand as this (potentially null) inline asm MDNode.
8459   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8460   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8461 
8462   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8463   // bits as operand 3.
8464   AsmNodeOperands.push_back(DAG.getTargetConstant(
8465       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8466 
8467   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8468   // this, assign virtual and physical registers for inputs and otput.
8469   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8470     // Assign Registers.
8471     SDISelAsmOperandInfo &RefOpInfo =
8472         OpInfo.isMatchingInputConstraint()
8473             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8474             : OpInfo;
8475     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8476 
8477     auto DetectWriteToReservedRegister = [&]() {
8478       const MachineFunction &MF = DAG.getMachineFunction();
8479       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8480       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8481         if (Register::isPhysicalRegister(Reg) &&
8482             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8483           const char *RegName = TRI.getName(Reg);
8484           emitInlineAsmError(Call, "write to reserved register '" +
8485                                        Twine(RegName) + "'");
8486           return true;
8487         }
8488       }
8489       return false;
8490     };
8491 
8492     switch (OpInfo.Type) {
8493     case InlineAsm::isOutput:
8494       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8495         unsigned ConstraintID =
8496             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8497         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8498                "Failed to convert memory constraint code to constraint id.");
8499 
8500         // Add information to the INLINEASM node to know about this output.
8501         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8502         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8503         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8504                                                         MVT::i32));
8505         AsmNodeOperands.push_back(OpInfo.CallOperand);
8506       } else {
8507         // Otherwise, this outputs to a register (directly for C_Register /
8508         // C_RegisterClass, and a target-defined fashion for
8509         // C_Immediate/C_Other). Find a register that we can use.
8510         if (OpInfo.AssignedRegs.Regs.empty()) {
8511           emitInlineAsmError(
8512               Call, "couldn't allocate output register for constraint '" +
8513                         Twine(OpInfo.ConstraintCode) + "'");
8514           return;
8515         }
8516 
8517         if (DetectWriteToReservedRegister())
8518           return;
8519 
8520         // Add information to the INLINEASM node to know that this register is
8521         // set.
8522         OpInfo.AssignedRegs.AddInlineAsmOperands(
8523             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8524                                   : InlineAsm::Kind_RegDef,
8525             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8526       }
8527       break;
8528 
8529     case InlineAsm::isInput: {
8530       SDValue InOperandVal = OpInfo.CallOperand;
8531 
8532       if (OpInfo.isMatchingInputConstraint()) {
8533         // If this is required to match an output register we have already set,
8534         // just use its register.
8535         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8536                                                   AsmNodeOperands);
8537         unsigned OpFlag =
8538           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8539         if (InlineAsm::isRegDefKind(OpFlag) ||
8540             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8541           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8542           if (OpInfo.isIndirect) {
8543             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8544             emitInlineAsmError(Call, "inline asm not supported yet: "
8545                                      "don't know how to handle tied "
8546                                      "indirect register inputs");
8547             return;
8548           }
8549 
8550           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8551           SmallVector<unsigned, 4> Regs;
8552 
8553           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8554             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8555             MachineRegisterInfo &RegInfo =
8556                 DAG.getMachineFunction().getRegInfo();
8557             for (unsigned i = 0; i != NumRegs; ++i)
8558               Regs.push_back(RegInfo.createVirtualRegister(RC));
8559           } else {
8560             emitInlineAsmError(Call,
8561                                "inline asm error: This value type register "
8562                                "class is not natively supported!");
8563             return;
8564           }
8565 
8566           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8567 
8568           SDLoc dl = getCurSDLoc();
8569           // Use the produced MatchedRegs object to
8570           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8571           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8572                                            true, OpInfo.getMatchedOperand(), dl,
8573                                            DAG, AsmNodeOperands);
8574           break;
8575         }
8576 
8577         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8578         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8579                "Unexpected number of operands");
8580         // Add information to the INLINEASM node to know about this input.
8581         // See InlineAsm.h isUseOperandTiedToDef.
8582         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8583         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8584                                                     OpInfo.getMatchedOperand());
8585         AsmNodeOperands.push_back(DAG.getTargetConstant(
8586             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8587         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8588         break;
8589       }
8590 
8591       // Treat indirect 'X' constraint as memory.
8592       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8593           OpInfo.isIndirect)
8594         OpInfo.ConstraintType = TargetLowering::C_Memory;
8595 
8596       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8597           OpInfo.ConstraintType == TargetLowering::C_Other) {
8598         std::vector<SDValue> Ops;
8599         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8600                                           Ops, DAG);
8601         if (Ops.empty()) {
8602           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8603             if (isa<ConstantSDNode>(InOperandVal)) {
8604               emitInlineAsmError(Call, "value out of range for constraint '" +
8605                                            Twine(OpInfo.ConstraintCode) + "'");
8606               return;
8607             }
8608 
8609           emitInlineAsmError(Call,
8610                              "invalid operand for inline asm constraint '" +
8611                                  Twine(OpInfo.ConstraintCode) + "'");
8612           return;
8613         }
8614 
8615         // Add information to the INLINEASM node to know about this input.
8616         unsigned ResOpType =
8617           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8618         AsmNodeOperands.push_back(DAG.getTargetConstant(
8619             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8620         llvm::append_range(AsmNodeOperands, Ops);
8621         break;
8622       }
8623 
8624       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8625         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8626         assert(InOperandVal.getValueType() ==
8627                    TLI.getPointerTy(DAG.getDataLayout()) &&
8628                "Memory operands expect pointer values");
8629 
8630         unsigned ConstraintID =
8631             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8632         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8633                "Failed to convert memory constraint code to constraint id.");
8634 
8635         // Add information to the INLINEASM node to know about this input.
8636         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8637         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8638         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8639                                                         getCurSDLoc(),
8640                                                         MVT::i32));
8641         AsmNodeOperands.push_back(InOperandVal);
8642         break;
8643       }
8644 
8645       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8646               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8647              "Unknown constraint type!");
8648 
8649       // TODO: Support this.
8650       if (OpInfo.isIndirect) {
8651         emitInlineAsmError(
8652             Call, "Don't know how to handle indirect register inputs yet "
8653                   "for constraint '" +
8654                       Twine(OpInfo.ConstraintCode) + "'");
8655         return;
8656       }
8657 
8658       // Copy the input into the appropriate registers.
8659       if (OpInfo.AssignedRegs.Regs.empty()) {
8660         emitInlineAsmError(Call,
8661                            "couldn't allocate input reg for constraint '" +
8662                                Twine(OpInfo.ConstraintCode) + "'");
8663         return;
8664       }
8665 
8666       if (DetectWriteToReservedRegister())
8667         return;
8668 
8669       SDLoc dl = getCurSDLoc();
8670 
8671       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8672                                         &Call);
8673 
8674       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8675                                                dl, DAG, AsmNodeOperands);
8676       break;
8677     }
8678     case InlineAsm::isClobber:
8679       // Add the clobbered value to the operand list, so that the register
8680       // allocator is aware that the physreg got clobbered.
8681       if (!OpInfo.AssignedRegs.Regs.empty())
8682         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8683                                                  false, 0, getCurSDLoc(), DAG,
8684                                                  AsmNodeOperands);
8685       break;
8686     }
8687   }
8688 
8689   // Finish up input operands.  Set the input chain and add the flag last.
8690   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8691   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8692 
8693   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8694   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8695                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8696   Flag = Chain.getValue(1);
8697 
8698   // Do additional work to generate outputs.
8699 
8700   SmallVector<EVT, 1> ResultVTs;
8701   SmallVector<SDValue, 1> ResultValues;
8702   SmallVector<SDValue, 8> OutChains;
8703 
8704   llvm::Type *CallResultType = Call.getType();
8705   ArrayRef<Type *> ResultTypes;
8706   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8707     ResultTypes = StructResult->elements();
8708   else if (!CallResultType->isVoidTy())
8709     ResultTypes = makeArrayRef(CallResultType);
8710 
8711   auto CurResultType = ResultTypes.begin();
8712   auto handleRegAssign = [&](SDValue V) {
8713     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8714     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8715     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8716     ++CurResultType;
8717     // If the type of the inline asm call site return value is different but has
8718     // same size as the type of the asm output bitcast it.  One example of this
8719     // is for vectors with different width / number of elements.  This can
8720     // happen for register classes that can contain multiple different value
8721     // types.  The preg or vreg allocated may not have the same VT as was
8722     // expected.
8723     //
8724     // This can also happen for a return value that disagrees with the register
8725     // class it is put in, eg. a double in a general-purpose register on a
8726     // 32-bit machine.
8727     if (ResultVT != V.getValueType() &&
8728         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8729       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8730     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8731              V.getValueType().isInteger()) {
8732       // If a result value was tied to an input value, the computed result
8733       // may have a wider width than the expected result.  Extract the
8734       // relevant portion.
8735       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8736     }
8737     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8738     ResultVTs.push_back(ResultVT);
8739     ResultValues.push_back(V);
8740   };
8741 
8742   // Deal with output operands.
8743   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8744     if (OpInfo.Type == InlineAsm::isOutput) {
8745       SDValue Val;
8746       // Skip trivial output operands.
8747       if (OpInfo.AssignedRegs.Regs.empty())
8748         continue;
8749 
8750       switch (OpInfo.ConstraintType) {
8751       case TargetLowering::C_Register:
8752       case TargetLowering::C_RegisterClass:
8753         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8754                                                   Chain, &Flag, &Call);
8755         break;
8756       case TargetLowering::C_Immediate:
8757       case TargetLowering::C_Other:
8758         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8759                                               OpInfo, DAG);
8760         break;
8761       case TargetLowering::C_Memory:
8762         break; // Already handled.
8763       case TargetLowering::C_Unknown:
8764         assert(false && "Unexpected unknown constraint");
8765       }
8766 
8767       // Indirect output manifest as stores. Record output chains.
8768       if (OpInfo.isIndirect) {
8769         const Value *Ptr = OpInfo.CallOperandVal;
8770         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8771         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8772                                      MachinePointerInfo(Ptr));
8773         OutChains.push_back(Store);
8774       } else {
8775         // generate CopyFromRegs to associated registers.
8776         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8777         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8778           for (const SDValue &V : Val->op_values())
8779             handleRegAssign(V);
8780         } else
8781           handleRegAssign(Val);
8782       }
8783     }
8784   }
8785 
8786   // Set results.
8787   if (!ResultValues.empty()) {
8788     assert(CurResultType == ResultTypes.end() &&
8789            "Mismatch in number of ResultTypes");
8790     assert(ResultValues.size() == ResultTypes.size() &&
8791            "Mismatch in number of output operands in asm result");
8792 
8793     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8794                             DAG.getVTList(ResultVTs), ResultValues);
8795     setValue(&Call, V);
8796   }
8797 
8798   // Collect store chains.
8799   if (!OutChains.empty())
8800     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8801 
8802   // Only Update Root if inline assembly has a memory effect.
8803   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8804     DAG.setRoot(Chain);
8805 }
8806 
8807 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8808                                              const Twine &Message) {
8809   LLVMContext &Ctx = *DAG.getContext();
8810   Ctx.emitError(&Call, Message);
8811 
8812   // Make sure we leave the DAG in a valid state
8813   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8814   SmallVector<EVT, 1> ValueVTs;
8815   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8816 
8817   if (ValueVTs.empty())
8818     return;
8819 
8820   SmallVector<SDValue, 1> Ops;
8821   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8822     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8823 
8824   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8825 }
8826 
8827 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8828   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8829                           MVT::Other, getRoot(),
8830                           getValue(I.getArgOperand(0)),
8831                           DAG.getSrcValue(I.getArgOperand(0))));
8832 }
8833 
8834 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8835   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8836   const DataLayout &DL = DAG.getDataLayout();
8837   SDValue V = DAG.getVAArg(
8838       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8839       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8840       DL.getABITypeAlign(I.getType()).value());
8841   DAG.setRoot(V.getValue(1));
8842 
8843   if (I.getType()->isPointerTy())
8844     V = DAG.getPtrExtOrTrunc(
8845         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8846   setValue(&I, V);
8847 }
8848 
8849 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8850   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8851                           MVT::Other, getRoot(),
8852                           getValue(I.getArgOperand(0)),
8853                           DAG.getSrcValue(I.getArgOperand(0))));
8854 }
8855 
8856 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8857   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8858                           MVT::Other, getRoot(),
8859                           getValue(I.getArgOperand(0)),
8860                           getValue(I.getArgOperand(1)),
8861                           DAG.getSrcValue(I.getArgOperand(0)),
8862                           DAG.getSrcValue(I.getArgOperand(1))));
8863 }
8864 
8865 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8866                                                     const Instruction &I,
8867                                                     SDValue Op) {
8868   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8869   if (!Range)
8870     return Op;
8871 
8872   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8873   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8874     return Op;
8875 
8876   APInt Lo = CR.getUnsignedMin();
8877   if (!Lo.isMinValue())
8878     return Op;
8879 
8880   APInt Hi = CR.getUnsignedMax();
8881   unsigned Bits = std::max(Hi.getActiveBits(),
8882                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8883 
8884   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8885 
8886   SDLoc SL = getCurSDLoc();
8887 
8888   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8889                              DAG.getValueType(SmallVT));
8890   unsigned NumVals = Op.getNode()->getNumValues();
8891   if (NumVals == 1)
8892     return ZExt;
8893 
8894   SmallVector<SDValue, 4> Ops;
8895 
8896   Ops.push_back(ZExt);
8897   for (unsigned I = 1; I != NumVals; ++I)
8898     Ops.push_back(Op.getValue(I));
8899 
8900   return DAG.getMergeValues(Ops, SL);
8901 }
8902 
8903 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8904 /// the call being lowered.
8905 ///
8906 /// This is a helper for lowering intrinsics that follow a target calling
8907 /// convention or require stack pointer adjustment. Only a subset of the
8908 /// intrinsic's operands need to participate in the calling convention.
8909 void SelectionDAGBuilder::populateCallLoweringInfo(
8910     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8911     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8912     bool IsPatchPoint) {
8913   TargetLowering::ArgListTy Args;
8914   Args.reserve(NumArgs);
8915 
8916   // Populate the argument list.
8917   // Attributes for args start at offset 1, after the return attribute.
8918   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8919        ArgI != ArgE; ++ArgI) {
8920     const Value *V = Call->getOperand(ArgI);
8921 
8922     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8923 
8924     TargetLowering::ArgListEntry Entry;
8925     Entry.Node = getValue(V);
8926     Entry.Ty = V->getType();
8927     Entry.setAttributes(Call, ArgI);
8928     Args.push_back(Entry);
8929   }
8930 
8931   CLI.setDebugLoc(getCurSDLoc())
8932       .setChain(getRoot())
8933       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8934       .setDiscardResult(Call->use_empty())
8935       .setIsPatchPoint(IsPatchPoint)
8936       .setIsPreallocated(
8937           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
8938 }
8939 
8940 /// Add a stack map intrinsic call's live variable operands to a stackmap
8941 /// or patchpoint target node's operand list.
8942 ///
8943 /// Constants are converted to TargetConstants purely as an optimization to
8944 /// avoid constant materialization and register allocation.
8945 ///
8946 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8947 /// generate addess computation nodes, and so FinalizeISel can convert the
8948 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8949 /// address materialization and register allocation, but may also be required
8950 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8951 /// alloca in the entry block, then the runtime may assume that the alloca's
8952 /// StackMap location can be read immediately after compilation and that the
8953 /// location is valid at any point during execution (this is similar to the
8954 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8955 /// only available in a register, then the runtime would need to trap when
8956 /// execution reaches the StackMap in order to read the alloca's location.
8957 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8958                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8959                                 SelectionDAGBuilder &Builder) {
8960   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8961     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8962     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8963       Ops.push_back(
8964         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8965       Ops.push_back(
8966         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8967     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8968       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8969       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8970           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8971     } else
8972       Ops.push_back(OpVal);
8973   }
8974 }
8975 
8976 /// Lower llvm.experimental.stackmap directly to its target opcode.
8977 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8978   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8979   //                                  [live variables...])
8980 
8981   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8982 
8983   SDValue Chain, InFlag, Callee, NullPtr;
8984   SmallVector<SDValue, 32> Ops;
8985 
8986   SDLoc DL = getCurSDLoc();
8987   Callee = getValue(CI.getCalledOperand());
8988   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8989 
8990   // The stackmap intrinsic only records the live variables (the arguments
8991   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8992   // intrinsic, this won't be lowered to a function call. This means we don't
8993   // have to worry about calling conventions and target specific lowering code.
8994   // Instead we perform the call lowering right here.
8995   //
8996   // chain, flag = CALLSEQ_START(chain, 0, 0)
8997   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8998   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8999   //
9000   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9001   InFlag = Chain.getValue(1);
9002 
9003   // Add the <id> and <numBytes> constants.
9004   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
9005   Ops.push_back(DAG.getTargetConstant(
9006                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
9007   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
9008   Ops.push_back(DAG.getTargetConstant(
9009                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
9010                   MVT::i32));
9011 
9012   // Push live variables for the stack map.
9013   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9014 
9015   // We are not pushing any register mask info here on the operands list,
9016   // because the stackmap doesn't clobber anything.
9017 
9018   // Push the chain and the glue flag.
9019   Ops.push_back(Chain);
9020   Ops.push_back(InFlag);
9021 
9022   // Create the STACKMAP node.
9023   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9024   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
9025   Chain = SDValue(SM, 0);
9026   InFlag = Chain.getValue(1);
9027 
9028   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9029 
9030   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9031 
9032   // Set the root to the target-lowered call chain.
9033   DAG.setRoot(Chain);
9034 
9035   // Inform the Frame Information that we have a stackmap in this function.
9036   FuncInfo.MF->getFrameInfo().setHasStackMap();
9037 }
9038 
9039 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9040 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9041                                           const BasicBlock *EHPadBB) {
9042   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9043   //                                                 i32 <numBytes>,
9044   //                                                 i8* <target>,
9045   //                                                 i32 <numArgs>,
9046   //                                                 [Args...],
9047   //                                                 [live variables...])
9048 
9049   CallingConv::ID CC = CB.getCallingConv();
9050   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9051   bool HasDef = !CB.getType()->isVoidTy();
9052   SDLoc dl = getCurSDLoc();
9053   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9054 
9055   // Handle immediate and symbolic callees.
9056   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9057     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9058                                    /*isTarget=*/true);
9059   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9060     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9061                                          SDLoc(SymbolicCallee),
9062                                          SymbolicCallee->getValueType(0));
9063 
9064   // Get the real number of arguments participating in the call <numArgs>
9065   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9066   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9067 
9068   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9069   // Intrinsics include all meta-operands up to but not including CC.
9070   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9071   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9072          "Not enough arguments provided to the patchpoint intrinsic");
9073 
9074   // For AnyRegCC the arguments are lowered later on manually.
9075   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9076   Type *ReturnTy =
9077       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9078 
9079   TargetLowering::CallLoweringInfo CLI(DAG);
9080   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9081                            ReturnTy, true);
9082   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9083 
9084   SDNode *CallEnd = Result.second.getNode();
9085   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9086     CallEnd = CallEnd->getOperand(0).getNode();
9087 
9088   /// Get a call instruction from the call sequence chain.
9089   /// Tail calls are not allowed.
9090   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9091          "Expected a callseq node.");
9092   SDNode *Call = CallEnd->getOperand(0).getNode();
9093   bool HasGlue = Call->getGluedNode();
9094 
9095   // Replace the target specific call node with the patchable intrinsic.
9096   SmallVector<SDValue, 8> Ops;
9097 
9098   // Add the <id> and <numBytes> constants.
9099   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9100   Ops.push_back(DAG.getTargetConstant(
9101                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9102   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9103   Ops.push_back(DAG.getTargetConstant(
9104                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9105                   MVT::i32));
9106 
9107   // Add the callee.
9108   Ops.push_back(Callee);
9109 
9110   // Adjust <numArgs> to account for any arguments that have been passed on the
9111   // stack instead.
9112   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9113   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9114   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9115   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9116 
9117   // Add the calling convention
9118   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9119 
9120   // Add the arguments we omitted previously. The register allocator should
9121   // place these in any free register.
9122   if (IsAnyRegCC)
9123     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9124       Ops.push_back(getValue(CB.getArgOperand(i)));
9125 
9126   // Push the arguments from the call instruction up to the register mask.
9127   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9128   Ops.append(Call->op_begin() + 2, e);
9129 
9130   // Push live variables for the stack map.
9131   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9132 
9133   // Push the register mask info.
9134   if (HasGlue)
9135     Ops.push_back(*(Call->op_end()-2));
9136   else
9137     Ops.push_back(*(Call->op_end()-1));
9138 
9139   // Push the chain (this is originally the first operand of the call, but
9140   // becomes now the last or second to last operand).
9141   Ops.push_back(*(Call->op_begin()));
9142 
9143   // Push the glue flag (last operand).
9144   if (HasGlue)
9145     Ops.push_back(*(Call->op_end()-1));
9146 
9147   SDVTList NodeTys;
9148   if (IsAnyRegCC && HasDef) {
9149     // Create the return types based on the intrinsic definition
9150     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9151     SmallVector<EVT, 3> ValueVTs;
9152     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9153     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9154 
9155     // There is always a chain and a glue type at the end
9156     ValueVTs.push_back(MVT::Other);
9157     ValueVTs.push_back(MVT::Glue);
9158     NodeTys = DAG.getVTList(ValueVTs);
9159   } else
9160     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9161 
9162   // Replace the target specific call node with a PATCHPOINT node.
9163   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9164                                          dl, NodeTys, Ops);
9165 
9166   // Update the NodeMap.
9167   if (HasDef) {
9168     if (IsAnyRegCC)
9169       setValue(&CB, SDValue(MN, 0));
9170     else
9171       setValue(&CB, Result.first);
9172   }
9173 
9174   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9175   // call sequence. Furthermore the location of the chain and glue can change
9176   // when the AnyReg calling convention is used and the intrinsic returns a
9177   // value.
9178   if (IsAnyRegCC && HasDef) {
9179     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9180     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9181     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9182   } else
9183     DAG.ReplaceAllUsesWith(Call, MN);
9184   DAG.DeleteNode(Call);
9185 
9186   // Inform the Frame Information that we have a patchpoint in this function.
9187   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9188 }
9189 
9190 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9191                                             unsigned Intrinsic) {
9192   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9193   SDValue Op1 = getValue(I.getArgOperand(0));
9194   SDValue Op2;
9195   if (I.getNumArgOperands() > 1)
9196     Op2 = getValue(I.getArgOperand(1));
9197   SDLoc dl = getCurSDLoc();
9198   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9199   SDValue Res;
9200   SDNodeFlags SDFlags;
9201   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9202     SDFlags.copyFMF(*FPMO);
9203 
9204   switch (Intrinsic) {
9205   case Intrinsic::vector_reduce_fadd:
9206     if (SDFlags.hasAllowReassociation())
9207       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9208                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9209                         SDFlags);
9210     else
9211       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9212     break;
9213   case Intrinsic::vector_reduce_fmul:
9214     if (SDFlags.hasAllowReassociation())
9215       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9216                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9217                         SDFlags);
9218     else
9219       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9220     break;
9221   case Intrinsic::vector_reduce_add:
9222     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9223     break;
9224   case Intrinsic::vector_reduce_mul:
9225     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9226     break;
9227   case Intrinsic::vector_reduce_and:
9228     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9229     break;
9230   case Intrinsic::vector_reduce_or:
9231     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9232     break;
9233   case Intrinsic::vector_reduce_xor:
9234     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9235     break;
9236   case Intrinsic::vector_reduce_smax:
9237     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9238     break;
9239   case Intrinsic::vector_reduce_smin:
9240     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9241     break;
9242   case Intrinsic::vector_reduce_umax:
9243     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9244     break;
9245   case Intrinsic::vector_reduce_umin:
9246     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9247     break;
9248   case Intrinsic::vector_reduce_fmax:
9249     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9250     break;
9251   case Intrinsic::vector_reduce_fmin:
9252     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9253     break;
9254   default:
9255     llvm_unreachable("Unhandled vector reduce intrinsic");
9256   }
9257   setValue(&I, Res);
9258 }
9259 
9260 /// Returns an AttributeList representing the attributes applied to the return
9261 /// value of the given call.
9262 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9263   SmallVector<Attribute::AttrKind, 2> Attrs;
9264   if (CLI.RetSExt)
9265     Attrs.push_back(Attribute::SExt);
9266   if (CLI.RetZExt)
9267     Attrs.push_back(Attribute::ZExt);
9268   if (CLI.IsInReg)
9269     Attrs.push_back(Attribute::InReg);
9270 
9271   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9272                             Attrs);
9273 }
9274 
9275 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9276 /// implementation, which just calls LowerCall.
9277 /// FIXME: When all targets are
9278 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9279 std::pair<SDValue, SDValue>
9280 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9281   // Handle the incoming return values from the call.
9282   CLI.Ins.clear();
9283   Type *OrigRetTy = CLI.RetTy;
9284   SmallVector<EVT, 4> RetTys;
9285   SmallVector<uint64_t, 4> Offsets;
9286   auto &DL = CLI.DAG.getDataLayout();
9287   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9288 
9289   if (CLI.IsPostTypeLegalization) {
9290     // If we are lowering a libcall after legalization, split the return type.
9291     SmallVector<EVT, 4> OldRetTys;
9292     SmallVector<uint64_t, 4> OldOffsets;
9293     RetTys.swap(OldRetTys);
9294     Offsets.swap(OldOffsets);
9295 
9296     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9297       EVT RetVT = OldRetTys[i];
9298       uint64_t Offset = OldOffsets[i];
9299       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9300       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9301       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9302       RetTys.append(NumRegs, RegisterVT);
9303       for (unsigned j = 0; j != NumRegs; ++j)
9304         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9305     }
9306   }
9307 
9308   SmallVector<ISD::OutputArg, 4> Outs;
9309   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9310 
9311   bool CanLowerReturn =
9312       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9313                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9314 
9315   SDValue DemoteStackSlot;
9316   int DemoteStackIdx = -100;
9317   if (!CanLowerReturn) {
9318     // FIXME: equivalent assert?
9319     // assert(!CS.hasInAllocaArgument() &&
9320     //        "sret demotion is incompatible with inalloca");
9321     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9322     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9323     MachineFunction &MF = CLI.DAG.getMachineFunction();
9324     DemoteStackIdx =
9325         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9326     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9327                                               DL.getAllocaAddrSpace());
9328 
9329     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9330     ArgListEntry Entry;
9331     Entry.Node = DemoteStackSlot;
9332     Entry.Ty = StackSlotPtrType;
9333     Entry.IsSExt = false;
9334     Entry.IsZExt = false;
9335     Entry.IsInReg = false;
9336     Entry.IsSRet = true;
9337     Entry.IsNest = false;
9338     Entry.IsByVal = false;
9339     Entry.IsByRef = false;
9340     Entry.IsReturned = false;
9341     Entry.IsSwiftSelf = false;
9342     Entry.IsSwiftError = false;
9343     Entry.IsCFGuardTarget = false;
9344     Entry.Alignment = Alignment;
9345     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9346     CLI.NumFixedArgs += 1;
9347     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9348 
9349     // sret demotion isn't compatible with tail-calls, since the sret argument
9350     // points into the callers stack frame.
9351     CLI.IsTailCall = false;
9352   } else {
9353     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9354         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9355     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9356       ISD::ArgFlagsTy Flags;
9357       if (NeedsRegBlock) {
9358         Flags.setInConsecutiveRegs();
9359         if (I == RetTys.size() - 1)
9360           Flags.setInConsecutiveRegsLast();
9361       }
9362       EVT VT = RetTys[I];
9363       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9364                                                      CLI.CallConv, VT);
9365       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9366                                                        CLI.CallConv, VT);
9367       for (unsigned i = 0; i != NumRegs; ++i) {
9368         ISD::InputArg MyFlags;
9369         MyFlags.Flags = Flags;
9370         MyFlags.VT = RegisterVT;
9371         MyFlags.ArgVT = VT;
9372         MyFlags.Used = CLI.IsReturnValueUsed;
9373         if (CLI.RetTy->isPointerTy()) {
9374           MyFlags.Flags.setPointer();
9375           MyFlags.Flags.setPointerAddrSpace(
9376               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9377         }
9378         if (CLI.RetSExt)
9379           MyFlags.Flags.setSExt();
9380         if (CLI.RetZExt)
9381           MyFlags.Flags.setZExt();
9382         if (CLI.IsInReg)
9383           MyFlags.Flags.setInReg();
9384         CLI.Ins.push_back(MyFlags);
9385       }
9386     }
9387   }
9388 
9389   // We push in swifterror return as the last element of CLI.Ins.
9390   ArgListTy &Args = CLI.getArgs();
9391   if (supportSwiftError()) {
9392     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9393       if (Args[i].IsSwiftError) {
9394         ISD::InputArg MyFlags;
9395         MyFlags.VT = getPointerTy(DL);
9396         MyFlags.ArgVT = EVT(getPointerTy(DL));
9397         MyFlags.Flags.setSwiftError();
9398         CLI.Ins.push_back(MyFlags);
9399       }
9400     }
9401   }
9402 
9403   // Handle all of the outgoing arguments.
9404   CLI.Outs.clear();
9405   CLI.OutVals.clear();
9406   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9407     SmallVector<EVT, 4> ValueVTs;
9408     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9409     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9410     Type *FinalType = Args[i].Ty;
9411     if (Args[i].IsByVal)
9412       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9413     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9414         FinalType, CLI.CallConv, CLI.IsVarArg);
9415     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9416          ++Value) {
9417       EVT VT = ValueVTs[Value];
9418       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9419       SDValue Op = SDValue(Args[i].Node.getNode(),
9420                            Args[i].Node.getResNo() + Value);
9421       ISD::ArgFlagsTy Flags;
9422 
9423       // Certain targets (such as MIPS), may have a different ABI alignment
9424       // for a type depending on the context. Give the target a chance to
9425       // specify the alignment it wants.
9426       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9427       Flags.setOrigAlign(OriginalAlignment);
9428 
9429       if (Args[i].Ty->isPointerTy()) {
9430         Flags.setPointer();
9431         Flags.setPointerAddrSpace(
9432             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9433       }
9434       if (Args[i].IsZExt)
9435         Flags.setZExt();
9436       if (Args[i].IsSExt)
9437         Flags.setSExt();
9438       if (Args[i].IsInReg) {
9439         // If we are using vectorcall calling convention, a structure that is
9440         // passed InReg - is surely an HVA
9441         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9442             isa<StructType>(FinalType)) {
9443           // The first value of a structure is marked
9444           if (0 == Value)
9445             Flags.setHvaStart();
9446           Flags.setHva();
9447         }
9448         // Set InReg Flag
9449         Flags.setInReg();
9450       }
9451       if (Args[i].IsSRet)
9452         Flags.setSRet();
9453       if (Args[i].IsSwiftSelf)
9454         Flags.setSwiftSelf();
9455       if (Args[i].IsSwiftError)
9456         Flags.setSwiftError();
9457       if (Args[i].IsCFGuardTarget)
9458         Flags.setCFGuardTarget();
9459       if (Args[i].IsByVal)
9460         Flags.setByVal();
9461       if (Args[i].IsByRef)
9462         Flags.setByRef();
9463       if (Args[i].IsPreallocated) {
9464         Flags.setPreallocated();
9465         // Set the byval flag for CCAssignFn callbacks that don't know about
9466         // preallocated.  This way we can know how many bytes we should've
9467         // allocated and how many bytes a callee cleanup function will pop.  If
9468         // we port preallocated to more targets, we'll have to add custom
9469         // preallocated handling in the various CC lowering callbacks.
9470         Flags.setByVal();
9471       }
9472       if (Args[i].IsInAlloca) {
9473         Flags.setInAlloca();
9474         // Set the byval flag for CCAssignFn callbacks that don't know about
9475         // inalloca.  This way we can know how many bytes we should've allocated
9476         // and how many bytes a callee cleanup function will pop.  If we port
9477         // inalloca to more targets, we'll have to add custom inalloca handling
9478         // in the various CC lowering callbacks.
9479         Flags.setByVal();
9480       }
9481       Align MemAlign;
9482       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9483         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9484         Type *ElementTy = Ty->getElementType();
9485 
9486         unsigned FrameSize = DL.getTypeAllocSize(
9487             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9488         Flags.setByValSize(FrameSize);
9489 
9490         // info is not there but there are cases it cannot get right.
9491         if (auto MA = Args[i].Alignment)
9492           MemAlign = *MA;
9493         else
9494           MemAlign = Align(getByValTypeAlignment(ElementTy, DL));
9495       } else if (auto MA = Args[i].Alignment) {
9496         MemAlign = *MA;
9497       } else {
9498         MemAlign = OriginalAlignment;
9499       }
9500       Flags.setMemAlign(MemAlign);
9501       if (Args[i].IsNest)
9502         Flags.setNest();
9503       if (NeedsRegBlock)
9504         Flags.setInConsecutiveRegs();
9505 
9506       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9507                                                  CLI.CallConv, VT);
9508       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9509                                                         CLI.CallConv, VT);
9510       SmallVector<SDValue, 4> Parts(NumParts);
9511       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9512 
9513       if (Args[i].IsSExt)
9514         ExtendKind = ISD::SIGN_EXTEND;
9515       else if (Args[i].IsZExt)
9516         ExtendKind = ISD::ZERO_EXTEND;
9517 
9518       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9519       // for now.
9520       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9521           CanLowerReturn) {
9522         assert((CLI.RetTy == Args[i].Ty ||
9523                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9524                  CLI.RetTy->getPointerAddressSpace() ==
9525                      Args[i].Ty->getPointerAddressSpace())) &&
9526                RetTys.size() == NumValues && "unexpected use of 'returned'");
9527         // Before passing 'returned' to the target lowering code, ensure that
9528         // either the register MVT and the actual EVT are the same size or that
9529         // the return value and argument are extended in the same way; in these
9530         // cases it's safe to pass the argument register value unchanged as the
9531         // return register value (although it's at the target's option whether
9532         // to do so)
9533         // TODO: allow code generation to take advantage of partially preserved
9534         // registers rather than clobbering the entire register when the
9535         // parameter extension method is not compatible with the return
9536         // extension method
9537         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9538             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9539              CLI.RetZExt == Args[i].IsZExt))
9540           Flags.setReturned();
9541       }
9542 
9543       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9544                      CLI.CallConv, ExtendKind);
9545 
9546       for (unsigned j = 0; j != NumParts; ++j) {
9547         // if it isn't first piece, alignment must be 1
9548         // For scalable vectors the scalable part is currently handled
9549         // by individual targets, so we just use the known minimum size here.
9550         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9551                     i < CLI.NumFixedArgs, i,
9552                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9553         if (NumParts > 1 && j == 0)
9554           MyFlags.Flags.setSplit();
9555         else if (j != 0) {
9556           MyFlags.Flags.setOrigAlign(Align(1));
9557           if (j == NumParts - 1)
9558             MyFlags.Flags.setSplitEnd();
9559         }
9560 
9561         CLI.Outs.push_back(MyFlags);
9562         CLI.OutVals.push_back(Parts[j]);
9563       }
9564 
9565       if (NeedsRegBlock && Value == NumValues - 1)
9566         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9567     }
9568   }
9569 
9570   SmallVector<SDValue, 4> InVals;
9571   CLI.Chain = LowerCall(CLI, InVals);
9572 
9573   // Update CLI.InVals to use outside of this function.
9574   CLI.InVals = InVals;
9575 
9576   // Verify that the target's LowerCall behaved as expected.
9577   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9578          "LowerCall didn't return a valid chain!");
9579   assert((!CLI.IsTailCall || InVals.empty()) &&
9580          "LowerCall emitted a return value for a tail call!");
9581   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9582          "LowerCall didn't emit the correct number of values!");
9583 
9584   // For a tail call, the return value is merely live-out and there aren't
9585   // any nodes in the DAG representing it. Return a special value to
9586   // indicate that a tail call has been emitted and no more Instructions
9587   // should be processed in the current block.
9588   if (CLI.IsTailCall) {
9589     CLI.DAG.setRoot(CLI.Chain);
9590     return std::make_pair(SDValue(), SDValue());
9591   }
9592 
9593 #ifndef NDEBUG
9594   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9595     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9596     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9597            "LowerCall emitted a value with the wrong type!");
9598   }
9599 #endif
9600 
9601   SmallVector<SDValue, 4> ReturnValues;
9602   if (!CanLowerReturn) {
9603     // The instruction result is the result of loading from the
9604     // hidden sret parameter.
9605     SmallVector<EVT, 1> PVTs;
9606     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9607 
9608     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9609     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9610     EVT PtrVT = PVTs[0];
9611 
9612     unsigned NumValues = RetTys.size();
9613     ReturnValues.resize(NumValues);
9614     SmallVector<SDValue, 4> Chains(NumValues);
9615 
9616     // An aggregate return value cannot wrap around the address space, so
9617     // offsets to its parts don't wrap either.
9618     SDNodeFlags Flags;
9619     Flags.setNoUnsignedWrap(true);
9620 
9621     MachineFunction &MF = CLI.DAG.getMachineFunction();
9622     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9623     for (unsigned i = 0; i < NumValues; ++i) {
9624       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9625                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9626                                                         PtrVT), Flags);
9627       SDValue L = CLI.DAG.getLoad(
9628           RetTys[i], CLI.DL, CLI.Chain, Add,
9629           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9630                                             DemoteStackIdx, Offsets[i]),
9631           HiddenSRetAlign);
9632       ReturnValues[i] = L;
9633       Chains[i] = L.getValue(1);
9634     }
9635 
9636     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9637   } else {
9638     // Collect the legal value parts into potentially illegal values
9639     // that correspond to the original function's return values.
9640     Optional<ISD::NodeType> AssertOp;
9641     if (CLI.RetSExt)
9642       AssertOp = ISD::AssertSext;
9643     else if (CLI.RetZExt)
9644       AssertOp = ISD::AssertZext;
9645     unsigned CurReg = 0;
9646     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9647       EVT VT = RetTys[I];
9648       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9649                                                      CLI.CallConv, VT);
9650       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9651                                                        CLI.CallConv, VT);
9652 
9653       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9654                                               NumRegs, RegisterVT, VT, nullptr,
9655                                               CLI.CallConv, AssertOp));
9656       CurReg += NumRegs;
9657     }
9658 
9659     // For a function returning void, there is no return value. We can't create
9660     // such a node, so we just return a null return value in that case. In
9661     // that case, nothing will actually look at the value.
9662     if (ReturnValues.empty())
9663       return std::make_pair(SDValue(), CLI.Chain);
9664   }
9665 
9666   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9667                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9668   return std::make_pair(Res, CLI.Chain);
9669 }
9670 
9671 /// Places new result values for the node in Results (their number
9672 /// and types must exactly match those of the original return values of
9673 /// the node), or leaves Results empty, which indicates that the node is not
9674 /// to be custom lowered after all.
9675 void TargetLowering::LowerOperationWrapper(SDNode *N,
9676                                            SmallVectorImpl<SDValue> &Results,
9677                                            SelectionDAG &DAG) const {
9678   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9679 
9680   if (!Res.getNode())
9681     return;
9682 
9683   // If the original node has one result, take the return value from
9684   // LowerOperation as is. It might not be result number 0.
9685   if (N->getNumValues() == 1) {
9686     Results.push_back(Res);
9687     return;
9688   }
9689 
9690   // If the original node has multiple results, then the return node should
9691   // have the same number of results.
9692   assert((N->getNumValues() == Res->getNumValues()) &&
9693       "Lowering returned the wrong number of results!");
9694 
9695   // Places new result values base on N result number.
9696   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
9697     Results.push_back(Res.getValue(I));
9698 }
9699 
9700 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9701   llvm_unreachable("LowerOperation not implemented for this target!");
9702 }
9703 
9704 void
9705 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9706   SDValue Op = getNonRegisterValue(V);
9707   assert((Op.getOpcode() != ISD::CopyFromReg ||
9708           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9709          "Copy from a reg to the same reg!");
9710   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9711 
9712   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9713   // If this is an InlineAsm we have to match the registers required, not the
9714   // notional registers required by the type.
9715 
9716   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9717                    None); // This is not an ABI copy.
9718   SDValue Chain = DAG.getEntryNode();
9719 
9720   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9721                               FuncInfo.PreferredExtendType.end())
9722                                  ? ISD::ANY_EXTEND
9723                                  : FuncInfo.PreferredExtendType[V];
9724   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9725   PendingExports.push_back(Chain);
9726 }
9727 
9728 #include "llvm/CodeGen/SelectionDAGISel.h"
9729 
9730 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9731 /// entry block, return true.  This includes arguments used by switches, since
9732 /// the switch may expand into multiple basic blocks.
9733 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9734   // With FastISel active, we may be splitting blocks, so force creation
9735   // of virtual registers for all non-dead arguments.
9736   if (FastISel)
9737     return A->use_empty();
9738 
9739   const BasicBlock &Entry = A->getParent()->front();
9740   for (const User *U : A->users())
9741     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9742       return false;  // Use not in entry block.
9743 
9744   return true;
9745 }
9746 
9747 using ArgCopyElisionMapTy =
9748     DenseMap<const Argument *,
9749              std::pair<const AllocaInst *, const StoreInst *>>;
9750 
9751 /// Scan the entry block of the function in FuncInfo for arguments that look
9752 /// like copies into a local alloca. Record any copied arguments in
9753 /// ArgCopyElisionCandidates.
9754 static void
9755 findArgumentCopyElisionCandidates(const DataLayout &DL,
9756                                   FunctionLoweringInfo *FuncInfo,
9757                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9758   // Record the state of every static alloca used in the entry block. Argument
9759   // allocas are all used in the entry block, so we need approximately as many
9760   // entries as we have arguments.
9761   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9762   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9763   unsigned NumArgs = FuncInfo->Fn->arg_size();
9764   StaticAllocas.reserve(NumArgs * 2);
9765 
9766   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9767     if (!V)
9768       return nullptr;
9769     V = V->stripPointerCasts();
9770     const auto *AI = dyn_cast<AllocaInst>(V);
9771     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9772       return nullptr;
9773     auto Iter = StaticAllocas.insert({AI, Unknown});
9774     return &Iter.first->second;
9775   };
9776 
9777   // Look for stores of arguments to static allocas. Look through bitcasts and
9778   // GEPs to handle type coercions, as long as the alloca is fully initialized
9779   // by the store. Any non-store use of an alloca escapes it and any subsequent
9780   // unanalyzed store might write it.
9781   // FIXME: Handle structs initialized with multiple stores.
9782   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9783     // Look for stores, and handle non-store uses conservatively.
9784     const auto *SI = dyn_cast<StoreInst>(&I);
9785     if (!SI) {
9786       // We will look through cast uses, so ignore them completely.
9787       if (I.isCast())
9788         continue;
9789       // Ignore debug info and pseudo op intrinsics, they don't escape or store
9790       // to allocas.
9791       if (I.isDebugOrPseudoInst())
9792         continue;
9793       // This is an unknown instruction. Assume it escapes or writes to all
9794       // static alloca operands.
9795       for (const Use &U : I.operands()) {
9796         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9797           *Info = StaticAllocaInfo::Clobbered;
9798       }
9799       continue;
9800     }
9801 
9802     // If the stored value is a static alloca, mark it as escaped.
9803     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9804       *Info = StaticAllocaInfo::Clobbered;
9805 
9806     // Check if the destination is a static alloca.
9807     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9808     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9809     if (!Info)
9810       continue;
9811     const AllocaInst *AI = cast<AllocaInst>(Dst);
9812 
9813     // Skip allocas that have been initialized or clobbered.
9814     if (*Info != StaticAllocaInfo::Unknown)
9815       continue;
9816 
9817     // Check if the stored value is an argument, and that this store fully
9818     // initializes the alloca. Don't elide copies from the same argument twice.
9819     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9820     const auto *Arg = dyn_cast<Argument>(Val);
9821     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
9822         Arg->getType()->isEmptyTy() ||
9823         DL.getTypeStoreSize(Arg->getType()) !=
9824             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9825         ArgCopyElisionCandidates.count(Arg)) {
9826       *Info = StaticAllocaInfo::Clobbered;
9827       continue;
9828     }
9829 
9830     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9831                       << '\n');
9832 
9833     // Mark this alloca and store for argument copy elision.
9834     *Info = StaticAllocaInfo::Elidable;
9835     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9836 
9837     // Stop scanning if we've seen all arguments. This will happen early in -O0
9838     // builds, which is useful, because -O0 builds have large entry blocks and
9839     // many allocas.
9840     if (ArgCopyElisionCandidates.size() == NumArgs)
9841       break;
9842   }
9843 }
9844 
9845 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9846 /// ArgVal is a load from a suitable fixed stack object.
9847 static void tryToElideArgumentCopy(
9848     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9849     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9850     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9851     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9852     SDValue ArgVal, bool &ArgHasUses) {
9853   // Check if this is a load from a fixed stack object.
9854   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9855   if (!LNode)
9856     return;
9857   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9858   if (!FINode)
9859     return;
9860 
9861   // Check that the fixed stack object is the right size and alignment.
9862   // Look at the alignment that the user wrote on the alloca instead of looking
9863   // at the stack object.
9864   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9865   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9866   const AllocaInst *AI = ArgCopyIter->second.first;
9867   int FixedIndex = FINode->getIndex();
9868   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9869   int OldIndex = AllocaIndex;
9870   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9871   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9872     LLVM_DEBUG(
9873         dbgs() << "  argument copy elision failed due to bad fixed stack "
9874                   "object size\n");
9875     return;
9876   }
9877   Align RequiredAlignment = AI->getAlign();
9878   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9879     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9880                          "greater than stack argument alignment ("
9881                       << DebugStr(RequiredAlignment) << " vs "
9882                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9883     return;
9884   }
9885 
9886   // Perform the elision. Delete the old stack object and replace its only use
9887   // in the variable info map. Mark the stack object as mutable.
9888   LLVM_DEBUG({
9889     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9890            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9891            << '\n';
9892   });
9893   MFI.RemoveStackObject(OldIndex);
9894   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9895   AllocaIndex = FixedIndex;
9896   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9897   Chains.push_back(ArgVal.getValue(1));
9898 
9899   // Avoid emitting code for the store implementing the copy.
9900   const StoreInst *SI = ArgCopyIter->second.second;
9901   ElidedArgCopyInstrs.insert(SI);
9902 
9903   // Check for uses of the argument again so that we can avoid exporting ArgVal
9904   // if it is't used by anything other than the store.
9905   for (const Value *U : Arg.users()) {
9906     if (U != SI) {
9907       ArgHasUses = true;
9908       break;
9909     }
9910   }
9911 }
9912 
9913 void SelectionDAGISel::LowerArguments(const Function &F) {
9914   SelectionDAG &DAG = SDB->DAG;
9915   SDLoc dl = SDB->getCurSDLoc();
9916   const DataLayout &DL = DAG.getDataLayout();
9917   SmallVector<ISD::InputArg, 16> Ins;
9918 
9919   // In Naked functions we aren't going to save any registers.
9920   if (F.hasFnAttribute(Attribute::Naked))
9921     return;
9922 
9923   if (!FuncInfo->CanLowerReturn) {
9924     // Put in an sret pointer parameter before all the other parameters.
9925     SmallVector<EVT, 1> ValueVTs;
9926     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9927                     F.getReturnType()->getPointerTo(
9928                         DAG.getDataLayout().getAllocaAddrSpace()),
9929                     ValueVTs);
9930 
9931     // NOTE: Assuming that a pointer will never break down to more than one VT
9932     // or one register.
9933     ISD::ArgFlagsTy Flags;
9934     Flags.setSRet();
9935     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9936     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9937                          ISD::InputArg::NoArgIndex, 0);
9938     Ins.push_back(RetArg);
9939   }
9940 
9941   // Look for stores of arguments to static allocas. Mark such arguments with a
9942   // flag to ask the target to give us the memory location of that argument if
9943   // available.
9944   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9945   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9946                                     ArgCopyElisionCandidates);
9947 
9948   // Set up the incoming argument description vector.
9949   for (const Argument &Arg : F.args()) {
9950     unsigned ArgNo = Arg.getArgNo();
9951     SmallVector<EVT, 4> ValueVTs;
9952     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9953     bool isArgValueUsed = !Arg.use_empty();
9954     unsigned PartBase = 0;
9955     Type *FinalType = Arg.getType();
9956     if (Arg.hasAttribute(Attribute::ByVal))
9957       FinalType = Arg.getParamByValType();
9958     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9959         FinalType, F.getCallingConv(), F.isVarArg());
9960     for (unsigned Value = 0, NumValues = ValueVTs.size();
9961          Value != NumValues; ++Value) {
9962       EVT VT = ValueVTs[Value];
9963       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9964       ISD::ArgFlagsTy Flags;
9965 
9966 
9967       if (Arg.getType()->isPointerTy()) {
9968         Flags.setPointer();
9969         Flags.setPointerAddrSpace(
9970             cast<PointerType>(Arg.getType())->getAddressSpace());
9971       }
9972       if (Arg.hasAttribute(Attribute::ZExt))
9973         Flags.setZExt();
9974       if (Arg.hasAttribute(Attribute::SExt))
9975         Flags.setSExt();
9976       if (Arg.hasAttribute(Attribute::InReg)) {
9977         // If we are using vectorcall calling convention, a structure that is
9978         // passed InReg - is surely an HVA
9979         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9980             isa<StructType>(Arg.getType())) {
9981           // The first value of a structure is marked
9982           if (0 == Value)
9983             Flags.setHvaStart();
9984           Flags.setHva();
9985         }
9986         // Set InReg Flag
9987         Flags.setInReg();
9988       }
9989       if (Arg.hasAttribute(Attribute::StructRet))
9990         Flags.setSRet();
9991       if (Arg.hasAttribute(Attribute::SwiftSelf))
9992         Flags.setSwiftSelf();
9993       if (Arg.hasAttribute(Attribute::SwiftError))
9994         Flags.setSwiftError();
9995       if (Arg.hasAttribute(Attribute::ByVal))
9996         Flags.setByVal();
9997       if (Arg.hasAttribute(Attribute::ByRef))
9998         Flags.setByRef();
9999       if (Arg.hasAttribute(Attribute::InAlloca)) {
10000         Flags.setInAlloca();
10001         // Set the byval flag for CCAssignFn callbacks that don't know about
10002         // inalloca.  This way we can know how many bytes we should've allocated
10003         // and how many bytes a callee cleanup function will pop.  If we port
10004         // inalloca to more targets, we'll have to add custom inalloca handling
10005         // in the various CC lowering callbacks.
10006         Flags.setByVal();
10007       }
10008       if (Arg.hasAttribute(Attribute::Preallocated)) {
10009         Flags.setPreallocated();
10010         // Set the byval flag for CCAssignFn callbacks that don't know about
10011         // preallocated.  This way we can know how many bytes we should've
10012         // allocated and how many bytes a callee cleanup function will pop.  If
10013         // we port preallocated to more targets, we'll have to add custom
10014         // preallocated handling in the various CC lowering callbacks.
10015         Flags.setByVal();
10016       }
10017 
10018       // Certain targets (such as MIPS), may have a different ABI alignment
10019       // for a type depending on the context. Give the target a chance to
10020       // specify the alignment it wants.
10021       const Align OriginalAlignment(
10022           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10023       Flags.setOrigAlign(OriginalAlignment);
10024 
10025       Align MemAlign;
10026       Type *ArgMemTy = nullptr;
10027       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10028           Flags.isByRef()) {
10029         if (!ArgMemTy)
10030           ArgMemTy = Arg.getPointeeInMemoryValueType();
10031 
10032         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10033 
10034         // For in-memory arguments, size and alignment should be passed from FE.
10035         // BE will guess if this info is not there but there are cases it cannot
10036         // get right.
10037         if (auto ParamAlign = Arg.getParamStackAlign())
10038           MemAlign = *ParamAlign;
10039         else if ((ParamAlign = Arg.getParamAlign()))
10040           MemAlign = *ParamAlign;
10041         else
10042           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10043         if (Flags.isByRef())
10044           Flags.setByRefSize(MemSize);
10045         else
10046           Flags.setByValSize(MemSize);
10047       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10048         MemAlign = *ParamAlign;
10049       } else {
10050         MemAlign = OriginalAlignment;
10051       }
10052       Flags.setMemAlign(MemAlign);
10053 
10054       if (Arg.hasAttribute(Attribute::Nest))
10055         Flags.setNest();
10056       if (NeedsRegBlock)
10057         Flags.setInConsecutiveRegs();
10058       if (ArgCopyElisionCandidates.count(&Arg))
10059         Flags.setCopyElisionCandidate();
10060       if (Arg.hasAttribute(Attribute::Returned))
10061         Flags.setReturned();
10062 
10063       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10064           *CurDAG->getContext(), F.getCallingConv(), VT);
10065       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10066           *CurDAG->getContext(), F.getCallingConv(), VT);
10067       for (unsigned i = 0; i != NumRegs; ++i) {
10068         // For scalable vectors, use the minimum size; individual targets
10069         // are responsible for handling scalable vector arguments and
10070         // return values.
10071         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10072                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10073         if (NumRegs > 1 && i == 0)
10074           MyFlags.Flags.setSplit();
10075         // if it isn't first piece, alignment must be 1
10076         else if (i > 0) {
10077           MyFlags.Flags.setOrigAlign(Align(1));
10078           if (i == NumRegs - 1)
10079             MyFlags.Flags.setSplitEnd();
10080         }
10081         Ins.push_back(MyFlags);
10082       }
10083       if (NeedsRegBlock && Value == NumValues - 1)
10084         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10085       PartBase += VT.getStoreSize().getKnownMinSize();
10086     }
10087   }
10088 
10089   // Call the target to set up the argument values.
10090   SmallVector<SDValue, 8> InVals;
10091   SDValue NewRoot = TLI->LowerFormalArguments(
10092       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10093 
10094   // Verify that the target's LowerFormalArguments behaved as expected.
10095   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10096          "LowerFormalArguments didn't return a valid chain!");
10097   assert(InVals.size() == Ins.size() &&
10098          "LowerFormalArguments didn't emit the correct number of values!");
10099   LLVM_DEBUG({
10100     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10101       assert(InVals[i].getNode() &&
10102              "LowerFormalArguments emitted a null value!");
10103       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10104              "LowerFormalArguments emitted a value with the wrong type!");
10105     }
10106   });
10107 
10108   // Update the DAG with the new chain value resulting from argument lowering.
10109   DAG.setRoot(NewRoot);
10110 
10111   // Set up the argument values.
10112   unsigned i = 0;
10113   if (!FuncInfo->CanLowerReturn) {
10114     // Create a virtual register for the sret pointer, and put in a copy
10115     // from the sret argument into it.
10116     SmallVector<EVT, 1> ValueVTs;
10117     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10118                     F.getReturnType()->getPointerTo(
10119                         DAG.getDataLayout().getAllocaAddrSpace()),
10120                     ValueVTs);
10121     MVT VT = ValueVTs[0].getSimpleVT();
10122     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10123     Optional<ISD::NodeType> AssertOp = None;
10124     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10125                                         nullptr, F.getCallingConv(), AssertOp);
10126 
10127     MachineFunction& MF = SDB->DAG.getMachineFunction();
10128     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10129     Register SRetReg =
10130         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10131     FuncInfo->DemoteRegister = SRetReg;
10132     NewRoot =
10133         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10134     DAG.setRoot(NewRoot);
10135 
10136     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10137     ++i;
10138   }
10139 
10140   SmallVector<SDValue, 4> Chains;
10141   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10142   for (const Argument &Arg : F.args()) {
10143     SmallVector<SDValue, 4> ArgValues;
10144     SmallVector<EVT, 4> ValueVTs;
10145     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10146     unsigned NumValues = ValueVTs.size();
10147     if (NumValues == 0)
10148       continue;
10149 
10150     bool ArgHasUses = !Arg.use_empty();
10151 
10152     // Elide the copying store if the target loaded this argument from a
10153     // suitable fixed stack object.
10154     if (Ins[i].Flags.isCopyElisionCandidate()) {
10155       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10156                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10157                              InVals[i], ArgHasUses);
10158     }
10159 
10160     // If this argument is unused then remember its value. It is used to generate
10161     // debugging information.
10162     bool isSwiftErrorArg =
10163         TLI->supportSwiftError() &&
10164         Arg.hasAttribute(Attribute::SwiftError);
10165     if (!ArgHasUses && !isSwiftErrorArg) {
10166       SDB->setUnusedArgValue(&Arg, InVals[i]);
10167 
10168       // Also remember any frame index for use in FastISel.
10169       if (FrameIndexSDNode *FI =
10170           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10171         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10172     }
10173 
10174     for (unsigned Val = 0; Val != NumValues; ++Val) {
10175       EVT VT = ValueVTs[Val];
10176       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10177                                                       F.getCallingConv(), VT);
10178       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10179           *CurDAG->getContext(), F.getCallingConv(), VT);
10180 
10181       // Even an apparent 'unused' swifterror argument needs to be returned. So
10182       // we do generate a copy for it that can be used on return from the
10183       // function.
10184       if (ArgHasUses || isSwiftErrorArg) {
10185         Optional<ISD::NodeType> AssertOp;
10186         if (Arg.hasAttribute(Attribute::SExt))
10187           AssertOp = ISD::AssertSext;
10188         else if (Arg.hasAttribute(Attribute::ZExt))
10189           AssertOp = ISD::AssertZext;
10190 
10191         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10192                                              PartVT, VT, nullptr,
10193                                              F.getCallingConv(), AssertOp));
10194       }
10195 
10196       i += NumParts;
10197     }
10198 
10199     // We don't need to do anything else for unused arguments.
10200     if (ArgValues.empty())
10201       continue;
10202 
10203     // Note down frame index.
10204     if (FrameIndexSDNode *FI =
10205         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10206       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10207 
10208     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10209                                      SDB->getCurSDLoc());
10210 
10211     SDB->setValue(&Arg, Res);
10212     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10213       // We want to associate the argument with the frame index, among
10214       // involved operands, that correspond to the lowest address. The
10215       // getCopyFromParts function, called earlier, is swapping the order of
10216       // the operands to BUILD_PAIR depending on endianness. The result of
10217       // that swapping is that the least significant bits of the argument will
10218       // be in the first operand of the BUILD_PAIR node, and the most
10219       // significant bits will be in the second operand.
10220       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10221       if (LoadSDNode *LNode =
10222           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10223         if (FrameIndexSDNode *FI =
10224             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10225           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10226     }
10227 
10228     // Analyses past this point are naive and don't expect an assertion.
10229     if (Res.getOpcode() == ISD::AssertZext)
10230       Res = Res.getOperand(0);
10231 
10232     // Update the SwiftErrorVRegDefMap.
10233     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10234       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10235       if (Register::isVirtualRegister(Reg))
10236         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10237                                    Reg);
10238     }
10239 
10240     // If this argument is live outside of the entry block, insert a copy from
10241     // wherever we got it to the vreg that other BB's will reference it as.
10242     if (Res.getOpcode() == ISD::CopyFromReg) {
10243       // If we can, though, try to skip creating an unnecessary vreg.
10244       // FIXME: This isn't very clean... it would be nice to make this more
10245       // general.
10246       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10247       if (Register::isVirtualRegister(Reg)) {
10248         FuncInfo->ValueMap[&Arg] = Reg;
10249         continue;
10250       }
10251     }
10252     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10253       FuncInfo->InitializeRegForValue(&Arg);
10254       SDB->CopyToExportRegsIfNeeded(&Arg);
10255     }
10256   }
10257 
10258   if (!Chains.empty()) {
10259     Chains.push_back(NewRoot);
10260     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10261   }
10262 
10263   DAG.setRoot(NewRoot);
10264 
10265   assert(i == InVals.size() && "Argument register count mismatch!");
10266 
10267   // If any argument copy elisions occurred and we have debug info, update the
10268   // stale frame indices used in the dbg.declare variable info table.
10269   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10270   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10271     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10272       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10273       if (I != ArgCopyElisionFrameIndexMap.end())
10274         VI.Slot = I->second;
10275     }
10276   }
10277 
10278   // Finally, if the target has anything special to do, allow it to do so.
10279   emitFunctionEntryCode();
10280 }
10281 
10282 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10283 /// ensure constants are generated when needed.  Remember the virtual registers
10284 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10285 /// directly add them, because expansion might result in multiple MBB's for one
10286 /// BB.  As such, the start of the BB might correspond to a different MBB than
10287 /// the end.
10288 void
10289 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10290   const Instruction *TI = LLVMBB->getTerminator();
10291 
10292   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10293 
10294   // Check PHI nodes in successors that expect a value to be available from this
10295   // block.
10296   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10297     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10298     if (!isa<PHINode>(SuccBB->begin())) continue;
10299     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10300 
10301     // If this terminator has multiple identical successors (common for
10302     // switches), only handle each succ once.
10303     if (!SuccsHandled.insert(SuccMBB).second)
10304       continue;
10305 
10306     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10307 
10308     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10309     // nodes and Machine PHI nodes, but the incoming operands have not been
10310     // emitted yet.
10311     for (const PHINode &PN : SuccBB->phis()) {
10312       // Ignore dead phi's.
10313       if (PN.use_empty())
10314         continue;
10315 
10316       // Skip empty types
10317       if (PN.getType()->isEmptyTy())
10318         continue;
10319 
10320       unsigned Reg;
10321       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10322 
10323       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10324         unsigned &RegOut = ConstantsOut[C];
10325         if (RegOut == 0) {
10326           RegOut = FuncInfo.CreateRegs(C);
10327           CopyValueToVirtualRegister(C, RegOut);
10328         }
10329         Reg = RegOut;
10330       } else {
10331         DenseMap<const Value *, Register>::iterator I =
10332           FuncInfo.ValueMap.find(PHIOp);
10333         if (I != FuncInfo.ValueMap.end())
10334           Reg = I->second;
10335         else {
10336           assert(isa<AllocaInst>(PHIOp) &&
10337                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10338                  "Didn't codegen value into a register!??");
10339           Reg = FuncInfo.CreateRegs(PHIOp);
10340           CopyValueToVirtualRegister(PHIOp, Reg);
10341         }
10342       }
10343 
10344       // Remember that this register needs to added to the machine PHI node as
10345       // the input for this MBB.
10346       SmallVector<EVT, 4> ValueVTs;
10347       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10348       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10349       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10350         EVT VT = ValueVTs[vti];
10351         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10352         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10353           FuncInfo.PHINodesToUpdate.push_back(
10354               std::make_pair(&*MBBI++, Reg + i));
10355         Reg += NumRegisters;
10356       }
10357     }
10358   }
10359 
10360   ConstantsOut.clear();
10361 }
10362 
10363 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10364 /// is 0.
10365 MachineBasicBlock *
10366 SelectionDAGBuilder::StackProtectorDescriptor::
10367 AddSuccessorMBB(const BasicBlock *BB,
10368                 MachineBasicBlock *ParentMBB,
10369                 bool IsLikely,
10370                 MachineBasicBlock *SuccMBB) {
10371   // If SuccBB has not been created yet, create it.
10372   if (!SuccMBB) {
10373     MachineFunction *MF = ParentMBB->getParent();
10374     MachineFunction::iterator BBI(ParentMBB);
10375     SuccMBB = MF->CreateMachineBasicBlock(BB);
10376     MF->insert(++BBI, SuccMBB);
10377   }
10378   // Add it as a successor of ParentMBB.
10379   ParentMBB->addSuccessor(
10380       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10381   return SuccMBB;
10382 }
10383 
10384 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10385   MachineFunction::iterator I(MBB);
10386   if (++I == FuncInfo.MF->end())
10387     return nullptr;
10388   return &*I;
10389 }
10390 
10391 /// During lowering new call nodes can be created (such as memset, etc.).
10392 /// Those will become new roots of the current DAG, but complications arise
10393 /// when they are tail calls. In such cases, the call lowering will update
10394 /// the root, but the builder still needs to know that a tail call has been
10395 /// lowered in order to avoid generating an additional return.
10396 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10397   // If the node is null, we do have a tail call.
10398   if (MaybeTC.getNode() != nullptr)
10399     DAG.setRoot(MaybeTC);
10400   else
10401     HasTailCall = true;
10402 }
10403 
10404 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10405                                         MachineBasicBlock *SwitchMBB,
10406                                         MachineBasicBlock *DefaultMBB) {
10407   MachineFunction *CurMF = FuncInfo.MF;
10408   MachineBasicBlock *NextMBB = nullptr;
10409   MachineFunction::iterator BBI(W.MBB);
10410   if (++BBI != FuncInfo.MF->end())
10411     NextMBB = &*BBI;
10412 
10413   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10414 
10415   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10416 
10417   if (Size == 2 && W.MBB == SwitchMBB) {
10418     // If any two of the cases has the same destination, and if one value
10419     // is the same as the other, but has one bit unset that the other has set,
10420     // use bit manipulation to do two compares at once.  For example:
10421     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10422     // TODO: This could be extended to merge any 2 cases in switches with 3
10423     // cases.
10424     // TODO: Handle cases where W.CaseBB != SwitchBB.
10425     CaseCluster &Small = *W.FirstCluster;
10426     CaseCluster &Big = *W.LastCluster;
10427 
10428     if (Small.Low == Small.High && Big.Low == Big.High &&
10429         Small.MBB == Big.MBB) {
10430       const APInt &SmallValue = Small.Low->getValue();
10431       const APInt &BigValue = Big.Low->getValue();
10432 
10433       // Check that there is only one bit different.
10434       APInt CommonBit = BigValue ^ SmallValue;
10435       if (CommonBit.isPowerOf2()) {
10436         SDValue CondLHS = getValue(Cond);
10437         EVT VT = CondLHS.getValueType();
10438         SDLoc DL = getCurSDLoc();
10439 
10440         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10441                                  DAG.getConstant(CommonBit, DL, VT));
10442         SDValue Cond = DAG.getSetCC(
10443             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10444             ISD::SETEQ);
10445 
10446         // Update successor info.
10447         // Both Small and Big will jump to Small.BB, so we sum up the
10448         // probabilities.
10449         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10450         if (BPI)
10451           addSuccessorWithProb(
10452               SwitchMBB, DefaultMBB,
10453               // The default destination is the first successor in IR.
10454               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10455         else
10456           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10457 
10458         // Insert the true branch.
10459         SDValue BrCond =
10460             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10461                         DAG.getBasicBlock(Small.MBB));
10462         // Insert the false branch.
10463         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10464                              DAG.getBasicBlock(DefaultMBB));
10465 
10466         DAG.setRoot(BrCond);
10467         return;
10468       }
10469     }
10470   }
10471 
10472   if (TM.getOptLevel() != CodeGenOpt::None) {
10473     // Here, we order cases by probability so the most likely case will be
10474     // checked first. However, two clusters can have the same probability in
10475     // which case their relative ordering is non-deterministic. So we use Low
10476     // as a tie-breaker as clusters are guaranteed to never overlap.
10477     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10478                [](const CaseCluster &a, const CaseCluster &b) {
10479       return a.Prob != b.Prob ?
10480              a.Prob > b.Prob :
10481              a.Low->getValue().slt(b.Low->getValue());
10482     });
10483 
10484     // Rearrange the case blocks so that the last one falls through if possible
10485     // without changing the order of probabilities.
10486     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10487       --I;
10488       if (I->Prob > W.LastCluster->Prob)
10489         break;
10490       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10491         std::swap(*I, *W.LastCluster);
10492         break;
10493       }
10494     }
10495   }
10496 
10497   // Compute total probability.
10498   BranchProbability DefaultProb = W.DefaultProb;
10499   BranchProbability UnhandledProbs = DefaultProb;
10500   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10501     UnhandledProbs += I->Prob;
10502 
10503   MachineBasicBlock *CurMBB = W.MBB;
10504   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10505     bool FallthroughUnreachable = false;
10506     MachineBasicBlock *Fallthrough;
10507     if (I == W.LastCluster) {
10508       // For the last cluster, fall through to the default destination.
10509       Fallthrough = DefaultMBB;
10510       FallthroughUnreachable = isa<UnreachableInst>(
10511           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10512     } else {
10513       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10514       CurMF->insert(BBI, Fallthrough);
10515       // Put Cond in a virtual register to make it available from the new blocks.
10516       ExportFromCurrentBlock(Cond);
10517     }
10518     UnhandledProbs -= I->Prob;
10519 
10520     switch (I->Kind) {
10521       case CC_JumpTable: {
10522         // FIXME: Optimize away range check based on pivot comparisons.
10523         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10524         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10525 
10526         // The jump block hasn't been inserted yet; insert it here.
10527         MachineBasicBlock *JumpMBB = JT->MBB;
10528         CurMF->insert(BBI, JumpMBB);
10529 
10530         auto JumpProb = I->Prob;
10531         auto FallthroughProb = UnhandledProbs;
10532 
10533         // If the default statement is a target of the jump table, we evenly
10534         // distribute the default probability to successors of CurMBB. Also
10535         // update the probability on the edge from JumpMBB to Fallthrough.
10536         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10537                                               SE = JumpMBB->succ_end();
10538              SI != SE; ++SI) {
10539           if (*SI == DefaultMBB) {
10540             JumpProb += DefaultProb / 2;
10541             FallthroughProb -= DefaultProb / 2;
10542             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10543             JumpMBB->normalizeSuccProbs();
10544             break;
10545           }
10546         }
10547 
10548         if (FallthroughUnreachable) {
10549           // Skip the range check if the fallthrough block is unreachable.
10550           JTH->OmitRangeCheck = true;
10551         }
10552 
10553         if (!JTH->OmitRangeCheck)
10554           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10555         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10556         CurMBB->normalizeSuccProbs();
10557 
10558         // The jump table header will be inserted in our current block, do the
10559         // range check, and fall through to our fallthrough block.
10560         JTH->HeaderBB = CurMBB;
10561         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10562 
10563         // If we're in the right place, emit the jump table header right now.
10564         if (CurMBB == SwitchMBB) {
10565           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10566           JTH->Emitted = true;
10567         }
10568         break;
10569       }
10570       case CC_BitTests: {
10571         // FIXME: Optimize away range check based on pivot comparisons.
10572         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10573 
10574         // The bit test blocks haven't been inserted yet; insert them here.
10575         for (BitTestCase &BTC : BTB->Cases)
10576           CurMF->insert(BBI, BTC.ThisBB);
10577 
10578         // Fill in fields of the BitTestBlock.
10579         BTB->Parent = CurMBB;
10580         BTB->Default = Fallthrough;
10581 
10582         BTB->DefaultProb = UnhandledProbs;
10583         // If the cases in bit test don't form a contiguous range, we evenly
10584         // distribute the probability on the edge to Fallthrough to two
10585         // successors of CurMBB.
10586         if (!BTB->ContiguousRange) {
10587           BTB->Prob += DefaultProb / 2;
10588           BTB->DefaultProb -= DefaultProb / 2;
10589         }
10590 
10591         if (FallthroughUnreachable) {
10592           // Skip the range check if the fallthrough block is unreachable.
10593           BTB->OmitRangeCheck = true;
10594         }
10595 
10596         // If we're in the right place, emit the bit test header right now.
10597         if (CurMBB == SwitchMBB) {
10598           visitBitTestHeader(*BTB, SwitchMBB);
10599           BTB->Emitted = true;
10600         }
10601         break;
10602       }
10603       case CC_Range: {
10604         const Value *RHS, *LHS, *MHS;
10605         ISD::CondCode CC;
10606         if (I->Low == I->High) {
10607           // Check Cond == I->Low.
10608           CC = ISD::SETEQ;
10609           LHS = Cond;
10610           RHS=I->Low;
10611           MHS = nullptr;
10612         } else {
10613           // Check I->Low <= Cond <= I->High.
10614           CC = ISD::SETLE;
10615           LHS = I->Low;
10616           MHS = Cond;
10617           RHS = I->High;
10618         }
10619 
10620         // If Fallthrough is unreachable, fold away the comparison.
10621         if (FallthroughUnreachable)
10622           CC = ISD::SETTRUE;
10623 
10624         // The false probability is the sum of all unhandled cases.
10625         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10626                      getCurSDLoc(), I->Prob, UnhandledProbs);
10627 
10628         if (CurMBB == SwitchMBB)
10629           visitSwitchCase(CB, SwitchMBB);
10630         else
10631           SL->SwitchCases.push_back(CB);
10632 
10633         break;
10634       }
10635     }
10636     CurMBB = Fallthrough;
10637   }
10638 }
10639 
10640 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10641                                               CaseClusterIt First,
10642                                               CaseClusterIt Last) {
10643   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10644     if (X.Prob != CC.Prob)
10645       return X.Prob > CC.Prob;
10646 
10647     // Ties are broken by comparing the case value.
10648     return X.Low->getValue().slt(CC.Low->getValue());
10649   });
10650 }
10651 
10652 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10653                                         const SwitchWorkListItem &W,
10654                                         Value *Cond,
10655                                         MachineBasicBlock *SwitchMBB) {
10656   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10657          "Clusters not sorted?");
10658 
10659   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10660 
10661   // Balance the tree based on branch probabilities to create a near-optimal (in
10662   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10663   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10664   CaseClusterIt LastLeft = W.FirstCluster;
10665   CaseClusterIt FirstRight = W.LastCluster;
10666   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10667   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10668 
10669   // Move LastLeft and FirstRight towards each other from opposite directions to
10670   // find a partitioning of the clusters which balances the probability on both
10671   // sides. If LeftProb and RightProb are equal, alternate which side is
10672   // taken to ensure 0-probability nodes are distributed evenly.
10673   unsigned I = 0;
10674   while (LastLeft + 1 < FirstRight) {
10675     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10676       LeftProb += (++LastLeft)->Prob;
10677     else
10678       RightProb += (--FirstRight)->Prob;
10679     I++;
10680   }
10681 
10682   while (true) {
10683     // Our binary search tree differs from a typical BST in that ours can have up
10684     // to three values in each leaf. The pivot selection above doesn't take that
10685     // into account, which means the tree might require more nodes and be less
10686     // efficient. We compensate for this here.
10687 
10688     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10689     unsigned NumRight = W.LastCluster - FirstRight + 1;
10690 
10691     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10692       // If one side has less than 3 clusters, and the other has more than 3,
10693       // consider taking a cluster from the other side.
10694 
10695       if (NumLeft < NumRight) {
10696         // Consider moving the first cluster on the right to the left side.
10697         CaseCluster &CC = *FirstRight;
10698         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10699         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10700         if (LeftSideRank <= RightSideRank) {
10701           // Moving the cluster to the left does not demote it.
10702           ++LastLeft;
10703           ++FirstRight;
10704           continue;
10705         }
10706       } else {
10707         assert(NumRight < NumLeft);
10708         // Consider moving the last element on the left to the right side.
10709         CaseCluster &CC = *LastLeft;
10710         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10711         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10712         if (RightSideRank <= LeftSideRank) {
10713           // Moving the cluster to the right does not demot it.
10714           --LastLeft;
10715           --FirstRight;
10716           continue;
10717         }
10718       }
10719     }
10720     break;
10721   }
10722 
10723   assert(LastLeft + 1 == FirstRight);
10724   assert(LastLeft >= W.FirstCluster);
10725   assert(FirstRight <= W.LastCluster);
10726 
10727   // Use the first element on the right as pivot since we will make less-than
10728   // comparisons against it.
10729   CaseClusterIt PivotCluster = FirstRight;
10730   assert(PivotCluster > W.FirstCluster);
10731   assert(PivotCluster <= W.LastCluster);
10732 
10733   CaseClusterIt FirstLeft = W.FirstCluster;
10734   CaseClusterIt LastRight = W.LastCluster;
10735 
10736   const ConstantInt *Pivot = PivotCluster->Low;
10737 
10738   // New blocks will be inserted immediately after the current one.
10739   MachineFunction::iterator BBI(W.MBB);
10740   ++BBI;
10741 
10742   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10743   // we can branch to its destination directly if it's squeezed exactly in
10744   // between the known lower bound and Pivot - 1.
10745   MachineBasicBlock *LeftMBB;
10746   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10747       FirstLeft->Low == W.GE &&
10748       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10749     LeftMBB = FirstLeft->MBB;
10750   } else {
10751     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10752     FuncInfo.MF->insert(BBI, LeftMBB);
10753     WorkList.push_back(
10754         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10755     // Put Cond in a virtual register to make it available from the new blocks.
10756     ExportFromCurrentBlock(Cond);
10757   }
10758 
10759   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10760   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10761   // directly if RHS.High equals the current upper bound.
10762   MachineBasicBlock *RightMBB;
10763   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10764       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10765     RightMBB = FirstRight->MBB;
10766   } else {
10767     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10768     FuncInfo.MF->insert(BBI, RightMBB);
10769     WorkList.push_back(
10770         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10771     // Put Cond in a virtual register to make it available from the new blocks.
10772     ExportFromCurrentBlock(Cond);
10773   }
10774 
10775   // Create the CaseBlock record that will be used to lower the branch.
10776   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10777                getCurSDLoc(), LeftProb, RightProb);
10778 
10779   if (W.MBB == SwitchMBB)
10780     visitSwitchCase(CB, SwitchMBB);
10781   else
10782     SL->SwitchCases.push_back(CB);
10783 }
10784 
10785 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10786 // from the swith statement.
10787 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10788                                             BranchProbability PeeledCaseProb) {
10789   if (PeeledCaseProb == BranchProbability::getOne())
10790     return BranchProbability::getZero();
10791   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10792 
10793   uint32_t Numerator = CaseProb.getNumerator();
10794   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10795   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10796 }
10797 
10798 // Try to peel the top probability case if it exceeds the threshold.
10799 // Return current MachineBasicBlock for the switch statement if the peeling
10800 // does not occur.
10801 // If the peeling is performed, return the newly created MachineBasicBlock
10802 // for the peeled switch statement. Also update Clusters to remove the peeled
10803 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10804 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10805     const SwitchInst &SI, CaseClusterVector &Clusters,
10806     BranchProbability &PeeledCaseProb) {
10807   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10808   // Don't perform if there is only one cluster or optimizing for size.
10809   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10810       TM.getOptLevel() == CodeGenOpt::None ||
10811       SwitchMBB->getParent()->getFunction().hasMinSize())
10812     return SwitchMBB;
10813 
10814   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10815   unsigned PeeledCaseIndex = 0;
10816   bool SwitchPeeled = false;
10817   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10818     CaseCluster &CC = Clusters[Index];
10819     if (CC.Prob < TopCaseProb)
10820       continue;
10821     TopCaseProb = CC.Prob;
10822     PeeledCaseIndex = Index;
10823     SwitchPeeled = true;
10824   }
10825   if (!SwitchPeeled)
10826     return SwitchMBB;
10827 
10828   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10829                     << TopCaseProb << "\n");
10830 
10831   // Record the MBB for the peeled switch statement.
10832   MachineFunction::iterator BBI(SwitchMBB);
10833   ++BBI;
10834   MachineBasicBlock *PeeledSwitchMBB =
10835       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10836   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10837 
10838   ExportFromCurrentBlock(SI.getCondition());
10839   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10840   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10841                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10842   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10843 
10844   Clusters.erase(PeeledCaseIt);
10845   for (CaseCluster &CC : Clusters) {
10846     LLVM_DEBUG(
10847         dbgs() << "Scale the probablity for one cluster, before scaling: "
10848                << CC.Prob << "\n");
10849     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10850     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10851   }
10852   PeeledCaseProb = TopCaseProb;
10853   return PeeledSwitchMBB;
10854 }
10855 
10856 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10857   // Extract cases from the switch.
10858   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10859   CaseClusterVector Clusters;
10860   Clusters.reserve(SI.getNumCases());
10861   for (auto I : SI.cases()) {
10862     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10863     const ConstantInt *CaseVal = I.getCaseValue();
10864     BranchProbability Prob =
10865         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10866             : BranchProbability(1, SI.getNumCases() + 1);
10867     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10868   }
10869 
10870   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10871 
10872   // Cluster adjacent cases with the same destination. We do this at all
10873   // optimization levels because it's cheap to do and will make codegen faster
10874   // if there are many clusters.
10875   sortAndRangeify(Clusters);
10876 
10877   // The branch probablity of the peeled case.
10878   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10879   MachineBasicBlock *PeeledSwitchMBB =
10880       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10881 
10882   // If there is only the default destination, jump there directly.
10883   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10884   if (Clusters.empty()) {
10885     assert(PeeledSwitchMBB == SwitchMBB);
10886     SwitchMBB->addSuccessor(DefaultMBB);
10887     if (DefaultMBB != NextBlock(SwitchMBB)) {
10888       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10889                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10890     }
10891     return;
10892   }
10893 
10894   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10895   SL->findBitTestClusters(Clusters, &SI);
10896 
10897   LLVM_DEBUG({
10898     dbgs() << "Case clusters: ";
10899     for (const CaseCluster &C : Clusters) {
10900       if (C.Kind == CC_JumpTable)
10901         dbgs() << "JT:";
10902       if (C.Kind == CC_BitTests)
10903         dbgs() << "BT:";
10904 
10905       C.Low->getValue().print(dbgs(), true);
10906       if (C.Low != C.High) {
10907         dbgs() << '-';
10908         C.High->getValue().print(dbgs(), true);
10909       }
10910       dbgs() << ' ';
10911     }
10912     dbgs() << '\n';
10913   });
10914 
10915   assert(!Clusters.empty());
10916   SwitchWorkList WorkList;
10917   CaseClusterIt First = Clusters.begin();
10918   CaseClusterIt Last = Clusters.end() - 1;
10919   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10920   // Scale the branchprobability for DefaultMBB if the peel occurs and
10921   // DefaultMBB is not replaced.
10922   if (PeeledCaseProb != BranchProbability::getZero() &&
10923       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10924     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10925   WorkList.push_back(
10926       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10927 
10928   while (!WorkList.empty()) {
10929     SwitchWorkListItem W = WorkList.pop_back_val();
10930     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10931 
10932     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10933         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10934       // For optimized builds, lower large range as a balanced binary tree.
10935       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10936       continue;
10937     }
10938 
10939     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10940   }
10941 }
10942 
10943 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
10944   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10945   auto DL = getCurSDLoc();
10946   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10947   EVT OpVT =
10948       TLI.getTypeToTransformTo(*DAG.getContext(), ResultVT.getScalarType());
10949   SDValue Step = DAG.getConstant(1, DL, OpVT);
10950   setValue(&I, DAG.getStepVector(DL, ResultVT, Step));
10951 }
10952 
10953 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
10954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10955   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10956 
10957   SDLoc DL = getCurSDLoc();
10958   SDValue V = getValue(I.getOperand(0));
10959   assert(VT == V.getValueType() && "Malformed vector.reverse!");
10960 
10961   if (VT.isScalableVector()) {
10962     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
10963     return;
10964   }
10965 
10966   // Use VECTOR_SHUFFLE for the fixed-length vector
10967   // to maintain existing behavior.
10968   SmallVector<int, 8> Mask;
10969   unsigned NumElts = VT.getVectorMinNumElements();
10970   for (unsigned i = 0; i != NumElts; ++i)
10971     Mask.push_back(NumElts - 1 - i);
10972 
10973   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
10974 }
10975 
10976 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10977   SmallVector<EVT, 4> ValueVTs;
10978   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10979                   ValueVTs);
10980   unsigned NumValues = ValueVTs.size();
10981   if (NumValues == 0) return;
10982 
10983   SmallVector<SDValue, 4> Values(NumValues);
10984   SDValue Op = getValue(I.getOperand(0));
10985 
10986   for (unsigned i = 0; i != NumValues; ++i)
10987     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10988                             SDValue(Op.getNode(), Op.getResNo() + i));
10989 
10990   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10991                            DAG.getVTList(ValueVTs), Values));
10992 }
10993 
10994 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
10995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10996   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10997 
10998   SDLoc DL = getCurSDLoc();
10999   SDValue V1 = getValue(I.getOperand(0));
11000   SDValue V2 = getValue(I.getOperand(1));
11001   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11002 
11003   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11004   if (VT.isScalableVector()) {
11005     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11006     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11007                              DAG.getConstant(Imm, DL, IdxVT)));
11008     return;
11009   }
11010 
11011   unsigned NumElts = VT.getVectorNumElements();
11012 
11013   if ((-Imm > NumElts) || (Imm >= NumElts)) {
11014     // Result is undefined if immediate is out-of-bounds.
11015     setValue(&I, DAG.getUNDEF(VT));
11016     return;
11017   }
11018 
11019   uint64_t Idx = (NumElts + Imm) % NumElts;
11020 
11021   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11022   SmallVector<int, 8> Mask;
11023   for (unsigned i = 0; i < NumElts; ++i)
11024     Mask.push_back(Idx + i);
11025   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11026 }
11027