xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 6d0d86a64d304d4fbeeadd13f56b6ca559f45921)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BlockFrequencyInfo.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/ProfileSummaryInfo.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/ValueTracking.h"
39 #include "llvm/Analysis/VectorUtils.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/FunctionLoweringInfo.h"
42 #include "llvm/CodeGen/GCMetadata.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineJumpTableInfo.h"
50 #include "llvm/CodeGen/MachineMemOperand.h"
51 #include "llvm/CodeGen/MachineModuleInfo.h"
52 #include "llvm/CodeGen/MachineOperand.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/RuntimeLibcalls.h"
55 #include "llvm/CodeGen/SelectionDAG.h"
56 #include "llvm/CodeGen/SelectionDAGNodes.h"
57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
58 #include "llvm/CodeGen/StackMaps.h"
59 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
60 #include "llvm/CodeGen/TargetFrameLowering.h"
61 #include "llvm/CodeGen/TargetInstrInfo.h"
62 #include "llvm/CodeGen/TargetLowering.h"
63 #include "llvm/CodeGen/TargetOpcodes.h"
64 #include "llvm/CodeGen/TargetRegisterInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include "llvm/CodeGen/ValueTypes.h"
67 #include "llvm/CodeGen/WinEHFuncInfo.h"
68 #include "llvm/IR/Argument.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/BasicBlock.h"
71 #include "llvm/IR/CFG.h"
72 #include "llvm/IR/CallSite.h"
73 #include "llvm/IR/CallingConv.h"
74 #include "llvm/IR/Constant.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DebugInfoMetadata.h"
79 #include "llvm/IR/DebugLoc.h"
80 #include "llvm/IR/DerivedTypes.h"
81 #include "llvm/IR/Function.h"
82 #include "llvm/IR/GetElementPtrTypeIterator.h"
83 #include "llvm/IR/InlineAsm.h"
84 #include "llvm/IR/InstrTypes.h"
85 #include "llvm/IR/Instruction.h"
86 #include "llvm/IR/Instructions.h"
87 #include "llvm/IR/IntrinsicInst.h"
88 #include "llvm/IR/Intrinsics.h"
89 #include "llvm/IR/IntrinsicsAArch64.h"
90 #include "llvm/IR/IntrinsicsWebAssembly.h"
91 #include "llvm/IR/LLVMContext.h"
92 #include "llvm/IR/Metadata.h"
93 #include "llvm/IR/Module.h"
94 #include "llvm/IR/Operator.h"
95 #include "llvm/IR/PatternMatch.h"
96 #include "llvm/IR/Statepoint.h"
97 #include "llvm/IR/Type.h"
98 #include "llvm/IR/User.h"
99 #include "llvm/IR/Value.h"
100 #include "llvm/MC/MCContext.h"
101 #include "llvm/MC/MCSymbol.h"
102 #include "llvm/Support/AtomicOrdering.h"
103 #include "llvm/Support/BranchProbability.h"
104 #include "llvm/Support/Casting.h"
105 #include "llvm/Support/CodeGen.h"
106 #include "llvm/Support/CommandLine.h"
107 #include "llvm/Support/Compiler.h"
108 #include "llvm/Support/Debug.h"
109 #include "llvm/Support/ErrorHandling.h"
110 #include "llvm/Support/MachineValueType.h"
111 #include "llvm/Support/MathExtras.h"
112 #include "llvm/Support/raw_ostream.h"
113 #include "llvm/Target/TargetIntrinsicInfo.h"
114 #include "llvm/Target/TargetMachine.h"
115 #include "llvm/Target/TargetOptions.h"
116 #include "llvm/Transforms/Utils/Local.h"
117 #include <algorithm>
118 #include <cassert>
119 #include <cstddef>
120 #include <cstdint>
121 #include <cstring>
122 #include <iterator>
123 #include <limits>
124 #include <numeric>
125 #include <tuple>
126 #include <utility>
127 #include <vector>
128 
129 using namespace llvm;
130 using namespace PatternMatch;
131 using namespace SwitchCG;
132 
133 #define DEBUG_TYPE "isel"
134 
135 /// LimitFloatPrecision - Generate low-precision inline sequences for
136 /// some float libcalls (6, 8 or 12 bits).
137 static unsigned LimitFloatPrecision;
138 
139 static cl::opt<unsigned, true>
140     LimitFPPrecision("limit-float-precision",
141                      cl::desc("Generate low-precision inline sequences "
142                               "for some float libcalls"),
143                      cl::location(LimitFloatPrecision), cl::Hidden,
144                      cl::init(0));
145 
146 static cl::opt<unsigned> SwitchPeelThreshold(
147     "switch-peel-threshold", cl::Hidden, cl::init(66),
148     cl::desc("Set the case probability threshold for peeling the case from a "
149              "switch statement. A value greater than 100 will void this "
150              "optimization"));
151 
152 // Limit the width of DAG chains. This is important in general to prevent
153 // DAG-based analysis from blowing up. For example, alias analysis and
154 // load clustering may not complete in reasonable time. It is difficult to
155 // recognize and avoid this situation within each individual analysis, and
156 // future analyses are likely to have the same behavior. Limiting DAG width is
157 // the safe approach and will be especially important with global DAGs.
158 //
159 // MaxParallelChains default is arbitrarily high to avoid affecting
160 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
161 // sequence over this should have been converted to llvm.memcpy by the
162 // frontend. It is easy to induce this behavior with .ll code such as:
163 // %buffer = alloca [4096 x i8]
164 // %data = load [4096 x i8]* %argPtr
165 // store [4096 x i8] %data, [4096 x i8]* %buffer
166 static const unsigned MaxParallelChains = 64;
167 
168 // Return the calling convention if the Value passed requires ABI mangling as it
169 // is a parameter to a function or a return value from a function which is not
170 // an intrinsic.
171 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
172   if (auto *R = dyn_cast<ReturnInst>(V))
173     return R->getParent()->getParent()->getCallingConv();
174 
175   if (auto *CI = dyn_cast<CallInst>(V)) {
176     const bool IsInlineAsm = CI->isInlineAsm();
177     const bool IsIndirectFunctionCall =
178         !IsInlineAsm && !CI->getCalledFunction();
179 
180     // It is possible that the call instruction is an inline asm statement or an
181     // indirect function call in which case the return value of
182     // getCalledFunction() would be nullptr.
183     const bool IsInstrinsicCall =
184         !IsInlineAsm && !IsIndirectFunctionCall &&
185         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
186 
187     if (!IsInlineAsm && !IsInstrinsicCall)
188       return CI->getCallingConv();
189   }
190 
191   return None;
192 }
193 
194 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
195                                       const SDValue *Parts, unsigned NumParts,
196                                       MVT PartVT, EVT ValueVT, const Value *V,
197                                       Optional<CallingConv::ID> CC);
198 
199 /// getCopyFromParts - Create a value that contains the specified legal parts
200 /// combined into the value they represent.  If the parts combine to a type
201 /// larger than ValueVT then AssertOp can be used to specify whether the extra
202 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
203 /// (ISD::AssertSext).
204 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
205                                 const SDValue *Parts, unsigned NumParts,
206                                 MVT PartVT, EVT ValueVT, const Value *V,
207                                 Optional<CallingConv::ID> CC = None,
208                                 Optional<ISD::NodeType> AssertOp = None) {
209   if (ValueVT.isVector())
210     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
211                                   CC);
212 
213   assert(NumParts > 0 && "No parts to assemble!");
214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
215   SDValue Val = Parts[0];
216 
217   if (NumParts > 1) {
218     // Assemble the value from multiple parts.
219     if (ValueVT.isInteger()) {
220       unsigned PartBits = PartVT.getSizeInBits();
221       unsigned ValueBits = ValueVT.getSizeInBits();
222 
223       // Assemble the power of 2 part.
224       unsigned RoundParts =
225           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
226       unsigned RoundBits = PartBits * RoundParts;
227       EVT RoundVT = RoundBits == ValueBits ?
228         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
229       SDValue Lo, Hi;
230 
231       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
232 
233       if (RoundParts > 2) {
234         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
235                               PartVT, HalfVT, V);
236         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
237                               RoundParts / 2, PartVT, HalfVT, V);
238       } else {
239         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
240         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
241       }
242 
243       if (DAG.getDataLayout().isBigEndian())
244         std::swap(Lo, Hi);
245 
246       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
247 
248       if (RoundParts < NumParts) {
249         // Assemble the trailing non-power-of-2 part.
250         unsigned OddParts = NumParts - RoundParts;
251         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
252         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
253                               OddVT, V, CC);
254 
255         // Combine the round and odd parts.
256         Lo = Val;
257         if (DAG.getDataLayout().isBigEndian())
258           std::swap(Lo, Hi);
259         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
260         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
261         Hi =
262             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
263                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
264                                         TLI.getPointerTy(DAG.getDataLayout())));
265         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
266         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
267       }
268     } else if (PartVT.isFloatingPoint()) {
269       // FP split into multiple FP parts (for ppcf128)
270       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
271              "Unexpected split");
272       SDValue Lo, Hi;
273       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
274       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
275       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
276         std::swap(Lo, Hi);
277       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
278     } else {
279       // FP split into integer parts (soft fp)
280       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
281              !PartVT.isVector() && "Unexpected split");
282       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
283       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
284     }
285   }
286 
287   // There is now one part, held in Val.  Correct it to match ValueVT.
288   // PartEVT is the type of the register class that holds the value.
289   // ValueVT is the type of the inline asm operation.
290   EVT PartEVT = Val.getValueType();
291 
292   if (PartEVT == ValueVT)
293     return Val;
294 
295   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
296       ValueVT.bitsLT(PartEVT)) {
297     // For an FP value in an integer part, we need to truncate to the right
298     // width first.
299     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
300     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
301   }
302 
303   // Handle types that have the same size.
304   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
305     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
306 
307   // Handle types with different sizes.
308   if (PartEVT.isInteger() && ValueVT.isInteger()) {
309     if (ValueVT.bitsLT(PartEVT)) {
310       // For a truncate, see if we have any information to
311       // indicate whether the truncated bits will always be
312       // zero or sign-extension.
313       if (AssertOp.hasValue())
314         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
315                           DAG.getValueType(ValueVT));
316       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317     }
318     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
319   }
320 
321   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
322     // FP_ROUND's are always exact here.
323     if (ValueVT.bitsLT(Val.getValueType()))
324       return DAG.getNode(
325           ISD::FP_ROUND, DL, ValueVT, Val,
326           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
327 
328     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
329   }
330 
331   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
332   // then truncating.
333   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
334       ValueVT.bitsLT(PartEVT)) {
335     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
336     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
337   }
338 
339   report_fatal_error("Unknown mismatch in getCopyFromParts!");
340 }
341 
342 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
343                                               const Twine &ErrMsg) {
344   const Instruction *I = dyn_cast_or_null<Instruction>(V);
345   if (!V)
346     return Ctx.emitError(ErrMsg);
347 
348   const char *AsmError = ", possible invalid constraint for vector type";
349   if (const CallInst *CI = dyn_cast<CallInst>(I))
350     if (isa<InlineAsm>(CI->getCalledValue()))
351       return Ctx.emitError(I, ErrMsg + AsmError);
352 
353   return Ctx.emitError(I, ErrMsg);
354 }
355 
356 /// getCopyFromPartsVector - Create a value that contains the specified legal
357 /// parts combined into the value they represent.  If the parts combine to a
358 /// type larger than ValueVT then AssertOp can be used to specify whether the
359 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
360 /// ValueVT (ISD::AssertSext).
361 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
362                                       const SDValue *Parts, unsigned NumParts,
363                                       MVT PartVT, EVT ValueVT, const Value *V,
364                                       Optional<CallingConv::ID> CallConv) {
365   assert(ValueVT.isVector() && "Not a vector value");
366   assert(NumParts > 0 && "No parts to assemble!");
367   const bool IsABIRegCopy = CallConv.hasValue();
368 
369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
370   SDValue Val = Parts[0];
371 
372   // Handle a multi-element vector.
373   if (NumParts > 1) {
374     EVT IntermediateVT;
375     MVT RegisterVT;
376     unsigned NumIntermediates;
377     unsigned NumRegs;
378 
379     if (IsABIRegCopy) {
380       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
381           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
382           NumIntermediates, RegisterVT);
383     } else {
384       NumRegs =
385           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
386                                      NumIntermediates, RegisterVT);
387     }
388 
389     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
390     NumParts = NumRegs; // Silence a compiler warning.
391     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
392     assert(RegisterVT.getSizeInBits() ==
393            Parts[0].getSimpleValueType().getSizeInBits() &&
394            "Part type sizes don't match!");
395 
396     // Assemble the parts into intermediate operands.
397     SmallVector<SDValue, 8> Ops(NumIntermediates);
398     if (NumIntermediates == NumParts) {
399       // If the register was not expanded, truncate or copy the value,
400       // as appropriate.
401       for (unsigned i = 0; i != NumParts; ++i)
402         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
403                                   PartVT, IntermediateVT, V);
404     } else if (NumParts > 0) {
405       // If the intermediate type was expanded, build the intermediate
406       // operands from the parts.
407       assert(NumParts % NumIntermediates == 0 &&
408              "Must expand into a divisible number of parts!");
409       unsigned Factor = NumParts / NumIntermediates;
410       for (unsigned i = 0; i != NumIntermediates; ++i)
411         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
412                                   PartVT, IntermediateVT, V);
413     }
414 
415     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
416     // intermediate operands.
417     EVT BuiltVectorTy =
418         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
419                          (IntermediateVT.isVector()
420                               ? IntermediateVT.getVectorNumElements() * NumParts
421                               : NumIntermediates));
422     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
423                                                 : ISD::BUILD_VECTOR,
424                       DL, BuiltVectorTy, Ops);
425   }
426 
427   // There is now one part, held in Val.  Correct it to match ValueVT.
428   EVT PartEVT = Val.getValueType();
429 
430   if (PartEVT == ValueVT)
431     return Val;
432 
433   if (PartEVT.isVector()) {
434     // If the element type of the source/dest vectors are the same, but the
435     // parts vector has more elements than the value vector, then we have a
436     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
437     // elements we want.
438     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
439       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
440              "Cannot narrow, it would be a lossy transformation");
441       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
442                          DAG.getVectorIdxConstant(0, DL));
443     }
444 
445     // Vector/Vector bitcast.
446     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
447       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
448 
449     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
450       "Cannot handle this kind of promotion");
451     // Promoted vector extract
452     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
453 
454   }
455 
456   // Trivial bitcast if the types are the same size and the destination
457   // vector type is legal.
458   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
459       TLI.isTypeLegal(ValueVT))
460     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
461 
462   if (ValueVT.getVectorNumElements() != 1) {
463      // Certain ABIs require that vectors are passed as integers. For vectors
464      // are the same size, this is an obvious bitcast.
465      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
466        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
467      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
468        // Bitcast Val back the original type and extract the corresponding
469        // vector we want.
470        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
471        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
472                                            ValueVT.getVectorElementType(), Elts);
473        Val = DAG.getBitcast(WiderVecType, Val);
474        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
475                           DAG.getVectorIdxConstant(0, DL));
476      }
477 
478      diagnosePossiblyInvalidConstraint(
479          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
480      return DAG.getUNDEF(ValueVT);
481   }
482 
483   // Handle cases such as i8 -> <1 x i1>
484   EVT ValueSVT = ValueVT.getVectorElementType();
485   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
486     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
487                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
488 
489   return DAG.getBuildVector(ValueVT, DL, Val);
490 }
491 
492 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
493                                  SDValue Val, SDValue *Parts, unsigned NumParts,
494                                  MVT PartVT, const Value *V,
495                                  Optional<CallingConv::ID> CallConv);
496 
497 /// getCopyToParts - Create a series of nodes that contain the specified value
498 /// split into legal parts.  If the parts contain more bits than Val, then, for
499 /// integers, ExtendKind can be used to specify how to generate the extra bits.
500 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
501                            SDValue *Parts, unsigned NumParts, MVT PartVT,
502                            const Value *V,
503                            Optional<CallingConv::ID> CallConv = None,
504                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
505   EVT ValueVT = Val.getValueType();
506 
507   // Handle the vector case separately.
508   if (ValueVT.isVector())
509     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
510                                 CallConv);
511 
512   unsigned PartBits = PartVT.getSizeInBits();
513   unsigned OrigNumParts = NumParts;
514   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
515          "Copying to an illegal type!");
516 
517   if (NumParts == 0)
518     return;
519 
520   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
521   EVT PartEVT = PartVT;
522   if (PartEVT == ValueVT) {
523     assert(NumParts == 1 && "No-op copy with multiple parts!");
524     Parts[0] = Val;
525     return;
526   }
527 
528   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
529     // If the parts cover more bits than the value has, promote the value.
530     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
531       assert(NumParts == 1 && "Do not know what to promote to!");
532       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
533     } else {
534       if (ValueVT.isFloatingPoint()) {
535         // FP values need to be bitcast, then extended if they are being put
536         // into a larger container.
537         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
538         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
539       }
540       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
541              ValueVT.isInteger() &&
542              "Unknown mismatch!");
543       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
544       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
545       if (PartVT == MVT::x86mmx)
546         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
547     }
548   } else if (PartBits == ValueVT.getSizeInBits()) {
549     // Different types of the same size.
550     assert(NumParts == 1 && PartEVT != ValueVT);
551     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
552   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
553     // If the parts cover less bits than value has, truncate the value.
554     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
555            ValueVT.isInteger() &&
556            "Unknown mismatch!");
557     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
558     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
559     if (PartVT == MVT::x86mmx)
560       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
561   }
562 
563   // The value may have changed - recompute ValueVT.
564   ValueVT = Val.getValueType();
565   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
566          "Failed to tile the value with PartVT!");
567 
568   if (NumParts == 1) {
569     if (PartEVT != ValueVT) {
570       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
571                                         "scalar-to-vector conversion failed");
572       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
573     }
574 
575     Parts[0] = Val;
576     return;
577   }
578 
579   // Expand the value into multiple parts.
580   if (NumParts & (NumParts - 1)) {
581     // The number of parts is not a power of 2.  Split off and copy the tail.
582     assert(PartVT.isInteger() && ValueVT.isInteger() &&
583            "Do not know what to expand to!");
584     unsigned RoundParts = 1 << Log2_32(NumParts);
585     unsigned RoundBits = RoundParts * PartBits;
586     unsigned OddParts = NumParts - RoundParts;
587     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
588       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
589 
590     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
591                    CallConv);
592 
593     if (DAG.getDataLayout().isBigEndian())
594       // The odd parts were reversed by getCopyToParts - unreverse them.
595       std::reverse(Parts + RoundParts, Parts + NumParts);
596 
597     NumParts = RoundParts;
598     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
599     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
600   }
601 
602   // The number of parts is a power of 2.  Repeatedly bisect the value using
603   // EXTRACT_ELEMENT.
604   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
605                          EVT::getIntegerVT(*DAG.getContext(),
606                                            ValueVT.getSizeInBits()),
607                          Val);
608 
609   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
610     for (unsigned i = 0; i < NumParts; i += StepSize) {
611       unsigned ThisBits = StepSize * PartBits / 2;
612       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
613       SDValue &Part0 = Parts[i];
614       SDValue &Part1 = Parts[i+StepSize/2];
615 
616       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
617                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
618       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
619                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
620 
621       if (ThisBits == PartBits && ThisVT != PartVT) {
622         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
623         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
624       }
625     }
626   }
627 
628   if (DAG.getDataLayout().isBigEndian())
629     std::reverse(Parts, Parts + OrigNumParts);
630 }
631 
632 static SDValue widenVectorToPartType(SelectionDAG &DAG,
633                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
634   if (!PartVT.isVector())
635     return SDValue();
636 
637   EVT ValueVT = Val.getValueType();
638   unsigned PartNumElts = PartVT.getVectorNumElements();
639   unsigned ValueNumElts = ValueVT.getVectorNumElements();
640   if (PartNumElts > ValueNumElts &&
641       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
642     EVT ElementVT = PartVT.getVectorElementType();
643     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
644     // undef elements.
645     SmallVector<SDValue, 16> Ops;
646     DAG.ExtractVectorElements(Val, Ops);
647     SDValue EltUndef = DAG.getUNDEF(ElementVT);
648     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
649       Ops.push_back(EltUndef);
650 
651     // FIXME: Use CONCAT for 2x -> 4x.
652     return DAG.getBuildVector(PartVT, DL, Ops);
653   }
654 
655   return SDValue();
656 }
657 
658 /// getCopyToPartsVector - Create a series of nodes that contain the specified
659 /// value split into legal parts.
660 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
661                                  SDValue Val, SDValue *Parts, unsigned NumParts,
662                                  MVT PartVT, const Value *V,
663                                  Optional<CallingConv::ID> CallConv) {
664   EVT ValueVT = Val.getValueType();
665   assert(ValueVT.isVector() && "Not a vector");
666   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
667   const bool IsABIRegCopy = CallConv.hasValue();
668 
669   if (NumParts == 1) {
670     EVT PartEVT = PartVT;
671     if (PartEVT == ValueVT) {
672       // Nothing to do.
673     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
674       // Bitconvert vector->vector case.
675       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
676     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
677       Val = Widened;
678     } else if (PartVT.isVector() &&
679                PartEVT.getVectorElementType().bitsGE(
680                  ValueVT.getVectorElementType()) &&
681                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
682 
683       // Promoted vector extract
684       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
685     } else {
686       if (ValueVT.getVectorNumElements() == 1) {
687         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
688                           DAG.getVectorIdxConstant(0, DL));
689       } else {
690         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
691                "lossy conversion of vector to scalar type");
692         EVT IntermediateType =
693             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
694         Val = DAG.getBitcast(IntermediateType, Val);
695         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
696       }
697     }
698 
699     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
700     Parts[0] = Val;
701     return;
702   }
703 
704   // Handle a multi-element vector.
705   EVT IntermediateVT;
706   MVT RegisterVT;
707   unsigned NumIntermediates;
708   unsigned NumRegs;
709   if (IsABIRegCopy) {
710     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
711         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
712         NumIntermediates, RegisterVT);
713   } else {
714     NumRegs =
715         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
716                                    NumIntermediates, RegisterVT);
717   }
718 
719   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
720   NumParts = NumRegs; // Silence a compiler warning.
721   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
722 
723   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
724     IntermediateVT.getVectorNumElements() : 1;
725 
726   // Convert the vector to the appropriate type if necessary.
727   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
728 
729   EVT BuiltVectorTy = EVT::getVectorVT(
730       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
731   if (ValueVT != BuiltVectorTy) {
732     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
733       Val = Widened;
734 
735     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
736   }
737 
738   // Split the vector into intermediate operands.
739   SmallVector<SDValue, 8> Ops(NumIntermediates);
740   for (unsigned i = 0; i != NumIntermediates; ++i) {
741     if (IntermediateVT.isVector()) {
742       Ops[i] =
743           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
744                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
745     } else {
746       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
747                            DAG.getVectorIdxConstant(i, DL));
748     }
749   }
750 
751   // Split the intermediate operands into legal parts.
752   if (NumParts == NumIntermediates) {
753     // If the register was not expanded, promote or copy the value,
754     // as appropriate.
755     for (unsigned i = 0; i != NumParts; ++i)
756       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
757   } else if (NumParts > 0) {
758     // If the intermediate type was expanded, split each the value into
759     // legal parts.
760     assert(NumIntermediates != 0 && "division by zero");
761     assert(NumParts % NumIntermediates == 0 &&
762            "Must expand into a divisible number of parts!");
763     unsigned Factor = NumParts / NumIntermediates;
764     for (unsigned i = 0; i != NumIntermediates; ++i)
765       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
766                      CallConv);
767   }
768 }
769 
770 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
771                            EVT valuevt, Optional<CallingConv::ID> CC)
772     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
773       RegCount(1, regs.size()), CallConv(CC) {}
774 
775 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
776                            const DataLayout &DL, unsigned Reg, Type *Ty,
777                            Optional<CallingConv::ID> CC) {
778   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
779 
780   CallConv = CC;
781 
782   for (EVT ValueVT : ValueVTs) {
783     unsigned NumRegs =
784         isABIMangled()
785             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
786             : TLI.getNumRegisters(Context, ValueVT);
787     MVT RegisterVT =
788         isABIMangled()
789             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
790             : TLI.getRegisterType(Context, ValueVT);
791     for (unsigned i = 0; i != NumRegs; ++i)
792       Regs.push_back(Reg + i);
793     RegVTs.push_back(RegisterVT);
794     RegCount.push_back(NumRegs);
795     Reg += NumRegs;
796   }
797 }
798 
799 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
800                                       FunctionLoweringInfo &FuncInfo,
801                                       const SDLoc &dl, SDValue &Chain,
802                                       SDValue *Flag, const Value *V) const {
803   // A Value with type {} or [0 x %t] needs no registers.
804   if (ValueVTs.empty())
805     return SDValue();
806 
807   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
808 
809   // Assemble the legal parts into the final values.
810   SmallVector<SDValue, 4> Values(ValueVTs.size());
811   SmallVector<SDValue, 8> Parts;
812   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
813     // Copy the legal parts from the registers.
814     EVT ValueVT = ValueVTs[Value];
815     unsigned NumRegs = RegCount[Value];
816     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
817                                           *DAG.getContext(),
818                                           CallConv.getValue(), RegVTs[Value])
819                                     : RegVTs[Value];
820 
821     Parts.resize(NumRegs);
822     for (unsigned i = 0; i != NumRegs; ++i) {
823       SDValue P;
824       if (!Flag) {
825         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
826       } else {
827         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
828         *Flag = P.getValue(2);
829       }
830 
831       Chain = P.getValue(1);
832       Parts[i] = P;
833 
834       // If the source register was virtual and if we know something about it,
835       // add an assert node.
836       if (!Register::isVirtualRegister(Regs[Part + i]) ||
837           !RegisterVT.isInteger())
838         continue;
839 
840       const FunctionLoweringInfo::LiveOutInfo *LOI =
841         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
842       if (!LOI)
843         continue;
844 
845       unsigned RegSize = RegisterVT.getScalarSizeInBits();
846       unsigned NumSignBits = LOI->NumSignBits;
847       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
848 
849       if (NumZeroBits == RegSize) {
850         // The current value is a zero.
851         // Explicitly express that as it would be easier for
852         // optimizations to kick in.
853         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
854         continue;
855       }
856 
857       // FIXME: We capture more information than the dag can represent.  For
858       // now, just use the tightest assertzext/assertsext possible.
859       bool isSExt;
860       EVT FromVT(MVT::Other);
861       if (NumZeroBits) {
862         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
863         isSExt = false;
864       } else if (NumSignBits > 1) {
865         FromVT =
866             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
867         isSExt = true;
868       } else {
869         continue;
870       }
871       // Add an assertion node.
872       assert(FromVT != MVT::Other);
873       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
874                              RegisterVT, P, DAG.getValueType(FromVT));
875     }
876 
877     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
878                                      RegisterVT, ValueVT, V, CallConv);
879     Part += NumRegs;
880     Parts.clear();
881   }
882 
883   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
884 }
885 
886 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
887                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
888                                  const Value *V,
889                                  ISD::NodeType PreferredExtendType) const {
890   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
891   ISD::NodeType ExtendKind = PreferredExtendType;
892 
893   // Get the list of the values's legal parts.
894   unsigned NumRegs = Regs.size();
895   SmallVector<SDValue, 8> Parts(NumRegs);
896   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
897     unsigned NumParts = RegCount[Value];
898 
899     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
900                                           *DAG.getContext(),
901                                           CallConv.getValue(), RegVTs[Value])
902                                     : RegVTs[Value];
903 
904     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
905       ExtendKind = ISD::ZERO_EXTEND;
906 
907     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
908                    NumParts, RegisterVT, V, CallConv, ExtendKind);
909     Part += NumParts;
910   }
911 
912   // Copy the parts into the registers.
913   SmallVector<SDValue, 8> Chains(NumRegs);
914   for (unsigned i = 0; i != NumRegs; ++i) {
915     SDValue Part;
916     if (!Flag) {
917       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
918     } else {
919       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
920       *Flag = Part.getValue(1);
921     }
922 
923     Chains[i] = Part.getValue(0);
924   }
925 
926   if (NumRegs == 1 || Flag)
927     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
928     // flagged to it. That is the CopyToReg nodes and the user are considered
929     // a single scheduling unit. If we create a TokenFactor and return it as
930     // chain, then the TokenFactor is both a predecessor (operand) of the
931     // user as well as a successor (the TF operands are flagged to the user).
932     // c1, f1 = CopyToReg
933     // c2, f2 = CopyToReg
934     // c3     = TokenFactor c1, c2
935     // ...
936     //        = op c3, ..., f2
937     Chain = Chains[NumRegs-1];
938   else
939     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
940 }
941 
942 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
943                                         unsigned MatchingIdx, const SDLoc &dl,
944                                         SelectionDAG &DAG,
945                                         std::vector<SDValue> &Ops) const {
946   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
947 
948   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
949   if (HasMatching)
950     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
951   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
952     // Put the register class of the virtual registers in the flag word.  That
953     // way, later passes can recompute register class constraints for inline
954     // assembly as well as normal instructions.
955     // Don't do this for tied operands that can use the regclass information
956     // from the def.
957     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
958     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
959     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
960   }
961 
962   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
963   Ops.push_back(Res);
964 
965   if (Code == InlineAsm::Kind_Clobber) {
966     // Clobbers should always have a 1:1 mapping with registers, and may
967     // reference registers that have illegal (e.g. vector) types. Hence, we
968     // shouldn't try to apply any sort of splitting logic to them.
969     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
970            "No 1:1 mapping from clobbers to regs?");
971     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
972     (void)SP;
973     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
974       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
975       assert(
976           (Regs[I] != SP ||
977            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
978           "If we clobbered the stack pointer, MFI should know about it.");
979     }
980     return;
981   }
982 
983   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
984     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
985     MVT RegisterVT = RegVTs[Value];
986     for (unsigned i = 0; i != NumRegs; ++i) {
987       assert(Reg < Regs.size() && "Mismatch in # registers expected");
988       unsigned TheReg = Regs[Reg++];
989       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
990     }
991   }
992 }
993 
994 SmallVector<std::pair<unsigned, unsigned>, 4>
995 RegsForValue::getRegsAndSizes() const {
996   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
997   unsigned I = 0;
998   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
999     unsigned RegCount = std::get<0>(CountAndVT);
1000     MVT RegisterVT = std::get<1>(CountAndVT);
1001     unsigned RegisterSize = RegisterVT.getSizeInBits();
1002     for (unsigned E = I + RegCount; I != E; ++I)
1003       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1004   }
1005   return OutVec;
1006 }
1007 
1008 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1009                                const TargetLibraryInfo *li) {
1010   AA = aa;
1011   GFI = gfi;
1012   LibInfo = li;
1013   DL = &DAG.getDataLayout();
1014   Context = DAG.getContext();
1015   LPadToCallSiteMap.clear();
1016   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1017 }
1018 
1019 void SelectionDAGBuilder::clear() {
1020   NodeMap.clear();
1021   UnusedArgNodeMap.clear();
1022   PendingLoads.clear();
1023   PendingExports.clear();
1024   PendingConstrainedFP.clear();
1025   PendingConstrainedFPStrict.clear();
1026   CurInst = nullptr;
1027   HasTailCall = false;
1028   SDNodeOrder = LowestSDNodeOrder;
1029   StatepointLowering.clear();
1030 }
1031 
1032 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1033   DanglingDebugInfoMap.clear();
1034 }
1035 
1036 // Update DAG root to include dependencies on Pending chains.
1037 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1038   SDValue Root = DAG.getRoot();
1039 
1040   if (Pending.empty())
1041     return Root;
1042 
1043   // Add current root to PendingChains, unless we already indirectly
1044   // depend on it.
1045   if (Root.getOpcode() != ISD::EntryToken) {
1046     unsigned i = 0, e = Pending.size();
1047     for (; i != e; ++i) {
1048       assert(Pending[i].getNode()->getNumOperands() > 1);
1049       if (Pending[i].getNode()->getOperand(0) == Root)
1050         break;  // Don't add the root if we already indirectly depend on it.
1051     }
1052 
1053     if (i == e)
1054       Pending.push_back(Root);
1055   }
1056 
1057   if (Pending.size() == 1)
1058     Root = Pending[0];
1059   else
1060     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1061 
1062   DAG.setRoot(Root);
1063   Pending.clear();
1064   return Root;
1065 }
1066 
1067 SDValue SelectionDAGBuilder::getMemoryRoot() {
1068   return updateRoot(PendingLoads);
1069 }
1070 
1071 SDValue SelectionDAGBuilder::getRoot() {
1072   // Chain up all pending constrained intrinsics together with all
1073   // pending loads, by simply appending them to PendingLoads and
1074   // then calling getMemoryRoot().
1075   PendingLoads.reserve(PendingLoads.size() +
1076                        PendingConstrainedFP.size() +
1077                        PendingConstrainedFPStrict.size());
1078   PendingLoads.append(PendingConstrainedFP.begin(),
1079                       PendingConstrainedFP.end());
1080   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1081                       PendingConstrainedFPStrict.end());
1082   PendingConstrainedFP.clear();
1083   PendingConstrainedFPStrict.clear();
1084   return getMemoryRoot();
1085 }
1086 
1087 SDValue SelectionDAGBuilder::getControlRoot() {
1088   // We need to emit pending fpexcept.strict constrained intrinsics,
1089   // so append them to the PendingExports list.
1090   PendingExports.append(PendingConstrainedFPStrict.begin(),
1091                         PendingConstrainedFPStrict.end());
1092   PendingConstrainedFPStrict.clear();
1093   return updateRoot(PendingExports);
1094 }
1095 
1096 void SelectionDAGBuilder::visit(const Instruction &I) {
1097   // Set up outgoing PHI node register values before emitting the terminator.
1098   if (I.isTerminator()) {
1099     HandlePHINodesInSuccessorBlocks(I.getParent());
1100   }
1101 
1102   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1103   if (!isa<DbgInfoIntrinsic>(I))
1104     ++SDNodeOrder;
1105 
1106   CurInst = &I;
1107 
1108   visit(I.getOpcode(), I);
1109 
1110   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1111     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1112     // maps to this instruction.
1113     // TODO: We could handle all flags (nsw, etc) here.
1114     // TODO: If an IR instruction maps to >1 node, only the final node will have
1115     //       flags set.
1116     if (SDNode *Node = getNodeForIRValue(&I)) {
1117       SDNodeFlags IncomingFlags;
1118       IncomingFlags.copyFMF(*FPMO);
1119       if (!Node->getFlags().isDefined())
1120         Node->setFlags(IncomingFlags);
1121       else
1122         Node->intersectFlagsWith(IncomingFlags);
1123     }
1124   }
1125   // Constrained FP intrinsics with fpexcept.ignore should also get
1126   // the NoFPExcept flag.
1127   if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(&I))
1128     if (FPI->getExceptionBehavior() == fp::ExceptionBehavior::ebIgnore)
1129       if (SDNode *Node = getNodeForIRValue(&I)) {
1130         SDNodeFlags Flags = Node->getFlags();
1131         Flags.setNoFPExcept(true);
1132         Node->setFlags(Flags);
1133       }
1134 
1135   if (!I.isTerminator() && !HasTailCall &&
1136       !isStatepoint(&I)) // statepoints handle their exports internally
1137     CopyToExportRegsIfNeeded(&I);
1138 
1139   CurInst = nullptr;
1140 }
1141 
1142 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1143   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1144 }
1145 
1146 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1147   // Note: this doesn't use InstVisitor, because it has to work with
1148   // ConstantExpr's in addition to instructions.
1149   switch (Opcode) {
1150   default: llvm_unreachable("Unknown instruction type encountered!");
1151     // Build the switch statement using the Instruction.def file.
1152 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1153     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1154 #include "llvm/IR/Instruction.def"
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     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
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 && "Ill-formed DanglingDebugInfo");
1196     DebugLoc dl = DDI.getdl();
1197     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1198     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1199     DILocalVariable *Variable = DI->getVariable();
1200     DIExpression *Expr = DI->getExpression();
1201     assert(Variable->isValidLocationForIntrinsic(dl) &&
1202            "Expected inlined-at fields to agree");
1203     SDDbgValue *SDV;
1204     if (Val.getNode()) {
1205       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1206       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1207       // we couldn't resolve it directly when examining the DbgValue intrinsic
1208       // in the first place we should not be more successful here). Unless we
1209       // have some test case that prove this to be correct we should avoid
1210       // calling EmitFuncArgumentDbgValue here.
1211       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1212         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1213                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1214         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1215         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1216         // inserted after the definition of Val when emitting the instructions
1217         // after ISel. An alternative could be to teach
1218         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1219         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1220                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1221                    << ValSDNodeOrder << "\n");
1222         SDV = getDbgValue(Val, Variable, Expr, dl,
1223                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1224         DAG.AddDbgValue(SDV, Val.getNode(), false);
1225       } else
1226         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1227                           << "in EmitFuncArgumentDbgValue\n");
1228     } else {
1229       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1230       auto Undef =
1231           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1232       auto SDV =
1233           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1234       DAG.AddDbgValue(SDV, nullptr, false);
1235     }
1236   }
1237   DDIV.clear();
1238 }
1239 
1240 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1241   Value *V = DDI.getDI()->getValue();
1242   DILocalVariable *Var = DDI.getDI()->getVariable();
1243   DIExpression *Expr = DDI.getDI()->getExpression();
1244   DebugLoc DL = DDI.getdl();
1245   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1246   unsigned SDOrder = DDI.getSDNodeOrder();
1247 
1248   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1249   // that DW_OP_stack_value is desired.
1250   assert(isa<DbgValueInst>(DDI.getDI()));
1251   bool StackValue = true;
1252 
1253   // Can this Value can be encoded without any further work?
1254   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1255     return;
1256 
1257   // Attempt to salvage back through as many instructions as possible. Bail if
1258   // a non-instruction is seen, such as a constant expression or global
1259   // variable. FIXME: Further work could recover those too.
1260   while (isa<Instruction>(V)) {
1261     Instruction &VAsInst = *cast<Instruction>(V);
1262     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1263 
1264     // If we cannot salvage any further, and haven't yet found a suitable debug
1265     // expression, bail out.
1266     if (!NewExpr)
1267       break;
1268 
1269     // New value and expr now represent this debuginfo.
1270     V = VAsInst.getOperand(0);
1271     Expr = NewExpr;
1272 
1273     // Some kind of simplification occurred: check whether the operand of the
1274     // salvaged debug expression can be encoded in this DAG.
1275     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1276       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1277                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1278       return;
1279     }
1280   }
1281 
1282   // This was the final opportunity to salvage this debug information, and it
1283   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1284   // any earlier variable location.
1285   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1286   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1287   DAG.AddDbgValue(SDV, nullptr, false);
1288 
1289   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1290                     << "\n");
1291   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1292                     << "\n");
1293 }
1294 
1295 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1296                                            DIExpression *Expr, DebugLoc dl,
1297                                            DebugLoc InstDL, unsigned Order) {
1298   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1299   SDDbgValue *SDV;
1300   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1301       isa<ConstantPointerNull>(V)) {
1302     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1303     DAG.AddDbgValue(SDV, nullptr, false);
1304     return true;
1305   }
1306 
1307   // If the Value is a frame index, we can create a FrameIndex debug value
1308   // without relying on the DAG at all.
1309   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1310     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1311     if (SI != FuncInfo.StaticAllocaMap.end()) {
1312       auto SDV =
1313           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1314                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1315       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1316       // is still available even if the SDNode gets optimized out.
1317       DAG.AddDbgValue(SDV, nullptr, false);
1318       return true;
1319     }
1320   }
1321 
1322   // Do not use getValue() in here; we don't want to generate code at
1323   // this point if it hasn't been done yet.
1324   SDValue N = NodeMap[V];
1325   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1326     N = UnusedArgNodeMap[V];
1327   if (N.getNode()) {
1328     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1329       return true;
1330     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1331     DAG.AddDbgValue(SDV, N.getNode(), false);
1332     return true;
1333   }
1334 
1335   // Special rules apply for the first dbg.values of parameter variables in a
1336   // function. Identify them by the fact they reference Argument Values, that
1337   // they're parameters, and they are parameters of the current function. We
1338   // need to let them dangle until they get an SDNode.
1339   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1340                        !InstDL.getInlinedAt();
1341   if (!IsParamOfFunc) {
1342     // The value is not used in this block yet (or it would have an SDNode).
1343     // We still want the value to appear for the user if possible -- if it has
1344     // an associated VReg, we can refer to that instead.
1345     auto VMI = FuncInfo.ValueMap.find(V);
1346     if (VMI != FuncInfo.ValueMap.end()) {
1347       unsigned Reg = VMI->second;
1348       // If this is a PHI node, it may be split up into several MI PHI nodes
1349       // (in FunctionLoweringInfo::set).
1350       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1351                        V->getType(), None);
1352       if (RFV.occupiesMultipleRegs()) {
1353         unsigned Offset = 0;
1354         unsigned BitsToDescribe = 0;
1355         if (auto VarSize = Var->getSizeInBits())
1356           BitsToDescribe = *VarSize;
1357         if (auto Fragment = Expr->getFragmentInfo())
1358           BitsToDescribe = Fragment->SizeInBits;
1359         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1360           unsigned RegisterSize = RegAndSize.second;
1361           // Bail out if all bits are described already.
1362           if (Offset >= BitsToDescribe)
1363             break;
1364           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1365               ? BitsToDescribe - Offset
1366               : RegisterSize;
1367           auto FragmentExpr = DIExpression::createFragmentExpression(
1368               Expr, Offset, FragmentSize);
1369           if (!FragmentExpr)
1370               continue;
1371           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1372                                     false, dl, SDNodeOrder);
1373           DAG.AddDbgValue(SDV, nullptr, false);
1374           Offset += RegisterSize;
1375         }
1376       } else {
1377         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1378         DAG.AddDbgValue(SDV, nullptr, false);
1379       }
1380       return true;
1381     }
1382   }
1383 
1384   return false;
1385 }
1386 
1387 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1388   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1389   for (auto &Pair : DanglingDebugInfoMap)
1390     for (auto &DDI : Pair.second)
1391       salvageUnresolvedDbgValue(DDI);
1392   clearDanglingDebugInfo();
1393 }
1394 
1395 /// getCopyFromRegs - If there was virtual register allocated for the value V
1396 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1397 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1398   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1399   SDValue Result;
1400 
1401   if (It != FuncInfo.ValueMap.end()) {
1402     unsigned InReg = It->second;
1403 
1404     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1405                      DAG.getDataLayout(), InReg, Ty,
1406                      None); // This is not an ABI copy.
1407     SDValue Chain = DAG.getEntryNode();
1408     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1409                                  V);
1410     resolveDanglingDebugInfo(V, Result);
1411   }
1412 
1413   return Result;
1414 }
1415 
1416 /// getValue - Return an SDValue for the given Value.
1417 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1418   // If we already have an SDValue for this value, use it. It's important
1419   // to do this first, so that we don't create a CopyFromReg if we already
1420   // have a regular SDValue.
1421   SDValue &N = NodeMap[V];
1422   if (N.getNode()) return N;
1423 
1424   // If there's a virtual register allocated and initialized for this
1425   // value, use it.
1426   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1427     return copyFromReg;
1428 
1429   // Otherwise create a new SDValue and remember it.
1430   SDValue Val = getValueImpl(V);
1431   NodeMap[V] = Val;
1432   resolveDanglingDebugInfo(V, Val);
1433   return Val;
1434 }
1435 
1436 // Return true if SDValue exists for the given Value
1437 bool SelectionDAGBuilder::findValue(const Value *V) const {
1438   return (NodeMap.find(V) != NodeMap.end()) ||
1439     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1440 }
1441 
1442 /// getNonRegisterValue - Return an SDValue for the given Value, but
1443 /// don't look in FuncInfo.ValueMap for a virtual register.
1444 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1445   // If we already have an SDValue for this value, use it.
1446   SDValue &N = NodeMap[V];
1447   if (N.getNode()) {
1448     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1449       // Remove the debug location from the node as the node is about to be used
1450       // in a location which may differ from the original debug location.  This
1451       // is relevant to Constant and ConstantFP nodes because they can appear
1452       // as constant expressions inside PHI nodes.
1453       N->setDebugLoc(DebugLoc());
1454     }
1455     return N;
1456   }
1457 
1458   // Otherwise create a new SDValue and remember it.
1459   SDValue Val = getValueImpl(V);
1460   NodeMap[V] = Val;
1461   resolveDanglingDebugInfo(V, Val);
1462   return Val;
1463 }
1464 
1465 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1466 /// Create an SDValue for the given value.
1467 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1468   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1469 
1470   if (const Constant *C = dyn_cast<Constant>(V)) {
1471     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1472 
1473     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1474       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1475 
1476     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1477       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1478 
1479     if (isa<ConstantPointerNull>(C)) {
1480       unsigned AS = V->getType()->getPointerAddressSpace();
1481       return DAG.getConstant(0, getCurSDLoc(),
1482                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1483     }
1484 
1485     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1486       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1487 
1488     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1489       return DAG.getUNDEF(VT);
1490 
1491     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1492       visit(CE->getOpcode(), *CE);
1493       SDValue N1 = NodeMap[V];
1494       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1495       return N1;
1496     }
1497 
1498     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1499       SmallVector<SDValue, 4> Constants;
1500       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1501            OI != OE; ++OI) {
1502         SDNode *Val = getValue(*OI).getNode();
1503         // If the operand is an empty aggregate, there are no values.
1504         if (!Val) continue;
1505         // Add each leaf value from the operand to the Constants list
1506         // to form a flattened list of all the values.
1507         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1508           Constants.push_back(SDValue(Val, i));
1509       }
1510 
1511       return DAG.getMergeValues(Constants, getCurSDLoc());
1512     }
1513 
1514     if (const ConstantDataSequential *CDS =
1515           dyn_cast<ConstantDataSequential>(C)) {
1516       SmallVector<SDValue, 4> Ops;
1517       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1518         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1519         // Add each leaf value from the operand to the Constants list
1520         // to form a flattened list of all the values.
1521         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1522           Ops.push_back(SDValue(Val, i));
1523       }
1524 
1525       if (isa<ArrayType>(CDS->getType()))
1526         return DAG.getMergeValues(Ops, getCurSDLoc());
1527       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1528     }
1529 
1530     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1531       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1532              "Unknown struct or array constant!");
1533 
1534       SmallVector<EVT, 4> ValueVTs;
1535       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1536       unsigned NumElts = ValueVTs.size();
1537       if (NumElts == 0)
1538         return SDValue(); // empty struct
1539       SmallVector<SDValue, 4> Constants(NumElts);
1540       for (unsigned i = 0; i != NumElts; ++i) {
1541         EVT EltVT = ValueVTs[i];
1542         if (isa<UndefValue>(C))
1543           Constants[i] = DAG.getUNDEF(EltVT);
1544         else if (EltVT.isFloatingPoint())
1545           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1546         else
1547           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1548       }
1549 
1550       return DAG.getMergeValues(Constants, getCurSDLoc());
1551     }
1552 
1553     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1554       return DAG.getBlockAddress(BA, VT);
1555 
1556     VectorType *VecTy = cast<VectorType>(V->getType());
1557     unsigned NumElements = VecTy->getNumElements();
1558 
1559     // Now that we know the number and type of the elements, get that number of
1560     // elements into the Ops array based on what kind of constant it is.
1561     SmallVector<SDValue, 16> Ops;
1562     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1563       for (unsigned i = 0; i != NumElements; ++i)
1564         Ops.push_back(getValue(CV->getOperand(i)));
1565     } else {
1566       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1567       EVT EltVT =
1568           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1569 
1570       SDValue Op;
1571       if (EltVT.isFloatingPoint())
1572         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1573       else
1574         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1575       Ops.assign(NumElements, Op);
1576     }
1577 
1578     // Create a BUILD_VECTOR node.
1579     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1580   }
1581 
1582   // If this is a static alloca, generate it as the frameindex instead of
1583   // computation.
1584   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1585     DenseMap<const AllocaInst*, int>::iterator SI =
1586       FuncInfo.StaticAllocaMap.find(AI);
1587     if (SI != FuncInfo.StaticAllocaMap.end())
1588       return DAG.getFrameIndex(SI->second,
1589                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1590   }
1591 
1592   // If this is an instruction which fast-isel has deferred, select it now.
1593   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1594     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1595 
1596     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1597                      Inst->getType(), getABIRegCopyCC(V));
1598     SDValue Chain = DAG.getEntryNode();
1599     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1600   }
1601 
1602   llvm_unreachable("Can't get register for value!");
1603 }
1604 
1605 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1606   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1607   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1608   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1609   bool IsSEH = isAsynchronousEHPersonality(Pers);
1610   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1611   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1612   if (!IsSEH)
1613     CatchPadMBB->setIsEHScopeEntry();
1614   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1615   if (IsMSVCCXX || IsCoreCLR)
1616     CatchPadMBB->setIsEHFuncletEntry();
1617   // Wasm does not need catchpads anymore
1618   if (!IsWasmCXX)
1619     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1620                             getControlRoot()));
1621 }
1622 
1623 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1624   // Update machine-CFG edge.
1625   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1626   FuncInfo.MBB->addSuccessor(TargetMBB);
1627 
1628   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1629   bool IsSEH = isAsynchronousEHPersonality(Pers);
1630   if (IsSEH) {
1631     // If this is not a fall-through branch or optimizations are switched off,
1632     // emit the branch.
1633     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1634         TM.getOptLevel() == CodeGenOpt::None)
1635       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1636                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1637     return;
1638   }
1639 
1640   // Figure out the funclet membership for the catchret's successor.
1641   // This will be used by the FuncletLayout pass to determine how to order the
1642   // BB's.
1643   // A 'catchret' returns to the outer scope's color.
1644   Value *ParentPad = I.getCatchSwitchParentPad();
1645   const BasicBlock *SuccessorColor;
1646   if (isa<ConstantTokenNone>(ParentPad))
1647     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1648   else
1649     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1650   assert(SuccessorColor && "No parent funclet for catchret!");
1651   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1652   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1653 
1654   // Create the terminator node.
1655   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1656                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1657                             DAG.getBasicBlock(SuccessorColorMBB));
1658   DAG.setRoot(Ret);
1659 }
1660 
1661 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1662   // Don't emit any special code for the cleanuppad instruction. It just marks
1663   // the start of an EH scope/funclet.
1664   FuncInfo.MBB->setIsEHScopeEntry();
1665   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1666   if (Pers != EHPersonality::Wasm_CXX) {
1667     FuncInfo.MBB->setIsEHFuncletEntry();
1668     FuncInfo.MBB->setIsCleanupFuncletEntry();
1669   }
1670 }
1671 
1672 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1673 // the control flow always stops at the single catch pad, as it does for a
1674 // cleanup pad. In case the exception caught is not of the types the catch pad
1675 // catches, it will be rethrown by a rethrow.
1676 static void findWasmUnwindDestinations(
1677     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1678     BranchProbability Prob,
1679     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1680         &UnwindDests) {
1681   while (EHPadBB) {
1682     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1683     if (isa<CleanupPadInst>(Pad)) {
1684       // Stop on cleanup pads.
1685       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1686       UnwindDests.back().first->setIsEHScopeEntry();
1687       break;
1688     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1689       // Add the catchpad handlers to the possible destinations. We don't
1690       // continue to the unwind destination of the catchswitch for wasm.
1691       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1692         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1693         UnwindDests.back().first->setIsEHScopeEntry();
1694       }
1695       break;
1696     } else {
1697       continue;
1698     }
1699   }
1700 }
1701 
1702 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1703 /// many places it could ultimately go. In the IR, we have a single unwind
1704 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1705 /// This function skips over imaginary basic blocks that hold catchswitch
1706 /// instructions, and finds all the "real" machine
1707 /// basic block destinations. As those destinations may not be successors of
1708 /// EHPadBB, here we also calculate the edge probability to those destinations.
1709 /// The passed-in Prob is the edge probability to EHPadBB.
1710 static void findUnwindDestinations(
1711     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1712     BranchProbability Prob,
1713     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1714         &UnwindDests) {
1715   EHPersonality Personality =
1716     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1717   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1718   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1719   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1720   bool IsSEH = isAsynchronousEHPersonality(Personality);
1721 
1722   if (IsWasmCXX) {
1723     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1724     assert(UnwindDests.size() <= 1 &&
1725            "There should be at most one unwind destination for wasm");
1726     return;
1727   }
1728 
1729   while (EHPadBB) {
1730     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1731     BasicBlock *NewEHPadBB = nullptr;
1732     if (isa<LandingPadInst>(Pad)) {
1733       // Stop on landingpads. They are not funclets.
1734       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1735       break;
1736     } else if (isa<CleanupPadInst>(Pad)) {
1737       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1738       // personalities.
1739       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1740       UnwindDests.back().first->setIsEHScopeEntry();
1741       UnwindDests.back().first->setIsEHFuncletEntry();
1742       break;
1743     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1744       // Add the catchpad handlers to the possible destinations.
1745       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1746         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1747         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1748         if (IsMSVCCXX || IsCoreCLR)
1749           UnwindDests.back().first->setIsEHFuncletEntry();
1750         if (!IsSEH)
1751           UnwindDests.back().first->setIsEHScopeEntry();
1752       }
1753       NewEHPadBB = CatchSwitch->getUnwindDest();
1754     } else {
1755       continue;
1756     }
1757 
1758     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1759     if (BPI && NewEHPadBB)
1760       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1761     EHPadBB = NewEHPadBB;
1762   }
1763 }
1764 
1765 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1766   // Update successor info.
1767   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1768   auto UnwindDest = I.getUnwindDest();
1769   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1770   BranchProbability UnwindDestProb =
1771       (BPI && UnwindDest)
1772           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1773           : BranchProbability::getZero();
1774   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1775   for (auto &UnwindDest : UnwindDests) {
1776     UnwindDest.first->setIsEHPad();
1777     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1778   }
1779   FuncInfo.MBB->normalizeSuccProbs();
1780 
1781   // Create the terminator node.
1782   SDValue Ret =
1783       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1784   DAG.setRoot(Ret);
1785 }
1786 
1787 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1788   report_fatal_error("visitCatchSwitch not yet implemented!");
1789 }
1790 
1791 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1792   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1793   auto &DL = DAG.getDataLayout();
1794   SDValue Chain = getControlRoot();
1795   SmallVector<ISD::OutputArg, 8> Outs;
1796   SmallVector<SDValue, 8> OutVals;
1797 
1798   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1799   // lower
1800   //
1801   //   %val = call <ty> @llvm.experimental.deoptimize()
1802   //   ret <ty> %val
1803   //
1804   // differently.
1805   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1806     LowerDeoptimizingReturn();
1807     return;
1808   }
1809 
1810   if (!FuncInfo.CanLowerReturn) {
1811     unsigned DemoteReg = FuncInfo.DemoteRegister;
1812     const Function *F = I.getParent()->getParent();
1813 
1814     // Emit a store of the return value through the virtual register.
1815     // Leave Outs empty so that LowerReturn won't try to load return
1816     // registers the usual way.
1817     SmallVector<EVT, 1> PtrValueVTs;
1818     ComputeValueVTs(TLI, DL,
1819                     F->getReturnType()->getPointerTo(
1820                         DAG.getDataLayout().getAllocaAddrSpace()),
1821                     PtrValueVTs);
1822 
1823     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1824                                         DemoteReg, PtrValueVTs[0]);
1825     SDValue RetOp = getValue(I.getOperand(0));
1826 
1827     SmallVector<EVT, 4> ValueVTs, MemVTs;
1828     SmallVector<uint64_t, 4> Offsets;
1829     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1830                     &Offsets);
1831     unsigned NumValues = ValueVTs.size();
1832 
1833     SmallVector<SDValue, 4> Chains(NumValues);
1834     for (unsigned i = 0; i != NumValues; ++i) {
1835       // An aggregate return value cannot wrap around the address space, so
1836       // offsets to its parts don't wrap either.
1837       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1838 
1839       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1840       if (MemVTs[i] != ValueVTs[i])
1841         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1842       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1843           // FIXME: better loc info would be nice.
1844           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1845     }
1846 
1847     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1848                         MVT::Other, Chains);
1849   } else if (I.getNumOperands() != 0) {
1850     SmallVector<EVT, 4> ValueVTs;
1851     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1852     unsigned NumValues = ValueVTs.size();
1853     if (NumValues) {
1854       SDValue RetOp = getValue(I.getOperand(0));
1855 
1856       const Function *F = I.getParent()->getParent();
1857 
1858       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1859           I.getOperand(0)->getType(), F->getCallingConv(),
1860           /*IsVarArg*/ false);
1861 
1862       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1863       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1864                                           Attribute::SExt))
1865         ExtendKind = ISD::SIGN_EXTEND;
1866       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1867                                                Attribute::ZExt))
1868         ExtendKind = ISD::ZERO_EXTEND;
1869 
1870       LLVMContext &Context = F->getContext();
1871       bool RetInReg = F->getAttributes().hasAttribute(
1872           AttributeList::ReturnIndex, Attribute::InReg);
1873 
1874       for (unsigned j = 0; j != NumValues; ++j) {
1875         EVT VT = ValueVTs[j];
1876 
1877         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1878           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1879 
1880         CallingConv::ID CC = F->getCallingConv();
1881 
1882         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1883         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1884         SmallVector<SDValue, 4> Parts(NumParts);
1885         getCopyToParts(DAG, getCurSDLoc(),
1886                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1887                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1888 
1889         // 'inreg' on function refers to return value
1890         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1891         if (RetInReg)
1892           Flags.setInReg();
1893 
1894         if (I.getOperand(0)->getType()->isPointerTy()) {
1895           Flags.setPointer();
1896           Flags.setPointerAddrSpace(
1897               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1898         }
1899 
1900         if (NeedsRegBlock) {
1901           Flags.setInConsecutiveRegs();
1902           if (j == NumValues - 1)
1903             Flags.setInConsecutiveRegsLast();
1904         }
1905 
1906         // Propagate extension type if any
1907         if (ExtendKind == ISD::SIGN_EXTEND)
1908           Flags.setSExt();
1909         else if (ExtendKind == ISD::ZERO_EXTEND)
1910           Flags.setZExt();
1911 
1912         for (unsigned i = 0; i < NumParts; ++i) {
1913           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1914                                         VT, /*isfixed=*/true, 0, 0));
1915           OutVals.push_back(Parts[i]);
1916         }
1917       }
1918     }
1919   }
1920 
1921   // Push in swifterror virtual register as the last element of Outs. This makes
1922   // sure swifterror virtual register will be returned in the swifterror
1923   // physical register.
1924   const Function *F = I.getParent()->getParent();
1925   if (TLI.supportSwiftError() &&
1926       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1927     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1928     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1929     Flags.setSwiftError();
1930     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1931                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1932                                   true /*isfixed*/, 1 /*origidx*/,
1933                                   0 /*partOffs*/));
1934     // Create SDNode for the swifterror virtual register.
1935     OutVals.push_back(
1936         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1937                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1938                         EVT(TLI.getPointerTy(DL))));
1939   }
1940 
1941   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1942   CallingConv::ID CallConv =
1943     DAG.getMachineFunction().getFunction().getCallingConv();
1944   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1945       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1946 
1947   // Verify that the target's LowerReturn behaved as expected.
1948   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1949          "LowerReturn didn't return a valid chain!");
1950 
1951   // Update the DAG with the new chain value resulting from return lowering.
1952   DAG.setRoot(Chain);
1953 }
1954 
1955 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1956 /// created for it, emit nodes to copy the value into the virtual
1957 /// registers.
1958 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1959   // Skip empty types
1960   if (V->getType()->isEmptyTy())
1961     return;
1962 
1963   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1964   if (VMI != FuncInfo.ValueMap.end()) {
1965     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1966     CopyValueToVirtualRegister(V, VMI->second);
1967   }
1968 }
1969 
1970 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1971 /// the current basic block, add it to ValueMap now so that we'll get a
1972 /// CopyTo/FromReg.
1973 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1974   // No need to export constants.
1975   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1976 
1977   // Already exported?
1978   if (FuncInfo.isExportedInst(V)) return;
1979 
1980   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1981   CopyValueToVirtualRegister(V, Reg);
1982 }
1983 
1984 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1985                                                      const BasicBlock *FromBB) {
1986   // The operands of the setcc have to be in this block.  We don't know
1987   // how to export them from some other block.
1988   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1989     // Can export from current BB.
1990     if (VI->getParent() == FromBB)
1991       return true;
1992 
1993     // Is already exported, noop.
1994     return FuncInfo.isExportedInst(V);
1995   }
1996 
1997   // If this is an argument, we can export it if the BB is the entry block or
1998   // if it is already exported.
1999   if (isa<Argument>(V)) {
2000     if (FromBB == &FromBB->getParent()->getEntryBlock())
2001       return true;
2002 
2003     // Otherwise, can only export this if it is already exported.
2004     return FuncInfo.isExportedInst(V);
2005   }
2006 
2007   // Otherwise, constants can always be exported.
2008   return true;
2009 }
2010 
2011 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2012 BranchProbability
2013 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2014                                         const MachineBasicBlock *Dst) const {
2015   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2016   const BasicBlock *SrcBB = Src->getBasicBlock();
2017   const BasicBlock *DstBB = Dst->getBasicBlock();
2018   if (!BPI) {
2019     // If BPI is not available, set the default probability as 1 / N, where N is
2020     // the number of successors.
2021     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2022     return BranchProbability(1, SuccSize);
2023   }
2024   return BPI->getEdgeProbability(SrcBB, DstBB);
2025 }
2026 
2027 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2028                                                MachineBasicBlock *Dst,
2029                                                BranchProbability Prob) {
2030   if (!FuncInfo.BPI)
2031     Src->addSuccessorWithoutProb(Dst);
2032   else {
2033     if (Prob.isUnknown())
2034       Prob = getEdgeProbability(Src, Dst);
2035     Src->addSuccessor(Dst, Prob);
2036   }
2037 }
2038 
2039 static bool InBlock(const Value *V, const BasicBlock *BB) {
2040   if (const Instruction *I = dyn_cast<Instruction>(V))
2041     return I->getParent() == BB;
2042   return true;
2043 }
2044 
2045 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2046 /// This function emits a branch and is used at the leaves of an OR or an
2047 /// AND operator tree.
2048 void
2049 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2050                                                   MachineBasicBlock *TBB,
2051                                                   MachineBasicBlock *FBB,
2052                                                   MachineBasicBlock *CurBB,
2053                                                   MachineBasicBlock *SwitchBB,
2054                                                   BranchProbability TProb,
2055                                                   BranchProbability FProb,
2056                                                   bool InvertCond) {
2057   const BasicBlock *BB = CurBB->getBasicBlock();
2058 
2059   // If the leaf of the tree is a comparison, merge the condition into
2060   // the caseblock.
2061   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2062     // The operands of the cmp have to be in this block.  We don't know
2063     // how to export them from some other block.  If this is the first block
2064     // of the sequence, no exporting is needed.
2065     if (CurBB == SwitchBB ||
2066         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2067          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2068       ISD::CondCode Condition;
2069       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2070         ICmpInst::Predicate Pred =
2071             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2072         Condition = getICmpCondCode(Pred);
2073       } else {
2074         const FCmpInst *FC = cast<FCmpInst>(Cond);
2075         FCmpInst::Predicate Pred =
2076             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2077         Condition = getFCmpCondCode(Pred);
2078         if (TM.Options.NoNaNsFPMath)
2079           Condition = getFCmpCodeWithoutNaN(Condition);
2080       }
2081 
2082       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2083                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2084       SL->SwitchCases.push_back(CB);
2085       return;
2086     }
2087   }
2088 
2089   // Create a CaseBlock record representing this branch.
2090   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2091   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2092                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2093   SL->SwitchCases.push_back(CB);
2094 }
2095 
2096 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2097                                                MachineBasicBlock *TBB,
2098                                                MachineBasicBlock *FBB,
2099                                                MachineBasicBlock *CurBB,
2100                                                MachineBasicBlock *SwitchBB,
2101                                                Instruction::BinaryOps Opc,
2102                                                BranchProbability TProb,
2103                                                BranchProbability FProb,
2104                                                bool InvertCond) {
2105   // Skip over not part of the tree and remember to invert op and operands at
2106   // next level.
2107   Value *NotCond;
2108   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2109       InBlock(NotCond, CurBB->getBasicBlock())) {
2110     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2111                          !InvertCond);
2112     return;
2113   }
2114 
2115   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2116   // Compute the effective opcode for Cond, taking into account whether it needs
2117   // to be inverted, e.g.
2118   //   and (not (or A, B)), C
2119   // gets lowered as
2120   //   and (and (not A, not B), C)
2121   unsigned BOpc = 0;
2122   if (BOp) {
2123     BOpc = BOp->getOpcode();
2124     if (InvertCond) {
2125       if (BOpc == Instruction::And)
2126         BOpc = Instruction::Or;
2127       else if (BOpc == Instruction::Or)
2128         BOpc = Instruction::And;
2129     }
2130   }
2131 
2132   // If this node is not part of the or/and tree, emit it as a branch.
2133   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2134       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2135       BOp->getParent() != CurBB->getBasicBlock() ||
2136       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2137       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2138     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2139                                  TProb, FProb, InvertCond);
2140     return;
2141   }
2142 
2143   //  Create TmpBB after CurBB.
2144   MachineFunction::iterator BBI(CurBB);
2145   MachineFunction &MF = DAG.getMachineFunction();
2146   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2147   CurBB->getParent()->insert(++BBI, TmpBB);
2148 
2149   if (Opc == Instruction::Or) {
2150     // Codegen X | Y as:
2151     // BB1:
2152     //   jmp_if_X TBB
2153     //   jmp TmpBB
2154     // TmpBB:
2155     //   jmp_if_Y TBB
2156     //   jmp FBB
2157     //
2158 
2159     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2160     // The requirement is that
2161     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2162     //     = TrueProb for original BB.
2163     // Assuming the original probabilities are A and B, one choice is to set
2164     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2165     // A/(1+B) and 2B/(1+B). This choice assumes that
2166     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2167     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2168     // TmpBB, but the math is more complicated.
2169 
2170     auto NewTrueProb = TProb / 2;
2171     auto NewFalseProb = TProb / 2 + FProb;
2172     // Emit the LHS condition.
2173     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2174                          NewTrueProb, NewFalseProb, InvertCond);
2175 
2176     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2177     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2178     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2179     // Emit the RHS condition into TmpBB.
2180     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2181                          Probs[0], Probs[1], InvertCond);
2182   } else {
2183     assert(Opc == Instruction::And && "Unknown merge op!");
2184     // Codegen X & Y as:
2185     // BB1:
2186     //   jmp_if_X TmpBB
2187     //   jmp FBB
2188     // TmpBB:
2189     //   jmp_if_Y TBB
2190     //   jmp FBB
2191     //
2192     //  This requires creation of TmpBB after CurBB.
2193 
2194     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2195     // The requirement is that
2196     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2197     //     = FalseProb for original BB.
2198     // Assuming the original probabilities are A and B, one choice is to set
2199     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2200     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2201     // TrueProb for BB1 * FalseProb for TmpBB.
2202 
2203     auto NewTrueProb = TProb + FProb / 2;
2204     auto NewFalseProb = FProb / 2;
2205     // Emit the LHS condition.
2206     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2207                          NewTrueProb, NewFalseProb, InvertCond);
2208 
2209     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2210     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2211     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2212     // Emit the RHS condition into TmpBB.
2213     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2214                          Probs[0], Probs[1], InvertCond);
2215   }
2216 }
2217 
2218 /// If the set of cases should be emitted as a series of branches, return true.
2219 /// If we should emit this as a bunch of and/or'd together conditions, return
2220 /// false.
2221 bool
2222 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2223   if (Cases.size() != 2) return true;
2224 
2225   // If this is two comparisons of the same values or'd or and'd together, they
2226   // will get folded into a single comparison, so don't emit two blocks.
2227   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2228        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2229       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2230        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2231     return false;
2232   }
2233 
2234   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2235   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2236   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2237       Cases[0].CC == Cases[1].CC &&
2238       isa<Constant>(Cases[0].CmpRHS) &&
2239       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2240     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2241       return false;
2242     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2243       return false;
2244   }
2245 
2246   return true;
2247 }
2248 
2249 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2250   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2251 
2252   // Update machine-CFG edges.
2253   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2254 
2255   if (I.isUnconditional()) {
2256     // Update machine-CFG edges.
2257     BrMBB->addSuccessor(Succ0MBB);
2258 
2259     // If this is not a fall-through branch or optimizations are switched off,
2260     // emit the branch.
2261     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2262       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2263                               MVT::Other, getControlRoot(),
2264                               DAG.getBasicBlock(Succ0MBB)));
2265 
2266     return;
2267   }
2268 
2269   // If this condition is one of the special cases we handle, do special stuff
2270   // now.
2271   const Value *CondVal = I.getCondition();
2272   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2273 
2274   // If this is a series of conditions that are or'd or and'd together, emit
2275   // this as a sequence of branches instead of setcc's with and/or operations.
2276   // As long as jumps are not expensive, this should improve performance.
2277   // For example, instead of something like:
2278   //     cmp A, B
2279   //     C = seteq
2280   //     cmp D, E
2281   //     F = setle
2282   //     or C, F
2283   //     jnz foo
2284   // Emit:
2285   //     cmp A, B
2286   //     je foo
2287   //     cmp D, E
2288   //     jle foo
2289   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2290     Instruction::BinaryOps Opcode = BOp->getOpcode();
2291     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2292         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2293         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2294       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2295                            Opcode,
2296                            getEdgeProbability(BrMBB, Succ0MBB),
2297                            getEdgeProbability(BrMBB, Succ1MBB),
2298                            /*InvertCond=*/false);
2299       // If the compares in later blocks need to use values not currently
2300       // exported from this block, export them now.  This block should always
2301       // be the first entry.
2302       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2303 
2304       // Allow some cases to be rejected.
2305       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2306         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2307           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2308           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2309         }
2310 
2311         // Emit the branch for this block.
2312         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2313         SL->SwitchCases.erase(SL->SwitchCases.begin());
2314         return;
2315       }
2316 
2317       // Okay, we decided not to do this, remove any inserted MBB's and clear
2318       // SwitchCases.
2319       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2320         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2321 
2322       SL->SwitchCases.clear();
2323     }
2324   }
2325 
2326   // Create a CaseBlock record representing this branch.
2327   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2328                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2329 
2330   // Use visitSwitchCase to actually insert the fast branch sequence for this
2331   // cond branch.
2332   visitSwitchCase(CB, BrMBB);
2333 }
2334 
2335 /// visitSwitchCase - Emits the necessary code to represent a single node in
2336 /// the binary search tree resulting from lowering a switch instruction.
2337 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2338                                           MachineBasicBlock *SwitchBB) {
2339   SDValue Cond;
2340   SDValue CondLHS = getValue(CB.CmpLHS);
2341   SDLoc dl = CB.DL;
2342 
2343   if (CB.CC == ISD::SETTRUE) {
2344     // Branch or fall through to TrueBB.
2345     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2346     SwitchBB->normalizeSuccProbs();
2347     if (CB.TrueBB != NextBlock(SwitchBB)) {
2348       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2349                               DAG.getBasicBlock(CB.TrueBB)));
2350     }
2351     return;
2352   }
2353 
2354   auto &TLI = DAG.getTargetLoweringInfo();
2355   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2356 
2357   // Build the setcc now.
2358   if (!CB.CmpMHS) {
2359     // Fold "(X == true)" to X and "(X == false)" to !X to
2360     // handle common cases produced by branch lowering.
2361     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2362         CB.CC == ISD::SETEQ)
2363       Cond = CondLHS;
2364     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2365              CB.CC == ISD::SETEQ) {
2366       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2367       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2368     } else {
2369       SDValue CondRHS = getValue(CB.CmpRHS);
2370 
2371       // If a pointer's DAG type is larger than its memory type then the DAG
2372       // values are zero-extended. This breaks signed comparisons so truncate
2373       // back to the underlying type before doing the compare.
2374       if (CondLHS.getValueType() != MemVT) {
2375         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2376         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2377       }
2378       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2379     }
2380   } else {
2381     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2382 
2383     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2384     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2385 
2386     SDValue CmpOp = getValue(CB.CmpMHS);
2387     EVT VT = CmpOp.getValueType();
2388 
2389     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2390       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2391                           ISD::SETLE);
2392     } else {
2393       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2394                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2395       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2396                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2397     }
2398   }
2399 
2400   // Update successor info
2401   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2402   // TrueBB and FalseBB are always different unless the incoming IR is
2403   // degenerate. This only happens when running llc on weird IR.
2404   if (CB.TrueBB != CB.FalseBB)
2405     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2406   SwitchBB->normalizeSuccProbs();
2407 
2408   // If the lhs block is the next block, invert the condition so that we can
2409   // fall through to the lhs instead of the rhs block.
2410   if (CB.TrueBB == NextBlock(SwitchBB)) {
2411     std::swap(CB.TrueBB, CB.FalseBB);
2412     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2413     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2414   }
2415 
2416   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2417                                MVT::Other, getControlRoot(), Cond,
2418                                DAG.getBasicBlock(CB.TrueBB));
2419 
2420   // Insert the false branch. Do this even if it's a fall through branch,
2421   // this makes it easier to do DAG optimizations which require inverting
2422   // the branch condition.
2423   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2424                        DAG.getBasicBlock(CB.FalseBB));
2425 
2426   DAG.setRoot(BrCond);
2427 }
2428 
2429 /// visitJumpTable - Emit JumpTable node in the current MBB
2430 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2431   // Emit the code for the jump table
2432   assert(JT.Reg != -1U && "Should lower JT Header first!");
2433   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2434   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2435                                      JT.Reg, PTy);
2436   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2437   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2438                                     MVT::Other, Index.getValue(1),
2439                                     Table, Index);
2440   DAG.setRoot(BrJumpTable);
2441 }
2442 
2443 /// visitJumpTableHeader - This function emits necessary code to produce index
2444 /// in the JumpTable from switch case.
2445 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2446                                                JumpTableHeader &JTH,
2447                                                MachineBasicBlock *SwitchBB) {
2448   SDLoc dl = getCurSDLoc();
2449 
2450   // Subtract the lowest switch case value from the value being switched on.
2451   SDValue SwitchOp = getValue(JTH.SValue);
2452   EVT VT = SwitchOp.getValueType();
2453   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2454                             DAG.getConstant(JTH.First, dl, VT));
2455 
2456   // The SDNode we just created, which holds the value being switched on minus
2457   // the smallest case value, needs to be copied to a virtual register so it
2458   // can be used as an index into the jump table in a subsequent basic block.
2459   // This value may be smaller or larger than the target's pointer type, and
2460   // therefore require extension or truncating.
2461   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2462   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2463 
2464   unsigned JumpTableReg =
2465       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2466   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2467                                     JumpTableReg, SwitchOp);
2468   JT.Reg = JumpTableReg;
2469 
2470   if (!JTH.OmitRangeCheck) {
2471     // Emit the range check for the jump table, and branch to the default block
2472     // for the switch statement if the value being switched on exceeds the
2473     // largest case in the switch.
2474     SDValue CMP = DAG.getSetCC(
2475         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2476                                    Sub.getValueType()),
2477         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2478 
2479     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2480                                  MVT::Other, CopyTo, CMP,
2481                                  DAG.getBasicBlock(JT.Default));
2482 
2483     // Avoid emitting unnecessary branches to the next block.
2484     if (JT.MBB != NextBlock(SwitchBB))
2485       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2486                            DAG.getBasicBlock(JT.MBB));
2487 
2488     DAG.setRoot(BrCond);
2489   } else {
2490     // Avoid emitting unnecessary branches to the next block.
2491     if (JT.MBB != NextBlock(SwitchBB))
2492       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2493                               DAG.getBasicBlock(JT.MBB)));
2494     else
2495       DAG.setRoot(CopyTo);
2496   }
2497 }
2498 
2499 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2500 /// variable if there exists one.
2501 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2502                                  SDValue &Chain) {
2503   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2504   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2505   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2506   MachineFunction &MF = DAG.getMachineFunction();
2507   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2508   MachineSDNode *Node =
2509       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2510   if (Global) {
2511     MachinePointerInfo MPInfo(Global);
2512     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2513                  MachineMemOperand::MODereferenceable;
2514     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2515         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2516     DAG.setNodeMemRefs(Node, {MemRef});
2517   }
2518   if (PtrTy != PtrMemTy)
2519     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2520   return SDValue(Node, 0);
2521 }
2522 
2523 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2524 /// tail spliced into a stack protector check success bb.
2525 ///
2526 /// For a high level explanation of how this fits into the stack protector
2527 /// generation see the comment on the declaration of class
2528 /// StackProtectorDescriptor.
2529 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2530                                                   MachineBasicBlock *ParentBB) {
2531 
2532   // First create the loads to the guard/stack slot for the comparison.
2533   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2534   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2535   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2536 
2537   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2538   int FI = MFI.getStackProtectorIndex();
2539 
2540   SDValue Guard;
2541   SDLoc dl = getCurSDLoc();
2542   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2543   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2544   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2545 
2546   // Generate code to load the content of the guard slot.
2547   SDValue GuardVal = DAG.getLoad(
2548       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2549       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2550       MachineMemOperand::MOVolatile);
2551 
2552   if (TLI.useStackGuardXorFP())
2553     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2554 
2555   // Retrieve guard check function, nullptr if instrumentation is inlined.
2556   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2557     // The target provides a guard check function to validate the guard value.
2558     // Generate a call to that function with the content of the guard slot as
2559     // argument.
2560     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2561     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2562 
2563     TargetLowering::ArgListTy Args;
2564     TargetLowering::ArgListEntry Entry;
2565     Entry.Node = GuardVal;
2566     Entry.Ty = FnTy->getParamType(0);
2567     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2568       Entry.IsInReg = true;
2569     Args.push_back(Entry);
2570 
2571     TargetLowering::CallLoweringInfo CLI(DAG);
2572     CLI.setDebugLoc(getCurSDLoc())
2573         .setChain(DAG.getEntryNode())
2574         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2575                    getValue(GuardCheckFn), std::move(Args));
2576 
2577     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2578     DAG.setRoot(Result.second);
2579     return;
2580   }
2581 
2582   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2583   // Otherwise, emit a volatile load to retrieve the stack guard value.
2584   SDValue Chain = DAG.getEntryNode();
2585   if (TLI.useLoadStackGuardNode()) {
2586     Guard = getLoadStackGuard(DAG, dl, Chain);
2587   } else {
2588     const Value *IRGuard = TLI.getSDagStackGuard(M);
2589     SDValue GuardPtr = getValue(IRGuard);
2590 
2591     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2592                         MachinePointerInfo(IRGuard, 0), Align,
2593                         MachineMemOperand::MOVolatile);
2594   }
2595 
2596   // Perform the comparison via a subtract/getsetcc.
2597   EVT VT = Guard.getValueType();
2598   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2599 
2600   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2601                                                         *DAG.getContext(),
2602                                                         Sub.getValueType()),
2603                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2604 
2605   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2606   // branch to failure MBB.
2607   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2608                                MVT::Other, GuardVal.getOperand(0),
2609                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2610   // Otherwise branch to success MBB.
2611   SDValue Br = DAG.getNode(ISD::BR, dl,
2612                            MVT::Other, BrCond,
2613                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2614 
2615   DAG.setRoot(Br);
2616 }
2617 
2618 /// Codegen the failure basic block for a stack protector check.
2619 ///
2620 /// A failure stack protector machine basic block consists simply of a call to
2621 /// __stack_chk_fail().
2622 ///
2623 /// For a high level explanation of how this fits into the stack protector
2624 /// generation see the comment on the declaration of class
2625 /// StackProtectorDescriptor.
2626 void
2627 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2628   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2629   TargetLowering::MakeLibCallOptions CallOptions;
2630   CallOptions.setDiscardResult(true);
2631   SDValue Chain =
2632       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2633                       None, CallOptions, getCurSDLoc()).second;
2634   // On PS4, the "return address" must still be within the calling function,
2635   // even if it's at the very end, so emit an explicit TRAP here.
2636   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2637   if (TM.getTargetTriple().isPS4CPU())
2638     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2639 
2640   DAG.setRoot(Chain);
2641 }
2642 
2643 /// visitBitTestHeader - This function emits necessary code to produce value
2644 /// suitable for "bit tests"
2645 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2646                                              MachineBasicBlock *SwitchBB) {
2647   SDLoc dl = getCurSDLoc();
2648 
2649   // Subtract the minimum value.
2650   SDValue SwitchOp = getValue(B.SValue);
2651   EVT VT = SwitchOp.getValueType();
2652   SDValue RangeSub =
2653       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2654 
2655   // Determine the type of the test operands.
2656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2657   bool UsePtrType = false;
2658   if (!TLI.isTypeLegal(VT)) {
2659     UsePtrType = true;
2660   } else {
2661     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2662       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2663         // Switch table case range are encoded into series of masks.
2664         // Just use pointer type, it's guaranteed to fit.
2665         UsePtrType = true;
2666         break;
2667       }
2668   }
2669   SDValue Sub = RangeSub;
2670   if (UsePtrType) {
2671     VT = TLI.getPointerTy(DAG.getDataLayout());
2672     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2673   }
2674 
2675   B.RegVT = VT.getSimpleVT();
2676   B.Reg = FuncInfo.CreateReg(B.RegVT);
2677   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2678 
2679   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2680 
2681   if (!B.OmitRangeCheck)
2682     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2683   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2684   SwitchBB->normalizeSuccProbs();
2685 
2686   SDValue Root = CopyTo;
2687   if (!B.OmitRangeCheck) {
2688     // Conditional branch to the default block.
2689     SDValue RangeCmp = DAG.getSetCC(dl,
2690         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2691                                RangeSub.getValueType()),
2692         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2693         ISD::SETUGT);
2694 
2695     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2696                        DAG.getBasicBlock(B.Default));
2697   }
2698 
2699   // Avoid emitting unnecessary branches to the next block.
2700   if (MBB != NextBlock(SwitchBB))
2701     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2702 
2703   DAG.setRoot(Root);
2704 }
2705 
2706 /// visitBitTestCase - this function produces one "bit test"
2707 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2708                                            MachineBasicBlock* NextMBB,
2709                                            BranchProbability BranchProbToNext,
2710                                            unsigned Reg,
2711                                            BitTestCase &B,
2712                                            MachineBasicBlock *SwitchBB) {
2713   SDLoc dl = getCurSDLoc();
2714   MVT VT = BB.RegVT;
2715   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2716   SDValue Cmp;
2717   unsigned PopCount = countPopulation(B.Mask);
2718   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2719   if (PopCount == 1) {
2720     // Testing for a single bit; just compare the shift count with what it
2721     // would need to be to shift a 1 bit in that position.
2722     Cmp = DAG.getSetCC(
2723         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2724         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2725         ISD::SETEQ);
2726   } else if (PopCount == BB.Range) {
2727     // There is only one zero bit in the range, test for it directly.
2728     Cmp = DAG.getSetCC(
2729         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2730         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2731         ISD::SETNE);
2732   } else {
2733     // Make desired shift
2734     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2735                                     DAG.getConstant(1, dl, VT), ShiftOp);
2736 
2737     // Emit bit tests and jumps
2738     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2739                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2740     Cmp = DAG.getSetCC(
2741         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2742         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2743   }
2744 
2745   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2746   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2747   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2748   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2749   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2750   // one as they are relative probabilities (and thus work more like weights),
2751   // and hence we need to normalize them to let the sum of them become one.
2752   SwitchBB->normalizeSuccProbs();
2753 
2754   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2755                               MVT::Other, getControlRoot(),
2756                               Cmp, DAG.getBasicBlock(B.TargetBB));
2757 
2758   // Avoid emitting unnecessary branches to the next block.
2759   if (NextMBB != NextBlock(SwitchBB))
2760     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2761                         DAG.getBasicBlock(NextMBB));
2762 
2763   DAG.setRoot(BrAnd);
2764 }
2765 
2766 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2767   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2768 
2769   // Retrieve successors. Look through artificial IR level blocks like
2770   // catchswitch for successors.
2771   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2772   const BasicBlock *EHPadBB = I.getSuccessor(1);
2773 
2774   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2775   // have to do anything here to lower funclet bundles.
2776   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2777                                         LLVMContext::OB_funclet,
2778                                         LLVMContext::OB_cfguardtarget}) &&
2779          "Cannot lower invokes with arbitrary operand bundles yet!");
2780 
2781   const Value *Callee(I.getCalledValue());
2782   const Function *Fn = dyn_cast<Function>(Callee);
2783   if (isa<InlineAsm>(Callee))
2784     visitInlineAsm(&I);
2785   else if (Fn && Fn->isIntrinsic()) {
2786     switch (Fn->getIntrinsicID()) {
2787     default:
2788       llvm_unreachable("Cannot invoke this intrinsic");
2789     case Intrinsic::donothing:
2790       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2791       break;
2792     case Intrinsic::experimental_patchpoint_void:
2793     case Intrinsic::experimental_patchpoint_i64:
2794       visitPatchpoint(&I, EHPadBB);
2795       break;
2796     case Intrinsic::experimental_gc_statepoint:
2797       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2798       break;
2799     case Intrinsic::wasm_rethrow_in_catch: {
2800       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2801       // special because it can be invoked, so we manually lower it to a DAG
2802       // node here.
2803       SmallVector<SDValue, 8> Ops;
2804       Ops.push_back(getRoot()); // inchain
2805       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2806       Ops.push_back(
2807           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2808                                 TLI.getPointerTy(DAG.getDataLayout())));
2809       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2810       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2811       break;
2812     }
2813     }
2814   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2815     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2816     // Eventually we will support lowering the @llvm.experimental.deoptimize
2817     // intrinsic, and right now there are no plans to support other intrinsics
2818     // with deopt state.
2819     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2820   } else {
2821     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2822   }
2823 
2824   // If the value of the invoke is used outside of its defining block, make it
2825   // available as a virtual register.
2826   // We already took care of the exported value for the statepoint instruction
2827   // during call to the LowerStatepoint.
2828   if (!isStatepoint(I)) {
2829     CopyToExportRegsIfNeeded(&I);
2830   }
2831 
2832   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2833   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2834   BranchProbability EHPadBBProb =
2835       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2836           : BranchProbability::getZero();
2837   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2838 
2839   // Update successor info.
2840   addSuccessorWithProb(InvokeMBB, Return);
2841   for (auto &UnwindDest : UnwindDests) {
2842     UnwindDest.first->setIsEHPad();
2843     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2844   }
2845   InvokeMBB->normalizeSuccProbs();
2846 
2847   // Drop into normal successor.
2848   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2849                           DAG.getBasicBlock(Return)));
2850 }
2851 
2852 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2853   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
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_funclet}) &&
2859          "Cannot lower callbrs with arbitrary operand bundles yet!");
2860 
2861   assert(isa<InlineAsm>(I.getCalledValue()) &&
2862          "Only know how to handle inlineasm callbr");
2863   visitInlineAsm(&I);
2864 
2865   // Retrieve successors.
2866   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2867 
2868   // Update successor info.
2869   addSuccessorWithProb(CallBrMBB, Return);
2870   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2871     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2872     addSuccessorWithProb(CallBrMBB, Target);
2873   }
2874   CallBrMBB->normalizeSuccProbs();
2875 
2876   // Drop into default successor.
2877   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2878                           MVT::Other, getControlRoot(),
2879                           DAG.getBasicBlock(Return)));
2880 }
2881 
2882 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2883   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2884 }
2885 
2886 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2887   assert(FuncInfo.MBB->isEHPad() &&
2888          "Call to landingpad not in landing pad!");
2889 
2890   // If there aren't registers to copy the values into (e.g., during SjLj
2891   // exceptions), then don't bother to create these DAG nodes.
2892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2893   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2894   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2895       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2896     return;
2897 
2898   // If landingpad's return type is token type, we don't create DAG nodes
2899   // for its exception pointer and selector value. The extraction of exception
2900   // pointer or selector value from token type landingpads is not currently
2901   // supported.
2902   if (LP.getType()->isTokenTy())
2903     return;
2904 
2905   SmallVector<EVT, 2> ValueVTs;
2906   SDLoc dl = getCurSDLoc();
2907   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2908   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2909 
2910   // Get the two live-in registers as SDValues. The physregs have already been
2911   // copied into virtual registers.
2912   SDValue Ops[2];
2913   if (FuncInfo.ExceptionPointerVirtReg) {
2914     Ops[0] = DAG.getZExtOrTrunc(
2915         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2916                            FuncInfo.ExceptionPointerVirtReg,
2917                            TLI.getPointerTy(DAG.getDataLayout())),
2918         dl, ValueVTs[0]);
2919   } else {
2920     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2921   }
2922   Ops[1] = DAG.getZExtOrTrunc(
2923       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2924                          FuncInfo.ExceptionSelectorVirtReg,
2925                          TLI.getPointerTy(DAG.getDataLayout())),
2926       dl, ValueVTs[1]);
2927 
2928   // Merge into one.
2929   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2930                             DAG.getVTList(ValueVTs), Ops);
2931   setValue(&LP, Res);
2932 }
2933 
2934 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2935                                            MachineBasicBlock *Last) {
2936   // Update JTCases.
2937   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2938     if (SL->JTCases[i].first.HeaderBB == First)
2939       SL->JTCases[i].first.HeaderBB = Last;
2940 
2941   // Update BitTestCases.
2942   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2943     if (SL->BitTestCases[i].Parent == First)
2944       SL->BitTestCases[i].Parent = Last;
2945 }
2946 
2947 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2948   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2949 
2950   // Update machine-CFG edges with unique successors.
2951   SmallSet<BasicBlock*, 32> Done;
2952   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2953     BasicBlock *BB = I.getSuccessor(i);
2954     bool Inserted = Done.insert(BB).second;
2955     if (!Inserted)
2956         continue;
2957 
2958     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2959     addSuccessorWithProb(IndirectBrMBB, Succ);
2960   }
2961   IndirectBrMBB->normalizeSuccProbs();
2962 
2963   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2964                           MVT::Other, getControlRoot(),
2965                           getValue(I.getAddress())));
2966 }
2967 
2968 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2969   if (!DAG.getTarget().Options.TrapUnreachable)
2970     return;
2971 
2972   // We may be able to ignore unreachable behind a noreturn call.
2973   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2974     const BasicBlock &BB = *I.getParent();
2975     if (&I != &BB.front()) {
2976       BasicBlock::const_iterator PredI =
2977         std::prev(BasicBlock::const_iterator(&I));
2978       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2979         if (Call->doesNotReturn())
2980           return;
2981       }
2982     }
2983   }
2984 
2985   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2986 }
2987 
2988 void SelectionDAGBuilder::visitFSub(const User &I) {
2989   // -0.0 - X --> fneg
2990   Type *Ty = I.getType();
2991   if (isa<Constant>(I.getOperand(0)) &&
2992       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2993     SDValue Op2 = getValue(I.getOperand(1));
2994     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2995                              Op2.getValueType(), Op2));
2996     return;
2997   }
2998 
2999   visitBinary(I, ISD::FSUB);
3000 }
3001 
3002 /// Checks if the given instruction performs a vector reduction, in which case
3003 /// we have the freedom to alter the elements in the result as long as the
3004 /// reduction of them stays unchanged.
3005 static bool isVectorReductionOp(const User *I) {
3006   const Instruction *Inst = dyn_cast<Instruction>(I);
3007   if (!Inst || !Inst->getType()->isVectorTy())
3008     return false;
3009 
3010   auto OpCode = Inst->getOpcode();
3011   switch (OpCode) {
3012   case Instruction::Add:
3013   case Instruction::Mul:
3014   case Instruction::And:
3015   case Instruction::Or:
3016   case Instruction::Xor:
3017     break;
3018   case Instruction::FAdd:
3019   case Instruction::FMul:
3020     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3021       if (FPOp->getFastMathFlags().isFast())
3022         break;
3023     LLVM_FALLTHROUGH;
3024   default:
3025     return false;
3026   }
3027 
3028   unsigned ElemNum = Inst->getType()->getVectorNumElements();
3029   // Ensure the reduction size is a power of 2.
3030   if (!isPowerOf2_32(ElemNum))
3031     return false;
3032 
3033   unsigned ElemNumToReduce = ElemNum;
3034 
3035   // Do DFS search on the def-use chain from the given instruction. We only
3036   // allow four kinds of operations during the search until we reach the
3037   // instruction that extracts the first element from the vector:
3038   //
3039   //   1. The reduction operation of the same opcode as the given instruction.
3040   //
3041   //   2. PHI node.
3042   //
3043   //   3. ShuffleVector instruction together with a reduction operation that
3044   //      does a partial reduction.
3045   //
3046   //   4. ExtractElement that extracts the first element from the vector, and we
3047   //      stop searching the def-use chain here.
3048   //
3049   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3050   // from 1-3 to the stack to continue the DFS. The given instruction is not
3051   // a reduction operation if we meet any other instructions other than those
3052   // listed above.
3053 
3054   SmallVector<const User *, 16> UsersToVisit{Inst};
3055   SmallPtrSet<const User *, 16> Visited;
3056   bool ReduxExtracted = false;
3057 
3058   while (!UsersToVisit.empty()) {
3059     auto User = UsersToVisit.back();
3060     UsersToVisit.pop_back();
3061     if (!Visited.insert(User).second)
3062       continue;
3063 
3064     for (const auto *U : User->users()) {
3065       auto Inst = dyn_cast<Instruction>(U);
3066       if (!Inst)
3067         return false;
3068 
3069       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3070         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3071           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3072             return false;
3073         UsersToVisit.push_back(U);
3074       } else if (const ShuffleVectorInst *ShufInst =
3075                      dyn_cast<ShuffleVectorInst>(U)) {
3076         // Detect the following pattern: A ShuffleVector instruction together
3077         // with a reduction that do partial reduction on the first and second
3078         // ElemNumToReduce / 2 elements, and store the result in
3079         // ElemNumToReduce / 2 elements in another vector.
3080 
3081         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3082         if (ResultElements < ElemNum)
3083           return false;
3084 
3085         if (ElemNumToReduce == 1)
3086           return false;
3087         if (!isa<UndefValue>(U->getOperand(1)))
3088           return false;
3089         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3090           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3091             return false;
3092         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3093           if (ShufInst->getMaskValue(i) != -1)
3094             return false;
3095 
3096         // There is only one user of this ShuffleVector instruction, which
3097         // must be a reduction operation.
3098         if (!U->hasOneUse())
3099           return false;
3100 
3101         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3102         if (!U2 || U2->getOpcode() != OpCode)
3103           return false;
3104 
3105         // Check operands of the reduction operation.
3106         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3107             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3108           UsersToVisit.push_back(U2);
3109           ElemNumToReduce /= 2;
3110         } else
3111           return false;
3112       } else if (isa<ExtractElementInst>(U)) {
3113         // At this moment we should have reduced all elements in the vector.
3114         if (ElemNumToReduce != 1)
3115           return false;
3116 
3117         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3118         if (!Val || !Val->isZero())
3119           return false;
3120 
3121         ReduxExtracted = true;
3122       } else
3123         return false;
3124     }
3125   }
3126   return ReduxExtracted;
3127 }
3128 
3129 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3130   SDNodeFlags Flags;
3131 
3132   SDValue Op = getValue(I.getOperand(0));
3133   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3134                                     Op, Flags);
3135   setValue(&I, UnNodeValue);
3136 }
3137 
3138 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3139   SDNodeFlags Flags;
3140   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3141     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3142     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3143   }
3144   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3145     Flags.setExact(ExactOp->isExact());
3146   }
3147   if (isVectorReductionOp(&I)) {
3148     Flags.setVectorReduction(true);
3149     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3150 
3151     // If no flags are set we will propagate the incoming flags, if any flags
3152     // are set, we will intersect them with the incoming flag and so we need to
3153     // copy the FMF flags here.
3154     if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) {
3155       Flags.copyFMF(*FPOp);
3156     }
3157   }
3158 
3159   SDValue Op1 = getValue(I.getOperand(0));
3160   SDValue Op2 = getValue(I.getOperand(1));
3161   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3162                                      Op1, Op2, Flags);
3163   setValue(&I, BinNodeValue);
3164 }
3165 
3166 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3167   SDValue Op1 = getValue(I.getOperand(0));
3168   SDValue Op2 = getValue(I.getOperand(1));
3169 
3170   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3171       Op1.getValueType(), DAG.getDataLayout());
3172 
3173   // Coerce the shift amount to the right type if we can.
3174   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3175     unsigned ShiftSize = ShiftTy.getSizeInBits();
3176     unsigned Op2Size = Op2.getValueSizeInBits();
3177     SDLoc DL = getCurSDLoc();
3178 
3179     // If the operand is smaller than the shift count type, promote it.
3180     if (ShiftSize > Op2Size)
3181       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3182 
3183     // If the operand is larger than the shift count type but the shift
3184     // count type has enough bits to represent any shift value, truncate
3185     // it now. This is a common case and it exposes the truncate to
3186     // optimization early.
3187     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3188       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3189     // Otherwise we'll need to temporarily settle for some other convenient
3190     // type.  Type legalization will make adjustments once the shiftee is split.
3191     else
3192       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3193   }
3194 
3195   bool nuw = false;
3196   bool nsw = false;
3197   bool exact = false;
3198 
3199   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3200 
3201     if (const OverflowingBinaryOperator *OFBinOp =
3202             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3203       nuw = OFBinOp->hasNoUnsignedWrap();
3204       nsw = OFBinOp->hasNoSignedWrap();
3205     }
3206     if (const PossiblyExactOperator *ExactOp =
3207             dyn_cast<const PossiblyExactOperator>(&I))
3208       exact = ExactOp->isExact();
3209   }
3210   SDNodeFlags Flags;
3211   Flags.setExact(exact);
3212   Flags.setNoSignedWrap(nsw);
3213   Flags.setNoUnsignedWrap(nuw);
3214   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3215                             Flags);
3216   setValue(&I, Res);
3217 }
3218 
3219 void SelectionDAGBuilder::visitSDiv(const User &I) {
3220   SDValue Op1 = getValue(I.getOperand(0));
3221   SDValue Op2 = getValue(I.getOperand(1));
3222 
3223   SDNodeFlags Flags;
3224   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3225                  cast<PossiblyExactOperator>(&I)->isExact());
3226   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3227                            Op2, Flags));
3228 }
3229 
3230 void SelectionDAGBuilder::visitICmp(const User &I) {
3231   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3232   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3233     predicate = IC->getPredicate();
3234   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3235     predicate = ICmpInst::Predicate(IC->getPredicate());
3236   SDValue Op1 = getValue(I.getOperand(0));
3237   SDValue Op2 = getValue(I.getOperand(1));
3238   ISD::CondCode Opcode = getICmpCondCode(predicate);
3239 
3240   auto &TLI = DAG.getTargetLoweringInfo();
3241   EVT MemVT =
3242       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3243 
3244   // If a pointer's DAG type is larger than its memory type then the DAG values
3245   // are zero-extended. This breaks signed comparisons so truncate back to the
3246   // underlying type before doing the compare.
3247   if (Op1.getValueType() != MemVT) {
3248     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3249     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3250   }
3251 
3252   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3253                                                         I.getType());
3254   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3255 }
3256 
3257 void SelectionDAGBuilder::visitFCmp(const User &I) {
3258   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3259   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3260     predicate = FC->getPredicate();
3261   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3262     predicate = FCmpInst::Predicate(FC->getPredicate());
3263   SDValue Op1 = getValue(I.getOperand(0));
3264   SDValue Op2 = getValue(I.getOperand(1));
3265 
3266   ISD::CondCode Condition = getFCmpCondCode(predicate);
3267   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3268   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3269     Condition = getFCmpCodeWithoutNaN(Condition);
3270 
3271   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3272                                                         I.getType());
3273   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3274 }
3275 
3276 // Check if the condition of the select has one use or two users that are both
3277 // selects with the same condition.
3278 static bool hasOnlySelectUsers(const Value *Cond) {
3279   return llvm::all_of(Cond->users(), [](const Value *V) {
3280     return isa<SelectInst>(V);
3281   });
3282 }
3283 
3284 void SelectionDAGBuilder::visitSelect(const User &I) {
3285   SmallVector<EVT, 4> ValueVTs;
3286   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3287                   ValueVTs);
3288   unsigned NumValues = ValueVTs.size();
3289   if (NumValues == 0) return;
3290 
3291   SmallVector<SDValue, 4> Values(NumValues);
3292   SDValue Cond     = getValue(I.getOperand(0));
3293   SDValue LHSVal   = getValue(I.getOperand(1));
3294   SDValue RHSVal   = getValue(I.getOperand(2));
3295   auto BaseOps = {Cond};
3296   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3297     ISD::VSELECT : ISD::SELECT;
3298 
3299   bool IsUnaryAbs = false;
3300 
3301   // Min/max matching is only viable if all output VTs are the same.
3302   if (is_splat(ValueVTs)) {
3303     EVT VT = ValueVTs[0];
3304     LLVMContext &Ctx = *DAG.getContext();
3305     auto &TLI = DAG.getTargetLoweringInfo();
3306 
3307     // We care about the legality of the operation after it has been type
3308     // legalized.
3309     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3310       VT = TLI.getTypeToTransformTo(Ctx, VT);
3311 
3312     // If the vselect is legal, assume we want to leave this as a vector setcc +
3313     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3314     // min/max is legal on the scalar type.
3315     bool UseScalarMinMax = VT.isVector() &&
3316       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3317 
3318     Value *LHS, *RHS;
3319     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3320     ISD::NodeType Opc = ISD::DELETED_NODE;
3321     switch (SPR.Flavor) {
3322     case SPF_UMAX:    Opc = ISD::UMAX; break;
3323     case SPF_UMIN:    Opc = ISD::UMIN; break;
3324     case SPF_SMAX:    Opc = ISD::SMAX; break;
3325     case SPF_SMIN:    Opc = ISD::SMIN; break;
3326     case SPF_FMINNUM:
3327       switch (SPR.NaNBehavior) {
3328       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3329       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3330       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3331       case SPNB_RETURNS_ANY: {
3332         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3333           Opc = ISD::FMINNUM;
3334         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3335           Opc = ISD::FMINIMUM;
3336         else if (UseScalarMinMax)
3337           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3338             ISD::FMINNUM : ISD::FMINIMUM;
3339         break;
3340       }
3341       }
3342       break;
3343     case SPF_FMAXNUM:
3344       switch (SPR.NaNBehavior) {
3345       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3346       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3347       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3348       case SPNB_RETURNS_ANY:
3349 
3350         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3351           Opc = ISD::FMAXNUM;
3352         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3353           Opc = ISD::FMAXIMUM;
3354         else if (UseScalarMinMax)
3355           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3356             ISD::FMAXNUM : ISD::FMAXIMUM;
3357         break;
3358       }
3359       break;
3360     case SPF_ABS:
3361       IsUnaryAbs = true;
3362       Opc = ISD::ABS;
3363       break;
3364     case SPF_NABS:
3365       // TODO: we need to produce sub(0, abs(X)).
3366     default: break;
3367     }
3368 
3369     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3370         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3371          (UseScalarMinMax &&
3372           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3373         // If the underlying comparison instruction is used by any other
3374         // instruction, the consumed instructions won't be destroyed, so it is
3375         // not profitable to convert to a min/max.
3376         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3377       OpCode = Opc;
3378       LHSVal = getValue(LHS);
3379       RHSVal = getValue(RHS);
3380       BaseOps = {};
3381     }
3382 
3383     if (IsUnaryAbs) {
3384       OpCode = Opc;
3385       LHSVal = getValue(LHS);
3386       BaseOps = {};
3387     }
3388   }
3389 
3390   if (IsUnaryAbs) {
3391     for (unsigned i = 0; i != NumValues; ++i) {
3392       Values[i] =
3393           DAG.getNode(OpCode, getCurSDLoc(),
3394                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3395                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3396     }
3397   } else {
3398     for (unsigned i = 0; i != NumValues; ++i) {
3399       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3400       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3401       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3402       Values[i] = DAG.getNode(
3403           OpCode, getCurSDLoc(),
3404           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3405     }
3406   }
3407 
3408   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3409                            DAG.getVTList(ValueVTs), Values));
3410 }
3411 
3412 void SelectionDAGBuilder::visitTrunc(const User &I) {
3413   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3414   SDValue N = getValue(I.getOperand(0));
3415   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3416                                                         I.getType());
3417   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3418 }
3419 
3420 void SelectionDAGBuilder::visitZExt(const User &I) {
3421   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3422   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3423   SDValue N = getValue(I.getOperand(0));
3424   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3425                                                         I.getType());
3426   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3427 }
3428 
3429 void SelectionDAGBuilder::visitSExt(const User &I) {
3430   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3431   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3432   SDValue N = getValue(I.getOperand(0));
3433   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3434                                                         I.getType());
3435   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3436 }
3437 
3438 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3439   // FPTrunc is never a no-op cast, no need to check
3440   SDValue N = getValue(I.getOperand(0));
3441   SDLoc dl = getCurSDLoc();
3442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3443   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3444   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3445                            DAG.getTargetConstant(
3446                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3447 }
3448 
3449 void SelectionDAGBuilder::visitFPExt(const User &I) {
3450   // FPExt is never a no-op cast, no need to check
3451   SDValue N = getValue(I.getOperand(0));
3452   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3453                                                         I.getType());
3454   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3455 }
3456 
3457 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3458   // FPToUI is never a no-op cast, no need to check
3459   SDValue N = getValue(I.getOperand(0));
3460   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3461                                                         I.getType());
3462   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3463 }
3464 
3465 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3466   // FPToSI is never a no-op cast, no need to check
3467   SDValue N = getValue(I.getOperand(0));
3468   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3469                                                         I.getType());
3470   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3471 }
3472 
3473 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3474   // UIToFP is never a no-op cast, no need to check
3475   SDValue N = getValue(I.getOperand(0));
3476   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3477                                                         I.getType());
3478   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3479 }
3480 
3481 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3482   // SIToFP is never a no-op cast, no need to check
3483   SDValue N = getValue(I.getOperand(0));
3484   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3485                                                         I.getType());
3486   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3487 }
3488 
3489 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3490   // What to do depends on the size of the integer and the size of the pointer.
3491   // We can either truncate, zero extend, or no-op, accordingly.
3492   SDValue N = getValue(I.getOperand(0));
3493   auto &TLI = DAG.getTargetLoweringInfo();
3494   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3495                                                         I.getType());
3496   EVT PtrMemVT =
3497       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3498   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3499   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3500   setValue(&I, N);
3501 }
3502 
3503 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3504   // What to do depends on the size of the integer and the size of the pointer.
3505   // We can either truncate, zero extend, or no-op, accordingly.
3506   SDValue N = getValue(I.getOperand(0));
3507   auto &TLI = DAG.getTargetLoweringInfo();
3508   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3509   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3510   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3511   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3512   setValue(&I, N);
3513 }
3514 
3515 void SelectionDAGBuilder::visitBitCast(const User &I) {
3516   SDValue N = getValue(I.getOperand(0));
3517   SDLoc dl = getCurSDLoc();
3518   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3519                                                         I.getType());
3520 
3521   // BitCast assures us that source and destination are the same size so this is
3522   // either a BITCAST or a no-op.
3523   if (DestVT != N.getValueType())
3524     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3525                              DestVT, N)); // convert types.
3526   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3527   // might fold any kind of constant expression to an integer constant and that
3528   // is not what we are looking for. Only recognize a bitcast of a genuine
3529   // constant integer as an opaque constant.
3530   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3531     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3532                                  /*isOpaque*/true));
3533   else
3534     setValue(&I, N);            // noop cast.
3535 }
3536 
3537 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3539   const Value *SV = I.getOperand(0);
3540   SDValue N = getValue(SV);
3541   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3542 
3543   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3544   unsigned DestAS = I.getType()->getPointerAddressSpace();
3545 
3546   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3547     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3548 
3549   setValue(&I, N);
3550 }
3551 
3552 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3553   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3554   SDValue InVec = getValue(I.getOperand(0));
3555   SDValue InVal = getValue(I.getOperand(1));
3556   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3557                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3558   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3559                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3560                            InVec, InVal, InIdx));
3561 }
3562 
3563 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3564   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3565   SDValue InVec = getValue(I.getOperand(0));
3566   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3567                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3568   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3569                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3570                            InVec, InIdx));
3571 }
3572 
3573 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3574   SDValue Src1 = getValue(I.getOperand(0));
3575   SDValue Src2 = getValue(I.getOperand(1));
3576   Constant *MaskV = cast<Constant>(I.getOperand(2));
3577   SDLoc DL = getCurSDLoc();
3578   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3579   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3580   EVT SrcVT = Src1.getValueType();
3581   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3582 
3583   if (MaskV->isNullValue() && VT.isScalableVector()) {
3584     // Canonical splat form of first element of first input vector.
3585     SDValue FirstElt =
3586         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3587                     DAG.getVectorIdxConstant(0, DL));
3588     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3589     return;
3590   }
3591 
3592   // For now, we only handle splats for scalable vectors.
3593   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3594   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3595   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3596 
3597   SmallVector<int, 8> Mask;
3598   ShuffleVectorInst::getShuffleMask(MaskV, Mask);
3599   unsigned MaskNumElts = Mask.size();
3600 
3601   if (SrcNumElts == MaskNumElts) {
3602     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3603     return;
3604   }
3605 
3606   // Normalize the shuffle vector since mask and vector length don't match.
3607   if (SrcNumElts < MaskNumElts) {
3608     // Mask is longer than the source vectors. We can use concatenate vector to
3609     // make the mask and vectors lengths match.
3610 
3611     if (MaskNumElts % SrcNumElts == 0) {
3612       // Mask length is a multiple of the source vector length.
3613       // Check if the shuffle is some kind of concatenation of the input
3614       // vectors.
3615       unsigned NumConcat = MaskNumElts / SrcNumElts;
3616       bool IsConcat = true;
3617       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3618       for (unsigned i = 0; i != MaskNumElts; ++i) {
3619         int Idx = Mask[i];
3620         if (Idx < 0)
3621           continue;
3622         // Ensure the indices in each SrcVT sized piece are sequential and that
3623         // the same source is used for the whole piece.
3624         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3625             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3626              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3627           IsConcat = false;
3628           break;
3629         }
3630         // Remember which source this index came from.
3631         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3632       }
3633 
3634       // The shuffle is concatenating multiple vectors together. Just emit
3635       // a CONCAT_VECTORS operation.
3636       if (IsConcat) {
3637         SmallVector<SDValue, 8> ConcatOps;
3638         for (auto Src : ConcatSrcs) {
3639           if (Src < 0)
3640             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3641           else if (Src == 0)
3642             ConcatOps.push_back(Src1);
3643           else
3644             ConcatOps.push_back(Src2);
3645         }
3646         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3647         return;
3648       }
3649     }
3650 
3651     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3652     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3653     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3654                                     PaddedMaskNumElts);
3655 
3656     // Pad both vectors with undefs to make them the same length as the mask.
3657     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3658 
3659     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3660     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3661     MOps1[0] = Src1;
3662     MOps2[0] = Src2;
3663 
3664     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3665     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3666 
3667     // Readjust mask for new input vector length.
3668     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3669     for (unsigned i = 0; i != MaskNumElts; ++i) {
3670       int Idx = Mask[i];
3671       if (Idx >= (int)SrcNumElts)
3672         Idx -= SrcNumElts - PaddedMaskNumElts;
3673       MappedOps[i] = Idx;
3674     }
3675 
3676     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3677 
3678     // If the concatenated vector was padded, extract a subvector with the
3679     // correct number of elements.
3680     if (MaskNumElts != PaddedMaskNumElts)
3681       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3682                            DAG.getVectorIdxConstant(0, DL));
3683 
3684     setValue(&I, Result);
3685     return;
3686   }
3687 
3688   if (SrcNumElts > MaskNumElts) {
3689     // Analyze the access pattern of the vector to see if we can extract
3690     // two subvectors and do the shuffle.
3691     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3692     bool CanExtract = true;
3693     for (int Idx : Mask) {
3694       unsigned Input = 0;
3695       if (Idx < 0)
3696         continue;
3697 
3698       if (Idx >= (int)SrcNumElts) {
3699         Input = 1;
3700         Idx -= SrcNumElts;
3701       }
3702 
3703       // If all the indices come from the same MaskNumElts sized portion of
3704       // the sources we can use extract. Also make sure the extract wouldn't
3705       // extract past the end of the source.
3706       int NewStartIdx = alignDown(Idx, MaskNumElts);
3707       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3708           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3709         CanExtract = false;
3710       // Make sure we always update StartIdx as we use it to track if all
3711       // elements are undef.
3712       StartIdx[Input] = NewStartIdx;
3713     }
3714 
3715     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3716       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3717       return;
3718     }
3719     if (CanExtract) {
3720       // Extract appropriate subvector and generate a vector shuffle
3721       for (unsigned Input = 0; Input < 2; ++Input) {
3722         SDValue &Src = Input == 0 ? Src1 : Src2;
3723         if (StartIdx[Input] < 0)
3724           Src = DAG.getUNDEF(VT);
3725         else {
3726           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3727                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3728         }
3729       }
3730 
3731       // Calculate new mask.
3732       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3733       for (int &Idx : MappedOps) {
3734         if (Idx >= (int)SrcNumElts)
3735           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3736         else if (Idx >= 0)
3737           Idx -= StartIdx[0];
3738       }
3739 
3740       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3741       return;
3742     }
3743   }
3744 
3745   // We can't use either concat vectors or extract subvectors so fall back to
3746   // replacing the shuffle with extract and build vector.
3747   // to insert and build vector.
3748   EVT EltVT = VT.getVectorElementType();
3749   SmallVector<SDValue,8> Ops;
3750   for (int Idx : Mask) {
3751     SDValue Res;
3752 
3753     if (Idx < 0) {
3754       Res = DAG.getUNDEF(EltVT);
3755     } else {
3756       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3757       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3758 
3759       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3760                         DAG.getVectorIdxConstant(Idx, DL));
3761     }
3762 
3763     Ops.push_back(Res);
3764   }
3765 
3766   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3767 }
3768 
3769 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3770   ArrayRef<unsigned> Indices;
3771   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3772     Indices = IV->getIndices();
3773   else
3774     Indices = cast<ConstantExpr>(&I)->getIndices();
3775 
3776   const Value *Op0 = I.getOperand(0);
3777   const Value *Op1 = I.getOperand(1);
3778   Type *AggTy = I.getType();
3779   Type *ValTy = Op1->getType();
3780   bool IntoUndef = isa<UndefValue>(Op0);
3781   bool FromUndef = isa<UndefValue>(Op1);
3782 
3783   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3784 
3785   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3786   SmallVector<EVT, 4> AggValueVTs;
3787   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3788   SmallVector<EVT, 4> ValValueVTs;
3789   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3790 
3791   unsigned NumAggValues = AggValueVTs.size();
3792   unsigned NumValValues = ValValueVTs.size();
3793   SmallVector<SDValue, 4> Values(NumAggValues);
3794 
3795   // Ignore an insertvalue that produces an empty object
3796   if (!NumAggValues) {
3797     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3798     return;
3799   }
3800 
3801   SDValue Agg = getValue(Op0);
3802   unsigned i = 0;
3803   // Copy the beginning value(s) from the original aggregate.
3804   for (; i != LinearIndex; ++i)
3805     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3806                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3807   // Copy values from the inserted value(s).
3808   if (NumValValues) {
3809     SDValue Val = getValue(Op1);
3810     for (; i != LinearIndex + NumValValues; ++i)
3811       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3812                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3813   }
3814   // Copy remaining value(s) from the original aggregate.
3815   for (; i != NumAggValues; ++i)
3816     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3817                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3818 
3819   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3820                            DAG.getVTList(AggValueVTs), Values));
3821 }
3822 
3823 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3824   ArrayRef<unsigned> Indices;
3825   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3826     Indices = EV->getIndices();
3827   else
3828     Indices = cast<ConstantExpr>(&I)->getIndices();
3829 
3830   const Value *Op0 = I.getOperand(0);
3831   Type *AggTy = Op0->getType();
3832   Type *ValTy = I.getType();
3833   bool OutOfUndef = isa<UndefValue>(Op0);
3834 
3835   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3836 
3837   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3838   SmallVector<EVT, 4> ValValueVTs;
3839   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3840 
3841   unsigned NumValValues = ValValueVTs.size();
3842 
3843   // Ignore a extractvalue that produces an empty object
3844   if (!NumValValues) {
3845     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3846     return;
3847   }
3848 
3849   SmallVector<SDValue, 4> Values(NumValValues);
3850 
3851   SDValue Agg = getValue(Op0);
3852   // Copy out the selected value(s).
3853   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3854     Values[i - LinearIndex] =
3855       OutOfUndef ?
3856         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3857         SDValue(Agg.getNode(), Agg.getResNo() + i);
3858 
3859   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3860                            DAG.getVTList(ValValueVTs), Values));
3861 }
3862 
3863 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3864   Value *Op0 = I.getOperand(0);
3865   // Note that the pointer operand may be a vector of pointers. Take the scalar
3866   // element which holds a pointer.
3867   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3868   SDValue N = getValue(Op0);
3869   SDLoc dl = getCurSDLoc();
3870   auto &TLI = DAG.getTargetLoweringInfo();
3871   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3872   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3873 
3874   // Normalize Vector GEP - all scalar operands should be converted to the
3875   // splat vector.
3876   unsigned VectorWidth = I.getType()->isVectorTy() ?
3877     I.getType()->getVectorNumElements() : 0;
3878 
3879   if (VectorWidth && !N.getValueType().isVector()) {
3880     LLVMContext &Context = *DAG.getContext();
3881     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3882     N = DAG.getSplatBuildVector(VT, dl, N);
3883   }
3884 
3885   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3886        GTI != E; ++GTI) {
3887     const Value *Idx = GTI.getOperand();
3888     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3889       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3890       if (Field) {
3891         // N = N + Offset
3892         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3893 
3894         // In an inbounds GEP with an offset that is nonnegative even when
3895         // interpreted as signed, assume there is no unsigned overflow.
3896         SDNodeFlags Flags;
3897         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3898           Flags.setNoUnsignedWrap(true);
3899 
3900         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3901                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3902       }
3903     } else {
3904       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3905       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3906       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3907 
3908       // If this is a scalar constant or a splat vector of constants,
3909       // handle it quickly.
3910       const auto *C = dyn_cast<Constant>(Idx);
3911       if (C && isa<VectorType>(C->getType()))
3912         C = C->getSplatValue();
3913 
3914       if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
3915         if (CI->isZero())
3916           continue;
3917         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3918         LLVMContext &Context = *DAG.getContext();
3919         SDValue OffsVal = VectorWidth ?
3920           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3921           DAG.getConstant(Offs, dl, IdxTy);
3922 
3923         // In an inbounds GEP with an offset that is nonnegative even when
3924         // interpreted as signed, assume there is no unsigned overflow.
3925         SDNodeFlags Flags;
3926         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3927           Flags.setNoUnsignedWrap(true);
3928 
3929         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3930 
3931         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3932         continue;
3933       }
3934 
3935       // N = N + Idx * ElementSize;
3936       SDValue IdxN = getValue(Idx);
3937 
3938       if (!IdxN.getValueType().isVector() && VectorWidth) {
3939         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3940         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3941       }
3942 
3943       // If the index is smaller or larger than intptr_t, truncate or extend
3944       // it.
3945       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3946 
3947       // If this is a multiply by a power of two, turn it into a shl
3948       // immediately.  This is a very common case.
3949       if (ElementSize != 1) {
3950         if (ElementSize.isPowerOf2()) {
3951           unsigned Amt = ElementSize.logBase2();
3952           IdxN = DAG.getNode(ISD::SHL, dl,
3953                              N.getValueType(), IdxN,
3954                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3955         } else {
3956           SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
3957                                           IdxN.getValueType());
3958           IdxN = DAG.getNode(ISD::MUL, dl,
3959                              N.getValueType(), IdxN, Scale);
3960         }
3961       }
3962 
3963       N = DAG.getNode(ISD::ADD, dl,
3964                       N.getValueType(), N, IdxN);
3965     }
3966   }
3967 
3968   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3969     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3970 
3971   setValue(&I, N);
3972 }
3973 
3974 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3975   // If this is a fixed sized alloca in the entry block of the function,
3976   // allocate it statically on the stack.
3977   if (FuncInfo.StaticAllocaMap.count(&I))
3978     return;   // getValue will auto-populate this.
3979 
3980   SDLoc dl = getCurSDLoc();
3981   Type *Ty = I.getAllocatedType();
3982   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3983   auto &DL = DAG.getDataLayout();
3984   uint64_t TySize = DL.getTypeAllocSize(Ty);
3985   unsigned Align =
3986       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3987 
3988   SDValue AllocSize = getValue(I.getArraySize());
3989 
3990   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3991   if (AllocSize.getValueType() != IntPtr)
3992     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3993 
3994   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3995                           AllocSize,
3996                           DAG.getConstant(TySize, dl, IntPtr));
3997 
3998   // Handle alignment.  If the requested alignment is less than or equal to
3999   // the stack alignment, ignore it.  If the size is greater than or equal to
4000   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4001   unsigned StackAlign =
4002       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
4003   if (Align <= StackAlign)
4004     Align = 0;
4005 
4006   // Round the size of the allocation up to the stack alignment size
4007   // by add SA-1 to the size. This doesn't overflow because we're computing
4008   // an address inside an alloca.
4009   SDNodeFlags Flags;
4010   Flags.setNoUnsignedWrap(true);
4011   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4012                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
4013 
4014   // Mask out the low bits for alignment purposes.
4015   AllocSize =
4016       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4017                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
4018 
4019   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
4020   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4021   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4022   setValue(&I, DSA);
4023   DAG.setRoot(DSA.getValue(1));
4024 
4025   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4026 }
4027 
4028 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4029   if (I.isAtomic())
4030     return visitAtomicLoad(I);
4031 
4032   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4033   const Value *SV = I.getOperand(0);
4034   if (TLI.supportSwiftError()) {
4035     // Swifterror values can come from either a function parameter with
4036     // swifterror attribute or an alloca with swifterror attribute.
4037     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4038       if (Arg->hasSwiftErrorAttr())
4039         return visitLoadFromSwiftError(I);
4040     }
4041 
4042     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4043       if (Alloca->isSwiftError())
4044         return visitLoadFromSwiftError(I);
4045     }
4046   }
4047 
4048   SDValue Ptr = getValue(SV);
4049 
4050   Type *Ty = I.getType();
4051   unsigned Alignment = I.getAlignment();
4052 
4053   AAMDNodes AAInfo;
4054   I.getAAMetadata(AAInfo);
4055   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4056 
4057   SmallVector<EVT, 4> ValueVTs, MemVTs;
4058   SmallVector<uint64_t, 4> Offsets;
4059   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4060   unsigned NumValues = ValueVTs.size();
4061   if (NumValues == 0)
4062     return;
4063 
4064   bool isVolatile = I.isVolatile();
4065 
4066   SDValue Root;
4067   bool ConstantMemory = false;
4068   if (isVolatile)
4069     // Serialize volatile loads with other side effects.
4070     Root = getRoot();
4071   else if (NumValues > MaxParallelChains)
4072     Root = getMemoryRoot();
4073   else if (AA &&
4074            AA->pointsToConstantMemory(MemoryLocation(
4075                SV,
4076                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4077                AAInfo))) {
4078     // Do not serialize (non-volatile) loads of constant memory with anything.
4079     Root = DAG.getEntryNode();
4080     ConstantMemory = true;
4081   } else {
4082     // Do not serialize non-volatile loads against each other.
4083     Root = DAG.getRoot();
4084   }
4085 
4086   SDLoc dl = getCurSDLoc();
4087 
4088   if (isVolatile)
4089     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4090 
4091   // An aggregate load cannot wrap around the address space, so offsets to its
4092   // parts don't wrap either.
4093   SDNodeFlags Flags;
4094   Flags.setNoUnsignedWrap(true);
4095 
4096   SmallVector<SDValue, 4> Values(NumValues);
4097   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4098   EVT PtrVT = Ptr.getValueType();
4099 
4100   MachineMemOperand::Flags MMOFlags
4101     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4102 
4103   unsigned ChainI = 0;
4104   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4105     // Serializing loads here may result in excessive register pressure, and
4106     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4107     // could recover a bit by hoisting nodes upward in the chain by recognizing
4108     // they are side-effect free or do not alias. The optimizer should really
4109     // avoid this case by converting large object/array copies to llvm.memcpy
4110     // (MaxParallelChains should always remain as failsafe).
4111     if (ChainI == MaxParallelChains) {
4112       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4113       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4114                                   makeArrayRef(Chains.data(), ChainI));
4115       Root = Chain;
4116       ChainI = 0;
4117     }
4118     SDValue A = DAG.getNode(ISD::ADD, dl,
4119                             PtrVT, Ptr,
4120                             DAG.getConstant(Offsets[i], dl, PtrVT),
4121                             Flags);
4122 
4123     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4124                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4125                             MMOFlags, AAInfo, Ranges);
4126     Chains[ChainI] = L.getValue(1);
4127 
4128     if (MemVTs[i] != ValueVTs[i])
4129       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4130 
4131     Values[i] = L;
4132   }
4133 
4134   if (!ConstantMemory) {
4135     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4136                                 makeArrayRef(Chains.data(), ChainI));
4137     if (isVolatile)
4138       DAG.setRoot(Chain);
4139     else
4140       PendingLoads.push_back(Chain);
4141   }
4142 
4143   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4144                            DAG.getVTList(ValueVTs), Values));
4145 }
4146 
4147 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4148   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4149          "call visitStoreToSwiftError when backend supports swifterror");
4150 
4151   SmallVector<EVT, 4> ValueVTs;
4152   SmallVector<uint64_t, 4> Offsets;
4153   const Value *SrcV = I.getOperand(0);
4154   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4155                   SrcV->getType(), ValueVTs, &Offsets);
4156   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4157          "expect a single EVT for swifterror");
4158 
4159   SDValue Src = getValue(SrcV);
4160   // Create a virtual register, then update the virtual register.
4161   Register VReg =
4162       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4163   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4164   // Chain can be getRoot or getControlRoot.
4165   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4166                                       SDValue(Src.getNode(), Src.getResNo()));
4167   DAG.setRoot(CopyNode);
4168 }
4169 
4170 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4171   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4172          "call visitLoadFromSwiftError when backend supports swifterror");
4173 
4174   assert(!I.isVolatile() &&
4175          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4176          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4177          "Support volatile, non temporal, invariant for load_from_swift_error");
4178 
4179   const Value *SV = I.getOperand(0);
4180   Type *Ty = I.getType();
4181   AAMDNodes AAInfo;
4182   I.getAAMetadata(AAInfo);
4183   assert(
4184       (!AA ||
4185        !AA->pointsToConstantMemory(MemoryLocation(
4186            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4187            AAInfo))) &&
4188       "load_from_swift_error should not be constant memory");
4189 
4190   SmallVector<EVT, 4> ValueVTs;
4191   SmallVector<uint64_t, 4> Offsets;
4192   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4193                   ValueVTs, &Offsets);
4194   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4195          "expect a single EVT for swifterror");
4196 
4197   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4198   SDValue L = DAG.getCopyFromReg(
4199       getRoot(), getCurSDLoc(),
4200       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4201 
4202   setValue(&I, L);
4203 }
4204 
4205 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4206   if (I.isAtomic())
4207     return visitAtomicStore(I);
4208 
4209   const Value *SrcV = I.getOperand(0);
4210   const Value *PtrV = I.getOperand(1);
4211 
4212   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4213   if (TLI.supportSwiftError()) {
4214     // Swifterror values can come from either a function parameter with
4215     // swifterror attribute or an alloca with swifterror attribute.
4216     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4217       if (Arg->hasSwiftErrorAttr())
4218         return visitStoreToSwiftError(I);
4219     }
4220 
4221     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4222       if (Alloca->isSwiftError())
4223         return visitStoreToSwiftError(I);
4224     }
4225   }
4226 
4227   SmallVector<EVT, 4> ValueVTs, MemVTs;
4228   SmallVector<uint64_t, 4> Offsets;
4229   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4230                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4231   unsigned NumValues = ValueVTs.size();
4232   if (NumValues == 0)
4233     return;
4234 
4235   // Get the lowered operands. Note that we do this after
4236   // checking if NumResults is zero, because with zero results
4237   // the operands won't have values in the map.
4238   SDValue Src = getValue(SrcV);
4239   SDValue Ptr = getValue(PtrV);
4240 
4241   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4242   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4243   SDLoc dl = getCurSDLoc();
4244   unsigned Alignment = I.getAlignment();
4245   AAMDNodes AAInfo;
4246   I.getAAMetadata(AAInfo);
4247 
4248   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4249 
4250   // An aggregate load cannot wrap around the address space, so offsets to its
4251   // parts don't wrap either.
4252   SDNodeFlags Flags;
4253   Flags.setNoUnsignedWrap(true);
4254 
4255   unsigned ChainI = 0;
4256   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4257     // See visitLoad comments.
4258     if (ChainI == MaxParallelChains) {
4259       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4260                                   makeArrayRef(Chains.data(), ChainI));
4261       Root = Chain;
4262       ChainI = 0;
4263     }
4264     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4265     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4266     if (MemVTs[i] != ValueVTs[i])
4267       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4268     SDValue St =
4269         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4270                      Alignment, MMOFlags, AAInfo);
4271     Chains[ChainI] = St;
4272   }
4273 
4274   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4275                                   makeArrayRef(Chains.data(), ChainI));
4276   DAG.setRoot(StoreNode);
4277 }
4278 
4279 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4280                                            bool IsCompressing) {
4281   SDLoc sdl = getCurSDLoc();
4282 
4283   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4284                            unsigned& Alignment) {
4285     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4286     Src0 = I.getArgOperand(0);
4287     Ptr = I.getArgOperand(1);
4288     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4289     Mask = I.getArgOperand(3);
4290   };
4291   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4292                            unsigned& Alignment) {
4293     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4294     Src0 = I.getArgOperand(0);
4295     Ptr = I.getArgOperand(1);
4296     Mask = I.getArgOperand(2);
4297     Alignment = 0;
4298   };
4299 
4300   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4301   unsigned Alignment;
4302   if (IsCompressing)
4303     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4304   else
4305     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4306 
4307   SDValue Ptr = getValue(PtrOperand);
4308   SDValue Src0 = getValue(Src0Operand);
4309   SDValue Mask = getValue(MaskOperand);
4310   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4311 
4312   EVT VT = Src0.getValueType();
4313   if (!Alignment)
4314     Alignment = DAG.getEVTAlignment(VT);
4315 
4316   AAMDNodes AAInfo;
4317   I.getAAMetadata(AAInfo);
4318 
4319   MachineMemOperand *MMO =
4320     DAG.getMachineFunction().
4321     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4322                           MachineMemOperand::MOStore,
4323                           // TODO: Make MachineMemOperands aware of scalable
4324                           // vectors.
4325                           VT.getStoreSize().getKnownMinSize(),
4326                           Alignment, AAInfo);
4327   SDValue StoreNode =
4328       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4329                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4330   DAG.setRoot(StoreNode);
4331   setValue(&I, StoreNode);
4332 }
4333 
4334 // Get a uniform base for the Gather/Scatter intrinsic.
4335 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4336 // We try to represent it as a base pointer + vector of indices.
4337 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4338 // The first operand of the GEP may be a single pointer or a vector of pointers
4339 // Example:
4340 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4341 //  or
4342 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4343 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4344 //
4345 // When the first GEP operand is a single pointer - it is the uniform base we
4346 // are looking for. If first operand of the GEP is a splat vector - we
4347 // extract the splat value and use it as a uniform base.
4348 // In all other cases the function returns 'false'.
4349 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
4350                            ISD::MemIndexType &IndexType, SDValue &Scale,
4351                            SelectionDAGBuilder *SDB) {
4352   SelectionDAG& DAG = SDB->DAG;
4353   LLVMContext &Context = *DAG.getContext();
4354 
4355   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4356   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4357   if (!GEP)
4358     return false;
4359 
4360   const Value *GEPPtr = GEP->getPointerOperand();
4361   if (!GEPPtr->getType()->isVectorTy())
4362     Ptr = GEPPtr;
4363   else if (!(Ptr = getSplatValue(GEPPtr)))
4364     return false;
4365 
4366   unsigned FinalIndex = GEP->getNumOperands() - 1;
4367   Value *IndexVal = GEP->getOperand(FinalIndex);
4368   gep_type_iterator GTI = gep_type_begin(*GEP);
4369 
4370   // Ensure all the other indices are 0.
4371   for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) {
4372     auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4373     if (!C)
4374       return false;
4375     if (isa<VectorType>(C->getType()))
4376       C = C->getSplatValue();
4377     auto *CI = dyn_cast_or_null<ConstantInt>(C);
4378     if (!CI || !CI->isZero())
4379       return false;
4380   }
4381 
4382   // The operands of the GEP may be defined in another basic block.
4383   // In this case we'll not find nodes for the operands.
4384   if (!SDB->findValue(Ptr))
4385     return false;
4386   Constant *C = dyn_cast<Constant>(IndexVal);
4387   if (!C && !SDB->findValue(IndexVal))
4388     return false;
4389 
4390   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4391   const DataLayout &DL = DAG.getDataLayout();
4392   StructType *STy = GTI.getStructTypeOrNull();
4393 
4394   if (STy) {
4395     const StructLayout *SL = DL.getStructLayout(STy);
4396     if (isa<VectorType>(C->getType())) {
4397       C = C->getSplatValue();
4398       // FIXME: If getSplatValue may return nullptr for a structure?
4399       // If not, the following check can be removed.
4400       if (!C)
4401         return false;
4402     }
4403     auto *CI = cast<ConstantInt>(C);
4404     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4405     Index = DAG.getConstant(SL->getElementOffset(CI->getZExtValue()),
4406                             SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4407   } else {
4408     Scale = DAG.getTargetConstant(
4409                 DL.getTypeAllocSize(GEP->getResultElementType()),
4410                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4411     Index = SDB->getValue(IndexVal);
4412   }
4413   Base = SDB->getValue(Ptr);
4414   IndexType = ISD::SIGNED_SCALED;
4415 
4416   if (STy || !Index.getValueType().isVector()) {
4417     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4418     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4419     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4420   }
4421   return true;
4422 }
4423 
4424 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4425   SDLoc sdl = getCurSDLoc();
4426 
4427   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4428   const Value *Ptr = I.getArgOperand(1);
4429   SDValue Src0 = getValue(I.getArgOperand(0));
4430   SDValue Mask = getValue(I.getArgOperand(3));
4431   EVT VT = Src0.getValueType();
4432   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4433   if (!Alignment)
4434     Alignment = DAG.getEVTAlignment(VT);
4435   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4436 
4437   AAMDNodes AAInfo;
4438   I.getAAMetadata(AAInfo);
4439 
4440   SDValue Base;
4441   SDValue Index;
4442   ISD::MemIndexType IndexType;
4443   SDValue Scale;
4444   const Value *BasePtr = Ptr;
4445   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4446                                     this);
4447 
4448   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4449   MachineMemOperand *MMO = DAG.getMachineFunction().
4450     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4451                          MachineMemOperand::MOStore,
4452                          // TODO: Make MachineMemOperands aware of scalable
4453                          // vectors.
4454                          VT.getStoreSize().getKnownMinSize(),
4455                          Alignment, AAInfo);
4456   if (!UniformBase) {
4457     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4458     Index = getValue(Ptr);
4459     IndexType = ISD::SIGNED_SCALED;
4460     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4461   }
4462   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4463   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4464                                          Ops, MMO, IndexType);
4465   DAG.setRoot(Scatter);
4466   setValue(&I, Scatter);
4467 }
4468 
4469 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4470   SDLoc sdl = getCurSDLoc();
4471 
4472   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4473                            unsigned& Alignment) {
4474     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4475     Ptr = I.getArgOperand(0);
4476     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4477     Mask = I.getArgOperand(2);
4478     Src0 = I.getArgOperand(3);
4479   };
4480   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4481                            unsigned& Alignment) {
4482     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4483     Ptr = I.getArgOperand(0);
4484     Alignment = 0;
4485     Mask = I.getArgOperand(1);
4486     Src0 = I.getArgOperand(2);
4487   };
4488 
4489   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4490   unsigned Alignment;
4491   if (IsExpanding)
4492     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4493   else
4494     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4495 
4496   SDValue Ptr = getValue(PtrOperand);
4497   SDValue Src0 = getValue(Src0Operand);
4498   SDValue Mask = getValue(MaskOperand);
4499   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4500 
4501   EVT VT = Src0.getValueType();
4502   if (!Alignment)
4503     Alignment = DAG.getEVTAlignment(VT);
4504 
4505   AAMDNodes AAInfo;
4506   I.getAAMetadata(AAInfo);
4507   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4508 
4509   // Do not serialize masked loads of constant memory with anything.
4510   MemoryLocation ML;
4511   if (VT.isScalableVector())
4512     ML = MemoryLocation(PtrOperand);
4513   else
4514     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4515                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4516                            AAInfo);
4517   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4518 
4519   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4520 
4521   MachineMemOperand *MMO =
4522     DAG.getMachineFunction().
4523     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4524                           MachineMemOperand::MOLoad,
4525                           // TODO: Make MachineMemOperands aware of scalable
4526                           // vectors.
4527                           VT.getStoreSize().getKnownMinSize(),
4528                           Alignment, AAInfo, Ranges);
4529 
4530   SDValue Load =
4531       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4532                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4533   if (AddToChain)
4534     PendingLoads.push_back(Load.getValue(1));
4535   setValue(&I, Load);
4536 }
4537 
4538 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4539   SDLoc sdl = getCurSDLoc();
4540 
4541   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4542   const Value *Ptr = I.getArgOperand(0);
4543   SDValue Src0 = getValue(I.getArgOperand(3));
4544   SDValue Mask = getValue(I.getArgOperand(2));
4545 
4546   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4547   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4548   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4549   if (!Alignment)
4550     Alignment = DAG.getEVTAlignment(VT);
4551 
4552   AAMDNodes AAInfo;
4553   I.getAAMetadata(AAInfo);
4554   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4555 
4556   SDValue Root = DAG.getRoot();
4557   SDValue Base;
4558   SDValue Index;
4559   ISD::MemIndexType IndexType;
4560   SDValue Scale;
4561   const Value *BasePtr = Ptr;
4562   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4563                                     this);
4564   bool ConstantMemory = false;
4565   if (UniformBase && AA &&
4566       AA->pointsToConstantMemory(
4567           MemoryLocation(BasePtr,
4568                          LocationSize::precise(
4569                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4570                          AAInfo))) {
4571     // Do not serialize (non-volatile) loads of constant memory with anything.
4572     Root = DAG.getEntryNode();
4573     ConstantMemory = true;
4574   }
4575 
4576   MachineMemOperand *MMO =
4577     DAG.getMachineFunction().
4578     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4579                          MachineMemOperand::MOLoad,
4580                          // TODO: Make MachineMemOperands aware of scalable
4581                          // vectors.
4582                          VT.getStoreSize().getKnownMinSize(),
4583                          Alignment, AAInfo, Ranges);
4584 
4585   if (!UniformBase) {
4586     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4587     Index = getValue(Ptr);
4588     IndexType = ISD::SIGNED_SCALED;
4589     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4590   }
4591   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4592   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4593                                        Ops, MMO, IndexType);
4594 
4595   SDValue OutChain = Gather.getValue(1);
4596   if (!ConstantMemory)
4597     PendingLoads.push_back(OutChain);
4598   setValue(&I, Gather);
4599 }
4600 
4601 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4602   SDLoc dl = getCurSDLoc();
4603   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4604   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4605   SyncScope::ID SSID = I.getSyncScopeID();
4606 
4607   SDValue InChain = getRoot();
4608 
4609   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4610   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4611 
4612   auto Alignment = DAG.getEVTAlignment(MemVT);
4613   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4614   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4615 
4616   MachineFunction &MF = DAG.getMachineFunction();
4617   MachineMemOperand *MMO =
4618     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4619                             Flags, MemVT.getStoreSize(), Alignment,
4620                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4621                             FailureOrdering);
4622 
4623   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4624                                    dl, MemVT, VTs, InChain,
4625                                    getValue(I.getPointerOperand()),
4626                                    getValue(I.getCompareOperand()),
4627                                    getValue(I.getNewValOperand()), MMO);
4628 
4629   SDValue OutChain = L.getValue(2);
4630 
4631   setValue(&I, L);
4632   DAG.setRoot(OutChain);
4633 }
4634 
4635 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4636   SDLoc dl = getCurSDLoc();
4637   ISD::NodeType NT;
4638   switch (I.getOperation()) {
4639   default: llvm_unreachable("Unknown atomicrmw operation");
4640   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4641   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4642   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4643   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4644   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4645   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4646   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4647   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4648   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4649   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4650   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4651   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4652   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4653   }
4654   AtomicOrdering Ordering = I.getOrdering();
4655   SyncScope::ID SSID = I.getSyncScopeID();
4656 
4657   SDValue InChain = getRoot();
4658 
4659   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4660   auto Alignment = DAG.getEVTAlignment(MemVT);
4661   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4662   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4663 
4664   MachineFunction &MF = DAG.getMachineFunction();
4665   MachineMemOperand *MMO =
4666     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4667                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4668                             nullptr, SSID, Ordering);
4669 
4670   SDValue L =
4671     DAG.getAtomic(NT, dl, MemVT, InChain,
4672                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4673                   MMO);
4674 
4675   SDValue OutChain = L.getValue(1);
4676 
4677   setValue(&I, L);
4678   DAG.setRoot(OutChain);
4679 }
4680 
4681 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4682   SDLoc dl = getCurSDLoc();
4683   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4684   SDValue Ops[3];
4685   Ops[0] = getRoot();
4686   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4687                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4688   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4689                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4690   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4691 }
4692 
4693 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4694   SDLoc dl = getCurSDLoc();
4695   AtomicOrdering Order = I.getOrdering();
4696   SyncScope::ID SSID = I.getSyncScopeID();
4697 
4698   SDValue InChain = getRoot();
4699 
4700   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4701   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4702   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4703 
4704   if (!TLI.supportsUnalignedAtomics() &&
4705       I.getAlignment() < MemVT.getSizeInBits() / 8)
4706     report_fatal_error("Cannot generate unaligned atomic load");
4707 
4708   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4709 
4710   MachineMemOperand *MMO =
4711       DAG.getMachineFunction().
4712       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4713                            Flags, MemVT.getStoreSize(),
4714                            I.getAlignment() ? I.getAlignment() :
4715                                               DAG.getEVTAlignment(MemVT),
4716                            AAMDNodes(), nullptr, SSID, Order);
4717 
4718   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4719 
4720   SDValue Ptr = getValue(I.getPointerOperand());
4721 
4722   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4723     // TODO: Once this is better exercised by tests, it should be merged with
4724     // the normal path for loads to prevent future divergence.
4725     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4726     if (MemVT != VT)
4727       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4728 
4729     setValue(&I, L);
4730     SDValue OutChain = L.getValue(1);
4731     if (!I.isUnordered())
4732       DAG.setRoot(OutChain);
4733     else
4734       PendingLoads.push_back(OutChain);
4735     return;
4736   }
4737 
4738   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4739                             Ptr, MMO);
4740 
4741   SDValue OutChain = L.getValue(1);
4742   if (MemVT != VT)
4743     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4744 
4745   setValue(&I, L);
4746   DAG.setRoot(OutChain);
4747 }
4748 
4749 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4750   SDLoc dl = getCurSDLoc();
4751 
4752   AtomicOrdering Ordering = I.getOrdering();
4753   SyncScope::ID SSID = I.getSyncScopeID();
4754 
4755   SDValue InChain = getRoot();
4756 
4757   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4758   EVT MemVT =
4759       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4760 
4761   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4762     report_fatal_error("Cannot generate unaligned atomic store");
4763 
4764   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4765 
4766   MachineFunction &MF = DAG.getMachineFunction();
4767   MachineMemOperand *MMO =
4768     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4769                             MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4770                             nullptr, SSID, Ordering);
4771 
4772   SDValue Val = getValue(I.getValueOperand());
4773   if (Val.getValueType() != MemVT)
4774     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4775   SDValue Ptr = getValue(I.getPointerOperand());
4776 
4777   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4778     // TODO: Once this is better exercised by tests, it should be merged with
4779     // the normal path for stores to prevent future divergence.
4780     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4781     DAG.setRoot(S);
4782     return;
4783   }
4784   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4785                                    Ptr, Val, MMO);
4786 
4787 
4788   DAG.setRoot(OutChain);
4789 }
4790 
4791 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4792 /// node.
4793 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4794                                                unsigned Intrinsic) {
4795   // Ignore the callsite's attributes. A specific call site may be marked with
4796   // readnone, but the lowering code will expect the chain based on the
4797   // definition.
4798   const Function *F = I.getCalledFunction();
4799   bool HasChain = !F->doesNotAccessMemory();
4800   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4801 
4802   // Build the operand list.
4803   SmallVector<SDValue, 8> Ops;
4804   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4805     if (OnlyLoad) {
4806       // We don't need to serialize loads against other loads.
4807       Ops.push_back(DAG.getRoot());
4808     } else {
4809       Ops.push_back(getRoot());
4810     }
4811   }
4812 
4813   // Info is set by getTgtMemInstrinsic
4814   TargetLowering::IntrinsicInfo Info;
4815   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4816   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4817                                                DAG.getMachineFunction(),
4818                                                Intrinsic);
4819 
4820   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4821   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4822       Info.opc == ISD::INTRINSIC_W_CHAIN)
4823     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4824                                         TLI.getPointerTy(DAG.getDataLayout())));
4825 
4826   // Add all operands of the call to the operand list.
4827   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4828     const Value *Arg = I.getArgOperand(i);
4829     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4830       Ops.push_back(getValue(Arg));
4831       continue;
4832     }
4833 
4834     // Use TargetConstant instead of a regular constant for immarg.
4835     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4836     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4837       assert(CI->getBitWidth() <= 64 &&
4838              "large intrinsic immediates not handled");
4839       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4840     } else {
4841       Ops.push_back(
4842           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4843     }
4844   }
4845 
4846   SmallVector<EVT, 4> ValueVTs;
4847   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4848 
4849   if (HasChain)
4850     ValueVTs.push_back(MVT::Other);
4851 
4852   SDVTList VTs = DAG.getVTList(ValueVTs);
4853 
4854   // Create the node.
4855   SDValue Result;
4856   if (IsTgtIntrinsic) {
4857     // This is target intrinsic that touches memory
4858     AAMDNodes AAInfo;
4859     I.getAAMetadata(AAInfo);
4860     Result = DAG.getMemIntrinsicNode(
4861         Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4862         MachinePointerInfo(Info.ptrVal, Info.offset),
4863         Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
4864   } else if (!HasChain) {
4865     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4866   } else if (!I.getType()->isVoidTy()) {
4867     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4868   } else {
4869     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4870   }
4871 
4872   if (HasChain) {
4873     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4874     if (OnlyLoad)
4875       PendingLoads.push_back(Chain);
4876     else
4877       DAG.setRoot(Chain);
4878   }
4879 
4880   if (!I.getType()->isVoidTy()) {
4881     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4882       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4883       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4884     } else
4885       Result = lowerRangeToAssertZExt(DAG, I, Result);
4886 
4887     setValue(&I, Result);
4888   }
4889 }
4890 
4891 /// GetSignificand - Get the significand and build it into a floating-point
4892 /// number with exponent of 1:
4893 ///
4894 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4895 ///
4896 /// where Op is the hexadecimal representation of floating point value.
4897 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4898   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4899                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4900   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4901                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4902   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4903 }
4904 
4905 /// GetExponent - Get the exponent:
4906 ///
4907 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4908 ///
4909 /// where Op is the hexadecimal representation of floating point value.
4910 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4911                            const TargetLowering &TLI, const SDLoc &dl) {
4912   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4913                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4914   SDValue t1 = DAG.getNode(
4915       ISD::SRL, dl, MVT::i32, t0,
4916       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4917   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4918                            DAG.getConstant(127, dl, MVT::i32));
4919   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4920 }
4921 
4922 /// getF32Constant - Get 32-bit floating point constant.
4923 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4924                               const SDLoc &dl) {
4925   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4926                            MVT::f32);
4927 }
4928 
4929 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4930                                        SelectionDAG &DAG) {
4931   // TODO: What fast-math-flags should be set on the floating-point nodes?
4932 
4933   //   IntegerPartOfX = ((int32_t)(t0);
4934   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4935 
4936   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4937   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4938   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4939 
4940   //   IntegerPartOfX <<= 23;
4941   IntegerPartOfX = DAG.getNode(
4942       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4943       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4944                                   DAG.getDataLayout())));
4945 
4946   SDValue TwoToFractionalPartOfX;
4947   if (LimitFloatPrecision <= 6) {
4948     // For floating-point precision of 6:
4949     //
4950     //   TwoToFractionalPartOfX =
4951     //     0.997535578f +
4952     //       (0.735607626f + 0.252464424f * x) * x;
4953     //
4954     // error 0.0144103317, which is 6 bits
4955     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4956                              getF32Constant(DAG, 0x3e814304, dl));
4957     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4958                              getF32Constant(DAG, 0x3f3c50c8, dl));
4959     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4960     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4961                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4962   } else if (LimitFloatPrecision <= 12) {
4963     // For floating-point precision of 12:
4964     //
4965     //   TwoToFractionalPartOfX =
4966     //     0.999892986f +
4967     //       (0.696457318f +
4968     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4969     //
4970     // error 0.000107046256, which is 13 to 14 bits
4971     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4972                              getF32Constant(DAG, 0x3da235e3, dl));
4973     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4974                              getF32Constant(DAG, 0x3e65b8f3, dl));
4975     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4976     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4977                              getF32Constant(DAG, 0x3f324b07, dl));
4978     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4979     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4980                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4981   } else { // LimitFloatPrecision <= 18
4982     // For floating-point precision of 18:
4983     //
4984     //   TwoToFractionalPartOfX =
4985     //     0.999999982f +
4986     //       (0.693148872f +
4987     //         (0.240227044f +
4988     //           (0.554906021e-1f +
4989     //             (0.961591928e-2f +
4990     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4991     // error 2.47208000*10^(-7), which is better than 18 bits
4992     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4993                              getF32Constant(DAG, 0x3924b03e, dl));
4994     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4995                              getF32Constant(DAG, 0x3ab24b87, dl));
4996     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4997     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4998                              getF32Constant(DAG, 0x3c1d8c17, dl));
4999     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5000     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5001                              getF32Constant(DAG, 0x3d634a1d, dl));
5002     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5003     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5004                              getF32Constant(DAG, 0x3e75fe14, dl));
5005     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5006     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5007                               getF32Constant(DAG, 0x3f317234, dl));
5008     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5009     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5010                                          getF32Constant(DAG, 0x3f800000, dl));
5011   }
5012 
5013   // Add the exponent into the result in integer domain.
5014   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5015   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5016                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5017 }
5018 
5019 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5020 /// limited-precision mode.
5021 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5022                          const TargetLowering &TLI) {
5023   if (Op.getValueType() == MVT::f32 &&
5024       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5025 
5026     // Put the exponent in the right bit position for later addition to the
5027     // final result:
5028     //
5029     // t0 = Op * log2(e)
5030 
5031     // TODO: What fast-math-flags should be set here?
5032     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5033                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5034     return getLimitedPrecisionExp2(t0, dl, DAG);
5035   }
5036 
5037   // No special expansion.
5038   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
5039 }
5040 
5041 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5042 /// limited-precision mode.
5043 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5044                          const TargetLowering &TLI) {
5045   // TODO: What fast-math-flags should be set on the floating-point nodes?
5046 
5047   if (Op.getValueType() == MVT::f32 &&
5048       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5049     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5050 
5051     // Scale the exponent by log(2).
5052     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5053     SDValue LogOfExponent =
5054         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5055                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5056 
5057     // Get the significand and build it into a floating-point number with
5058     // exponent of 1.
5059     SDValue X = GetSignificand(DAG, Op1, dl);
5060 
5061     SDValue LogOfMantissa;
5062     if (LimitFloatPrecision <= 6) {
5063       // For floating-point precision of 6:
5064       //
5065       //   LogofMantissa =
5066       //     -1.1609546f +
5067       //       (1.4034025f - 0.23903021f * x) * x;
5068       //
5069       // error 0.0034276066, which is better than 8 bits
5070       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5071                                getF32Constant(DAG, 0xbe74c456, dl));
5072       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5073                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5074       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5075       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5076                                   getF32Constant(DAG, 0x3f949a29, dl));
5077     } else if (LimitFloatPrecision <= 12) {
5078       // For floating-point precision of 12:
5079       //
5080       //   LogOfMantissa =
5081       //     -1.7417939f +
5082       //       (2.8212026f +
5083       //         (-1.4699568f +
5084       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5085       //
5086       // error 0.000061011436, which is 14 bits
5087       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5088                                getF32Constant(DAG, 0xbd67b6d6, dl));
5089       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5090                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5091       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5092       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5093                                getF32Constant(DAG, 0x3fbc278b, dl));
5094       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5095       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5096                                getF32Constant(DAG, 0x40348e95, dl));
5097       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5098       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5099                                   getF32Constant(DAG, 0x3fdef31a, dl));
5100     } else { // LimitFloatPrecision <= 18
5101       // For floating-point precision of 18:
5102       //
5103       //   LogOfMantissa =
5104       //     -2.1072184f +
5105       //       (4.2372794f +
5106       //         (-3.7029485f +
5107       //           (2.2781945f +
5108       //             (-0.87823314f +
5109       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5110       //
5111       // error 0.0000023660568, which is better than 18 bits
5112       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5113                                getF32Constant(DAG, 0xbc91e5ac, dl));
5114       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5115                                getF32Constant(DAG, 0x3e4350aa, dl));
5116       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5117       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5118                                getF32Constant(DAG, 0x3f60d3e3, dl));
5119       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5120       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5121                                getF32Constant(DAG, 0x4011cdf0, dl));
5122       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5123       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5124                                getF32Constant(DAG, 0x406cfd1c, dl));
5125       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5126       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5127                                getF32Constant(DAG, 0x408797cb, dl));
5128       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5129       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5130                                   getF32Constant(DAG, 0x4006dcab, dl));
5131     }
5132 
5133     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5134   }
5135 
5136   // No special expansion.
5137   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5138 }
5139 
5140 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5141 /// limited-precision mode.
5142 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5143                           const TargetLowering &TLI) {
5144   // TODO: What fast-math-flags should be set on the floating-point nodes?
5145 
5146   if (Op.getValueType() == MVT::f32 &&
5147       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5148     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5149 
5150     // Get the exponent.
5151     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5152 
5153     // Get the significand and build it into a floating-point number with
5154     // exponent of 1.
5155     SDValue X = GetSignificand(DAG, Op1, dl);
5156 
5157     // Different possible minimax approximations of significand in
5158     // floating-point for various degrees of accuracy over [1,2].
5159     SDValue Log2ofMantissa;
5160     if (LimitFloatPrecision <= 6) {
5161       // For floating-point precision of 6:
5162       //
5163       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5164       //
5165       // error 0.0049451742, which is more than 7 bits
5166       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5167                                getF32Constant(DAG, 0xbeb08fe0, dl));
5168       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5169                                getF32Constant(DAG, 0x40019463, dl));
5170       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5171       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5172                                    getF32Constant(DAG, 0x3fd6633d, dl));
5173     } else if (LimitFloatPrecision <= 12) {
5174       // For floating-point precision of 12:
5175       //
5176       //   Log2ofMantissa =
5177       //     -2.51285454f +
5178       //       (4.07009056f +
5179       //         (-2.12067489f +
5180       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5181       //
5182       // error 0.0000876136000, which is better than 13 bits
5183       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5184                                getF32Constant(DAG, 0xbda7262e, dl));
5185       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5186                                getF32Constant(DAG, 0x3f25280b, dl));
5187       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5188       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5189                                getF32Constant(DAG, 0x4007b923, dl));
5190       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5191       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5192                                getF32Constant(DAG, 0x40823e2f, dl));
5193       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5194       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5195                                    getF32Constant(DAG, 0x4020d29c, dl));
5196     } else { // LimitFloatPrecision <= 18
5197       // For floating-point precision of 18:
5198       //
5199       //   Log2ofMantissa =
5200       //     -3.0400495f +
5201       //       (6.1129976f +
5202       //         (-5.3420409f +
5203       //           (3.2865683f +
5204       //             (-1.2669343f +
5205       //               (0.27515199f -
5206       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5207       //
5208       // error 0.0000018516, which is better than 18 bits
5209       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5210                                getF32Constant(DAG, 0xbcd2769e, dl));
5211       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5212                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5213       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5214       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5215                                getF32Constant(DAG, 0x3fa22ae7, dl));
5216       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5217       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5218                                getF32Constant(DAG, 0x40525723, dl));
5219       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5220       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5221                                getF32Constant(DAG, 0x40aaf200, dl));
5222       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5223       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5224                                getF32Constant(DAG, 0x40c39dad, dl));
5225       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5226       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5227                                    getF32Constant(DAG, 0x4042902c, dl));
5228     }
5229 
5230     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5231   }
5232 
5233   // No special expansion.
5234   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5235 }
5236 
5237 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5238 /// limited-precision mode.
5239 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5240                            const TargetLowering &TLI) {
5241   // TODO: What fast-math-flags should be set on the floating-point nodes?
5242 
5243   if (Op.getValueType() == MVT::f32 &&
5244       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5245     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5246 
5247     // Scale the exponent by log10(2) [0.30102999f].
5248     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5249     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5250                                         getF32Constant(DAG, 0x3e9a209a, dl));
5251 
5252     // Get the significand and build it into a floating-point number with
5253     // exponent of 1.
5254     SDValue X = GetSignificand(DAG, Op1, dl);
5255 
5256     SDValue Log10ofMantissa;
5257     if (LimitFloatPrecision <= 6) {
5258       // For floating-point precision of 6:
5259       //
5260       //   Log10ofMantissa =
5261       //     -0.50419619f +
5262       //       (0.60948995f - 0.10380950f * x) * x;
5263       //
5264       // error 0.0014886165, which is 6 bits
5265       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5266                                getF32Constant(DAG, 0xbdd49a13, dl));
5267       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5268                                getF32Constant(DAG, 0x3f1c0789, dl));
5269       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5270       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5271                                     getF32Constant(DAG, 0x3f011300, dl));
5272     } else if (LimitFloatPrecision <= 12) {
5273       // For floating-point precision of 12:
5274       //
5275       //   Log10ofMantissa =
5276       //     -0.64831180f +
5277       //       (0.91751397f +
5278       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5279       //
5280       // error 0.00019228036, which is better than 12 bits
5281       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5282                                getF32Constant(DAG, 0x3d431f31, dl));
5283       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5284                                getF32Constant(DAG, 0x3ea21fb2, dl));
5285       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5286       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5287                                getF32Constant(DAG, 0x3f6ae232, dl));
5288       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5289       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5290                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5291     } else { // LimitFloatPrecision <= 18
5292       // For floating-point precision of 18:
5293       //
5294       //   Log10ofMantissa =
5295       //     -0.84299375f +
5296       //       (1.5327582f +
5297       //         (-1.0688956f +
5298       //           (0.49102474f +
5299       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5300       //
5301       // error 0.0000037995730, which is better than 18 bits
5302       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5303                                getF32Constant(DAG, 0x3c5d51ce, dl));
5304       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5305                                getF32Constant(DAG, 0x3e00685a, dl));
5306       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5307       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5308                                getF32Constant(DAG, 0x3efb6798, dl));
5309       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5310       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5311                                getF32Constant(DAG, 0x3f88d192, dl));
5312       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5313       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5314                                getF32Constant(DAG, 0x3fc4316c, dl));
5315       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5316       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5317                                     getF32Constant(DAG, 0x3f57ce70, dl));
5318     }
5319 
5320     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5321   }
5322 
5323   // No special expansion.
5324   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5325 }
5326 
5327 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5328 /// limited-precision mode.
5329 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5330                           const TargetLowering &TLI) {
5331   if (Op.getValueType() == MVT::f32 &&
5332       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5333     return getLimitedPrecisionExp2(Op, dl, DAG);
5334 
5335   // No special expansion.
5336   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5337 }
5338 
5339 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5340 /// limited-precision mode with x == 10.0f.
5341 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5342                          SelectionDAG &DAG, const TargetLowering &TLI) {
5343   bool IsExp10 = false;
5344   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5345       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5346     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5347       APFloat Ten(10.0f);
5348       IsExp10 = LHSC->isExactlyValue(Ten);
5349     }
5350   }
5351 
5352   // TODO: What fast-math-flags should be set on the FMUL node?
5353   if (IsExp10) {
5354     // Put the exponent in the right bit position for later addition to the
5355     // final result:
5356     //
5357     //   #define LOG2OF10 3.3219281f
5358     //   t0 = Op * LOG2OF10;
5359     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5360                              getF32Constant(DAG, 0x40549a78, dl));
5361     return getLimitedPrecisionExp2(t0, dl, DAG);
5362   }
5363 
5364   // No special expansion.
5365   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5366 }
5367 
5368 /// ExpandPowI - Expand a llvm.powi intrinsic.
5369 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5370                           SelectionDAG &DAG) {
5371   // If RHS is a constant, we can expand this out to a multiplication tree,
5372   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5373   // optimizing for size, we only want to do this if the expansion would produce
5374   // a small number of multiplies, otherwise we do the full expansion.
5375   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5376     // Get the exponent as a positive value.
5377     unsigned Val = RHSC->getSExtValue();
5378     if ((int)Val < 0) Val = -Val;
5379 
5380     // powi(x, 0) -> 1.0
5381     if (Val == 0)
5382       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5383 
5384     bool OptForSize = DAG.shouldOptForSize();
5385     if (!OptForSize ||
5386         // If optimizing for size, don't insert too many multiplies.
5387         // This inserts up to 5 multiplies.
5388         countPopulation(Val) + Log2_32(Val) < 7) {
5389       // We use the simple binary decomposition method to generate the multiply
5390       // sequence.  There are more optimal ways to do this (for example,
5391       // powi(x,15) generates one more multiply than it should), but this has
5392       // the benefit of being both really simple and much better than a libcall.
5393       SDValue Res;  // Logically starts equal to 1.0
5394       SDValue CurSquare = LHS;
5395       // TODO: Intrinsics should have fast-math-flags that propagate to these
5396       // nodes.
5397       while (Val) {
5398         if (Val & 1) {
5399           if (Res.getNode())
5400             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5401           else
5402             Res = CurSquare;  // 1.0*CurSquare.
5403         }
5404 
5405         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5406                                 CurSquare, CurSquare);
5407         Val >>= 1;
5408       }
5409 
5410       // If the original was negative, invert the result, producing 1/(x*x*x).
5411       if (RHSC->getSExtValue() < 0)
5412         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5413                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5414       return Res;
5415     }
5416   }
5417 
5418   // Otherwise, expand to a libcall.
5419   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5420 }
5421 
5422 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5423                             SDValue LHS, SDValue RHS, SDValue Scale,
5424                             SelectionDAG &DAG, const TargetLowering &TLI) {
5425   EVT VT = LHS.getValueType();
5426   bool Signed = Opcode == ISD::SDIVFIX;
5427   LLVMContext &Ctx = *DAG.getContext();
5428 
5429   // If the type is legal but the operation isn't, this node might survive all
5430   // the way to operation legalization. If we end up there and we do not have
5431   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5432   // node.
5433 
5434   // Coax the legalizer into expanding the node during type legalization instead
5435   // by bumping the size by one bit. This will force it to Promote, enabling the
5436   // early expansion and avoiding the need to expand later.
5437 
5438   // We don't have to do this if Scale is 0; that can always be expanded.
5439 
5440   // FIXME: We wouldn't have to do this (or any of the early
5441   // expansion/promotion) if it was possible to expand a libcall of an
5442   // illegal type during operation legalization. But it's not, so things
5443   // get a bit hacky.
5444   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5445   if (ScaleInt > 0 &&
5446       (TLI.isTypeLegal(VT) ||
5447        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5448     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5449         Opcode, VT, ScaleInt);
5450     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5451       EVT PromVT;
5452       if (VT.isScalarInteger())
5453         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5454       else if (VT.isVector()) {
5455         PromVT = VT.getVectorElementType();
5456         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5457         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5458       } else
5459         llvm_unreachable("Wrong VT for DIVFIX?");
5460       if (Signed) {
5461         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5462         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5463       } else {
5464         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5465         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5466       }
5467       // TODO: Saturation.
5468       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5469       return DAG.getZExtOrTrunc(Res, DL, VT);
5470     }
5471   }
5472 
5473   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5474 }
5475 
5476 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5477 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5478 static void
5479 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5480                      const SDValue &N) {
5481   switch (N.getOpcode()) {
5482   case ISD::CopyFromReg: {
5483     SDValue Op = N.getOperand(1);
5484     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5485                       Op.getValueType().getSizeInBits());
5486     return;
5487   }
5488   case ISD::BITCAST:
5489   case ISD::AssertZext:
5490   case ISD::AssertSext:
5491   case ISD::TRUNCATE:
5492     getUnderlyingArgRegs(Regs, N.getOperand(0));
5493     return;
5494   case ISD::BUILD_PAIR:
5495   case ISD::BUILD_VECTOR:
5496   case ISD::CONCAT_VECTORS:
5497     for (SDValue Op : N->op_values())
5498       getUnderlyingArgRegs(Regs, Op);
5499     return;
5500   default:
5501     return;
5502   }
5503 }
5504 
5505 /// If the DbgValueInst is a dbg_value of a function argument, create the
5506 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5507 /// instruction selection, they will be inserted to the entry BB.
5508 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5509     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5510     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5511   const Argument *Arg = dyn_cast<Argument>(V);
5512   if (!Arg)
5513     return false;
5514 
5515   if (!IsDbgDeclare) {
5516     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5517     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5518     // the entry block.
5519     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5520     if (!IsInEntryBlock)
5521       return false;
5522 
5523     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5524     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5525     // variable that also is a param.
5526     //
5527     // Although, if we are at the top of the entry block already, we can still
5528     // emit using ArgDbgValue. This might catch some situations when the
5529     // dbg.value refers to an argument that isn't used in the entry block, so
5530     // any CopyToReg node would be optimized out and the only way to express
5531     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5532     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5533     // we should only emit as ArgDbgValue if the Variable is an argument to the
5534     // current function, and the dbg.value intrinsic is found in the entry
5535     // block.
5536     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5537         !DL->getInlinedAt();
5538     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5539     if (!IsInPrologue && !VariableIsFunctionInputArg)
5540       return false;
5541 
5542     // Here we assume that a function argument on IR level only can be used to
5543     // describe one input parameter on source level. If we for example have
5544     // source code like this
5545     //
5546     //    struct A { long x, y; };
5547     //    void foo(struct A a, long b) {
5548     //      ...
5549     //      b = a.x;
5550     //      ...
5551     //    }
5552     //
5553     // and IR like this
5554     //
5555     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5556     //  entry:
5557     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5558     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5559     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5560     //    ...
5561     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5562     //    ...
5563     //
5564     // then the last dbg.value is describing a parameter "b" using a value that
5565     // is an argument. But since we already has used %a1 to describe a parameter
5566     // we should not handle that last dbg.value here (that would result in an
5567     // incorrect hoisting of the DBG_VALUE to the function entry).
5568     // Notice that we allow one dbg.value per IR level argument, to accommodate
5569     // for the situation with fragments above.
5570     if (VariableIsFunctionInputArg) {
5571       unsigned ArgNo = Arg->getArgNo();
5572       if (ArgNo >= FuncInfo.DescribedArgs.size())
5573         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5574       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5575         return false;
5576       FuncInfo.DescribedArgs.set(ArgNo);
5577     }
5578   }
5579 
5580   MachineFunction &MF = DAG.getMachineFunction();
5581   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5582 
5583   Optional<MachineOperand> Op;
5584   // Some arguments' frame index is recorded during argument lowering.
5585   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5586   if (FI != std::numeric_limits<int>::max())
5587     Op = MachineOperand::CreateFI(FI);
5588 
5589   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5590   if (!Op && N.getNode()) {
5591     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5592     Register Reg;
5593     if (ArgRegsAndSizes.size() == 1)
5594       Reg = ArgRegsAndSizes.front().first;
5595 
5596     if (Reg && Reg.isVirtual()) {
5597       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5598       Register PR = RegInfo.getLiveInPhysReg(Reg);
5599       if (PR)
5600         Reg = PR;
5601     }
5602     if (Reg) {
5603       Op = MachineOperand::CreateReg(Reg, false);
5604     }
5605   }
5606 
5607   if (!Op && N.getNode()) {
5608     // Check if frame index is available.
5609     SDValue LCandidate = peekThroughBitcasts(N);
5610     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5611       if (FrameIndexSDNode *FINode =
5612           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5613         Op = MachineOperand::CreateFI(FINode->getIndex());
5614   }
5615 
5616   if (!Op) {
5617     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5618     auto splitMultiRegDbgValue
5619       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5620       unsigned Offset = 0;
5621       for (auto RegAndSize : SplitRegs) {
5622         // If the expression is already a fragment, the current register
5623         // offset+size might extend beyond the fragment. In this case, only
5624         // the register bits that are inside the fragment are relevant.
5625         int RegFragmentSizeInBits = RegAndSize.second;
5626         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5627           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5628           // The register is entirely outside the expression fragment,
5629           // so is irrelevant for debug info.
5630           if (Offset >= ExprFragmentSizeInBits)
5631             break;
5632           // The register is partially outside the expression fragment, only
5633           // the low bits within the fragment are relevant for debug info.
5634           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5635             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5636           }
5637         }
5638 
5639         auto FragmentExpr = DIExpression::createFragmentExpression(
5640             Expr, Offset, RegFragmentSizeInBits);
5641         Offset += RegAndSize.second;
5642         // If a valid fragment expression cannot be created, the variable's
5643         // correct value cannot be determined and so it is set as Undef.
5644         if (!FragmentExpr) {
5645           SDDbgValue *SDV = DAG.getConstantDbgValue(
5646               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5647           DAG.AddDbgValue(SDV, nullptr, false);
5648           continue;
5649         }
5650         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5651         FuncInfo.ArgDbgValues.push_back(
5652           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5653                   RegAndSize.first, Variable, *FragmentExpr));
5654       }
5655     };
5656 
5657     // Check if ValueMap has reg number.
5658     DenseMap<const Value *, unsigned>::const_iterator
5659       VMI = FuncInfo.ValueMap.find(V);
5660     if (VMI != FuncInfo.ValueMap.end()) {
5661       const auto &TLI = DAG.getTargetLoweringInfo();
5662       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5663                        V->getType(), getABIRegCopyCC(V));
5664       if (RFV.occupiesMultipleRegs()) {
5665         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5666         return true;
5667       }
5668 
5669       Op = MachineOperand::CreateReg(VMI->second, false);
5670     } else if (ArgRegsAndSizes.size() > 1) {
5671       // This was split due to the calling convention, and no virtual register
5672       // mapping exists for the value.
5673       splitMultiRegDbgValue(ArgRegsAndSizes);
5674       return true;
5675     }
5676   }
5677 
5678   if (!Op)
5679     return false;
5680 
5681   assert(Variable->isValidLocationForIntrinsic(DL) &&
5682          "Expected inlined-at fields to agree");
5683 
5684   // If the argument arrives in a stack slot, then what the IR thought was a
5685   // normal Value is actually in memory, and we must add a deref to load it.
5686   if (Op->isFI()) {
5687     int FI = Op->getIndex();
5688     unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI);
5689     if (Expr->isImplicit()) {
5690       SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
5691       Expr = DIExpression::prependOpcodes(Expr, Ops);
5692     } else {
5693       Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
5694     }
5695   }
5696 
5697   // If this location was specified with a dbg.declare, then it and its
5698   // expression calculate the address of the variable. Append a deref to
5699   // force it to be a memory location.
5700   if (IsDbgDeclare)
5701     Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref});
5702 
5703   FuncInfo.ArgDbgValues.push_back(
5704       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5705               *Op, Variable, Expr));
5706 
5707   return true;
5708 }
5709 
5710 /// Return the appropriate SDDbgValue based on N.
5711 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5712                                              DILocalVariable *Variable,
5713                                              DIExpression *Expr,
5714                                              const DebugLoc &dl,
5715                                              unsigned DbgSDNodeOrder) {
5716   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5717     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5718     // stack slot locations.
5719     //
5720     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5721     // debug values here after optimization:
5722     //
5723     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5724     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5725     //
5726     // Both describe the direct values of their associated variables.
5727     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5728                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5729   }
5730   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5731                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5732 }
5733 
5734 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5735   switch (Intrinsic) {
5736   case Intrinsic::smul_fix:
5737     return ISD::SMULFIX;
5738   case Intrinsic::umul_fix:
5739     return ISD::UMULFIX;
5740   case Intrinsic::smul_fix_sat:
5741     return ISD::SMULFIXSAT;
5742   case Intrinsic::umul_fix_sat:
5743     return ISD::UMULFIXSAT;
5744   case Intrinsic::sdiv_fix:
5745     return ISD::SDIVFIX;
5746   case Intrinsic::udiv_fix:
5747     return ISD::UDIVFIX;
5748   default:
5749     llvm_unreachable("Unhandled fixed point intrinsic");
5750   }
5751 }
5752 
5753 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5754                                            const char *FunctionName) {
5755   assert(FunctionName && "FunctionName must not be nullptr");
5756   SDValue Callee = DAG.getExternalSymbol(
5757       FunctionName,
5758       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5759   LowerCallTo(&I, Callee, I.isTailCall());
5760 }
5761 
5762 /// Lower the call to the specified intrinsic function.
5763 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5764                                              unsigned Intrinsic) {
5765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5766   SDLoc sdl = getCurSDLoc();
5767   DebugLoc dl = getCurDebugLoc();
5768   SDValue Res;
5769 
5770   switch (Intrinsic) {
5771   default:
5772     // By default, turn this into a target intrinsic node.
5773     visitTargetIntrinsic(I, Intrinsic);
5774     return;
5775   case Intrinsic::vastart:  visitVAStart(I); return;
5776   case Intrinsic::vaend:    visitVAEnd(I); return;
5777   case Intrinsic::vacopy:   visitVACopy(I); return;
5778   case Intrinsic::returnaddress:
5779     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5780                              TLI.getPointerTy(DAG.getDataLayout()),
5781                              getValue(I.getArgOperand(0))));
5782     return;
5783   case Intrinsic::addressofreturnaddress:
5784     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5785                              TLI.getPointerTy(DAG.getDataLayout())));
5786     return;
5787   case Intrinsic::sponentry:
5788     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5789                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5790     return;
5791   case Intrinsic::frameaddress:
5792     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5793                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5794                              getValue(I.getArgOperand(0))));
5795     return;
5796   case Intrinsic::read_register: {
5797     Value *Reg = I.getArgOperand(0);
5798     SDValue Chain = getRoot();
5799     SDValue RegName =
5800         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5801     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5802     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5803       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5804     setValue(&I, Res);
5805     DAG.setRoot(Res.getValue(1));
5806     return;
5807   }
5808   case Intrinsic::write_register: {
5809     Value *Reg = I.getArgOperand(0);
5810     Value *RegValue = I.getArgOperand(1);
5811     SDValue Chain = getRoot();
5812     SDValue RegName =
5813         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5814     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5815                             RegName, getValue(RegValue)));
5816     return;
5817   }
5818   case Intrinsic::memcpy: {
5819     const auto &MCI = cast<MemCpyInst>(I);
5820     SDValue Op1 = getValue(I.getArgOperand(0));
5821     SDValue Op2 = getValue(I.getArgOperand(1));
5822     SDValue Op3 = getValue(I.getArgOperand(2));
5823     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5824     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5825     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5826     unsigned Align = MinAlign(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 Root = isVol ? getRoot() : getMemoryRoot();
5832     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Align, isVol,
5833                                false, isTC,
5834                                MachinePointerInfo(I.getArgOperand(0)),
5835                                MachinePointerInfo(I.getArgOperand(1)));
5836     updateDAGForMaybeTailCall(MC);
5837     return;
5838   }
5839   case Intrinsic::memset: {
5840     const auto &MSI = cast<MemSetInst>(I);
5841     SDValue Op1 = getValue(I.getArgOperand(0));
5842     SDValue Op2 = getValue(I.getArgOperand(1));
5843     SDValue Op3 = getValue(I.getArgOperand(2));
5844     // @llvm.memset defines 0 and 1 to both mean no alignment.
5845     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5846     bool isVol = MSI.isVolatile();
5847     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5848     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5849     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Align, isVol,
5850                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5851     updateDAGForMaybeTailCall(MS);
5852     return;
5853   }
5854   case Intrinsic::memmove: {
5855     const auto &MMI = cast<MemMoveInst>(I);
5856     SDValue Op1 = getValue(I.getArgOperand(0));
5857     SDValue Op2 = getValue(I.getArgOperand(1));
5858     SDValue Op3 = getValue(I.getArgOperand(2));
5859     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5860     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5861     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5862     unsigned Align = MinAlign(DstAlign, SrcAlign);
5863     bool isVol = MMI.isVolatile();
5864     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5865     // FIXME: Support passing different dest/src alignments to the memmove DAG
5866     // node.
5867     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5868     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Align, isVol,
5869                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5870                                 MachinePointerInfo(I.getArgOperand(1)));
5871     updateDAGForMaybeTailCall(MM);
5872     return;
5873   }
5874   case Intrinsic::memcpy_element_unordered_atomic: {
5875     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5876     SDValue Dst = getValue(MI.getRawDest());
5877     SDValue Src = getValue(MI.getRawSource());
5878     SDValue Length = getValue(MI.getLength());
5879 
5880     unsigned DstAlign = MI.getDestAlignment();
5881     unsigned SrcAlign = MI.getSourceAlignment();
5882     Type *LengthTy = MI.getLength()->getType();
5883     unsigned ElemSz = MI.getElementSizeInBytes();
5884     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5885     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5886                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5887                                      MachinePointerInfo(MI.getRawDest()),
5888                                      MachinePointerInfo(MI.getRawSource()));
5889     updateDAGForMaybeTailCall(MC);
5890     return;
5891   }
5892   case Intrinsic::memmove_element_unordered_atomic: {
5893     auto &MI = cast<AtomicMemMoveInst>(I);
5894     SDValue Dst = getValue(MI.getRawDest());
5895     SDValue Src = getValue(MI.getRawSource());
5896     SDValue Length = getValue(MI.getLength());
5897 
5898     unsigned DstAlign = MI.getDestAlignment();
5899     unsigned SrcAlign = MI.getSourceAlignment();
5900     Type *LengthTy = MI.getLength()->getType();
5901     unsigned ElemSz = MI.getElementSizeInBytes();
5902     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5903     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5904                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5905                                       MachinePointerInfo(MI.getRawDest()),
5906                                       MachinePointerInfo(MI.getRawSource()));
5907     updateDAGForMaybeTailCall(MC);
5908     return;
5909   }
5910   case Intrinsic::memset_element_unordered_atomic: {
5911     auto &MI = cast<AtomicMemSetInst>(I);
5912     SDValue Dst = getValue(MI.getRawDest());
5913     SDValue Val = getValue(MI.getValue());
5914     SDValue Length = getValue(MI.getLength());
5915 
5916     unsigned DstAlign = MI.getDestAlignment();
5917     Type *LengthTy = MI.getLength()->getType();
5918     unsigned ElemSz = MI.getElementSizeInBytes();
5919     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5920     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5921                                      LengthTy, ElemSz, isTC,
5922                                      MachinePointerInfo(MI.getRawDest()));
5923     updateDAGForMaybeTailCall(MC);
5924     return;
5925   }
5926   case Intrinsic::dbg_addr:
5927   case Intrinsic::dbg_declare: {
5928     const auto &DI = cast<DbgVariableIntrinsic>(I);
5929     DILocalVariable *Variable = DI.getVariable();
5930     DIExpression *Expression = DI.getExpression();
5931     dropDanglingDebugInfo(Variable, Expression);
5932     assert(Variable && "Missing variable");
5933 
5934     // Check if address has undef value.
5935     const Value *Address = DI.getVariableLocation();
5936     if (!Address || isa<UndefValue>(Address) ||
5937         (Address->use_empty() && !isa<Argument>(Address))) {
5938       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5939       return;
5940     }
5941 
5942     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5943 
5944     // Check if this variable can be described by a frame index, typically
5945     // either as a static alloca or a byval parameter.
5946     int FI = std::numeric_limits<int>::max();
5947     if (const auto *AI =
5948             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5949       if (AI->isStaticAlloca()) {
5950         auto I = FuncInfo.StaticAllocaMap.find(AI);
5951         if (I != FuncInfo.StaticAllocaMap.end())
5952           FI = I->second;
5953       }
5954     } else if (const auto *Arg = dyn_cast<Argument>(
5955                    Address->stripInBoundsConstantOffsets())) {
5956       FI = FuncInfo.getArgumentFrameIndex(Arg);
5957     }
5958 
5959     // llvm.dbg.addr is control dependent and always generates indirect
5960     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5961     // the MachineFunction variable table.
5962     if (FI != std::numeric_limits<int>::max()) {
5963       if (Intrinsic == Intrinsic::dbg_addr) {
5964         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5965             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5966         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5967       }
5968       return;
5969     }
5970 
5971     SDValue &N = NodeMap[Address];
5972     if (!N.getNode() && isa<Argument>(Address))
5973       // Check unused arguments map.
5974       N = UnusedArgNodeMap[Address];
5975     SDDbgValue *SDV;
5976     if (N.getNode()) {
5977       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5978         Address = BCI->getOperand(0);
5979       // Parameters are handled specially.
5980       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5981       if (isParameter && FINode) {
5982         // Byval parameter. We have a frame index at this point.
5983         SDV =
5984             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5985                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5986       } else if (isa<Argument>(Address)) {
5987         // Address is an argument, so try to emit its dbg value using
5988         // virtual register info from the FuncInfo.ValueMap.
5989         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5990         return;
5991       } else {
5992         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5993                               true, dl, SDNodeOrder);
5994       }
5995       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5996     } else {
5997       // If Address is an argument then try to emit its dbg value using
5998       // virtual register info from the FuncInfo.ValueMap.
5999       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6000                                     N)) {
6001         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
6002       }
6003     }
6004     return;
6005   }
6006   case Intrinsic::dbg_label: {
6007     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6008     DILabel *Label = DI.getLabel();
6009     assert(Label && "Missing label");
6010 
6011     SDDbgLabel *SDV;
6012     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6013     DAG.AddDbgLabel(SDV);
6014     return;
6015   }
6016   case Intrinsic::dbg_value: {
6017     const DbgValueInst &DI = cast<DbgValueInst>(I);
6018     assert(DI.getVariable() && "Missing variable");
6019 
6020     DILocalVariable *Variable = DI.getVariable();
6021     DIExpression *Expression = DI.getExpression();
6022     dropDanglingDebugInfo(Variable, Expression);
6023     const Value *V = DI.getValue();
6024     if (!V)
6025       return;
6026 
6027     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
6028         SDNodeOrder))
6029       return;
6030 
6031     // TODO: Dangling debug info will eventually either be resolved or produce
6032     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
6033     // between the original dbg.value location and its resolved DBG_VALUE, which
6034     // we should ideally fill with an extra Undef DBG_VALUE.
6035 
6036     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
6037     return;
6038   }
6039 
6040   case Intrinsic::eh_typeid_for: {
6041     // Find the type id for the given typeinfo.
6042     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6043     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6044     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6045     setValue(&I, Res);
6046     return;
6047   }
6048 
6049   case Intrinsic::eh_return_i32:
6050   case Intrinsic::eh_return_i64:
6051     DAG.getMachineFunction().setCallsEHReturn(true);
6052     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6053                             MVT::Other,
6054                             getControlRoot(),
6055                             getValue(I.getArgOperand(0)),
6056                             getValue(I.getArgOperand(1))));
6057     return;
6058   case Intrinsic::eh_unwind_init:
6059     DAG.getMachineFunction().setCallsUnwindInit(true);
6060     return;
6061   case Intrinsic::eh_dwarf_cfa:
6062     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6063                              TLI.getPointerTy(DAG.getDataLayout()),
6064                              getValue(I.getArgOperand(0))));
6065     return;
6066   case Intrinsic::eh_sjlj_callsite: {
6067     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6068     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6069     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6070     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6071 
6072     MMI.setCurrentCallSite(CI->getZExtValue());
6073     return;
6074   }
6075   case Intrinsic::eh_sjlj_functioncontext: {
6076     // Get and store the index of the function context.
6077     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6078     AllocaInst *FnCtx =
6079       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6080     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6081     MFI.setFunctionContextIndex(FI);
6082     return;
6083   }
6084   case Intrinsic::eh_sjlj_setjmp: {
6085     SDValue Ops[2];
6086     Ops[0] = getRoot();
6087     Ops[1] = getValue(I.getArgOperand(0));
6088     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6089                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6090     setValue(&I, Op.getValue(0));
6091     DAG.setRoot(Op.getValue(1));
6092     return;
6093   }
6094   case Intrinsic::eh_sjlj_longjmp:
6095     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6096                             getRoot(), getValue(I.getArgOperand(0))));
6097     return;
6098   case Intrinsic::eh_sjlj_setup_dispatch:
6099     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6100                             getRoot()));
6101     return;
6102   case Intrinsic::masked_gather:
6103     visitMaskedGather(I);
6104     return;
6105   case Intrinsic::masked_load:
6106     visitMaskedLoad(I);
6107     return;
6108   case Intrinsic::masked_scatter:
6109     visitMaskedScatter(I);
6110     return;
6111   case Intrinsic::masked_store:
6112     visitMaskedStore(I);
6113     return;
6114   case Intrinsic::masked_expandload:
6115     visitMaskedLoad(I, true /* IsExpanding */);
6116     return;
6117   case Intrinsic::masked_compressstore:
6118     visitMaskedStore(I, true /* IsCompressing */);
6119     return;
6120   case Intrinsic::powi:
6121     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6122                             getValue(I.getArgOperand(1)), DAG));
6123     return;
6124   case Intrinsic::log:
6125     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6126     return;
6127   case Intrinsic::log2:
6128     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6129     return;
6130   case Intrinsic::log10:
6131     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6132     return;
6133   case Intrinsic::exp:
6134     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6135     return;
6136   case Intrinsic::exp2:
6137     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6138     return;
6139   case Intrinsic::pow:
6140     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6141                            getValue(I.getArgOperand(1)), DAG, TLI));
6142     return;
6143   case Intrinsic::sqrt:
6144   case Intrinsic::fabs:
6145   case Intrinsic::sin:
6146   case Intrinsic::cos:
6147   case Intrinsic::floor:
6148   case Intrinsic::ceil:
6149   case Intrinsic::trunc:
6150   case Intrinsic::rint:
6151   case Intrinsic::nearbyint:
6152   case Intrinsic::round:
6153   case Intrinsic::canonicalize: {
6154     unsigned Opcode;
6155     switch (Intrinsic) {
6156     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6157     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6158     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6159     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6160     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6161     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6162     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6163     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6164     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6165     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6166     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6167     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6168     }
6169 
6170     setValue(&I, DAG.getNode(Opcode, sdl,
6171                              getValue(I.getArgOperand(0)).getValueType(),
6172                              getValue(I.getArgOperand(0))));
6173     return;
6174   }
6175   case Intrinsic::lround:
6176   case Intrinsic::llround:
6177   case Intrinsic::lrint:
6178   case Intrinsic::llrint: {
6179     unsigned Opcode;
6180     switch (Intrinsic) {
6181     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6182     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6183     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6184     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6185     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6186     }
6187 
6188     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6189     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6190                              getValue(I.getArgOperand(0))));
6191     return;
6192   }
6193   case Intrinsic::minnum:
6194     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6195                              getValue(I.getArgOperand(0)).getValueType(),
6196                              getValue(I.getArgOperand(0)),
6197                              getValue(I.getArgOperand(1))));
6198     return;
6199   case Intrinsic::maxnum:
6200     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6201                              getValue(I.getArgOperand(0)).getValueType(),
6202                              getValue(I.getArgOperand(0)),
6203                              getValue(I.getArgOperand(1))));
6204     return;
6205   case Intrinsic::minimum:
6206     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6207                              getValue(I.getArgOperand(0)).getValueType(),
6208                              getValue(I.getArgOperand(0)),
6209                              getValue(I.getArgOperand(1))));
6210     return;
6211   case Intrinsic::maximum:
6212     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6213                              getValue(I.getArgOperand(0)).getValueType(),
6214                              getValue(I.getArgOperand(0)),
6215                              getValue(I.getArgOperand(1))));
6216     return;
6217   case Intrinsic::copysign:
6218     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6219                              getValue(I.getArgOperand(0)).getValueType(),
6220                              getValue(I.getArgOperand(0)),
6221                              getValue(I.getArgOperand(1))));
6222     return;
6223   case Intrinsic::fma:
6224     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6225                              getValue(I.getArgOperand(0)).getValueType(),
6226                              getValue(I.getArgOperand(0)),
6227                              getValue(I.getArgOperand(1)),
6228                              getValue(I.getArgOperand(2))));
6229     return;
6230 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
6231   case Intrinsic::INTRINSIC:
6232 #include "llvm/IR/ConstrainedOps.def"
6233     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6234     return;
6235   case Intrinsic::fmuladd: {
6236     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6237     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6238         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6239       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6240                                getValue(I.getArgOperand(0)).getValueType(),
6241                                getValue(I.getArgOperand(0)),
6242                                getValue(I.getArgOperand(1)),
6243                                getValue(I.getArgOperand(2))));
6244     } else {
6245       // TODO: Intrinsic calls should have fast-math-flags.
6246       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6247                                 getValue(I.getArgOperand(0)).getValueType(),
6248                                 getValue(I.getArgOperand(0)),
6249                                 getValue(I.getArgOperand(1)));
6250       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6251                                 getValue(I.getArgOperand(0)).getValueType(),
6252                                 Mul,
6253                                 getValue(I.getArgOperand(2)));
6254       setValue(&I, Add);
6255     }
6256     return;
6257   }
6258   case Intrinsic::convert_to_fp16:
6259     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6260                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6261                                          getValue(I.getArgOperand(0)),
6262                                          DAG.getTargetConstant(0, sdl,
6263                                                                MVT::i32))));
6264     return;
6265   case Intrinsic::convert_from_fp16:
6266     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6267                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6268                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6269                                          getValue(I.getArgOperand(0)))));
6270     return;
6271   case Intrinsic::pcmarker: {
6272     SDValue Tmp = getValue(I.getArgOperand(0));
6273     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6274     return;
6275   }
6276   case Intrinsic::readcyclecounter: {
6277     SDValue Op = getRoot();
6278     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6279                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6280     setValue(&I, Res);
6281     DAG.setRoot(Res.getValue(1));
6282     return;
6283   }
6284   case Intrinsic::bitreverse:
6285     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6286                              getValue(I.getArgOperand(0)).getValueType(),
6287                              getValue(I.getArgOperand(0))));
6288     return;
6289   case Intrinsic::bswap:
6290     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6291                              getValue(I.getArgOperand(0)).getValueType(),
6292                              getValue(I.getArgOperand(0))));
6293     return;
6294   case Intrinsic::cttz: {
6295     SDValue Arg = getValue(I.getArgOperand(0));
6296     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6297     EVT Ty = Arg.getValueType();
6298     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6299                              sdl, Ty, Arg));
6300     return;
6301   }
6302   case Intrinsic::ctlz: {
6303     SDValue Arg = getValue(I.getArgOperand(0));
6304     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6305     EVT Ty = Arg.getValueType();
6306     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6307                              sdl, Ty, Arg));
6308     return;
6309   }
6310   case Intrinsic::ctpop: {
6311     SDValue Arg = getValue(I.getArgOperand(0));
6312     EVT Ty = Arg.getValueType();
6313     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6314     return;
6315   }
6316   case Intrinsic::fshl:
6317   case Intrinsic::fshr: {
6318     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6319     SDValue X = getValue(I.getArgOperand(0));
6320     SDValue Y = getValue(I.getArgOperand(1));
6321     SDValue Z = getValue(I.getArgOperand(2));
6322     EVT VT = X.getValueType();
6323     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6324     SDValue Zero = DAG.getConstant(0, sdl, VT);
6325     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6326 
6327     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6328     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6329       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6330       return;
6331     }
6332 
6333     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6334     // avoid the select that is necessary in the general case to filter out
6335     // the 0-shift possibility that leads to UB.
6336     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6337       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6338       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6339         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6340         return;
6341       }
6342 
6343       // Some targets only rotate one way. Try the opposite direction.
6344       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6345       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6346         // Negate the shift amount because it is safe to ignore the high bits.
6347         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6348         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6349         return;
6350       }
6351 
6352       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6353       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6354       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6355       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6356       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6357       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6358       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6359       return;
6360     }
6361 
6362     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6363     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6364     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6365     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6366     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6367     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6368 
6369     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6370     // and that is undefined. We must compare and select to avoid UB.
6371     EVT CCVT = MVT::i1;
6372     if (VT.isVector())
6373       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6374 
6375     // For fshl, 0-shift returns the 1st arg (X).
6376     // For fshr, 0-shift returns the 2nd arg (Y).
6377     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6378     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6379     return;
6380   }
6381   case Intrinsic::sadd_sat: {
6382     SDValue Op1 = getValue(I.getArgOperand(0));
6383     SDValue Op2 = getValue(I.getArgOperand(1));
6384     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6385     return;
6386   }
6387   case Intrinsic::uadd_sat: {
6388     SDValue Op1 = getValue(I.getArgOperand(0));
6389     SDValue Op2 = getValue(I.getArgOperand(1));
6390     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6391     return;
6392   }
6393   case Intrinsic::ssub_sat: {
6394     SDValue Op1 = getValue(I.getArgOperand(0));
6395     SDValue Op2 = getValue(I.getArgOperand(1));
6396     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6397     return;
6398   }
6399   case Intrinsic::usub_sat: {
6400     SDValue Op1 = getValue(I.getArgOperand(0));
6401     SDValue Op2 = getValue(I.getArgOperand(1));
6402     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6403     return;
6404   }
6405   case Intrinsic::smul_fix:
6406   case Intrinsic::umul_fix:
6407   case Intrinsic::smul_fix_sat:
6408   case Intrinsic::umul_fix_sat: {
6409     SDValue Op1 = getValue(I.getArgOperand(0));
6410     SDValue Op2 = getValue(I.getArgOperand(1));
6411     SDValue Op3 = getValue(I.getArgOperand(2));
6412     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6413                              Op1.getValueType(), Op1, Op2, Op3));
6414     return;
6415   }
6416   case Intrinsic::sdiv_fix:
6417   case Intrinsic::udiv_fix: {
6418     SDValue Op1 = getValue(I.getArgOperand(0));
6419     SDValue Op2 = getValue(I.getArgOperand(1));
6420     SDValue Op3 = getValue(I.getArgOperand(2));
6421     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6422                               Op1, Op2, Op3, DAG, TLI));
6423     return;
6424   }
6425   case Intrinsic::stacksave: {
6426     SDValue Op = getRoot();
6427     Res = DAG.getNode(
6428         ISD::STACKSAVE, sdl,
6429         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6430     setValue(&I, Res);
6431     DAG.setRoot(Res.getValue(1));
6432     return;
6433   }
6434   case Intrinsic::stackrestore:
6435     Res = getValue(I.getArgOperand(0));
6436     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6437     return;
6438   case Intrinsic::get_dynamic_area_offset: {
6439     SDValue Op = getRoot();
6440     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6441     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6442     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6443     // target.
6444     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6445       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6446                          " intrinsic!");
6447     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6448                       Op);
6449     DAG.setRoot(Op);
6450     setValue(&I, Res);
6451     return;
6452   }
6453   case Intrinsic::stackguard: {
6454     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6455     MachineFunction &MF = DAG.getMachineFunction();
6456     const Module &M = *MF.getFunction().getParent();
6457     SDValue Chain = getRoot();
6458     if (TLI.useLoadStackGuardNode()) {
6459       Res = getLoadStackGuard(DAG, sdl, Chain);
6460     } else {
6461       const Value *Global = TLI.getSDagStackGuard(M);
6462       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6463       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6464                         MachinePointerInfo(Global, 0), Align,
6465                         MachineMemOperand::MOVolatile);
6466     }
6467     if (TLI.useStackGuardXorFP())
6468       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6469     DAG.setRoot(Chain);
6470     setValue(&I, Res);
6471     return;
6472   }
6473   case Intrinsic::stackprotector: {
6474     // Emit code into the DAG to store the stack guard onto the stack.
6475     MachineFunction &MF = DAG.getMachineFunction();
6476     MachineFrameInfo &MFI = MF.getFrameInfo();
6477     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6478     SDValue Src, Chain = getRoot();
6479 
6480     if (TLI.useLoadStackGuardNode())
6481       Src = getLoadStackGuard(DAG, sdl, Chain);
6482     else
6483       Src = getValue(I.getArgOperand(0));   // The guard's value.
6484 
6485     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6486 
6487     int FI = FuncInfo.StaticAllocaMap[Slot];
6488     MFI.setStackProtectorIndex(FI);
6489 
6490     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6491 
6492     // Store the stack protector onto the stack.
6493     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6494                                                  DAG.getMachineFunction(), FI),
6495                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6496     setValue(&I, Res);
6497     DAG.setRoot(Res);
6498     return;
6499   }
6500   case Intrinsic::objectsize:
6501     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6502 
6503   case Intrinsic::is_constant:
6504     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6505 
6506   case Intrinsic::annotation:
6507   case Intrinsic::ptr_annotation:
6508   case Intrinsic::launder_invariant_group:
6509   case Intrinsic::strip_invariant_group:
6510     // Drop the intrinsic, but forward the value
6511     setValue(&I, getValue(I.getOperand(0)));
6512     return;
6513   case Intrinsic::assume:
6514   case Intrinsic::var_annotation:
6515   case Intrinsic::sideeffect:
6516     // Discard annotate attributes, assumptions, and artificial side-effects.
6517     return;
6518 
6519   case Intrinsic::codeview_annotation: {
6520     // Emit a label associated with this metadata.
6521     MachineFunction &MF = DAG.getMachineFunction();
6522     MCSymbol *Label =
6523         MF.getMMI().getContext().createTempSymbol("annotation", true);
6524     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6525     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6526     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6527     DAG.setRoot(Res);
6528     return;
6529   }
6530 
6531   case Intrinsic::init_trampoline: {
6532     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6533 
6534     SDValue Ops[6];
6535     Ops[0] = getRoot();
6536     Ops[1] = getValue(I.getArgOperand(0));
6537     Ops[2] = getValue(I.getArgOperand(1));
6538     Ops[3] = getValue(I.getArgOperand(2));
6539     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6540     Ops[5] = DAG.getSrcValue(F);
6541 
6542     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6543 
6544     DAG.setRoot(Res);
6545     return;
6546   }
6547   case Intrinsic::adjust_trampoline:
6548     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6549                              TLI.getPointerTy(DAG.getDataLayout()),
6550                              getValue(I.getArgOperand(0))));
6551     return;
6552   case Intrinsic::gcroot: {
6553     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6554            "only valid in functions with gc specified, enforced by Verifier");
6555     assert(GFI && "implied by previous");
6556     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6557     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6558 
6559     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6560     GFI->addStackRoot(FI->getIndex(), TypeMap);
6561     return;
6562   }
6563   case Intrinsic::gcread:
6564   case Intrinsic::gcwrite:
6565     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6566   case Intrinsic::flt_rounds:
6567     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6568     return;
6569 
6570   case Intrinsic::expect:
6571     // Just replace __builtin_expect(exp, c) with EXP.
6572     setValue(&I, getValue(I.getArgOperand(0)));
6573     return;
6574 
6575   case Intrinsic::debugtrap:
6576   case Intrinsic::trap: {
6577     StringRef TrapFuncName =
6578         I.getAttributes()
6579             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6580             .getValueAsString();
6581     if (TrapFuncName.empty()) {
6582       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6583         ISD::TRAP : ISD::DEBUGTRAP;
6584       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6585       return;
6586     }
6587     TargetLowering::ArgListTy Args;
6588 
6589     TargetLowering::CallLoweringInfo CLI(DAG);
6590     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6591         CallingConv::C, I.getType(),
6592         DAG.getExternalSymbol(TrapFuncName.data(),
6593                               TLI.getPointerTy(DAG.getDataLayout())),
6594         std::move(Args));
6595 
6596     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6597     DAG.setRoot(Result.second);
6598     return;
6599   }
6600 
6601   case Intrinsic::uadd_with_overflow:
6602   case Intrinsic::sadd_with_overflow:
6603   case Intrinsic::usub_with_overflow:
6604   case Intrinsic::ssub_with_overflow:
6605   case Intrinsic::umul_with_overflow:
6606   case Intrinsic::smul_with_overflow: {
6607     ISD::NodeType Op;
6608     switch (Intrinsic) {
6609     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6610     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6611     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6612     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6613     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6614     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6615     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6616     }
6617     SDValue Op1 = getValue(I.getArgOperand(0));
6618     SDValue Op2 = getValue(I.getArgOperand(1));
6619 
6620     EVT ResultVT = Op1.getValueType();
6621     EVT OverflowVT = MVT::i1;
6622     if (ResultVT.isVector())
6623       OverflowVT = EVT::getVectorVT(
6624           *Context, OverflowVT, ResultVT.getVectorNumElements());
6625 
6626     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6627     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6628     return;
6629   }
6630   case Intrinsic::prefetch: {
6631     SDValue Ops[5];
6632     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6633     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6634     Ops[0] = DAG.getRoot();
6635     Ops[1] = getValue(I.getArgOperand(0));
6636     Ops[2] = getValue(I.getArgOperand(1));
6637     Ops[3] = getValue(I.getArgOperand(2));
6638     Ops[4] = getValue(I.getArgOperand(3));
6639     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6640                                              DAG.getVTList(MVT::Other), Ops,
6641                                              EVT::getIntegerVT(*Context, 8),
6642                                              MachinePointerInfo(I.getArgOperand(0)),
6643                                              0, /* align */
6644                                              Flags);
6645 
6646     // Chain the prefetch in parallell with any pending loads, to stay out of
6647     // the way of later optimizations.
6648     PendingLoads.push_back(Result);
6649     Result = getRoot();
6650     DAG.setRoot(Result);
6651     return;
6652   }
6653   case Intrinsic::lifetime_start:
6654   case Intrinsic::lifetime_end: {
6655     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6656     // Stack coloring is not enabled in O0, discard region information.
6657     if (TM.getOptLevel() == CodeGenOpt::None)
6658       return;
6659 
6660     const int64_t ObjectSize =
6661         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6662     Value *const ObjectPtr = I.getArgOperand(1);
6663     SmallVector<const Value *, 4> Allocas;
6664     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6665 
6666     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6667            E = Allocas.end(); Object != E; ++Object) {
6668       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6669 
6670       // Could not find an Alloca.
6671       if (!LifetimeObject)
6672         continue;
6673 
6674       // First check that the Alloca is static, otherwise it won't have a
6675       // valid frame index.
6676       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6677       if (SI == FuncInfo.StaticAllocaMap.end())
6678         return;
6679 
6680       const int FrameIndex = SI->second;
6681       int64_t Offset;
6682       if (GetPointerBaseWithConstantOffset(
6683               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6684         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6685       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6686                                 Offset);
6687       DAG.setRoot(Res);
6688     }
6689     return;
6690   }
6691   case Intrinsic::invariant_start:
6692     // Discard region information.
6693     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6694     return;
6695   case Intrinsic::invariant_end:
6696     // Discard region information.
6697     return;
6698   case Intrinsic::clear_cache:
6699     /// FunctionName may be null.
6700     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6701       lowerCallToExternalSymbol(I, FunctionName);
6702     return;
6703   case Intrinsic::donothing:
6704     // ignore
6705     return;
6706   case Intrinsic::experimental_stackmap:
6707     visitStackmap(I);
6708     return;
6709   case Intrinsic::experimental_patchpoint_void:
6710   case Intrinsic::experimental_patchpoint_i64:
6711     visitPatchpoint(&I);
6712     return;
6713   case Intrinsic::experimental_gc_statepoint:
6714     LowerStatepoint(ImmutableStatepoint(&I));
6715     return;
6716   case Intrinsic::experimental_gc_result:
6717     visitGCResult(cast<GCResultInst>(I));
6718     return;
6719   case Intrinsic::experimental_gc_relocate:
6720     visitGCRelocate(cast<GCRelocateInst>(I));
6721     return;
6722   case Intrinsic::instrprof_increment:
6723     llvm_unreachable("instrprof failed to lower an increment");
6724   case Intrinsic::instrprof_value_profile:
6725     llvm_unreachable("instrprof failed to lower a value profiling call");
6726   case Intrinsic::localescape: {
6727     MachineFunction &MF = DAG.getMachineFunction();
6728     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6729 
6730     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6731     // is the same on all targets.
6732     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6733       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6734       if (isa<ConstantPointerNull>(Arg))
6735         continue; // Skip null pointers. They represent a hole in index space.
6736       AllocaInst *Slot = cast<AllocaInst>(Arg);
6737       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6738              "can only escape static allocas");
6739       int FI = FuncInfo.StaticAllocaMap[Slot];
6740       MCSymbol *FrameAllocSym =
6741           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6742               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6743       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6744               TII->get(TargetOpcode::LOCAL_ESCAPE))
6745           .addSym(FrameAllocSym)
6746           .addFrameIndex(FI);
6747     }
6748 
6749     return;
6750   }
6751 
6752   case Intrinsic::localrecover: {
6753     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6754     MachineFunction &MF = DAG.getMachineFunction();
6755     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6756 
6757     // Get the symbol that defines the frame offset.
6758     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6759     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6760     unsigned IdxVal =
6761         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6762     MCSymbol *FrameAllocSym =
6763         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6764             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6765 
6766     // Create a MCSymbol for the label to avoid any target lowering
6767     // that would make this PC relative.
6768     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6769     SDValue OffsetVal =
6770         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6771 
6772     // Add the offset to the FP.
6773     Value *FP = I.getArgOperand(1);
6774     SDValue FPVal = getValue(FP);
6775     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6776     setValue(&I, Add);
6777 
6778     return;
6779   }
6780 
6781   case Intrinsic::eh_exceptionpointer:
6782   case Intrinsic::eh_exceptioncode: {
6783     // Get the exception pointer vreg, copy from it, and resize it to fit.
6784     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6785     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6786     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6787     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6788     SDValue N =
6789         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6790     if (Intrinsic == Intrinsic::eh_exceptioncode)
6791       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6792     setValue(&I, N);
6793     return;
6794   }
6795   case Intrinsic::xray_customevent: {
6796     // Here we want to make sure that the intrinsic behaves as if it has a
6797     // specific calling convention, and only for x86_64.
6798     // FIXME: Support other platforms later.
6799     const auto &Triple = DAG.getTarget().getTargetTriple();
6800     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6801       return;
6802 
6803     SDLoc DL = getCurSDLoc();
6804     SmallVector<SDValue, 8> Ops;
6805 
6806     // We want to say that we always want the arguments in registers.
6807     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6808     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6809     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6810     SDValue Chain = getRoot();
6811     Ops.push_back(LogEntryVal);
6812     Ops.push_back(StrSizeVal);
6813     Ops.push_back(Chain);
6814 
6815     // We need to enforce the calling convention for the callsite, so that
6816     // argument ordering is enforced correctly, and that register allocation can
6817     // see that some registers may be assumed clobbered and have to preserve
6818     // them across calls to the intrinsic.
6819     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6820                                            DL, NodeTys, Ops);
6821     SDValue patchableNode = SDValue(MN, 0);
6822     DAG.setRoot(patchableNode);
6823     setValue(&I, patchableNode);
6824     return;
6825   }
6826   case Intrinsic::xray_typedevent: {
6827     // Here we want to make sure that the intrinsic behaves as if it has a
6828     // specific calling convention, and only for x86_64.
6829     // FIXME: Support other platforms later.
6830     const auto &Triple = DAG.getTarget().getTargetTriple();
6831     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6832       return;
6833 
6834     SDLoc DL = getCurSDLoc();
6835     SmallVector<SDValue, 8> Ops;
6836 
6837     // We want to say that we always want the arguments in registers.
6838     // It's unclear to me how manipulating the selection DAG here forces callers
6839     // to provide arguments in registers instead of on the stack.
6840     SDValue LogTypeId = getValue(I.getArgOperand(0));
6841     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6842     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6843     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6844     SDValue Chain = getRoot();
6845     Ops.push_back(LogTypeId);
6846     Ops.push_back(LogEntryVal);
6847     Ops.push_back(StrSizeVal);
6848     Ops.push_back(Chain);
6849 
6850     // We need to enforce the calling convention for the callsite, so that
6851     // argument ordering is enforced correctly, and that register allocation can
6852     // see that some registers may be assumed clobbered and have to preserve
6853     // them across calls to the intrinsic.
6854     MachineSDNode *MN = DAG.getMachineNode(
6855         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6856     SDValue patchableNode = SDValue(MN, 0);
6857     DAG.setRoot(patchableNode);
6858     setValue(&I, patchableNode);
6859     return;
6860   }
6861   case Intrinsic::experimental_deoptimize:
6862     LowerDeoptimizeCall(&I);
6863     return;
6864 
6865   case Intrinsic::experimental_vector_reduce_v2_fadd:
6866   case Intrinsic::experimental_vector_reduce_v2_fmul:
6867   case Intrinsic::experimental_vector_reduce_add:
6868   case Intrinsic::experimental_vector_reduce_mul:
6869   case Intrinsic::experimental_vector_reduce_and:
6870   case Intrinsic::experimental_vector_reduce_or:
6871   case Intrinsic::experimental_vector_reduce_xor:
6872   case Intrinsic::experimental_vector_reduce_smax:
6873   case Intrinsic::experimental_vector_reduce_smin:
6874   case Intrinsic::experimental_vector_reduce_umax:
6875   case Intrinsic::experimental_vector_reduce_umin:
6876   case Intrinsic::experimental_vector_reduce_fmax:
6877   case Intrinsic::experimental_vector_reduce_fmin:
6878     visitVectorReduce(I, Intrinsic);
6879     return;
6880 
6881   case Intrinsic::icall_branch_funnel: {
6882     SmallVector<SDValue, 16> Ops;
6883     Ops.push_back(getValue(I.getArgOperand(0)));
6884 
6885     int64_t Offset;
6886     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6887         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6888     if (!Base)
6889       report_fatal_error(
6890           "llvm.icall.branch.funnel operand must be a GlobalValue");
6891     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6892 
6893     struct BranchFunnelTarget {
6894       int64_t Offset;
6895       SDValue Target;
6896     };
6897     SmallVector<BranchFunnelTarget, 8> Targets;
6898 
6899     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6900       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6901           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6902       if (ElemBase != Base)
6903         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6904                            "to the same GlobalValue");
6905 
6906       SDValue Val = getValue(I.getArgOperand(Op + 1));
6907       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6908       if (!GA)
6909         report_fatal_error(
6910             "llvm.icall.branch.funnel operand must be a GlobalValue");
6911       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6912                                      GA->getGlobal(), getCurSDLoc(),
6913                                      Val.getValueType(), GA->getOffset())});
6914     }
6915     llvm::sort(Targets,
6916                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6917                  return T1.Offset < T2.Offset;
6918                });
6919 
6920     for (auto &T : Targets) {
6921       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6922       Ops.push_back(T.Target);
6923     }
6924 
6925     Ops.push_back(DAG.getRoot()); // Chain
6926     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6927                                  getCurSDLoc(), MVT::Other, Ops),
6928               0);
6929     DAG.setRoot(N);
6930     setValue(&I, N);
6931     HasTailCall = true;
6932     return;
6933   }
6934 
6935   case Intrinsic::wasm_landingpad_index:
6936     // Information this intrinsic contained has been transferred to
6937     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6938     // delete it now.
6939     return;
6940 
6941   case Intrinsic::aarch64_settag:
6942   case Intrinsic::aarch64_settag_zero: {
6943     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6944     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6945     SDValue Val = TSI.EmitTargetCodeForSetTag(
6946         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6947         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6948         ZeroMemory);
6949     DAG.setRoot(Val);
6950     setValue(&I, Val);
6951     return;
6952   }
6953   case Intrinsic::ptrmask: {
6954     SDValue Ptr = getValue(I.getOperand(0));
6955     SDValue Const = getValue(I.getOperand(1));
6956 
6957     EVT DestVT =
6958         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6959 
6960     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
6961                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
6962     return;
6963   }
6964   }
6965 }
6966 
6967 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6968     const ConstrainedFPIntrinsic &FPI) {
6969   SDLoc sdl = getCurSDLoc();
6970 
6971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6972   SmallVector<EVT, 4> ValueVTs;
6973   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6974   ValueVTs.push_back(MVT::Other); // Out chain
6975 
6976   // We do not need to serialize constrained FP intrinsics against
6977   // each other or against (nonvolatile) loads, so they can be
6978   // chained like loads.
6979   SDValue Chain = DAG.getRoot();
6980   SmallVector<SDValue, 4> Opers;
6981   Opers.push_back(Chain);
6982   if (FPI.isUnaryOp()) {
6983     Opers.push_back(getValue(FPI.getArgOperand(0)));
6984   } else if (FPI.isTernaryOp()) {
6985     Opers.push_back(getValue(FPI.getArgOperand(0)));
6986     Opers.push_back(getValue(FPI.getArgOperand(1)));
6987     Opers.push_back(getValue(FPI.getArgOperand(2)));
6988   } else {
6989     Opers.push_back(getValue(FPI.getArgOperand(0)));
6990     Opers.push_back(getValue(FPI.getArgOperand(1)));
6991   }
6992 
6993   unsigned Opcode;
6994   switch (FPI.getIntrinsicID()) {
6995   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6996 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
6997   case Intrinsic::INTRINSIC:                                                   \
6998     Opcode = ISD::STRICT_##DAGN;                                               \
6999     break;
7000 #include "llvm/IR/ConstrainedOps.def"
7001   }
7002 
7003   // A few strict DAG nodes carry additional operands that are not
7004   // set up by the default code above.
7005   switch (Opcode) {
7006   default: break;
7007   case ISD::STRICT_FP_ROUND:
7008     Opers.push_back(
7009         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7010     break;
7011   case ISD::STRICT_FSETCC:
7012   case ISD::STRICT_FSETCCS: {
7013     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7014     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
7015     break;
7016   }
7017   }
7018 
7019   SDVTList VTs = DAG.getVTList(ValueVTs);
7020   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers);
7021 
7022   assert(Result.getNode()->getNumValues() == 2);
7023 
7024   // Push node to the appropriate list so that future instructions can be
7025   // chained up correctly.
7026   SDValue OutChain = Result.getValue(1);
7027   switch (FPI.getExceptionBehavior().getValue()) {
7028   case fp::ExceptionBehavior::ebIgnore:
7029     // The only reason why ebIgnore nodes still need to be chained is that
7030     // they might depend on the current rounding mode, and therefore must
7031     // not be moved across instruction that may change that mode.
7032     LLVM_FALLTHROUGH;
7033   case fp::ExceptionBehavior::ebMayTrap:
7034     // These must not be moved across calls or instructions that may change
7035     // floating-point exception masks.
7036     PendingConstrainedFP.push_back(OutChain);
7037     break;
7038   case fp::ExceptionBehavior::ebStrict:
7039     // These must not be moved across calls or instructions that may change
7040     // floating-point exception masks or read floating-point exception flags.
7041     // In addition, they cannot be optimized out even if unused.
7042     PendingConstrainedFPStrict.push_back(OutChain);
7043     break;
7044   }
7045 
7046   SDValue FPResult = Result.getValue(0);
7047   setValue(&FPI, FPResult);
7048 }
7049 
7050 std::pair<SDValue, SDValue>
7051 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7052                                     const BasicBlock *EHPadBB) {
7053   MachineFunction &MF = DAG.getMachineFunction();
7054   MachineModuleInfo &MMI = MF.getMMI();
7055   MCSymbol *BeginLabel = nullptr;
7056 
7057   if (EHPadBB) {
7058     // Insert a label before the invoke call to mark the try range.  This can be
7059     // used to detect deletion of the invoke via the MachineModuleInfo.
7060     BeginLabel = MMI.getContext().createTempSymbol();
7061 
7062     // For SjLj, keep track of which landing pads go with which invokes
7063     // so as to maintain the ordering of pads in the LSDA.
7064     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7065     if (CallSiteIndex) {
7066       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7067       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7068 
7069       // Now that the call site is handled, stop tracking it.
7070       MMI.setCurrentCallSite(0);
7071     }
7072 
7073     // Both PendingLoads and PendingExports must be flushed here;
7074     // this call might not return.
7075     (void)getRoot();
7076     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7077 
7078     CLI.setChain(getRoot());
7079   }
7080   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7081   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7082 
7083   assert((CLI.IsTailCall || Result.second.getNode()) &&
7084          "Non-null chain expected with non-tail call!");
7085   assert((Result.second.getNode() || !Result.first.getNode()) &&
7086          "Null value expected with tail call!");
7087 
7088   if (!Result.second.getNode()) {
7089     // As a special case, a null chain means that a tail call has been emitted
7090     // and the DAG root is already updated.
7091     HasTailCall = true;
7092 
7093     // Since there's no actual continuation from this block, nothing can be
7094     // relying on us setting vregs for them.
7095     PendingExports.clear();
7096   } else {
7097     DAG.setRoot(Result.second);
7098   }
7099 
7100   if (EHPadBB) {
7101     // Insert a label at the end of the invoke call to mark the try range.  This
7102     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7103     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7104     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7105 
7106     // Inform MachineModuleInfo of range.
7107     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7108     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7109     // actually use outlined funclets and their LSDA info style.
7110     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7111       assert(CLI.CS);
7112       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7113       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7114                                 BeginLabel, EndLabel);
7115     } else if (!isScopedEHPersonality(Pers)) {
7116       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7117     }
7118   }
7119 
7120   return Result;
7121 }
7122 
7123 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7124                                       bool isTailCall,
7125                                       const BasicBlock *EHPadBB) {
7126   auto &DL = DAG.getDataLayout();
7127   FunctionType *FTy = CS.getFunctionType();
7128   Type *RetTy = CS.getType();
7129 
7130   TargetLowering::ArgListTy Args;
7131   Args.reserve(CS.arg_size());
7132 
7133   const Value *SwiftErrorVal = nullptr;
7134   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7135 
7136   if (isTailCall) {
7137     // Avoid emitting tail calls in functions with the disable-tail-calls
7138     // attribute.
7139     auto *Caller = CS.getInstruction()->getParent()->getParent();
7140     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7141         "true")
7142       isTailCall = false;
7143 
7144     // We can't tail call inside a function with a swifterror argument. Lowering
7145     // does not support this yet. It would have to move into the swifterror
7146     // register before the call.
7147     if (TLI.supportSwiftError() &&
7148         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7149       isTailCall = false;
7150   }
7151 
7152   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7153        i != e; ++i) {
7154     TargetLowering::ArgListEntry Entry;
7155     const Value *V = *i;
7156 
7157     // Skip empty types
7158     if (V->getType()->isEmptyTy())
7159       continue;
7160 
7161     SDValue ArgNode = getValue(V);
7162     Entry.Node = ArgNode; Entry.Ty = V->getType();
7163 
7164     Entry.setAttributes(&CS, i - CS.arg_begin());
7165 
7166     // Use swifterror virtual register as input to the call.
7167     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7168       SwiftErrorVal = V;
7169       // We find the virtual register for the actual swifterror argument.
7170       // Instead of using the Value, we use the virtual register instead.
7171       Entry.Node = DAG.getRegister(
7172           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7173           EVT(TLI.getPointerTy(DL)));
7174     }
7175 
7176     Args.push_back(Entry);
7177 
7178     // If we have an explicit sret argument that is an Instruction, (i.e., it
7179     // might point to function-local memory), we can't meaningfully tail-call.
7180     if (Entry.IsSRet && isa<Instruction>(V))
7181       isTailCall = false;
7182   }
7183 
7184   // If call site has a cfguardtarget operand bundle, create and add an
7185   // additional ArgListEntry.
7186   if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7187     TargetLowering::ArgListEntry Entry;
7188     Value *V = Bundle->Inputs[0];
7189     SDValue ArgNode = getValue(V);
7190     Entry.Node = ArgNode;
7191     Entry.Ty = V->getType();
7192     Entry.IsCFGuardTarget = true;
7193     Args.push_back(Entry);
7194   }
7195 
7196   // Check if target-independent constraints permit a tail call here.
7197   // Target-dependent constraints are checked within TLI->LowerCallTo.
7198   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7199     isTailCall = false;
7200 
7201   // Disable tail calls if there is an swifterror argument. Targets have not
7202   // been updated to support tail calls.
7203   if (TLI.supportSwiftError() && SwiftErrorVal)
7204     isTailCall = false;
7205 
7206   TargetLowering::CallLoweringInfo CLI(DAG);
7207   CLI.setDebugLoc(getCurSDLoc())
7208       .setChain(getRoot())
7209       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7210       .setTailCall(isTailCall)
7211       .setConvergent(CS.isConvergent());
7212   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7213 
7214   if (Result.first.getNode()) {
7215     const Instruction *Inst = CS.getInstruction();
7216     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7217     setValue(Inst, Result.first);
7218   }
7219 
7220   // The last element of CLI.InVals has the SDValue for swifterror return.
7221   // Here we copy it to a virtual register and update SwiftErrorMap for
7222   // book-keeping.
7223   if (SwiftErrorVal && TLI.supportSwiftError()) {
7224     // Get the last element of InVals.
7225     SDValue Src = CLI.InVals.back();
7226     Register VReg = SwiftError.getOrCreateVRegDefAt(
7227         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7228     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7229     DAG.setRoot(CopyNode);
7230   }
7231 }
7232 
7233 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7234                              SelectionDAGBuilder &Builder) {
7235   // Check to see if this load can be trivially constant folded, e.g. if the
7236   // input is from a string literal.
7237   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7238     // Cast pointer to the type we really want to load.
7239     Type *LoadTy =
7240         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7241     if (LoadVT.isVector())
7242       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7243 
7244     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7245                                          PointerType::getUnqual(LoadTy));
7246 
7247     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7248             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7249       return Builder.getValue(LoadCst);
7250   }
7251 
7252   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7253   // still constant memory, the input chain can be the entry node.
7254   SDValue Root;
7255   bool ConstantMemory = false;
7256 
7257   // Do not serialize (non-volatile) loads of constant memory with anything.
7258   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7259     Root = Builder.DAG.getEntryNode();
7260     ConstantMemory = true;
7261   } else {
7262     // Do not serialize non-volatile loads against each other.
7263     Root = Builder.DAG.getRoot();
7264   }
7265 
7266   SDValue Ptr = Builder.getValue(PtrVal);
7267   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7268                                         Ptr, MachinePointerInfo(PtrVal),
7269                                         /* Alignment = */ 1);
7270 
7271   if (!ConstantMemory)
7272     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7273   return LoadVal;
7274 }
7275 
7276 /// Record the value for an instruction that produces an integer result,
7277 /// converting the type where necessary.
7278 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7279                                                   SDValue Value,
7280                                                   bool IsSigned) {
7281   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7282                                                     I.getType(), true);
7283   if (IsSigned)
7284     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7285   else
7286     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7287   setValue(&I, Value);
7288 }
7289 
7290 /// See if we can lower a memcmp call into an optimized form. If so, return
7291 /// true and lower it. Otherwise return false, and it will be lowered like a
7292 /// normal call.
7293 /// The caller already checked that \p I calls the appropriate LibFunc with a
7294 /// correct prototype.
7295 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7296   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7297   const Value *Size = I.getArgOperand(2);
7298   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7299   if (CSize && CSize->getZExtValue() == 0) {
7300     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7301                                                           I.getType(), true);
7302     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7303     return true;
7304   }
7305 
7306   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7307   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7308       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7309       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7310   if (Res.first.getNode()) {
7311     processIntegerCallValue(I, Res.first, true);
7312     PendingLoads.push_back(Res.second);
7313     return true;
7314   }
7315 
7316   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7317   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7318   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7319     return false;
7320 
7321   // If the target has a fast compare for the given size, it will return a
7322   // preferred load type for that size. Require that the load VT is legal and
7323   // that the target supports unaligned loads of that type. Otherwise, return
7324   // INVALID.
7325   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7326     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7327     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7328     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7329       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7330       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7331       // TODO: Check alignment of src and dest ptrs.
7332       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7333       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7334       if (!TLI.isTypeLegal(LVT) ||
7335           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7336           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7337         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7338     }
7339 
7340     return LVT;
7341   };
7342 
7343   // This turns into unaligned loads. We only do this if the target natively
7344   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7345   // we'll only produce a small number of byte loads.
7346   MVT LoadVT;
7347   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7348   switch (NumBitsToCompare) {
7349   default:
7350     return false;
7351   case 16:
7352     LoadVT = MVT::i16;
7353     break;
7354   case 32:
7355     LoadVT = MVT::i32;
7356     break;
7357   case 64:
7358   case 128:
7359   case 256:
7360     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7361     break;
7362   }
7363 
7364   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7365     return false;
7366 
7367   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7368   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7369 
7370   // Bitcast to a wide integer type if the loads are vectors.
7371   if (LoadVT.isVector()) {
7372     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7373     LoadL = DAG.getBitcast(CmpVT, LoadL);
7374     LoadR = DAG.getBitcast(CmpVT, LoadR);
7375   }
7376 
7377   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7378   processIntegerCallValue(I, Cmp, false);
7379   return true;
7380 }
7381 
7382 /// See if we can lower a memchr call into an optimized form. If so, return
7383 /// true and lower it. Otherwise return false, and it will be lowered like a
7384 /// normal call.
7385 /// The caller already checked that \p I calls the appropriate LibFunc with a
7386 /// correct prototype.
7387 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7388   const Value *Src = I.getArgOperand(0);
7389   const Value *Char = I.getArgOperand(1);
7390   const Value *Length = I.getArgOperand(2);
7391 
7392   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7393   std::pair<SDValue, SDValue> Res =
7394     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7395                                 getValue(Src), getValue(Char), getValue(Length),
7396                                 MachinePointerInfo(Src));
7397   if (Res.first.getNode()) {
7398     setValue(&I, Res.first);
7399     PendingLoads.push_back(Res.second);
7400     return true;
7401   }
7402 
7403   return false;
7404 }
7405 
7406 /// See if we can lower a mempcpy call into an optimized form. If so, return
7407 /// true and lower it. Otherwise return false, and it will be lowered like a
7408 /// normal call.
7409 /// The caller already checked that \p I calls the appropriate LibFunc with a
7410 /// correct prototype.
7411 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7412   SDValue Dst = getValue(I.getArgOperand(0));
7413   SDValue Src = getValue(I.getArgOperand(1));
7414   SDValue Size = getValue(I.getArgOperand(2));
7415 
7416   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7417   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7418   unsigned Align = std::min(DstAlign, SrcAlign);
7419   if (Align == 0) // Alignment of one or both could not be inferred.
7420     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7421 
7422   bool isVol = false;
7423   SDLoc sdl = getCurSDLoc();
7424 
7425   // In the mempcpy context we need to pass in a false value for isTailCall
7426   // because the return pointer needs to be adjusted by the size of
7427   // the copied memory.
7428   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7429   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Align, isVol,
7430                              false, /*isTailCall=*/false,
7431                              MachinePointerInfo(I.getArgOperand(0)),
7432                              MachinePointerInfo(I.getArgOperand(1)));
7433   assert(MC.getNode() != nullptr &&
7434          "** memcpy should not be lowered as TailCall in mempcpy context **");
7435   DAG.setRoot(MC);
7436 
7437   // Check if Size needs to be truncated or extended.
7438   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7439 
7440   // Adjust return pointer to point just past the last dst byte.
7441   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7442                                     Dst, Size);
7443   setValue(&I, DstPlusSize);
7444   return true;
7445 }
7446 
7447 /// See if we can lower a strcpy call into an optimized form.  If so, return
7448 /// true and lower it, otherwise return false and it will be lowered like a
7449 /// normal call.
7450 /// The caller already checked that \p I calls the appropriate LibFunc with a
7451 /// correct prototype.
7452 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7453   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7454 
7455   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7456   std::pair<SDValue, SDValue> Res =
7457     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7458                                 getValue(Arg0), getValue(Arg1),
7459                                 MachinePointerInfo(Arg0),
7460                                 MachinePointerInfo(Arg1), isStpcpy);
7461   if (Res.first.getNode()) {
7462     setValue(&I, Res.first);
7463     DAG.setRoot(Res.second);
7464     return true;
7465   }
7466 
7467   return false;
7468 }
7469 
7470 /// See if we can lower a strcmp call into an optimized form.  If so, return
7471 /// true and lower it, otherwise return false and it will be lowered like a
7472 /// normal call.
7473 /// The caller already checked that \p I calls the appropriate LibFunc with a
7474 /// correct prototype.
7475 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7476   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7477 
7478   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7479   std::pair<SDValue, SDValue> Res =
7480     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7481                                 getValue(Arg0), getValue(Arg1),
7482                                 MachinePointerInfo(Arg0),
7483                                 MachinePointerInfo(Arg1));
7484   if (Res.first.getNode()) {
7485     processIntegerCallValue(I, Res.first, true);
7486     PendingLoads.push_back(Res.second);
7487     return true;
7488   }
7489 
7490   return false;
7491 }
7492 
7493 /// See if we can lower a strlen call into an optimized form.  If so, return
7494 /// true and lower it, otherwise return false and it will be lowered like a
7495 /// normal call.
7496 /// The caller already checked that \p I calls the appropriate LibFunc with a
7497 /// correct prototype.
7498 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7499   const Value *Arg0 = I.getArgOperand(0);
7500 
7501   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7502   std::pair<SDValue, SDValue> Res =
7503     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7504                                 getValue(Arg0), MachinePointerInfo(Arg0));
7505   if (Res.first.getNode()) {
7506     processIntegerCallValue(I, Res.first, false);
7507     PendingLoads.push_back(Res.second);
7508     return true;
7509   }
7510 
7511   return false;
7512 }
7513 
7514 /// See if we can lower a strnlen 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::visitStrNLenCall(const CallInst &I) {
7520   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7521 
7522   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7523   std::pair<SDValue, SDValue> Res =
7524     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7525                                  getValue(Arg0), getValue(Arg1),
7526                                  MachinePointerInfo(Arg0));
7527   if (Res.first.getNode()) {
7528     processIntegerCallValue(I, Res.first, false);
7529     PendingLoads.push_back(Res.second);
7530     return true;
7531   }
7532 
7533   return false;
7534 }
7535 
7536 /// See if we can lower a unary floating-point operation into an SDNode with
7537 /// the specified Opcode.  If so, return true and lower it, otherwise return
7538 /// false and it will be lowered like a normal call.
7539 /// The caller already checked that \p I calls the appropriate LibFunc with a
7540 /// correct prototype.
7541 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7542                                               unsigned Opcode) {
7543   // We already checked this call's prototype; verify it doesn't modify errno.
7544   if (!I.onlyReadsMemory())
7545     return false;
7546 
7547   SDValue Tmp = getValue(I.getArgOperand(0));
7548   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7549   return true;
7550 }
7551 
7552 /// See if we can lower a binary floating-point operation into an SDNode with
7553 /// the specified Opcode. If so, return true and lower it. Otherwise return
7554 /// false, and it will be lowered like a normal call.
7555 /// The caller already checked that \p I calls the appropriate LibFunc with a
7556 /// correct prototype.
7557 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7558                                                unsigned Opcode) {
7559   // We already checked this call's prototype; verify it doesn't modify errno.
7560   if (!I.onlyReadsMemory())
7561     return false;
7562 
7563   SDValue Tmp0 = getValue(I.getArgOperand(0));
7564   SDValue Tmp1 = getValue(I.getArgOperand(1));
7565   EVT VT = Tmp0.getValueType();
7566   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7567   return true;
7568 }
7569 
7570 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7571   // Handle inline assembly differently.
7572   if (isa<InlineAsm>(I.getCalledValue())) {
7573     visitInlineAsm(&I);
7574     return;
7575   }
7576 
7577   if (Function *F = I.getCalledFunction()) {
7578     if (F->isDeclaration()) {
7579       // Is this an LLVM intrinsic or a target-specific intrinsic?
7580       unsigned IID = F->getIntrinsicID();
7581       if (!IID)
7582         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7583           IID = II->getIntrinsicID(F);
7584 
7585       if (IID) {
7586         visitIntrinsicCall(I, IID);
7587         return;
7588       }
7589     }
7590 
7591     // Check for well-known libc/libm calls.  If the function is internal, it
7592     // can't be a library call.  Don't do the check if marked as nobuiltin for
7593     // some reason or the call site requires strict floating point semantics.
7594     LibFunc Func;
7595     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7596         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7597         LibInfo->hasOptimizedCodeGen(Func)) {
7598       switch (Func) {
7599       default: break;
7600       case LibFunc_copysign:
7601       case LibFunc_copysignf:
7602       case LibFunc_copysignl:
7603         // We already checked this call's prototype; verify it doesn't modify
7604         // errno.
7605         if (I.onlyReadsMemory()) {
7606           SDValue LHS = getValue(I.getArgOperand(0));
7607           SDValue RHS = getValue(I.getArgOperand(1));
7608           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7609                                    LHS.getValueType(), LHS, RHS));
7610           return;
7611         }
7612         break;
7613       case LibFunc_fabs:
7614       case LibFunc_fabsf:
7615       case LibFunc_fabsl:
7616         if (visitUnaryFloatCall(I, ISD::FABS))
7617           return;
7618         break;
7619       case LibFunc_fmin:
7620       case LibFunc_fminf:
7621       case LibFunc_fminl:
7622         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7623           return;
7624         break;
7625       case LibFunc_fmax:
7626       case LibFunc_fmaxf:
7627       case LibFunc_fmaxl:
7628         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7629           return;
7630         break;
7631       case LibFunc_sin:
7632       case LibFunc_sinf:
7633       case LibFunc_sinl:
7634         if (visitUnaryFloatCall(I, ISD::FSIN))
7635           return;
7636         break;
7637       case LibFunc_cos:
7638       case LibFunc_cosf:
7639       case LibFunc_cosl:
7640         if (visitUnaryFloatCall(I, ISD::FCOS))
7641           return;
7642         break;
7643       case LibFunc_sqrt:
7644       case LibFunc_sqrtf:
7645       case LibFunc_sqrtl:
7646       case LibFunc_sqrt_finite:
7647       case LibFunc_sqrtf_finite:
7648       case LibFunc_sqrtl_finite:
7649         if (visitUnaryFloatCall(I, ISD::FSQRT))
7650           return;
7651         break;
7652       case LibFunc_floor:
7653       case LibFunc_floorf:
7654       case LibFunc_floorl:
7655         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7656           return;
7657         break;
7658       case LibFunc_nearbyint:
7659       case LibFunc_nearbyintf:
7660       case LibFunc_nearbyintl:
7661         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7662           return;
7663         break;
7664       case LibFunc_ceil:
7665       case LibFunc_ceilf:
7666       case LibFunc_ceill:
7667         if (visitUnaryFloatCall(I, ISD::FCEIL))
7668           return;
7669         break;
7670       case LibFunc_rint:
7671       case LibFunc_rintf:
7672       case LibFunc_rintl:
7673         if (visitUnaryFloatCall(I, ISD::FRINT))
7674           return;
7675         break;
7676       case LibFunc_round:
7677       case LibFunc_roundf:
7678       case LibFunc_roundl:
7679         if (visitUnaryFloatCall(I, ISD::FROUND))
7680           return;
7681         break;
7682       case LibFunc_trunc:
7683       case LibFunc_truncf:
7684       case LibFunc_truncl:
7685         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7686           return;
7687         break;
7688       case LibFunc_log2:
7689       case LibFunc_log2f:
7690       case LibFunc_log2l:
7691         if (visitUnaryFloatCall(I, ISD::FLOG2))
7692           return;
7693         break;
7694       case LibFunc_exp2:
7695       case LibFunc_exp2f:
7696       case LibFunc_exp2l:
7697         if (visitUnaryFloatCall(I, ISD::FEXP2))
7698           return;
7699         break;
7700       case LibFunc_memcmp:
7701         if (visitMemCmpCall(I))
7702           return;
7703         break;
7704       case LibFunc_mempcpy:
7705         if (visitMemPCpyCall(I))
7706           return;
7707         break;
7708       case LibFunc_memchr:
7709         if (visitMemChrCall(I))
7710           return;
7711         break;
7712       case LibFunc_strcpy:
7713         if (visitStrCpyCall(I, false))
7714           return;
7715         break;
7716       case LibFunc_stpcpy:
7717         if (visitStrCpyCall(I, true))
7718           return;
7719         break;
7720       case LibFunc_strcmp:
7721         if (visitStrCmpCall(I))
7722           return;
7723         break;
7724       case LibFunc_strlen:
7725         if (visitStrLenCall(I))
7726           return;
7727         break;
7728       case LibFunc_strnlen:
7729         if (visitStrNLenCall(I))
7730           return;
7731         break;
7732       }
7733     }
7734   }
7735 
7736   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7737   // have to do anything here to lower funclet bundles.
7738   // CFGuardTarget bundles are lowered in LowerCallTo.
7739   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7740                                         LLVMContext::OB_funclet,
7741                                         LLVMContext::OB_cfguardtarget}) &&
7742          "Cannot lower calls with arbitrary operand bundles!");
7743 
7744   SDValue Callee = getValue(I.getCalledValue());
7745 
7746   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7747     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7748   else
7749     // Check if we can potentially perform a tail call. More detailed checking
7750     // is be done within LowerCallTo, after more information about the call is
7751     // known.
7752     LowerCallTo(&I, Callee, I.isTailCall());
7753 }
7754 
7755 namespace {
7756 
7757 /// AsmOperandInfo - This contains information for each constraint that we are
7758 /// lowering.
7759 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7760 public:
7761   /// CallOperand - If this is the result output operand or a clobber
7762   /// this is null, otherwise it is the incoming operand to the CallInst.
7763   /// This gets modified as the asm is processed.
7764   SDValue CallOperand;
7765 
7766   /// AssignedRegs - If this is a register or register class operand, this
7767   /// contains the set of register corresponding to the operand.
7768   RegsForValue AssignedRegs;
7769 
7770   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7771     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7772   }
7773 
7774   /// Whether or not this operand accesses memory
7775   bool hasMemory(const TargetLowering &TLI) const {
7776     // Indirect operand accesses access memory.
7777     if (isIndirect)
7778       return true;
7779 
7780     for (const auto &Code : Codes)
7781       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7782         return true;
7783 
7784     return false;
7785   }
7786 
7787   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7788   /// corresponds to.  If there is no Value* for this operand, it returns
7789   /// MVT::Other.
7790   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7791                            const DataLayout &DL) const {
7792     if (!CallOperandVal) return MVT::Other;
7793 
7794     if (isa<BasicBlock>(CallOperandVal))
7795       return TLI.getPointerTy(DL);
7796 
7797     llvm::Type *OpTy = CallOperandVal->getType();
7798 
7799     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7800     // If this is an indirect operand, the operand is a pointer to the
7801     // accessed type.
7802     if (isIndirect) {
7803       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7804       if (!PtrTy)
7805         report_fatal_error("Indirect operand for inline asm not a pointer!");
7806       OpTy = PtrTy->getElementType();
7807     }
7808 
7809     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7810     if (StructType *STy = dyn_cast<StructType>(OpTy))
7811       if (STy->getNumElements() == 1)
7812         OpTy = STy->getElementType(0);
7813 
7814     // If OpTy is not a single value, it may be a struct/union that we
7815     // can tile with integers.
7816     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7817       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7818       switch (BitSize) {
7819       default: break;
7820       case 1:
7821       case 8:
7822       case 16:
7823       case 32:
7824       case 64:
7825       case 128:
7826         OpTy = IntegerType::get(Context, BitSize);
7827         break;
7828       }
7829     }
7830 
7831     return TLI.getValueType(DL, OpTy, true);
7832   }
7833 };
7834 
7835 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7836 
7837 } // end anonymous namespace
7838 
7839 /// Make sure that the output operand \p OpInfo and its corresponding input
7840 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7841 /// out).
7842 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7843                                SDISelAsmOperandInfo &MatchingOpInfo,
7844                                SelectionDAG &DAG) {
7845   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7846     return;
7847 
7848   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7849   const auto &TLI = DAG.getTargetLoweringInfo();
7850 
7851   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7852       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7853                                        OpInfo.ConstraintVT);
7854   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7855       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7856                                        MatchingOpInfo.ConstraintVT);
7857   if ((OpInfo.ConstraintVT.isInteger() !=
7858        MatchingOpInfo.ConstraintVT.isInteger()) ||
7859       (MatchRC.second != InputRC.second)) {
7860     // FIXME: error out in a more elegant fashion
7861     report_fatal_error("Unsupported asm: input constraint"
7862                        " with a matching output constraint of"
7863                        " incompatible type!");
7864   }
7865   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7866 }
7867 
7868 /// Get a direct memory input to behave well as an indirect operand.
7869 /// This may introduce stores, hence the need for a \p Chain.
7870 /// \return The (possibly updated) chain.
7871 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7872                                         SDISelAsmOperandInfo &OpInfo,
7873                                         SelectionDAG &DAG) {
7874   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7875 
7876   // If we don't have an indirect input, put it in the constpool if we can,
7877   // otherwise spill it to a stack slot.
7878   // TODO: This isn't quite right. We need to handle these according to
7879   // the addressing mode that the constraint wants. Also, this may take
7880   // an additional register for the computation and we don't want that
7881   // either.
7882 
7883   // If the operand is a float, integer, or vector constant, spill to a
7884   // constant pool entry to get its address.
7885   const Value *OpVal = OpInfo.CallOperandVal;
7886   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7887       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7888     OpInfo.CallOperand = DAG.getConstantPool(
7889         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7890     return Chain;
7891   }
7892 
7893   // Otherwise, create a stack slot and emit a store to it before the asm.
7894   Type *Ty = OpVal->getType();
7895   auto &DL = DAG.getDataLayout();
7896   uint64_t TySize = DL.getTypeAllocSize(Ty);
7897   unsigned Align = DL.getPrefTypeAlignment(Ty);
7898   MachineFunction &MF = DAG.getMachineFunction();
7899   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7900   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7901   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7902                             MachinePointerInfo::getFixedStack(MF, SSFI),
7903                             TLI.getMemValueType(DL, Ty));
7904   OpInfo.CallOperand = StackSlot;
7905 
7906   return Chain;
7907 }
7908 
7909 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7910 /// specified operand.  We prefer to assign virtual registers, to allow the
7911 /// register allocator to handle the assignment process.  However, if the asm
7912 /// uses features that we can't model on machineinstrs, we have SDISel do the
7913 /// allocation.  This produces generally horrible, but correct, code.
7914 ///
7915 ///   OpInfo describes the operand
7916 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7917 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7918                                  SDISelAsmOperandInfo &OpInfo,
7919                                  SDISelAsmOperandInfo &RefOpInfo) {
7920   LLVMContext &Context = *DAG.getContext();
7921   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7922 
7923   MachineFunction &MF = DAG.getMachineFunction();
7924   SmallVector<unsigned, 4> Regs;
7925   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7926 
7927   // No work to do for memory operations.
7928   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7929     return;
7930 
7931   // If this is a constraint for a single physreg, or a constraint for a
7932   // register class, find it.
7933   unsigned AssignedReg;
7934   const TargetRegisterClass *RC;
7935   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7936       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7937   // RC is unset only on failure. Return immediately.
7938   if (!RC)
7939     return;
7940 
7941   // Get the actual register value type.  This is important, because the user
7942   // may have asked for (e.g.) the AX register in i32 type.  We need to
7943   // remember that AX is actually i16 to get the right extension.
7944   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7945 
7946   if (OpInfo.ConstraintVT != MVT::Other) {
7947     // If this is an FP operand in an integer register (or visa versa), or more
7948     // generally if the operand value disagrees with the register class we plan
7949     // to stick it in, fix the operand type.
7950     //
7951     // If this is an input value, the bitcast to the new type is done now.
7952     // Bitcast for output value is done at the end of visitInlineAsm().
7953     if ((OpInfo.Type == InlineAsm::isOutput ||
7954          OpInfo.Type == InlineAsm::isInput) &&
7955         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7956       // Try to convert to the first EVT that the reg class contains.  If the
7957       // types are identical size, use a bitcast to convert (e.g. two differing
7958       // vector types).  Note: output bitcast is done at the end of
7959       // visitInlineAsm().
7960       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7961         // Exclude indirect inputs while they are unsupported because the code
7962         // to perform the load is missing and thus OpInfo.CallOperand still
7963         // refers to the input address rather than the pointed-to value.
7964         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7965           OpInfo.CallOperand =
7966               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7967         OpInfo.ConstraintVT = RegVT;
7968         // If the operand is an FP value and we want it in integer registers,
7969         // use the corresponding integer type. This turns an f64 value into
7970         // i64, which can be passed with two i32 values on a 32-bit machine.
7971       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7972         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7973         if (OpInfo.Type == InlineAsm::isInput)
7974           OpInfo.CallOperand =
7975               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7976         OpInfo.ConstraintVT = VT;
7977       }
7978     }
7979   }
7980 
7981   // No need to allocate a matching input constraint since the constraint it's
7982   // matching to has already been allocated.
7983   if (OpInfo.isMatchingInputConstraint())
7984     return;
7985 
7986   EVT ValueVT = OpInfo.ConstraintVT;
7987   if (OpInfo.ConstraintVT == MVT::Other)
7988     ValueVT = RegVT;
7989 
7990   // Initialize NumRegs.
7991   unsigned NumRegs = 1;
7992   if (OpInfo.ConstraintVT != MVT::Other)
7993     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7994 
7995   // If this is a constraint for a specific physical register, like {r17},
7996   // assign it now.
7997 
7998   // If this associated to a specific register, initialize iterator to correct
7999   // place. If virtual, make sure we have enough registers
8000 
8001   // Initialize iterator if necessary
8002   TargetRegisterClass::iterator I = RC->begin();
8003   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8004 
8005   // Do not check for single registers.
8006   if (AssignedReg) {
8007       for (; *I != AssignedReg; ++I)
8008         assert(I != RC->end() && "AssignedReg should be member of RC");
8009   }
8010 
8011   for (; NumRegs; --NumRegs, ++I) {
8012     assert(I != RC->end() && "Ran out of registers to allocate!");
8013     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8014     Regs.push_back(R);
8015   }
8016 
8017   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8018 }
8019 
8020 static unsigned
8021 findMatchingInlineAsmOperand(unsigned OperandNo,
8022                              const std::vector<SDValue> &AsmNodeOperands) {
8023   // Scan until we find the definition we already emitted of this operand.
8024   unsigned CurOp = InlineAsm::Op_FirstOperand;
8025   for (; OperandNo; --OperandNo) {
8026     // Advance to the next operand.
8027     unsigned OpFlag =
8028         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8029     assert((InlineAsm::isRegDefKind(OpFlag) ||
8030             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8031             InlineAsm::isMemKind(OpFlag)) &&
8032            "Skipped past definitions?");
8033     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8034   }
8035   return CurOp;
8036 }
8037 
8038 namespace {
8039 
8040 class ExtraFlags {
8041   unsigned Flags = 0;
8042 
8043 public:
8044   explicit ExtraFlags(ImmutableCallSite CS) {
8045     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8046     if (IA->hasSideEffects())
8047       Flags |= InlineAsm::Extra_HasSideEffects;
8048     if (IA->isAlignStack())
8049       Flags |= InlineAsm::Extra_IsAlignStack;
8050     if (CS.isConvergent())
8051       Flags |= InlineAsm::Extra_IsConvergent;
8052     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8053   }
8054 
8055   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8056     // Ideally, we would only check against memory constraints.  However, the
8057     // meaning of an Other constraint can be target-specific and we can't easily
8058     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8059     // for Other constraints as well.
8060     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8061         OpInfo.ConstraintType == TargetLowering::C_Other) {
8062       if (OpInfo.Type == InlineAsm::isInput)
8063         Flags |= InlineAsm::Extra_MayLoad;
8064       else if (OpInfo.Type == InlineAsm::isOutput)
8065         Flags |= InlineAsm::Extra_MayStore;
8066       else if (OpInfo.Type == InlineAsm::isClobber)
8067         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8068     }
8069   }
8070 
8071   unsigned get() const { return Flags; }
8072 };
8073 
8074 } // end anonymous namespace
8075 
8076 /// visitInlineAsm - Handle a call to an InlineAsm object.
8077 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
8078   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8079 
8080   /// ConstraintOperands - Information about all of the constraints.
8081   SDISelAsmOperandInfoVector ConstraintOperands;
8082 
8083   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8084   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8085       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
8086 
8087   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8088   // AsmDialect, MayLoad, MayStore).
8089   bool HasSideEffect = IA->hasSideEffects();
8090   ExtraFlags ExtraInfo(CS);
8091 
8092   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8093   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8094   for (auto &T : TargetConstraints) {
8095     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8096     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8097 
8098     // Compute the value type for each operand.
8099     if (OpInfo.Type == InlineAsm::isInput ||
8100         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8101       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
8102 
8103       // Process the call argument. BasicBlocks are labels, currently appearing
8104       // only in asm's.
8105       const Instruction *I = CS.getInstruction();
8106       if (isa<CallBrInst>(I) &&
8107           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
8108                           cast<CallBrInst>(I)->getNumIndirectDests())) {
8109         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8110         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8111         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8112       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8113         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8114       } else {
8115         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8116       }
8117 
8118       OpInfo.ConstraintVT =
8119           OpInfo
8120               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8121               .getSimpleVT();
8122     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8123       // The return value of the call is this value.  As such, there is no
8124       // corresponding argument.
8125       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8126       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8127         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8128             DAG.getDataLayout(), STy->getElementType(ResNo));
8129       } else {
8130         assert(ResNo == 0 && "Asm only has one result!");
8131         OpInfo.ConstraintVT =
8132             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8133       }
8134       ++ResNo;
8135     } else {
8136       OpInfo.ConstraintVT = MVT::Other;
8137     }
8138 
8139     if (!HasSideEffect)
8140       HasSideEffect = OpInfo.hasMemory(TLI);
8141 
8142     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8143     // FIXME: Could we compute this on OpInfo rather than T?
8144 
8145     // Compute the constraint code and ConstraintType to use.
8146     TLI.ComputeConstraintToUse(T, SDValue());
8147 
8148     if (T.ConstraintType == TargetLowering::C_Immediate &&
8149         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8150       // We've delayed emitting a diagnostic like the "n" constraint because
8151       // inlining could cause an integer showing up.
8152       return emitInlineAsmError(
8153           CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8154                   "integer constant expression");
8155 
8156     ExtraInfo.update(T);
8157   }
8158 
8159 
8160   // We won't need to flush pending loads if this asm doesn't touch
8161   // memory and is nonvolatile.
8162   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8163 
8164   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8165   if (IsCallBr) {
8166     // If this is a callbr we need to flush pending exports since inlineasm_br
8167     // is a terminator. We need to do this before nodes are glued to
8168     // the inlineasm_br node.
8169     Chain = getControlRoot();
8170   }
8171 
8172   // Second pass over the constraints: compute which constraint option to use.
8173   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8174     // If this is an output operand with a matching input operand, look up the
8175     // matching input. If their types mismatch, e.g. one is an integer, the
8176     // other is floating point, or their sizes are different, flag it as an
8177     // error.
8178     if (OpInfo.hasMatchingInput()) {
8179       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8180       patchMatchingInput(OpInfo, Input, DAG);
8181     }
8182 
8183     // Compute the constraint code and ConstraintType to use.
8184     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8185 
8186     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8187         OpInfo.Type == InlineAsm::isClobber)
8188       continue;
8189 
8190     // If this is a memory input, and if the operand is not indirect, do what we
8191     // need to provide an address for the memory input.
8192     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8193         !OpInfo.isIndirect) {
8194       assert((OpInfo.isMultipleAlternative ||
8195               (OpInfo.Type == InlineAsm::isInput)) &&
8196              "Can only indirectify direct input operands!");
8197 
8198       // Memory operands really want the address of the value.
8199       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8200 
8201       // There is no longer a Value* corresponding to this operand.
8202       OpInfo.CallOperandVal = nullptr;
8203 
8204       // It is now an indirect operand.
8205       OpInfo.isIndirect = true;
8206     }
8207 
8208   }
8209 
8210   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8211   std::vector<SDValue> AsmNodeOperands;
8212   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8213   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8214       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8215 
8216   // If we have a !srcloc metadata node associated with it, we want to attach
8217   // this to the ultimately generated inline asm machineinstr.  To do this, we
8218   // pass in the third operand as this (potentially null) inline asm MDNode.
8219   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8220   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8221 
8222   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8223   // bits as operand 3.
8224   AsmNodeOperands.push_back(DAG.getTargetConstant(
8225       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8226 
8227   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8228   // this, assign virtual and physical registers for inputs and otput.
8229   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8230     // Assign Registers.
8231     SDISelAsmOperandInfo &RefOpInfo =
8232         OpInfo.isMatchingInputConstraint()
8233             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8234             : OpInfo;
8235     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8236 
8237     switch (OpInfo.Type) {
8238     case InlineAsm::isOutput:
8239       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8240         unsigned ConstraintID =
8241             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8242         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8243                "Failed to convert memory constraint code to constraint id.");
8244 
8245         // Add information to the INLINEASM node to know about this output.
8246         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8247         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8248         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8249                                                         MVT::i32));
8250         AsmNodeOperands.push_back(OpInfo.CallOperand);
8251       } else {
8252         // Otherwise, this outputs to a register (directly for C_Register /
8253         // C_RegisterClass, and a target-defined fashion for
8254         // C_Immediate/C_Other). Find a register that we can use.
8255         if (OpInfo.AssignedRegs.Regs.empty()) {
8256           emitInlineAsmError(
8257               CS, "couldn't allocate output register for constraint '" +
8258                       Twine(OpInfo.ConstraintCode) + "'");
8259           return;
8260         }
8261 
8262         // Add information to the INLINEASM node to know that this register is
8263         // set.
8264         OpInfo.AssignedRegs.AddInlineAsmOperands(
8265             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8266                                   : InlineAsm::Kind_RegDef,
8267             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8268       }
8269       break;
8270 
8271     case InlineAsm::isInput: {
8272       SDValue InOperandVal = OpInfo.CallOperand;
8273 
8274       if (OpInfo.isMatchingInputConstraint()) {
8275         // If this is required to match an output register we have already set,
8276         // just use its register.
8277         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8278                                                   AsmNodeOperands);
8279         unsigned OpFlag =
8280           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8281         if (InlineAsm::isRegDefKind(OpFlag) ||
8282             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8283           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8284           if (OpInfo.isIndirect) {
8285             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8286             emitInlineAsmError(CS, "inline asm not supported yet:"
8287                                    " don't know how to handle tied "
8288                                    "indirect register inputs");
8289             return;
8290           }
8291 
8292           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8293           SmallVector<unsigned, 4> Regs;
8294 
8295           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8296             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8297             MachineRegisterInfo &RegInfo =
8298                 DAG.getMachineFunction().getRegInfo();
8299             for (unsigned i = 0; i != NumRegs; ++i)
8300               Regs.push_back(RegInfo.createVirtualRegister(RC));
8301           } else {
8302             emitInlineAsmError(CS, "inline asm error: This value type register "
8303                                    "class is not natively supported!");
8304             return;
8305           }
8306 
8307           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8308 
8309           SDLoc dl = getCurSDLoc();
8310           // Use the produced MatchedRegs object to
8311           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8312                                     CS.getInstruction());
8313           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8314                                            true, OpInfo.getMatchedOperand(), dl,
8315                                            DAG, AsmNodeOperands);
8316           break;
8317         }
8318 
8319         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8320         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8321                "Unexpected number of operands");
8322         // Add information to the INLINEASM node to know about this input.
8323         // See InlineAsm.h isUseOperandTiedToDef.
8324         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8325         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8326                                                     OpInfo.getMatchedOperand());
8327         AsmNodeOperands.push_back(DAG.getTargetConstant(
8328             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8329         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8330         break;
8331       }
8332 
8333       // Treat indirect 'X' constraint as memory.
8334       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8335           OpInfo.isIndirect)
8336         OpInfo.ConstraintType = TargetLowering::C_Memory;
8337 
8338       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8339           OpInfo.ConstraintType == TargetLowering::C_Other) {
8340         std::vector<SDValue> Ops;
8341         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8342                                           Ops, DAG);
8343         if (Ops.empty()) {
8344           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8345             if (isa<ConstantSDNode>(InOperandVal)) {
8346               emitInlineAsmError(CS, "value out of range for constraint '" +
8347                                  Twine(OpInfo.ConstraintCode) + "'");
8348               return;
8349             }
8350 
8351           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8352                                      Twine(OpInfo.ConstraintCode) + "'");
8353           return;
8354         }
8355 
8356         // Add information to the INLINEASM node to know about this input.
8357         unsigned ResOpType =
8358           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8359         AsmNodeOperands.push_back(DAG.getTargetConstant(
8360             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8361         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8362         break;
8363       }
8364 
8365       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8366         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8367         assert(InOperandVal.getValueType() ==
8368                    TLI.getPointerTy(DAG.getDataLayout()) &&
8369                "Memory operands expect pointer values");
8370 
8371         unsigned ConstraintID =
8372             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8373         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8374                "Failed to convert memory constraint code to constraint id.");
8375 
8376         // Add information to the INLINEASM node to know about this input.
8377         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8378         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8379         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8380                                                         getCurSDLoc(),
8381                                                         MVT::i32));
8382         AsmNodeOperands.push_back(InOperandVal);
8383         break;
8384       }
8385 
8386       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8387               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8388              "Unknown constraint type!");
8389 
8390       // TODO: Support this.
8391       if (OpInfo.isIndirect) {
8392         emitInlineAsmError(
8393             CS, "Don't know how to handle indirect register inputs yet "
8394                 "for constraint '" +
8395                     Twine(OpInfo.ConstraintCode) + "'");
8396         return;
8397       }
8398 
8399       // Copy the input into the appropriate registers.
8400       if (OpInfo.AssignedRegs.Regs.empty()) {
8401         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8402                                    Twine(OpInfo.ConstraintCode) + "'");
8403         return;
8404       }
8405 
8406       SDLoc dl = getCurSDLoc();
8407 
8408       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8409                                         Chain, &Flag, CS.getInstruction());
8410 
8411       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8412                                                dl, DAG, AsmNodeOperands);
8413       break;
8414     }
8415     case InlineAsm::isClobber:
8416       // Add the clobbered value to the operand list, so that the register
8417       // allocator is aware that the physreg got clobbered.
8418       if (!OpInfo.AssignedRegs.Regs.empty())
8419         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8420                                                  false, 0, getCurSDLoc(), DAG,
8421                                                  AsmNodeOperands);
8422       break;
8423     }
8424   }
8425 
8426   // Finish up input operands.  Set the input chain and add the flag last.
8427   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8428   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8429 
8430   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8431   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8432                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8433   Flag = Chain.getValue(1);
8434 
8435   // Do additional work to generate outputs.
8436 
8437   SmallVector<EVT, 1> ResultVTs;
8438   SmallVector<SDValue, 1> ResultValues;
8439   SmallVector<SDValue, 8> OutChains;
8440 
8441   llvm::Type *CSResultType = CS.getType();
8442   ArrayRef<Type *> ResultTypes;
8443   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8444     ResultTypes = StructResult->elements();
8445   else if (!CSResultType->isVoidTy())
8446     ResultTypes = makeArrayRef(CSResultType);
8447 
8448   auto CurResultType = ResultTypes.begin();
8449   auto handleRegAssign = [&](SDValue V) {
8450     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8451     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8452     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8453     ++CurResultType;
8454     // If the type of the inline asm call site return value is different but has
8455     // same size as the type of the asm output bitcast it.  One example of this
8456     // is for vectors with different width / number of elements.  This can
8457     // happen for register classes that can contain multiple different value
8458     // types.  The preg or vreg allocated may not have the same VT as was
8459     // expected.
8460     //
8461     // This can also happen for a return value that disagrees with the register
8462     // class it is put in, eg. a double in a general-purpose register on a
8463     // 32-bit machine.
8464     if (ResultVT != V.getValueType() &&
8465         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8466       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8467     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8468              V.getValueType().isInteger()) {
8469       // If a result value was tied to an input value, the computed result
8470       // may have a wider width than the expected result.  Extract the
8471       // relevant portion.
8472       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8473     }
8474     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8475     ResultVTs.push_back(ResultVT);
8476     ResultValues.push_back(V);
8477   };
8478 
8479   // Deal with output operands.
8480   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8481     if (OpInfo.Type == InlineAsm::isOutput) {
8482       SDValue Val;
8483       // Skip trivial output operands.
8484       if (OpInfo.AssignedRegs.Regs.empty())
8485         continue;
8486 
8487       switch (OpInfo.ConstraintType) {
8488       case TargetLowering::C_Register:
8489       case TargetLowering::C_RegisterClass:
8490         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8491             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8492         break;
8493       case TargetLowering::C_Immediate:
8494       case TargetLowering::C_Other:
8495         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8496                                               OpInfo, DAG);
8497         break;
8498       case TargetLowering::C_Memory:
8499         break; // Already handled.
8500       case TargetLowering::C_Unknown:
8501         assert(false && "Unexpected unknown constraint");
8502       }
8503 
8504       // Indirect output manifest as stores. Record output chains.
8505       if (OpInfo.isIndirect) {
8506         const Value *Ptr = OpInfo.CallOperandVal;
8507         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8508         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8509                                      MachinePointerInfo(Ptr));
8510         OutChains.push_back(Store);
8511       } else {
8512         // generate CopyFromRegs to associated registers.
8513         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8514         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8515           for (const SDValue &V : Val->op_values())
8516             handleRegAssign(V);
8517         } else
8518           handleRegAssign(Val);
8519       }
8520     }
8521   }
8522 
8523   // Set results.
8524   if (!ResultValues.empty()) {
8525     assert(CurResultType == ResultTypes.end() &&
8526            "Mismatch in number of ResultTypes");
8527     assert(ResultValues.size() == ResultTypes.size() &&
8528            "Mismatch in number of output operands in asm result");
8529 
8530     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8531                             DAG.getVTList(ResultVTs), ResultValues);
8532     setValue(CS.getInstruction(), V);
8533   }
8534 
8535   // Collect store chains.
8536   if (!OutChains.empty())
8537     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8538 
8539   // Only Update Root if inline assembly has a memory effect.
8540   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8541     DAG.setRoot(Chain);
8542 }
8543 
8544 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8545                                              const Twine &Message) {
8546   LLVMContext &Ctx = *DAG.getContext();
8547   Ctx.emitError(CS.getInstruction(), Message);
8548 
8549   // Make sure we leave the DAG in a valid state
8550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8551   SmallVector<EVT, 1> ValueVTs;
8552   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8553 
8554   if (ValueVTs.empty())
8555     return;
8556 
8557   SmallVector<SDValue, 1> Ops;
8558   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8559     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8560 
8561   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8562 }
8563 
8564 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8565   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8566                           MVT::Other, getRoot(),
8567                           getValue(I.getArgOperand(0)),
8568                           DAG.getSrcValue(I.getArgOperand(0))));
8569 }
8570 
8571 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8572   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8573   const DataLayout &DL = DAG.getDataLayout();
8574   SDValue V = DAG.getVAArg(
8575       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8576       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8577       DL.getABITypeAlignment(I.getType()));
8578   DAG.setRoot(V.getValue(1));
8579 
8580   if (I.getType()->isPointerTy())
8581     V = DAG.getPtrExtOrTrunc(
8582         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8583   setValue(&I, V);
8584 }
8585 
8586 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8587   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8588                           MVT::Other, getRoot(),
8589                           getValue(I.getArgOperand(0)),
8590                           DAG.getSrcValue(I.getArgOperand(0))));
8591 }
8592 
8593 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8594   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8595                           MVT::Other, getRoot(),
8596                           getValue(I.getArgOperand(0)),
8597                           getValue(I.getArgOperand(1)),
8598                           DAG.getSrcValue(I.getArgOperand(0)),
8599                           DAG.getSrcValue(I.getArgOperand(1))));
8600 }
8601 
8602 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8603                                                     const Instruction &I,
8604                                                     SDValue Op) {
8605   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8606   if (!Range)
8607     return Op;
8608 
8609   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8610   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8611     return Op;
8612 
8613   APInt Lo = CR.getUnsignedMin();
8614   if (!Lo.isMinValue())
8615     return Op;
8616 
8617   APInt Hi = CR.getUnsignedMax();
8618   unsigned Bits = std::max(Hi.getActiveBits(),
8619                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8620 
8621   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8622 
8623   SDLoc SL = getCurSDLoc();
8624 
8625   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8626                              DAG.getValueType(SmallVT));
8627   unsigned NumVals = Op.getNode()->getNumValues();
8628   if (NumVals == 1)
8629     return ZExt;
8630 
8631   SmallVector<SDValue, 4> Ops;
8632 
8633   Ops.push_back(ZExt);
8634   for (unsigned I = 1; I != NumVals; ++I)
8635     Ops.push_back(Op.getValue(I));
8636 
8637   return DAG.getMergeValues(Ops, SL);
8638 }
8639 
8640 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8641 /// the call being lowered.
8642 ///
8643 /// This is a helper for lowering intrinsics that follow a target calling
8644 /// convention or require stack pointer adjustment. Only a subset of the
8645 /// intrinsic's operands need to participate in the calling convention.
8646 void SelectionDAGBuilder::populateCallLoweringInfo(
8647     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8648     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8649     bool IsPatchPoint) {
8650   TargetLowering::ArgListTy Args;
8651   Args.reserve(NumArgs);
8652 
8653   // Populate the argument list.
8654   // Attributes for args start at offset 1, after the return attribute.
8655   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8656        ArgI != ArgE; ++ArgI) {
8657     const Value *V = Call->getOperand(ArgI);
8658 
8659     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8660 
8661     TargetLowering::ArgListEntry Entry;
8662     Entry.Node = getValue(V);
8663     Entry.Ty = V->getType();
8664     Entry.setAttributes(Call, ArgI);
8665     Args.push_back(Entry);
8666   }
8667 
8668   CLI.setDebugLoc(getCurSDLoc())
8669       .setChain(getRoot())
8670       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8671       .setDiscardResult(Call->use_empty())
8672       .setIsPatchPoint(IsPatchPoint);
8673 }
8674 
8675 /// Add a stack map intrinsic call's live variable operands to a stackmap
8676 /// or patchpoint target node's operand list.
8677 ///
8678 /// Constants are converted to TargetConstants purely as an optimization to
8679 /// avoid constant materialization and register allocation.
8680 ///
8681 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8682 /// generate addess computation nodes, and so FinalizeISel can convert the
8683 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8684 /// address materialization and register allocation, but may also be required
8685 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8686 /// alloca in the entry block, then the runtime may assume that the alloca's
8687 /// StackMap location can be read immediately after compilation and that the
8688 /// location is valid at any point during execution (this is similar to the
8689 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8690 /// only available in a register, then the runtime would need to trap when
8691 /// execution reaches the StackMap in order to read the alloca's location.
8692 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8693                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8694                                 SelectionDAGBuilder &Builder) {
8695   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8696     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8697     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8698       Ops.push_back(
8699         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8700       Ops.push_back(
8701         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8702     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8703       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8704       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8705           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8706     } else
8707       Ops.push_back(OpVal);
8708   }
8709 }
8710 
8711 /// Lower llvm.experimental.stackmap directly to its target opcode.
8712 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8713   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8714   //                                  [live variables...])
8715 
8716   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8717 
8718   SDValue Chain, InFlag, Callee, NullPtr;
8719   SmallVector<SDValue, 32> Ops;
8720 
8721   SDLoc DL = getCurSDLoc();
8722   Callee = getValue(CI.getCalledValue());
8723   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8724 
8725   // The stackmap intrinsic only records the live variables (the arguments
8726   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8727   // intrinsic, this won't be lowered to a function call. This means we don't
8728   // have to worry about calling conventions and target specific lowering code.
8729   // Instead we perform the call lowering right here.
8730   //
8731   // chain, flag = CALLSEQ_START(chain, 0, 0)
8732   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8733   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8734   //
8735   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8736   InFlag = Chain.getValue(1);
8737 
8738   // Add the <id> and <numBytes> constants.
8739   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8740   Ops.push_back(DAG.getTargetConstant(
8741                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8742   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8743   Ops.push_back(DAG.getTargetConstant(
8744                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8745                   MVT::i32));
8746 
8747   // Push live variables for the stack map.
8748   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8749 
8750   // We are not pushing any register mask info here on the operands list,
8751   // because the stackmap doesn't clobber anything.
8752 
8753   // Push the chain and the glue flag.
8754   Ops.push_back(Chain);
8755   Ops.push_back(InFlag);
8756 
8757   // Create the STACKMAP node.
8758   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8759   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8760   Chain = SDValue(SM, 0);
8761   InFlag = Chain.getValue(1);
8762 
8763   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8764 
8765   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8766 
8767   // Set the root to the target-lowered call chain.
8768   DAG.setRoot(Chain);
8769 
8770   // Inform the Frame Information that we have a stackmap in this function.
8771   FuncInfo.MF->getFrameInfo().setHasStackMap();
8772 }
8773 
8774 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8775 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8776                                           const BasicBlock *EHPadBB) {
8777   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8778   //                                                 i32 <numBytes>,
8779   //                                                 i8* <target>,
8780   //                                                 i32 <numArgs>,
8781   //                                                 [Args...],
8782   //                                                 [live variables...])
8783 
8784   CallingConv::ID CC = CS.getCallingConv();
8785   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8786   bool HasDef = !CS->getType()->isVoidTy();
8787   SDLoc dl = getCurSDLoc();
8788   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8789 
8790   // Handle immediate and symbolic callees.
8791   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8792     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8793                                    /*isTarget=*/true);
8794   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8795     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8796                                          SDLoc(SymbolicCallee),
8797                                          SymbolicCallee->getValueType(0));
8798 
8799   // Get the real number of arguments participating in the call <numArgs>
8800   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8801   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8802 
8803   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8804   // Intrinsics include all meta-operands up to but not including CC.
8805   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8806   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8807          "Not enough arguments provided to the patchpoint intrinsic");
8808 
8809   // For AnyRegCC the arguments are lowered later on manually.
8810   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8811   Type *ReturnTy =
8812     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8813 
8814   TargetLowering::CallLoweringInfo CLI(DAG);
8815   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8816                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8817   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8818 
8819   SDNode *CallEnd = Result.second.getNode();
8820   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8821     CallEnd = CallEnd->getOperand(0).getNode();
8822 
8823   /// Get a call instruction from the call sequence chain.
8824   /// Tail calls are not allowed.
8825   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8826          "Expected a callseq node.");
8827   SDNode *Call = CallEnd->getOperand(0).getNode();
8828   bool HasGlue = Call->getGluedNode();
8829 
8830   // Replace the target specific call node with the patchable intrinsic.
8831   SmallVector<SDValue, 8> Ops;
8832 
8833   // Add the <id> and <numBytes> constants.
8834   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8835   Ops.push_back(DAG.getTargetConstant(
8836                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8837   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8838   Ops.push_back(DAG.getTargetConstant(
8839                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8840                   MVT::i32));
8841 
8842   // Add the callee.
8843   Ops.push_back(Callee);
8844 
8845   // Adjust <numArgs> to account for any arguments that have been passed on the
8846   // stack instead.
8847   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8848   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8849   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8850   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8851 
8852   // Add the calling convention
8853   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8854 
8855   // Add the arguments we omitted previously. The register allocator should
8856   // place these in any free register.
8857   if (IsAnyRegCC)
8858     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8859       Ops.push_back(getValue(CS.getArgument(i)));
8860 
8861   // Push the arguments from the call instruction up to the register mask.
8862   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8863   Ops.append(Call->op_begin() + 2, e);
8864 
8865   // Push live variables for the stack map.
8866   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8867 
8868   // Push the register mask info.
8869   if (HasGlue)
8870     Ops.push_back(*(Call->op_end()-2));
8871   else
8872     Ops.push_back(*(Call->op_end()-1));
8873 
8874   // Push the chain (this is originally the first operand of the call, but
8875   // becomes now the last or second to last operand).
8876   Ops.push_back(*(Call->op_begin()));
8877 
8878   // Push the glue flag (last operand).
8879   if (HasGlue)
8880     Ops.push_back(*(Call->op_end()-1));
8881 
8882   SDVTList NodeTys;
8883   if (IsAnyRegCC && HasDef) {
8884     // Create the return types based on the intrinsic definition
8885     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8886     SmallVector<EVT, 3> ValueVTs;
8887     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8888     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8889 
8890     // There is always a chain and a glue type at the end
8891     ValueVTs.push_back(MVT::Other);
8892     ValueVTs.push_back(MVT::Glue);
8893     NodeTys = DAG.getVTList(ValueVTs);
8894   } else
8895     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8896 
8897   // Replace the target specific call node with a PATCHPOINT node.
8898   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8899                                          dl, NodeTys, Ops);
8900 
8901   // Update the NodeMap.
8902   if (HasDef) {
8903     if (IsAnyRegCC)
8904       setValue(CS.getInstruction(), SDValue(MN, 0));
8905     else
8906       setValue(CS.getInstruction(), Result.first);
8907   }
8908 
8909   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8910   // call sequence. Furthermore the location of the chain and glue can change
8911   // when the AnyReg calling convention is used and the intrinsic returns a
8912   // value.
8913   if (IsAnyRegCC && HasDef) {
8914     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8915     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8916     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8917   } else
8918     DAG.ReplaceAllUsesWith(Call, MN);
8919   DAG.DeleteNode(Call);
8920 
8921   // Inform the Frame Information that we have a patchpoint in this function.
8922   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8923 }
8924 
8925 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8926                                             unsigned Intrinsic) {
8927   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8928   SDValue Op1 = getValue(I.getArgOperand(0));
8929   SDValue Op2;
8930   if (I.getNumArgOperands() > 1)
8931     Op2 = getValue(I.getArgOperand(1));
8932   SDLoc dl = getCurSDLoc();
8933   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8934   SDValue Res;
8935   FastMathFlags FMF;
8936   if (isa<FPMathOperator>(I))
8937     FMF = I.getFastMathFlags();
8938 
8939   switch (Intrinsic) {
8940   case Intrinsic::experimental_vector_reduce_v2_fadd:
8941     if (FMF.allowReassoc())
8942       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8943                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8944     else
8945       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8946     break;
8947   case Intrinsic::experimental_vector_reduce_v2_fmul:
8948     if (FMF.allowReassoc())
8949       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8950                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8951     else
8952       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8953     break;
8954   case Intrinsic::experimental_vector_reduce_add:
8955     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8956     break;
8957   case Intrinsic::experimental_vector_reduce_mul:
8958     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8959     break;
8960   case Intrinsic::experimental_vector_reduce_and:
8961     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8962     break;
8963   case Intrinsic::experimental_vector_reduce_or:
8964     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8965     break;
8966   case Intrinsic::experimental_vector_reduce_xor:
8967     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8968     break;
8969   case Intrinsic::experimental_vector_reduce_smax:
8970     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8971     break;
8972   case Intrinsic::experimental_vector_reduce_smin:
8973     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8974     break;
8975   case Intrinsic::experimental_vector_reduce_umax:
8976     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8977     break;
8978   case Intrinsic::experimental_vector_reduce_umin:
8979     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8980     break;
8981   case Intrinsic::experimental_vector_reduce_fmax:
8982     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8983     break;
8984   case Intrinsic::experimental_vector_reduce_fmin:
8985     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8986     break;
8987   default:
8988     llvm_unreachable("Unhandled vector reduce intrinsic");
8989   }
8990   setValue(&I, Res);
8991 }
8992 
8993 /// Returns an AttributeList representing the attributes applied to the return
8994 /// value of the given call.
8995 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8996   SmallVector<Attribute::AttrKind, 2> Attrs;
8997   if (CLI.RetSExt)
8998     Attrs.push_back(Attribute::SExt);
8999   if (CLI.RetZExt)
9000     Attrs.push_back(Attribute::ZExt);
9001   if (CLI.IsInReg)
9002     Attrs.push_back(Attribute::InReg);
9003 
9004   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9005                             Attrs);
9006 }
9007 
9008 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9009 /// implementation, which just calls LowerCall.
9010 /// FIXME: When all targets are
9011 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9012 std::pair<SDValue, SDValue>
9013 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9014   // Handle the incoming return values from the call.
9015   CLI.Ins.clear();
9016   Type *OrigRetTy = CLI.RetTy;
9017   SmallVector<EVT, 4> RetTys;
9018   SmallVector<uint64_t, 4> Offsets;
9019   auto &DL = CLI.DAG.getDataLayout();
9020   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9021 
9022   if (CLI.IsPostTypeLegalization) {
9023     // If we are lowering a libcall after legalization, split the return type.
9024     SmallVector<EVT, 4> OldRetTys;
9025     SmallVector<uint64_t, 4> OldOffsets;
9026     RetTys.swap(OldRetTys);
9027     Offsets.swap(OldOffsets);
9028 
9029     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9030       EVT RetVT = OldRetTys[i];
9031       uint64_t Offset = OldOffsets[i];
9032       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9033       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9034       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9035       RetTys.append(NumRegs, RegisterVT);
9036       for (unsigned j = 0; j != NumRegs; ++j)
9037         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9038     }
9039   }
9040 
9041   SmallVector<ISD::OutputArg, 4> Outs;
9042   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9043 
9044   bool CanLowerReturn =
9045       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9046                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9047 
9048   SDValue DemoteStackSlot;
9049   int DemoteStackIdx = -100;
9050   if (!CanLowerReturn) {
9051     // FIXME: equivalent assert?
9052     // assert(!CS.hasInAllocaArgument() &&
9053     //        "sret demotion is incompatible with inalloca");
9054     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9055     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
9056     MachineFunction &MF = CLI.DAG.getMachineFunction();
9057     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
9058     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9059                                               DL.getAllocaAddrSpace());
9060 
9061     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9062     ArgListEntry Entry;
9063     Entry.Node = DemoteStackSlot;
9064     Entry.Ty = StackSlotPtrType;
9065     Entry.IsSExt = false;
9066     Entry.IsZExt = false;
9067     Entry.IsInReg = false;
9068     Entry.IsSRet = true;
9069     Entry.IsNest = false;
9070     Entry.IsByVal = false;
9071     Entry.IsReturned = false;
9072     Entry.IsSwiftSelf = false;
9073     Entry.IsSwiftError = false;
9074     Entry.IsCFGuardTarget = false;
9075     Entry.Alignment = Align;
9076     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9077     CLI.NumFixedArgs += 1;
9078     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9079 
9080     // sret demotion isn't compatible with tail-calls, since the sret argument
9081     // points into the callers stack frame.
9082     CLI.IsTailCall = false;
9083   } else {
9084     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9085         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9086     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9087       ISD::ArgFlagsTy Flags;
9088       if (NeedsRegBlock) {
9089         Flags.setInConsecutiveRegs();
9090         if (I == RetTys.size() - 1)
9091           Flags.setInConsecutiveRegsLast();
9092       }
9093       EVT VT = RetTys[I];
9094       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9095                                                      CLI.CallConv, VT);
9096       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9097                                                        CLI.CallConv, VT);
9098       for (unsigned i = 0; i != NumRegs; ++i) {
9099         ISD::InputArg MyFlags;
9100         MyFlags.Flags = Flags;
9101         MyFlags.VT = RegisterVT;
9102         MyFlags.ArgVT = VT;
9103         MyFlags.Used = CLI.IsReturnValueUsed;
9104         if (CLI.RetTy->isPointerTy()) {
9105           MyFlags.Flags.setPointer();
9106           MyFlags.Flags.setPointerAddrSpace(
9107               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9108         }
9109         if (CLI.RetSExt)
9110           MyFlags.Flags.setSExt();
9111         if (CLI.RetZExt)
9112           MyFlags.Flags.setZExt();
9113         if (CLI.IsInReg)
9114           MyFlags.Flags.setInReg();
9115         CLI.Ins.push_back(MyFlags);
9116       }
9117     }
9118   }
9119 
9120   // We push in swifterror return as the last element of CLI.Ins.
9121   ArgListTy &Args = CLI.getArgs();
9122   if (supportSwiftError()) {
9123     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9124       if (Args[i].IsSwiftError) {
9125         ISD::InputArg MyFlags;
9126         MyFlags.VT = getPointerTy(DL);
9127         MyFlags.ArgVT = EVT(getPointerTy(DL));
9128         MyFlags.Flags.setSwiftError();
9129         CLI.Ins.push_back(MyFlags);
9130       }
9131     }
9132   }
9133 
9134   // Handle all of the outgoing arguments.
9135   CLI.Outs.clear();
9136   CLI.OutVals.clear();
9137   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9138     SmallVector<EVT, 4> ValueVTs;
9139     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9140     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9141     Type *FinalType = Args[i].Ty;
9142     if (Args[i].IsByVal)
9143       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9144     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9145         FinalType, CLI.CallConv, CLI.IsVarArg);
9146     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9147          ++Value) {
9148       EVT VT = ValueVTs[Value];
9149       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9150       SDValue Op = SDValue(Args[i].Node.getNode(),
9151                            Args[i].Node.getResNo() + Value);
9152       ISD::ArgFlagsTy Flags;
9153 
9154       // Certain targets (such as MIPS), may have a different ABI alignment
9155       // for a type depending on the context. Give the target a chance to
9156       // specify the alignment it wants.
9157       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9158 
9159       if (Args[i].Ty->isPointerTy()) {
9160         Flags.setPointer();
9161         Flags.setPointerAddrSpace(
9162             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9163       }
9164       if (Args[i].IsZExt)
9165         Flags.setZExt();
9166       if (Args[i].IsSExt)
9167         Flags.setSExt();
9168       if (Args[i].IsInReg) {
9169         // If we are using vectorcall calling convention, a structure that is
9170         // passed InReg - is surely an HVA
9171         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9172             isa<StructType>(FinalType)) {
9173           // The first value of a structure is marked
9174           if (0 == Value)
9175             Flags.setHvaStart();
9176           Flags.setHva();
9177         }
9178         // Set InReg Flag
9179         Flags.setInReg();
9180       }
9181       if (Args[i].IsSRet)
9182         Flags.setSRet();
9183       if (Args[i].IsSwiftSelf)
9184         Flags.setSwiftSelf();
9185       if (Args[i].IsSwiftError)
9186         Flags.setSwiftError();
9187       if (Args[i].IsCFGuardTarget)
9188         Flags.setCFGuardTarget();
9189       if (Args[i].IsByVal)
9190         Flags.setByVal();
9191       if (Args[i].IsInAlloca) {
9192         Flags.setInAlloca();
9193         // Set the byval flag for CCAssignFn callbacks that don't know about
9194         // inalloca.  This way we can know how many bytes we should've allocated
9195         // and how many bytes a callee cleanup function will pop.  If we port
9196         // inalloca to more targets, we'll have to add custom inalloca handling
9197         // in the various CC lowering callbacks.
9198         Flags.setByVal();
9199       }
9200       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9201         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9202         Type *ElementTy = Ty->getElementType();
9203 
9204         unsigned FrameSize = DL.getTypeAllocSize(
9205             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9206         Flags.setByValSize(FrameSize);
9207 
9208         // info is not there but there are cases it cannot get right.
9209         unsigned FrameAlign;
9210         if (Args[i].Alignment)
9211           FrameAlign = Args[i].Alignment;
9212         else
9213           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9214         Flags.setByValAlign(Align(FrameAlign));
9215       }
9216       if (Args[i].IsNest)
9217         Flags.setNest();
9218       if (NeedsRegBlock)
9219         Flags.setInConsecutiveRegs();
9220       Flags.setOrigAlign(OriginalAlignment);
9221 
9222       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9223                                                  CLI.CallConv, VT);
9224       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9225                                                         CLI.CallConv, VT);
9226       SmallVector<SDValue, 4> Parts(NumParts);
9227       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9228 
9229       if (Args[i].IsSExt)
9230         ExtendKind = ISD::SIGN_EXTEND;
9231       else if (Args[i].IsZExt)
9232         ExtendKind = ISD::ZERO_EXTEND;
9233 
9234       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9235       // for now.
9236       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9237           CanLowerReturn) {
9238         assert((CLI.RetTy == Args[i].Ty ||
9239                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9240                  CLI.RetTy->getPointerAddressSpace() ==
9241                      Args[i].Ty->getPointerAddressSpace())) &&
9242                RetTys.size() == NumValues && "unexpected use of 'returned'");
9243         // Before passing 'returned' to the target lowering code, ensure that
9244         // either the register MVT and the actual EVT are the same size or that
9245         // the return value and argument are extended in the same way; in these
9246         // cases it's safe to pass the argument register value unchanged as the
9247         // return register value (although it's at the target's option whether
9248         // to do so)
9249         // TODO: allow code generation to take advantage of partially preserved
9250         // registers rather than clobbering the entire register when the
9251         // parameter extension method is not compatible with the return
9252         // extension method
9253         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9254             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9255              CLI.RetZExt == Args[i].IsZExt))
9256           Flags.setReturned();
9257       }
9258 
9259       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9260                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9261 
9262       for (unsigned j = 0; j != NumParts; ++j) {
9263         // if it isn't first piece, alignment must be 1
9264         // For scalable vectors the scalable part is currently handled
9265         // by individual targets, so we just use the known minimum size here.
9266         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9267                     i < CLI.NumFixedArgs, i,
9268                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9269         if (NumParts > 1 && j == 0)
9270           MyFlags.Flags.setSplit();
9271         else if (j != 0) {
9272           MyFlags.Flags.setOrigAlign(Align::None());
9273           if (j == NumParts - 1)
9274             MyFlags.Flags.setSplitEnd();
9275         }
9276 
9277         CLI.Outs.push_back(MyFlags);
9278         CLI.OutVals.push_back(Parts[j]);
9279       }
9280 
9281       if (NeedsRegBlock && Value == NumValues - 1)
9282         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9283     }
9284   }
9285 
9286   SmallVector<SDValue, 4> InVals;
9287   CLI.Chain = LowerCall(CLI, InVals);
9288 
9289   // Update CLI.InVals to use outside of this function.
9290   CLI.InVals = InVals;
9291 
9292   // Verify that the target's LowerCall behaved as expected.
9293   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9294          "LowerCall didn't return a valid chain!");
9295   assert((!CLI.IsTailCall || InVals.empty()) &&
9296          "LowerCall emitted a return value for a tail call!");
9297   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9298          "LowerCall didn't emit the correct number of values!");
9299 
9300   // For a tail call, the return value is merely live-out and there aren't
9301   // any nodes in the DAG representing it. Return a special value to
9302   // indicate that a tail call has been emitted and no more Instructions
9303   // should be processed in the current block.
9304   if (CLI.IsTailCall) {
9305     CLI.DAG.setRoot(CLI.Chain);
9306     return std::make_pair(SDValue(), SDValue());
9307   }
9308 
9309 #ifndef NDEBUG
9310   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9311     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9312     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9313            "LowerCall emitted a value with the wrong type!");
9314   }
9315 #endif
9316 
9317   SmallVector<SDValue, 4> ReturnValues;
9318   if (!CanLowerReturn) {
9319     // The instruction result is the result of loading from the
9320     // hidden sret parameter.
9321     SmallVector<EVT, 1> PVTs;
9322     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9323 
9324     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9325     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9326     EVT PtrVT = PVTs[0];
9327 
9328     unsigned NumValues = RetTys.size();
9329     ReturnValues.resize(NumValues);
9330     SmallVector<SDValue, 4> Chains(NumValues);
9331 
9332     // An aggregate return value cannot wrap around the address space, so
9333     // offsets to its parts don't wrap either.
9334     SDNodeFlags Flags;
9335     Flags.setNoUnsignedWrap(true);
9336 
9337     for (unsigned i = 0; i < NumValues; ++i) {
9338       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9339                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9340                                                         PtrVT), Flags);
9341       SDValue L = CLI.DAG.getLoad(
9342           RetTys[i], CLI.DL, CLI.Chain, Add,
9343           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9344                                             DemoteStackIdx, Offsets[i]),
9345           /* Alignment = */ 1);
9346       ReturnValues[i] = L;
9347       Chains[i] = L.getValue(1);
9348     }
9349 
9350     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9351   } else {
9352     // Collect the legal value parts into potentially illegal values
9353     // that correspond to the original function's return values.
9354     Optional<ISD::NodeType> AssertOp;
9355     if (CLI.RetSExt)
9356       AssertOp = ISD::AssertSext;
9357     else if (CLI.RetZExt)
9358       AssertOp = ISD::AssertZext;
9359     unsigned CurReg = 0;
9360     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9361       EVT VT = RetTys[I];
9362       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9363                                                      CLI.CallConv, VT);
9364       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9365                                                        CLI.CallConv, VT);
9366 
9367       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9368                                               NumRegs, RegisterVT, VT, nullptr,
9369                                               CLI.CallConv, AssertOp));
9370       CurReg += NumRegs;
9371     }
9372 
9373     // For a function returning void, there is no return value. We can't create
9374     // such a node, so we just return a null return value in that case. In
9375     // that case, nothing will actually look at the value.
9376     if (ReturnValues.empty())
9377       return std::make_pair(SDValue(), CLI.Chain);
9378   }
9379 
9380   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9381                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9382   return std::make_pair(Res, CLI.Chain);
9383 }
9384 
9385 void TargetLowering::LowerOperationWrapper(SDNode *N,
9386                                            SmallVectorImpl<SDValue> &Results,
9387                                            SelectionDAG &DAG) const {
9388   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9389     Results.push_back(Res);
9390 }
9391 
9392 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9393   llvm_unreachable("LowerOperation not implemented for this target!");
9394 }
9395 
9396 void
9397 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9398   SDValue Op = getNonRegisterValue(V);
9399   assert((Op.getOpcode() != ISD::CopyFromReg ||
9400           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9401          "Copy from a reg to the same reg!");
9402   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9403 
9404   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9405   // If this is an InlineAsm we have to match the registers required, not the
9406   // notional registers required by the type.
9407 
9408   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9409                    None); // This is not an ABI copy.
9410   SDValue Chain = DAG.getEntryNode();
9411 
9412   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9413                               FuncInfo.PreferredExtendType.end())
9414                                  ? ISD::ANY_EXTEND
9415                                  : FuncInfo.PreferredExtendType[V];
9416   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9417   PendingExports.push_back(Chain);
9418 }
9419 
9420 #include "llvm/CodeGen/SelectionDAGISel.h"
9421 
9422 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9423 /// entry block, return true.  This includes arguments used by switches, since
9424 /// the switch may expand into multiple basic blocks.
9425 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9426   // With FastISel active, we may be splitting blocks, so force creation
9427   // of virtual registers for all non-dead arguments.
9428   if (FastISel)
9429     return A->use_empty();
9430 
9431   const BasicBlock &Entry = A->getParent()->front();
9432   for (const User *U : A->users())
9433     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9434       return false;  // Use not in entry block.
9435 
9436   return true;
9437 }
9438 
9439 using ArgCopyElisionMapTy =
9440     DenseMap<const Argument *,
9441              std::pair<const AllocaInst *, const StoreInst *>>;
9442 
9443 /// Scan the entry block of the function in FuncInfo for arguments that look
9444 /// like copies into a local alloca. Record any copied arguments in
9445 /// ArgCopyElisionCandidates.
9446 static void
9447 findArgumentCopyElisionCandidates(const DataLayout &DL,
9448                                   FunctionLoweringInfo *FuncInfo,
9449                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9450   // Record the state of every static alloca used in the entry block. Argument
9451   // allocas are all used in the entry block, so we need approximately as many
9452   // entries as we have arguments.
9453   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9454   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9455   unsigned NumArgs = FuncInfo->Fn->arg_size();
9456   StaticAllocas.reserve(NumArgs * 2);
9457 
9458   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9459     if (!V)
9460       return nullptr;
9461     V = V->stripPointerCasts();
9462     const auto *AI = dyn_cast<AllocaInst>(V);
9463     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9464       return nullptr;
9465     auto Iter = StaticAllocas.insert({AI, Unknown});
9466     return &Iter.first->second;
9467   };
9468 
9469   // Look for stores of arguments to static allocas. Look through bitcasts and
9470   // GEPs to handle type coercions, as long as the alloca is fully initialized
9471   // by the store. Any non-store use of an alloca escapes it and any subsequent
9472   // unanalyzed store might write it.
9473   // FIXME: Handle structs initialized with multiple stores.
9474   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9475     // Look for stores, and handle non-store uses conservatively.
9476     const auto *SI = dyn_cast<StoreInst>(&I);
9477     if (!SI) {
9478       // We will look through cast uses, so ignore them completely.
9479       if (I.isCast())
9480         continue;
9481       // Ignore debug info intrinsics, they don't escape or store to allocas.
9482       if (isa<DbgInfoIntrinsic>(I))
9483         continue;
9484       // This is an unknown instruction. Assume it escapes or writes to all
9485       // static alloca operands.
9486       for (const Use &U : I.operands()) {
9487         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9488           *Info = StaticAllocaInfo::Clobbered;
9489       }
9490       continue;
9491     }
9492 
9493     // If the stored value is a static alloca, mark it as escaped.
9494     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9495       *Info = StaticAllocaInfo::Clobbered;
9496 
9497     // Check if the destination is a static alloca.
9498     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9499     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9500     if (!Info)
9501       continue;
9502     const AllocaInst *AI = cast<AllocaInst>(Dst);
9503 
9504     // Skip allocas that have been initialized or clobbered.
9505     if (*Info != StaticAllocaInfo::Unknown)
9506       continue;
9507 
9508     // Check if the stored value is an argument, and that this store fully
9509     // initializes the alloca. Don't elide copies from the same argument twice.
9510     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9511     const auto *Arg = dyn_cast<Argument>(Val);
9512     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9513         Arg->getType()->isEmptyTy() ||
9514         DL.getTypeStoreSize(Arg->getType()) !=
9515             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9516         ArgCopyElisionCandidates.count(Arg)) {
9517       *Info = StaticAllocaInfo::Clobbered;
9518       continue;
9519     }
9520 
9521     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9522                       << '\n');
9523 
9524     // Mark this alloca and store for argument copy elision.
9525     *Info = StaticAllocaInfo::Elidable;
9526     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9527 
9528     // Stop scanning if we've seen all arguments. This will happen early in -O0
9529     // builds, which is useful, because -O0 builds have large entry blocks and
9530     // many allocas.
9531     if (ArgCopyElisionCandidates.size() == NumArgs)
9532       break;
9533   }
9534 }
9535 
9536 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9537 /// ArgVal is a load from a suitable fixed stack object.
9538 static void tryToElideArgumentCopy(
9539     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9540     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9541     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9542     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9543     SDValue ArgVal, bool &ArgHasUses) {
9544   // Check if this is a load from a fixed stack object.
9545   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9546   if (!LNode)
9547     return;
9548   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9549   if (!FINode)
9550     return;
9551 
9552   // Check that the fixed stack object is the right size and alignment.
9553   // Look at the alignment that the user wrote on the alloca instead of looking
9554   // at the stack object.
9555   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9556   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9557   const AllocaInst *AI = ArgCopyIter->second.first;
9558   int FixedIndex = FINode->getIndex();
9559   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9560   int OldIndex = AllocaIndex;
9561   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9562   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9563     LLVM_DEBUG(
9564         dbgs() << "  argument copy elision failed due to bad fixed stack "
9565                   "object size\n");
9566     return;
9567   }
9568   unsigned RequiredAlignment = AI->getAlignment();
9569   if (!RequiredAlignment) {
9570     RequiredAlignment = FuncInfo.MF->getDataLayout().getABITypeAlignment(
9571         AI->getAllocatedType());
9572   }
9573   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9574     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9575                          "greater than stack argument alignment ("
9576                       << RequiredAlignment << " vs "
9577                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9578     return;
9579   }
9580 
9581   // Perform the elision. Delete the old stack object and replace its only use
9582   // in the variable info map. Mark the stack object as mutable.
9583   LLVM_DEBUG({
9584     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9585            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9586            << '\n';
9587   });
9588   MFI.RemoveStackObject(OldIndex);
9589   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9590   AllocaIndex = FixedIndex;
9591   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9592   Chains.push_back(ArgVal.getValue(1));
9593 
9594   // Avoid emitting code for the store implementing the copy.
9595   const StoreInst *SI = ArgCopyIter->second.second;
9596   ElidedArgCopyInstrs.insert(SI);
9597 
9598   // Check for uses of the argument again so that we can avoid exporting ArgVal
9599   // if it is't used by anything other than the store.
9600   for (const Value *U : Arg.users()) {
9601     if (U != SI) {
9602       ArgHasUses = true;
9603       break;
9604     }
9605   }
9606 }
9607 
9608 void SelectionDAGISel::LowerArguments(const Function &F) {
9609   SelectionDAG &DAG = SDB->DAG;
9610   SDLoc dl = SDB->getCurSDLoc();
9611   const DataLayout &DL = DAG.getDataLayout();
9612   SmallVector<ISD::InputArg, 16> Ins;
9613 
9614   if (!FuncInfo->CanLowerReturn) {
9615     // Put in an sret pointer parameter before all the other parameters.
9616     SmallVector<EVT, 1> ValueVTs;
9617     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9618                     F.getReturnType()->getPointerTo(
9619                         DAG.getDataLayout().getAllocaAddrSpace()),
9620                     ValueVTs);
9621 
9622     // NOTE: Assuming that a pointer will never break down to more than one VT
9623     // or one register.
9624     ISD::ArgFlagsTy Flags;
9625     Flags.setSRet();
9626     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9627     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9628                          ISD::InputArg::NoArgIndex, 0);
9629     Ins.push_back(RetArg);
9630   }
9631 
9632   // Look for stores of arguments to static allocas. Mark such arguments with a
9633   // flag to ask the target to give us the memory location of that argument if
9634   // available.
9635   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9636   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9637                                     ArgCopyElisionCandidates);
9638 
9639   // Set up the incoming argument description vector.
9640   for (const Argument &Arg : F.args()) {
9641     unsigned ArgNo = Arg.getArgNo();
9642     SmallVector<EVT, 4> ValueVTs;
9643     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9644     bool isArgValueUsed = !Arg.use_empty();
9645     unsigned PartBase = 0;
9646     Type *FinalType = Arg.getType();
9647     if (Arg.hasAttribute(Attribute::ByVal))
9648       FinalType = Arg.getParamByValType();
9649     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9650         FinalType, F.getCallingConv(), F.isVarArg());
9651     for (unsigned Value = 0, NumValues = ValueVTs.size();
9652          Value != NumValues; ++Value) {
9653       EVT VT = ValueVTs[Value];
9654       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9655       ISD::ArgFlagsTy Flags;
9656 
9657       // Certain targets (such as MIPS), may have a different ABI alignment
9658       // for a type depending on the context. Give the target a chance to
9659       // specify the alignment it wants.
9660       const Align OriginalAlignment(
9661           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9662 
9663       if (Arg.getType()->isPointerTy()) {
9664         Flags.setPointer();
9665         Flags.setPointerAddrSpace(
9666             cast<PointerType>(Arg.getType())->getAddressSpace());
9667       }
9668       if (Arg.hasAttribute(Attribute::ZExt))
9669         Flags.setZExt();
9670       if (Arg.hasAttribute(Attribute::SExt))
9671         Flags.setSExt();
9672       if (Arg.hasAttribute(Attribute::InReg)) {
9673         // If we are using vectorcall calling convention, a structure that is
9674         // passed InReg - is surely an HVA
9675         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9676             isa<StructType>(Arg.getType())) {
9677           // The first value of a structure is marked
9678           if (0 == Value)
9679             Flags.setHvaStart();
9680           Flags.setHva();
9681         }
9682         // Set InReg Flag
9683         Flags.setInReg();
9684       }
9685       if (Arg.hasAttribute(Attribute::StructRet))
9686         Flags.setSRet();
9687       if (Arg.hasAttribute(Attribute::SwiftSelf))
9688         Flags.setSwiftSelf();
9689       if (Arg.hasAttribute(Attribute::SwiftError))
9690         Flags.setSwiftError();
9691       if (Arg.hasAttribute(Attribute::ByVal))
9692         Flags.setByVal();
9693       if (Arg.hasAttribute(Attribute::InAlloca)) {
9694         Flags.setInAlloca();
9695         // Set the byval flag for CCAssignFn callbacks that don't know about
9696         // inalloca.  This way we can know how many bytes we should've allocated
9697         // and how many bytes a callee cleanup function will pop.  If we port
9698         // inalloca to more targets, we'll have to add custom inalloca handling
9699         // in the various CC lowering callbacks.
9700         Flags.setByVal();
9701       }
9702       if (F.getCallingConv() == CallingConv::X86_INTR) {
9703         // IA Interrupt passes frame (1st parameter) by value in the stack.
9704         if (ArgNo == 0)
9705           Flags.setByVal();
9706       }
9707       if (Flags.isByVal() || Flags.isInAlloca()) {
9708         Type *ElementTy = Arg.getParamByValType();
9709 
9710         // For ByVal, size and alignment should be passed from FE.  BE will
9711         // guess if this info is not there but there are cases it cannot get
9712         // right.
9713         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9714         Flags.setByValSize(FrameSize);
9715 
9716         unsigned FrameAlign;
9717         if (Arg.getParamAlignment())
9718           FrameAlign = Arg.getParamAlignment();
9719         else
9720           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9721         Flags.setByValAlign(Align(FrameAlign));
9722       }
9723       if (Arg.hasAttribute(Attribute::Nest))
9724         Flags.setNest();
9725       if (NeedsRegBlock)
9726         Flags.setInConsecutiveRegs();
9727       Flags.setOrigAlign(OriginalAlignment);
9728       if (ArgCopyElisionCandidates.count(&Arg))
9729         Flags.setCopyElisionCandidate();
9730       if (Arg.hasAttribute(Attribute::Returned))
9731         Flags.setReturned();
9732 
9733       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9734           *CurDAG->getContext(), F.getCallingConv(), VT);
9735       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9736           *CurDAG->getContext(), F.getCallingConv(), VT);
9737       for (unsigned i = 0; i != NumRegs; ++i) {
9738         // For scalable vectors, use the minimum size; individual targets
9739         // are responsible for handling scalable vector arguments and
9740         // return values.
9741         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9742                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9743         if (NumRegs > 1 && i == 0)
9744           MyFlags.Flags.setSplit();
9745         // if it isn't first piece, alignment must be 1
9746         else if (i > 0) {
9747           MyFlags.Flags.setOrigAlign(Align::None());
9748           if (i == NumRegs - 1)
9749             MyFlags.Flags.setSplitEnd();
9750         }
9751         Ins.push_back(MyFlags);
9752       }
9753       if (NeedsRegBlock && Value == NumValues - 1)
9754         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9755       PartBase += VT.getStoreSize().getKnownMinSize();
9756     }
9757   }
9758 
9759   // Call the target to set up the argument values.
9760   SmallVector<SDValue, 8> InVals;
9761   SDValue NewRoot = TLI->LowerFormalArguments(
9762       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9763 
9764   // Verify that the target's LowerFormalArguments behaved as expected.
9765   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9766          "LowerFormalArguments didn't return a valid chain!");
9767   assert(InVals.size() == Ins.size() &&
9768          "LowerFormalArguments didn't emit the correct number of values!");
9769   LLVM_DEBUG({
9770     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9771       assert(InVals[i].getNode() &&
9772              "LowerFormalArguments emitted a null value!");
9773       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9774              "LowerFormalArguments emitted a value with the wrong type!");
9775     }
9776   });
9777 
9778   // Update the DAG with the new chain value resulting from argument lowering.
9779   DAG.setRoot(NewRoot);
9780 
9781   // Set up the argument values.
9782   unsigned i = 0;
9783   if (!FuncInfo->CanLowerReturn) {
9784     // Create a virtual register for the sret pointer, and put in a copy
9785     // from the sret argument into it.
9786     SmallVector<EVT, 1> ValueVTs;
9787     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9788                     F.getReturnType()->getPointerTo(
9789                         DAG.getDataLayout().getAllocaAddrSpace()),
9790                     ValueVTs);
9791     MVT VT = ValueVTs[0].getSimpleVT();
9792     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9793     Optional<ISD::NodeType> AssertOp = None;
9794     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9795                                         nullptr, F.getCallingConv(), AssertOp);
9796 
9797     MachineFunction& MF = SDB->DAG.getMachineFunction();
9798     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9799     Register SRetReg =
9800         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9801     FuncInfo->DemoteRegister = SRetReg;
9802     NewRoot =
9803         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9804     DAG.setRoot(NewRoot);
9805 
9806     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9807     ++i;
9808   }
9809 
9810   SmallVector<SDValue, 4> Chains;
9811   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9812   for (const Argument &Arg : F.args()) {
9813     SmallVector<SDValue, 4> ArgValues;
9814     SmallVector<EVT, 4> ValueVTs;
9815     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9816     unsigned NumValues = ValueVTs.size();
9817     if (NumValues == 0)
9818       continue;
9819 
9820     bool ArgHasUses = !Arg.use_empty();
9821 
9822     // Elide the copying store if the target loaded this argument from a
9823     // suitable fixed stack object.
9824     if (Ins[i].Flags.isCopyElisionCandidate()) {
9825       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9826                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9827                              InVals[i], ArgHasUses);
9828     }
9829 
9830     // If this argument is unused then remember its value. It is used to generate
9831     // debugging information.
9832     bool isSwiftErrorArg =
9833         TLI->supportSwiftError() &&
9834         Arg.hasAttribute(Attribute::SwiftError);
9835     if (!ArgHasUses && !isSwiftErrorArg) {
9836       SDB->setUnusedArgValue(&Arg, InVals[i]);
9837 
9838       // Also remember any frame index for use in FastISel.
9839       if (FrameIndexSDNode *FI =
9840           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9841         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9842     }
9843 
9844     for (unsigned Val = 0; Val != NumValues; ++Val) {
9845       EVT VT = ValueVTs[Val];
9846       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9847                                                       F.getCallingConv(), VT);
9848       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9849           *CurDAG->getContext(), F.getCallingConv(), VT);
9850 
9851       // Even an apparent 'unused' swifterror argument needs to be returned. So
9852       // we do generate a copy for it that can be used on return from the
9853       // function.
9854       if (ArgHasUses || isSwiftErrorArg) {
9855         Optional<ISD::NodeType> AssertOp;
9856         if (Arg.hasAttribute(Attribute::SExt))
9857           AssertOp = ISD::AssertSext;
9858         else if (Arg.hasAttribute(Attribute::ZExt))
9859           AssertOp = ISD::AssertZext;
9860 
9861         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9862                                              PartVT, VT, nullptr,
9863                                              F.getCallingConv(), AssertOp));
9864       }
9865 
9866       i += NumParts;
9867     }
9868 
9869     // We don't need to do anything else for unused arguments.
9870     if (ArgValues.empty())
9871       continue;
9872 
9873     // Note down frame index.
9874     if (FrameIndexSDNode *FI =
9875         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9876       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9877 
9878     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9879                                      SDB->getCurSDLoc());
9880 
9881     SDB->setValue(&Arg, Res);
9882     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9883       // We want to associate the argument with the frame index, among
9884       // involved operands, that correspond to the lowest address. The
9885       // getCopyFromParts function, called earlier, is swapping the order of
9886       // the operands to BUILD_PAIR depending on endianness. The result of
9887       // that swapping is that the least significant bits of the argument will
9888       // be in the first operand of the BUILD_PAIR node, and the most
9889       // significant bits will be in the second operand.
9890       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9891       if (LoadSDNode *LNode =
9892           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9893         if (FrameIndexSDNode *FI =
9894             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9895           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9896     }
9897 
9898     // Analyses past this point are naive and don't expect an assertion.
9899     if (Res.getOpcode() == ISD::AssertZext)
9900       Res = Res.getOperand(0);
9901 
9902     // Update the SwiftErrorVRegDefMap.
9903     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9904       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9905       if (Register::isVirtualRegister(Reg))
9906         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9907                                    Reg);
9908     }
9909 
9910     // If this argument is live outside of the entry block, insert a copy from
9911     // wherever we got it to the vreg that other BB's will reference it as.
9912     if (Res.getOpcode() == ISD::CopyFromReg) {
9913       // If we can, though, try to skip creating an unnecessary vreg.
9914       // FIXME: This isn't very clean... it would be nice to make this more
9915       // general.
9916       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9917       if (Register::isVirtualRegister(Reg)) {
9918         FuncInfo->ValueMap[&Arg] = Reg;
9919         continue;
9920       }
9921     }
9922     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9923       FuncInfo->InitializeRegForValue(&Arg);
9924       SDB->CopyToExportRegsIfNeeded(&Arg);
9925     }
9926   }
9927 
9928   if (!Chains.empty()) {
9929     Chains.push_back(NewRoot);
9930     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9931   }
9932 
9933   DAG.setRoot(NewRoot);
9934 
9935   assert(i == InVals.size() && "Argument register count mismatch!");
9936 
9937   // If any argument copy elisions occurred and we have debug info, update the
9938   // stale frame indices used in the dbg.declare variable info table.
9939   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9940   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9941     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9942       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9943       if (I != ArgCopyElisionFrameIndexMap.end())
9944         VI.Slot = I->second;
9945     }
9946   }
9947 
9948   // Finally, if the target has anything special to do, allow it to do so.
9949   EmitFunctionEntryCode();
9950 }
9951 
9952 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9953 /// ensure constants are generated when needed.  Remember the virtual registers
9954 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9955 /// directly add them, because expansion might result in multiple MBB's for one
9956 /// BB.  As such, the start of the BB might correspond to a different MBB than
9957 /// the end.
9958 void
9959 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9960   const Instruction *TI = LLVMBB->getTerminator();
9961 
9962   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9963 
9964   // Check PHI nodes in successors that expect a value to be available from this
9965   // block.
9966   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9967     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9968     if (!isa<PHINode>(SuccBB->begin())) continue;
9969     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9970 
9971     // If this terminator has multiple identical successors (common for
9972     // switches), only handle each succ once.
9973     if (!SuccsHandled.insert(SuccMBB).second)
9974       continue;
9975 
9976     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9977 
9978     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9979     // nodes and Machine PHI nodes, but the incoming operands have not been
9980     // emitted yet.
9981     for (const PHINode &PN : SuccBB->phis()) {
9982       // Ignore dead phi's.
9983       if (PN.use_empty())
9984         continue;
9985 
9986       // Skip empty types
9987       if (PN.getType()->isEmptyTy())
9988         continue;
9989 
9990       unsigned Reg;
9991       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9992 
9993       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9994         unsigned &RegOut = ConstantsOut[C];
9995         if (RegOut == 0) {
9996           RegOut = FuncInfo.CreateRegs(C);
9997           CopyValueToVirtualRegister(C, RegOut);
9998         }
9999         Reg = RegOut;
10000       } else {
10001         DenseMap<const Value *, unsigned>::iterator I =
10002           FuncInfo.ValueMap.find(PHIOp);
10003         if (I != FuncInfo.ValueMap.end())
10004           Reg = I->second;
10005         else {
10006           assert(isa<AllocaInst>(PHIOp) &&
10007                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10008                  "Didn't codegen value into a register!??");
10009           Reg = FuncInfo.CreateRegs(PHIOp);
10010           CopyValueToVirtualRegister(PHIOp, Reg);
10011         }
10012       }
10013 
10014       // Remember that this register needs to added to the machine PHI node as
10015       // the input for this MBB.
10016       SmallVector<EVT, 4> ValueVTs;
10017       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10018       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10019       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10020         EVT VT = ValueVTs[vti];
10021         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10022         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10023           FuncInfo.PHINodesToUpdate.push_back(
10024               std::make_pair(&*MBBI++, Reg + i));
10025         Reg += NumRegisters;
10026       }
10027     }
10028   }
10029 
10030   ConstantsOut.clear();
10031 }
10032 
10033 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10034 /// is 0.
10035 MachineBasicBlock *
10036 SelectionDAGBuilder::StackProtectorDescriptor::
10037 AddSuccessorMBB(const BasicBlock *BB,
10038                 MachineBasicBlock *ParentMBB,
10039                 bool IsLikely,
10040                 MachineBasicBlock *SuccMBB) {
10041   // If SuccBB has not been created yet, create it.
10042   if (!SuccMBB) {
10043     MachineFunction *MF = ParentMBB->getParent();
10044     MachineFunction::iterator BBI(ParentMBB);
10045     SuccMBB = MF->CreateMachineBasicBlock(BB);
10046     MF->insert(++BBI, SuccMBB);
10047   }
10048   // Add it as a successor of ParentMBB.
10049   ParentMBB->addSuccessor(
10050       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10051   return SuccMBB;
10052 }
10053 
10054 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10055   MachineFunction::iterator I(MBB);
10056   if (++I == FuncInfo.MF->end())
10057     return nullptr;
10058   return &*I;
10059 }
10060 
10061 /// During lowering new call nodes can be created (such as memset, etc.).
10062 /// Those will become new roots of the current DAG, but complications arise
10063 /// when they are tail calls. In such cases, the call lowering will update
10064 /// the root, but the builder still needs to know that a tail call has been
10065 /// lowered in order to avoid generating an additional return.
10066 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10067   // If the node is null, we do have a tail call.
10068   if (MaybeTC.getNode() != nullptr)
10069     DAG.setRoot(MaybeTC);
10070   else
10071     HasTailCall = true;
10072 }
10073 
10074 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10075                                         MachineBasicBlock *SwitchMBB,
10076                                         MachineBasicBlock *DefaultMBB) {
10077   MachineFunction *CurMF = FuncInfo.MF;
10078   MachineBasicBlock *NextMBB = nullptr;
10079   MachineFunction::iterator BBI(W.MBB);
10080   if (++BBI != FuncInfo.MF->end())
10081     NextMBB = &*BBI;
10082 
10083   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10084 
10085   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10086 
10087   if (Size == 2 && W.MBB == SwitchMBB) {
10088     // If any two of the cases has the same destination, and if one value
10089     // is the same as the other, but has one bit unset that the other has set,
10090     // use bit manipulation to do two compares at once.  For example:
10091     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10092     // TODO: This could be extended to merge any 2 cases in switches with 3
10093     // cases.
10094     // TODO: Handle cases where W.CaseBB != SwitchBB.
10095     CaseCluster &Small = *W.FirstCluster;
10096     CaseCluster &Big = *W.LastCluster;
10097 
10098     if (Small.Low == Small.High && Big.Low == Big.High &&
10099         Small.MBB == Big.MBB) {
10100       const APInt &SmallValue = Small.Low->getValue();
10101       const APInt &BigValue = Big.Low->getValue();
10102 
10103       // Check that there is only one bit different.
10104       APInt CommonBit = BigValue ^ SmallValue;
10105       if (CommonBit.isPowerOf2()) {
10106         SDValue CondLHS = getValue(Cond);
10107         EVT VT = CondLHS.getValueType();
10108         SDLoc DL = getCurSDLoc();
10109 
10110         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10111                                  DAG.getConstant(CommonBit, DL, VT));
10112         SDValue Cond = DAG.getSetCC(
10113             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10114             ISD::SETEQ);
10115 
10116         // Update successor info.
10117         // Both Small and Big will jump to Small.BB, so we sum up the
10118         // probabilities.
10119         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10120         if (BPI)
10121           addSuccessorWithProb(
10122               SwitchMBB, DefaultMBB,
10123               // The default destination is the first successor in IR.
10124               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10125         else
10126           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10127 
10128         // Insert the true branch.
10129         SDValue BrCond =
10130             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10131                         DAG.getBasicBlock(Small.MBB));
10132         // Insert the false branch.
10133         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10134                              DAG.getBasicBlock(DefaultMBB));
10135 
10136         DAG.setRoot(BrCond);
10137         return;
10138       }
10139     }
10140   }
10141 
10142   if (TM.getOptLevel() != CodeGenOpt::None) {
10143     // Here, we order cases by probability so the most likely case will be
10144     // checked first. However, two clusters can have the same probability in
10145     // which case their relative ordering is non-deterministic. So we use Low
10146     // as a tie-breaker as clusters are guaranteed to never overlap.
10147     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10148                [](const CaseCluster &a, const CaseCluster &b) {
10149       return a.Prob != b.Prob ?
10150              a.Prob > b.Prob :
10151              a.Low->getValue().slt(b.Low->getValue());
10152     });
10153 
10154     // Rearrange the case blocks so that the last one falls through if possible
10155     // without changing the order of probabilities.
10156     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10157       --I;
10158       if (I->Prob > W.LastCluster->Prob)
10159         break;
10160       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10161         std::swap(*I, *W.LastCluster);
10162         break;
10163       }
10164     }
10165   }
10166 
10167   // Compute total probability.
10168   BranchProbability DefaultProb = W.DefaultProb;
10169   BranchProbability UnhandledProbs = DefaultProb;
10170   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10171     UnhandledProbs += I->Prob;
10172 
10173   MachineBasicBlock *CurMBB = W.MBB;
10174   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10175     bool FallthroughUnreachable = false;
10176     MachineBasicBlock *Fallthrough;
10177     if (I == W.LastCluster) {
10178       // For the last cluster, fall through to the default destination.
10179       Fallthrough = DefaultMBB;
10180       FallthroughUnreachable = isa<UnreachableInst>(
10181           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10182     } else {
10183       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10184       CurMF->insert(BBI, Fallthrough);
10185       // Put Cond in a virtual register to make it available from the new blocks.
10186       ExportFromCurrentBlock(Cond);
10187     }
10188     UnhandledProbs -= I->Prob;
10189 
10190     switch (I->Kind) {
10191       case CC_JumpTable: {
10192         // FIXME: Optimize away range check based on pivot comparisons.
10193         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10194         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10195 
10196         // The jump block hasn't been inserted yet; insert it here.
10197         MachineBasicBlock *JumpMBB = JT->MBB;
10198         CurMF->insert(BBI, JumpMBB);
10199 
10200         auto JumpProb = I->Prob;
10201         auto FallthroughProb = UnhandledProbs;
10202 
10203         // If the default statement is a target of the jump table, we evenly
10204         // distribute the default probability to successors of CurMBB. Also
10205         // update the probability on the edge from JumpMBB to Fallthrough.
10206         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10207                                               SE = JumpMBB->succ_end();
10208              SI != SE; ++SI) {
10209           if (*SI == DefaultMBB) {
10210             JumpProb += DefaultProb / 2;
10211             FallthroughProb -= DefaultProb / 2;
10212             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10213             JumpMBB->normalizeSuccProbs();
10214             break;
10215           }
10216         }
10217 
10218         if (FallthroughUnreachable) {
10219           // Skip the range check if the fallthrough block is unreachable.
10220           JTH->OmitRangeCheck = true;
10221         }
10222 
10223         if (!JTH->OmitRangeCheck)
10224           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10225         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10226         CurMBB->normalizeSuccProbs();
10227 
10228         // The jump table header will be inserted in our current block, do the
10229         // range check, and fall through to our fallthrough block.
10230         JTH->HeaderBB = CurMBB;
10231         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10232 
10233         // If we're in the right place, emit the jump table header right now.
10234         if (CurMBB == SwitchMBB) {
10235           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10236           JTH->Emitted = true;
10237         }
10238         break;
10239       }
10240       case CC_BitTests: {
10241         // FIXME: Optimize away range check based on pivot comparisons.
10242         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10243 
10244         // The bit test blocks haven't been inserted yet; insert them here.
10245         for (BitTestCase &BTC : BTB->Cases)
10246           CurMF->insert(BBI, BTC.ThisBB);
10247 
10248         // Fill in fields of the BitTestBlock.
10249         BTB->Parent = CurMBB;
10250         BTB->Default = Fallthrough;
10251 
10252         BTB->DefaultProb = UnhandledProbs;
10253         // If the cases in bit test don't form a contiguous range, we evenly
10254         // distribute the probability on the edge to Fallthrough to two
10255         // successors of CurMBB.
10256         if (!BTB->ContiguousRange) {
10257           BTB->Prob += DefaultProb / 2;
10258           BTB->DefaultProb -= DefaultProb / 2;
10259         }
10260 
10261         if (FallthroughUnreachable) {
10262           // Skip the range check if the fallthrough block is unreachable.
10263           BTB->OmitRangeCheck = true;
10264         }
10265 
10266         // If we're in the right place, emit the bit test header right now.
10267         if (CurMBB == SwitchMBB) {
10268           visitBitTestHeader(*BTB, SwitchMBB);
10269           BTB->Emitted = true;
10270         }
10271         break;
10272       }
10273       case CC_Range: {
10274         const Value *RHS, *LHS, *MHS;
10275         ISD::CondCode CC;
10276         if (I->Low == I->High) {
10277           // Check Cond == I->Low.
10278           CC = ISD::SETEQ;
10279           LHS = Cond;
10280           RHS=I->Low;
10281           MHS = nullptr;
10282         } else {
10283           // Check I->Low <= Cond <= I->High.
10284           CC = ISD::SETLE;
10285           LHS = I->Low;
10286           MHS = Cond;
10287           RHS = I->High;
10288         }
10289 
10290         // If Fallthrough is unreachable, fold away the comparison.
10291         if (FallthroughUnreachable)
10292           CC = ISD::SETTRUE;
10293 
10294         // The false probability is the sum of all unhandled cases.
10295         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10296                      getCurSDLoc(), I->Prob, UnhandledProbs);
10297 
10298         if (CurMBB == SwitchMBB)
10299           visitSwitchCase(CB, SwitchMBB);
10300         else
10301           SL->SwitchCases.push_back(CB);
10302 
10303         break;
10304       }
10305     }
10306     CurMBB = Fallthrough;
10307   }
10308 }
10309 
10310 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10311                                               CaseClusterIt First,
10312                                               CaseClusterIt Last) {
10313   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10314     if (X.Prob != CC.Prob)
10315       return X.Prob > CC.Prob;
10316 
10317     // Ties are broken by comparing the case value.
10318     return X.Low->getValue().slt(CC.Low->getValue());
10319   });
10320 }
10321 
10322 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10323                                         const SwitchWorkListItem &W,
10324                                         Value *Cond,
10325                                         MachineBasicBlock *SwitchMBB) {
10326   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10327          "Clusters not sorted?");
10328 
10329   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10330 
10331   // Balance the tree based on branch probabilities to create a near-optimal (in
10332   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10333   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10334   CaseClusterIt LastLeft = W.FirstCluster;
10335   CaseClusterIt FirstRight = W.LastCluster;
10336   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10337   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10338 
10339   // Move LastLeft and FirstRight towards each other from opposite directions to
10340   // find a partitioning of the clusters which balances the probability on both
10341   // sides. If LeftProb and RightProb are equal, alternate which side is
10342   // taken to ensure 0-probability nodes are distributed evenly.
10343   unsigned I = 0;
10344   while (LastLeft + 1 < FirstRight) {
10345     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10346       LeftProb += (++LastLeft)->Prob;
10347     else
10348       RightProb += (--FirstRight)->Prob;
10349     I++;
10350   }
10351 
10352   while (true) {
10353     // Our binary search tree differs from a typical BST in that ours can have up
10354     // to three values in each leaf. The pivot selection above doesn't take that
10355     // into account, which means the tree might require more nodes and be less
10356     // efficient. We compensate for this here.
10357 
10358     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10359     unsigned NumRight = W.LastCluster - FirstRight + 1;
10360 
10361     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10362       // If one side has less than 3 clusters, and the other has more than 3,
10363       // consider taking a cluster from the other side.
10364 
10365       if (NumLeft < NumRight) {
10366         // Consider moving the first cluster on the right to the left side.
10367         CaseCluster &CC = *FirstRight;
10368         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10369         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10370         if (LeftSideRank <= RightSideRank) {
10371           // Moving the cluster to the left does not demote it.
10372           ++LastLeft;
10373           ++FirstRight;
10374           continue;
10375         }
10376       } else {
10377         assert(NumRight < NumLeft);
10378         // Consider moving the last element on the left to the right side.
10379         CaseCluster &CC = *LastLeft;
10380         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10381         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10382         if (RightSideRank <= LeftSideRank) {
10383           // Moving the cluster to the right does not demot it.
10384           --LastLeft;
10385           --FirstRight;
10386           continue;
10387         }
10388       }
10389     }
10390     break;
10391   }
10392 
10393   assert(LastLeft + 1 == FirstRight);
10394   assert(LastLeft >= W.FirstCluster);
10395   assert(FirstRight <= W.LastCluster);
10396 
10397   // Use the first element on the right as pivot since we will make less-than
10398   // comparisons against it.
10399   CaseClusterIt PivotCluster = FirstRight;
10400   assert(PivotCluster > W.FirstCluster);
10401   assert(PivotCluster <= W.LastCluster);
10402 
10403   CaseClusterIt FirstLeft = W.FirstCluster;
10404   CaseClusterIt LastRight = W.LastCluster;
10405 
10406   const ConstantInt *Pivot = PivotCluster->Low;
10407 
10408   // New blocks will be inserted immediately after the current one.
10409   MachineFunction::iterator BBI(W.MBB);
10410   ++BBI;
10411 
10412   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10413   // we can branch to its destination directly if it's squeezed exactly in
10414   // between the known lower bound and Pivot - 1.
10415   MachineBasicBlock *LeftMBB;
10416   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10417       FirstLeft->Low == W.GE &&
10418       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10419     LeftMBB = FirstLeft->MBB;
10420   } else {
10421     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10422     FuncInfo.MF->insert(BBI, LeftMBB);
10423     WorkList.push_back(
10424         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10425     // Put Cond in a virtual register to make it available from the new blocks.
10426     ExportFromCurrentBlock(Cond);
10427   }
10428 
10429   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10430   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10431   // directly if RHS.High equals the current upper bound.
10432   MachineBasicBlock *RightMBB;
10433   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10434       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10435     RightMBB = FirstRight->MBB;
10436   } else {
10437     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10438     FuncInfo.MF->insert(BBI, RightMBB);
10439     WorkList.push_back(
10440         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10441     // Put Cond in a virtual register to make it available from the new blocks.
10442     ExportFromCurrentBlock(Cond);
10443   }
10444 
10445   // Create the CaseBlock record that will be used to lower the branch.
10446   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10447                getCurSDLoc(), LeftProb, RightProb);
10448 
10449   if (W.MBB == SwitchMBB)
10450     visitSwitchCase(CB, SwitchMBB);
10451   else
10452     SL->SwitchCases.push_back(CB);
10453 }
10454 
10455 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10456 // from the swith statement.
10457 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10458                                             BranchProbability PeeledCaseProb) {
10459   if (PeeledCaseProb == BranchProbability::getOne())
10460     return BranchProbability::getZero();
10461   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10462 
10463   uint32_t Numerator = CaseProb.getNumerator();
10464   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10465   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10466 }
10467 
10468 // Try to peel the top probability case if it exceeds the threshold.
10469 // Return current MachineBasicBlock for the switch statement if the peeling
10470 // does not occur.
10471 // If the peeling is performed, return the newly created MachineBasicBlock
10472 // for the peeled switch statement. Also update Clusters to remove the peeled
10473 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10474 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10475     const SwitchInst &SI, CaseClusterVector &Clusters,
10476     BranchProbability &PeeledCaseProb) {
10477   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10478   // Don't perform if there is only one cluster or optimizing for size.
10479   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10480       TM.getOptLevel() == CodeGenOpt::None ||
10481       SwitchMBB->getParent()->getFunction().hasMinSize())
10482     return SwitchMBB;
10483 
10484   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10485   unsigned PeeledCaseIndex = 0;
10486   bool SwitchPeeled = false;
10487   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10488     CaseCluster &CC = Clusters[Index];
10489     if (CC.Prob < TopCaseProb)
10490       continue;
10491     TopCaseProb = CC.Prob;
10492     PeeledCaseIndex = Index;
10493     SwitchPeeled = true;
10494   }
10495   if (!SwitchPeeled)
10496     return SwitchMBB;
10497 
10498   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10499                     << TopCaseProb << "\n");
10500 
10501   // Record the MBB for the peeled switch statement.
10502   MachineFunction::iterator BBI(SwitchMBB);
10503   ++BBI;
10504   MachineBasicBlock *PeeledSwitchMBB =
10505       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10506   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10507 
10508   ExportFromCurrentBlock(SI.getCondition());
10509   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10510   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10511                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10512   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10513 
10514   Clusters.erase(PeeledCaseIt);
10515   for (CaseCluster &CC : Clusters) {
10516     LLVM_DEBUG(
10517         dbgs() << "Scale the probablity for one cluster, before scaling: "
10518                << CC.Prob << "\n");
10519     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10520     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10521   }
10522   PeeledCaseProb = TopCaseProb;
10523   return PeeledSwitchMBB;
10524 }
10525 
10526 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10527   // Extract cases from the switch.
10528   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10529   CaseClusterVector Clusters;
10530   Clusters.reserve(SI.getNumCases());
10531   for (auto I : SI.cases()) {
10532     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10533     const ConstantInt *CaseVal = I.getCaseValue();
10534     BranchProbability Prob =
10535         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10536             : BranchProbability(1, SI.getNumCases() + 1);
10537     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10538   }
10539 
10540   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10541 
10542   // Cluster adjacent cases with the same destination. We do this at all
10543   // optimization levels because it's cheap to do and will make codegen faster
10544   // if there are many clusters.
10545   sortAndRangeify(Clusters);
10546 
10547   // The branch probablity of the peeled case.
10548   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10549   MachineBasicBlock *PeeledSwitchMBB =
10550       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10551 
10552   // If there is only the default destination, jump there directly.
10553   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10554   if (Clusters.empty()) {
10555     assert(PeeledSwitchMBB == SwitchMBB);
10556     SwitchMBB->addSuccessor(DefaultMBB);
10557     if (DefaultMBB != NextBlock(SwitchMBB)) {
10558       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10559                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10560     }
10561     return;
10562   }
10563 
10564   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10565   SL->findBitTestClusters(Clusters, &SI);
10566 
10567   LLVM_DEBUG({
10568     dbgs() << "Case clusters: ";
10569     for (const CaseCluster &C : Clusters) {
10570       if (C.Kind == CC_JumpTable)
10571         dbgs() << "JT:";
10572       if (C.Kind == CC_BitTests)
10573         dbgs() << "BT:";
10574 
10575       C.Low->getValue().print(dbgs(), true);
10576       if (C.Low != C.High) {
10577         dbgs() << '-';
10578         C.High->getValue().print(dbgs(), true);
10579       }
10580       dbgs() << ' ';
10581     }
10582     dbgs() << '\n';
10583   });
10584 
10585   assert(!Clusters.empty());
10586   SwitchWorkList WorkList;
10587   CaseClusterIt First = Clusters.begin();
10588   CaseClusterIt Last = Clusters.end() - 1;
10589   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10590   // Scale the branchprobability for DefaultMBB if the peel occurs and
10591   // DefaultMBB is not replaced.
10592   if (PeeledCaseProb != BranchProbability::getZero() &&
10593       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10594     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10595   WorkList.push_back(
10596       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10597 
10598   while (!WorkList.empty()) {
10599     SwitchWorkListItem W = WorkList.back();
10600     WorkList.pop_back();
10601     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10602 
10603     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10604         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10605       // For optimized builds, lower large range as a balanced binary tree.
10606       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10607       continue;
10608     }
10609 
10610     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10611   }
10612 }
10613 
10614 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10615   SDValue N = getValue(I.getOperand(0));
10616   setValue(&I, N);
10617 }
10618