xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision ed13fef47741d0a8fcaefeedbe6dc47a8552b928)
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/BranchProbabilityInfo.h"
31 #include "llvm/Analysis/ConstantFolding.h"
32 #include "llvm/Analysis/EHPersonalities.h"
33 #include "llvm/Analysis/Loads.h"
34 #include "llvm/Analysis/MemoryLocation.h"
35 #include "llvm/Analysis/TargetLibraryInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/Analysis/VectorUtils.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/FunctionLoweringInfo.h"
40 #include "llvm/CodeGen/GCMetadata.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineJumpTableInfo.h"
48 #include "llvm/CodeGen/MachineMemOperand.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/RuntimeLibcalls.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
56 #include "llvm/CodeGen/StackMaps.h"
57 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
58 #include "llvm/CodeGen/TargetFrameLowering.h"
59 #include "llvm/CodeGen/TargetInstrInfo.h"
60 #include "llvm/CodeGen/TargetLowering.h"
61 #include "llvm/CodeGen/TargetOpcodes.h"
62 #include "llvm/CodeGen/TargetRegisterInfo.h"
63 #include "llvm/CodeGen/TargetSubtargetInfo.h"
64 #include "llvm/CodeGen/ValueTypes.h"
65 #include "llvm/CodeGen/WinEHFuncInfo.h"
66 #include "llvm/IR/Argument.h"
67 #include "llvm/IR/Attributes.h"
68 #include "llvm/IR/BasicBlock.h"
69 #include "llvm/IR/CFG.h"
70 #include "llvm/IR/CallSite.h"
71 #include "llvm/IR/CallingConv.h"
72 #include "llvm/IR/Constant.h"
73 #include "llvm/IR/ConstantRange.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DebugInfoMetadata.h"
77 #include "llvm/IR/DebugLoc.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/InlineAsm.h"
82 #include "llvm/IR/InstrTypes.h"
83 #include "llvm/IR/Instruction.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/Intrinsics.h"
87 #include "llvm/IR/LLVMContext.h"
88 #include "llvm/IR/Metadata.h"
89 #include "llvm/IR/Module.h"
90 #include "llvm/IR/Operator.h"
91 #include "llvm/IR/PatternMatch.h"
92 #include "llvm/IR/Statepoint.h"
93 #include "llvm/IR/Type.h"
94 #include "llvm/IR/User.h"
95 #include "llvm/IR/Value.h"
96 #include "llvm/MC/MCContext.h"
97 #include "llvm/MC/MCSymbol.h"
98 #include "llvm/Support/AtomicOrdering.h"
99 #include "llvm/Support/BranchProbability.h"
100 #include "llvm/Support/Casting.h"
101 #include "llvm/Support/CodeGen.h"
102 #include "llvm/Support/CommandLine.h"
103 #include "llvm/Support/Compiler.h"
104 #include "llvm/Support/Debug.h"
105 #include "llvm/Support/ErrorHandling.h"
106 #include "llvm/Support/MachineValueType.h"
107 #include "llvm/Support/MathExtras.h"
108 #include "llvm/Support/raw_ostream.h"
109 #include "llvm/Target/TargetIntrinsicInfo.h"
110 #include "llvm/Target/TargetMachine.h"
111 #include "llvm/Target/TargetOptions.h"
112 #include "llvm/Transforms/Utils/Local.h"
113 #include <algorithm>
114 #include <cassert>
115 #include <cstddef>
116 #include <cstdint>
117 #include <cstring>
118 #include <iterator>
119 #include <limits>
120 #include <numeric>
121 #include <tuple>
122 #include <utility>
123 #include <vector>
124 
125 using namespace llvm;
126 using namespace PatternMatch;
127 using namespace SwitchCG;
128 
129 #define DEBUG_TYPE "isel"
130 
131 /// LimitFloatPrecision - Generate low-precision inline sequences for
132 /// some float libcalls (6, 8 or 12 bits).
133 static unsigned LimitFloatPrecision;
134 
135 static cl::opt<unsigned, true>
136     LimitFPPrecision("limit-float-precision",
137                      cl::desc("Generate low-precision inline sequences "
138                               "for some float libcalls"),
139                      cl::location(LimitFloatPrecision), cl::Hidden,
140                      cl::init(0));
141 
142 static cl::opt<unsigned> SwitchPeelThreshold(
143     "switch-peel-threshold", cl::Hidden, cl::init(66),
144     cl::desc("Set the case probability threshold for peeling the case from a "
145              "switch statement. A value greater than 100 will void this "
146              "optimization"));
147 
148 // Limit the width of DAG chains. This is important in general to prevent
149 // DAG-based analysis from blowing up. For example, alias analysis and
150 // load clustering may not complete in reasonable time. It is difficult to
151 // recognize and avoid this situation within each individual analysis, and
152 // future analyses are likely to have the same behavior. Limiting DAG width is
153 // the safe approach and will be especially important with global DAGs.
154 //
155 // MaxParallelChains default is arbitrarily high to avoid affecting
156 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
157 // sequence over this should have been converted to llvm.memcpy by the
158 // frontend. It is easy to induce this behavior with .ll code such as:
159 // %buffer = alloca [4096 x i8]
160 // %data = load [4096 x i8]* %argPtr
161 // store [4096 x i8] %data, [4096 x i8]* %buffer
162 static const unsigned MaxParallelChains = 64;
163 
164 // Return the calling convention if the Value passed requires ABI mangling as it
165 // is a parameter to a function or a return value from a function which is not
166 // an intrinsic.
167 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
168   if (auto *R = dyn_cast<ReturnInst>(V))
169     return R->getParent()->getParent()->getCallingConv();
170 
171   if (auto *CI = dyn_cast<CallInst>(V)) {
172     const bool IsInlineAsm = CI->isInlineAsm();
173     const bool IsIndirectFunctionCall =
174         !IsInlineAsm && !CI->getCalledFunction();
175 
176     // It is possible that the call instruction is an inline asm statement or an
177     // indirect function call in which case the return value of
178     // getCalledFunction() would be nullptr.
179     const bool IsInstrinsicCall =
180         !IsInlineAsm && !IsIndirectFunctionCall &&
181         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
182 
183     if (!IsInlineAsm && !IsInstrinsicCall)
184       return CI->getCallingConv();
185   }
186 
187   return None;
188 }
189 
190 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
191                                       const SDValue *Parts, unsigned NumParts,
192                                       MVT PartVT, EVT ValueVT, const Value *V,
193                                       Optional<CallingConv::ID> CC);
194 
195 /// getCopyFromParts - Create a value that contains the specified legal parts
196 /// combined into the value they represent.  If the parts combine to a type
197 /// larger than ValueVT then AssertOp can be used to specify whether the extra
198 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
199 /// (ISD::AssertSext).
200 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
201                                 const SDValue *Parts, unsigned NumParts,
202                                 MVT PartVT, EVT ValueVT, const Value *V,
203                                 Optional<CallingConv::ID> CC = None,
204                                 Optional<ISD::NodeType> AssertOp = None) {
205   if (ValueVT.isVector())
206     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
207                                   CC);
208 
209   assert(NumParts > 0 && "No parts to assemble!");
210   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
211   SDValue Val = Parts[0];
212 
213   if (NumParts > 1) {
214     // Assemble the value from multiple parts.
215     if (ValueVT.isInteger()) {
216       unsigned PartBits = PartVT.getSizeInBits();
217       unsigned ValueBits = ValueVT.getSizeInBits();
218 
219       // Assemble the power of 2 part.
220       unsigned RoundParts =
221           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
222       unsigned RoundBits = PartBits * RoundParts;
223       EVT RoundVT = RoundBits == ValueBits ?
224         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
225       SDValue Lo, Hi;
226 
227       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
228 
229       if (RoundParts > 2) {
230         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
231                               PartVT, HalfVT, V);
232         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
233                               RoundParts / 2, PartVT, HalfVT, V);
234       } else {
235         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
236         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
237       }
238 
239       if (DAG.getDataLayout().isBigEndian())
240         std::swap(Lo, Hi);
241 
242       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
243 
244       if (RoundParts < NumParts) {
245         // Assemble the trailing non-power-of-2 part.
246         unsigned OddParts = NumParts - RoundParts;
247         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
248         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
249                               OddVT, V, CC);
250 
251         // Combine the round and odd parts.
252         Lo = Val;
253         if (DAG.getDataLayout().isBigEndian())
254           std::swap(Lo, Hi);
255         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
256         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
257         Hi =
258             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
259                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
260                                         TLI.getPointerTy(DAG.getDataLayout())));
261         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
262         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
263       }
264     } else if (PartVT.isFloatingPoint()) {
265       // FP split into multiple FP parts (for ppcf128)
266       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
267              "Unexpected split");
268       SDValue Lo, Hi;
269       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
270       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
271       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
272         std::swap(Lo, Hi);
273       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
274     } else {
275       // FP split into integer parts (soft fp)
276       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
277              !PartVT.isVector() && "Unexpected split");
278       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
279       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
280     }
281   }
282 
283   // There is now one part, held in Val.  Correct it to match ValueVT.
284   // PartEVT is the type of the register class that holds the value.
285   // ValueVT is the type of the inline asm operation.
286   EVT PartEVT = Val.getValueType();
287 
288   if (PartEVT == ValueVT)
289     return Val;
290 
291   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
292       ValueVT.bitsLT(PartEVT)) {
293     // For an FP value in an integer part, we need to truncate to the right
294     // width first.
295     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
296     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
297   }
298 
299   // Handle types that have the same size.
300   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
301     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
302 
303   // Handle types with different sizes.
304   if (PartEVT.isInteger() && ValueVT.isInteger()) {
305     if (ValueVT.bitsLT(PartEVT)) {
306       // For a truncate, see if we have any information to
307       // indicate whether the truncated bits will always be
308       // zero or sign-extension.
309       if (AssertOp.hasValue())
310         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
311                           DAG.getValueType(ValueVT));
312       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
313     }
314     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
315   }
316 
317   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
318     // FP_ROUND's are always exact here.
319     if (ValueVT.bitsLT(Val.getValueType()))
320       return DAG.getNode(
321           ISD::FP_ROUND, DL, ValueVT, Val,
322           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
323 
324     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
325   }
326 
327   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
328   // then truncating.
329   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
330       ValueVT.bitsLT(PartEVT)) {
331     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
332     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
333   }
334 
335   report_fatal_error("Unknown mismatch in getCopyFromParts!");
336 }
337 
338 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
339                                               const Twine &ErrMsg) {
340   const Instruction *I = dyn_cast_or_null<Instruction>(V);
341   if (!V)
342     return Ctx.emitError(ErrMsg);
343 
344   const char *AsmError = ", possible invalid constraint for vector type";
345   if (const CallInst *CI = dyn_cast<CallInst>(I))
346     if (isa<InlineAsm>(CI->getCalledValue()))
347       return Ctx.emitError(I, ErrMsg + AsmError);
348 
349   return Ctx.emitError(I, ErrMsg);
350 }
351 
352 /// getCopyFromPartsVector - Create a value that contains the specified legal
353 /// parts combined into the value they represent.  If the parts combine to a
354 /// type larger than ValueVT then AssertOp can be used to specify whether the
355 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
356 /// ValueVT (ISD::AssertSext).
357 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
358                                       const SDValue *Parts, unsigned NumParts,
359                                       MVT PartVT, EVT ValueVT, const Value *V,
360                                       Optional<CallingConv::ID> CallConv) {
361   assert(ValueVT.isVector() && "Not a vector value");
362   assert(NumParts > 0 && "No parts to assemble!");
363   const bool IsABIRegCopy = CallConv.hasValue();
364 
365   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
366   SDValue Val = Parts[0];
367 
368   // Handle a multi-element vector.
369   if (NumParts > 1) {
370     EVT IntermediateVT;
371     MVT RegisterVT;
372     unsigned NumIntermediates;
373     unsigned NumRegs;
374 
375     if (IsABIRegCopy) {
376       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
377           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
378           NumIntermediates, RegisterVT);
379     } else {
380       NumRegs =
381           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
382                                      NumIntermediates, RegisterVT);
383     }
384 
385     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
386     NumParts = NumRegs; // Silence a compiler warning.
387     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
388     assert(RegisterVT.getSizeInBits() ==
389            Parts[0].getSimpleValueType().getSizeInBits() &&
390            "Part type sizes don't match!");
391 
392     // Assemble the parts into intermediate operands.
393     SmallVector<SDValue, 8> Ops(NumIntermediates);
394     if (NumIntermediates == NumParts) {
395       // If the register was not expanded, truncate or copy the value,
396       // as appropriate.
397       for (unsigned i = 0; i != NumParts; ++i)
398         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
399                                   PartVT, IntermediateVT, V);
400     } else if (NumParts > 0) {
401       // If the intermediate type was expanded, build the intermediate
402       // operands from the parts.
403       assert(NumParts % NumIntermediates == 0 &&
404              "Must expand into a divisible number of parts!");
405       unsigned Factor = NumParts / NumIntermediates;
406       for (unsigned i = 0; i != NumIntermediates; ++i)
407         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
408                                   PartVT, IntermediateVT, V);
409     }
410 
411     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
412     // intermediate operands.
413     EVT BuiltVectorTy =
414         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
415                          (IntermediateVT.isVector()
416                               ? IntermediateVT.getVectorNumElements() * NumParts
417                               : NumIntermediates));
418     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
419                                                 : ISD::BUILD_VECTOR,
420                       DL, BuiltVectorTy, Ops);
421   }
422 
423   // There is now one part, held in Val.  Correct it to match ValueVT.
424   EVT PartEVT = Val.getValueType();
425 
426   if (PartEVT == ValueVT)
427     return Val;
428 
429   if (PartEVT.isVector()) {
430     // If the element type of the source/dest vectors are the same, but the
431     // parts vector has more elements than the value vector, then we have a
432     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
433     // elements we want.
434     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
435       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
436              "Cannot narrow, it would be a lossy transformation");
437       return DAG.getNode(
438           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
439           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
440     }
441 
442     // Vector/Vector bitcast.
443     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
444       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
445 
446     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
447       "Cannot handle this kind of promotion");
448     // Promoted vector extract
449     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
450 
451   }
452 
453   // Trivial bitcast if the types are the same size and the destination
454   // vector type is legal.
455   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
456       TLI.isTypeLegal(ValueVT))
457     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
458 
459   if (ValueVT.getVectorNumElements() != 1) {
460      // Certain ABIs require that vectors are passed as integers. For vectors
461      // are the same size, this is an obvious bitcast.
462      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
463        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
464      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
465        // Bitcast Val back the original type and extract the corresponding
466        // vector we want.
467        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
468        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
469                                            ValueVT.getVectorElementType(), Elts);
470        Val = DAG.getBitcast(WiderVecType, Val);
471        return DAG.getNode(
472            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
473            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
474      }
475 
476      diagnosePossiblyInvalidConstraint(
477          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
478      return DAG.getUNDEF(ValueVT);
479   }
480 
481   // Handle cases such as i8 -> <1 x i1>
482   EVT ValueSVT = ValueVT.getVectorElementType();
483   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
484     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
485                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
486 
487   return DAG.getBuildVector(ValueVT, DL, Val);
488 }
489 
490 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
491                                  SDValue Val, SDValue *Parts, unsigned NumParts,
492                                  MVT PartVT, const Value *V,
493                                  Optional<CallingConv::ID> CallConv);
494 
495 /// getCopyToParts - Create a series of nodes that contain the specified value
496 /// split into legal parts.  If the parts contain more bits than Val, then, for
497 /// integers, ExtendKind can be used to specify how to generate the extra bits.
498 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
499                            SDValue *Parts, unsigned NumParts, MVT PartVT,
500                            const Value *V,
501                            Optional<CallingConv::ID> CallConv = None,
502                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
503   EVT ValueVT = Val.getValueType();
504 
505   // Handle the vector case separately.
506   if (ValueVT.isVector())
507     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
508                                 CallConv);
509 
510   unsigned PartBits = PartVT.getSizeInBits();
511   unsigned OrigNumParts = NumParts;
512   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
513          "Copying to an illegal type!");
514 
515   if (NumParts == 0)
516     return;
517 
518   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
519   EVT PartEVT = PartVT;
520   if (PartEVT == ValueVT) {
521     assert(NumParts == 1 && "No-op copy with multiple parts!");
522     Parts[0] = Val;
523     return;
524   }
525 
526   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
527     // If the parts cover more bits than the value has, promote the value.
528     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
529       assert(NumParts == 1 && "Do not know what to promote to!");
530       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
531     } else {
532       if (ValueVT.isFloatingPoint()) {
533         // FP values need to be bitcast, then extended if they are being put
534         // into a larger container.
535         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
536         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
537       }
538       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
539              ValueVT.isInteger() &&
540              "Unknown mismatch!");
541       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
542       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
543       if (PartVT == MVT::x86mmx)
544         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
545     }
546   } else if (PartBits == ValueVT.getSizeInBits()) {
547     // Different types of the same size.
548     assert(NumParts == 1 && PartEVT != ValueVT);
549     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
550   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
551     // If the parts cover less bits than value has, truncate the value.
552     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
553            ValueVT.isInteger() &&
554            "Unknown mismatch!");
555     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
556     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
557     if (PartVT == MVT::x86mmx)
558       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
559   }
560 
561   // The value may have changed - recompute ValueVT.
562   ValueVT = Val.getValueType();
563   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
564          "Failed to tile the value with PartVT!");
565 
566   if (NumParts == 1) {
567     if (PartEVT != ValueVT) {
568       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
569                                         "scalar-to-vector conversion failed");
570       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
571     }
572 
573     Parts[0] = Val;
574     return;
575   }
576 
577   // Expand the value into multiple parts.
578   if (NumParts & (NumParts - 1)) {
579     // The number of parts is not a power of 2.  Split off and copy the tail.
580     assert(PartVT.isInteger() && ValueVT.isInteger() &&
581            "Do not know what to expand to!");
582     unsigned RoundParts = 1 << Log2_32(NumParts);
583     unsigned RoundBits = RoundParts * PartBits;
584     unsigned OddParts = NumParts - RoundParts;
585     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
586       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
587 
588     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
589                    CallConv);
590 
591     if (DAG.getDataLayout().isBigEndian())
592       // The odd parts were reversed by getCopyToParts - unreverse them.
593       std::reverse(Parts + RoundParts, Parts + NumParts);
594 
595     NumParts = RoundParts;
596     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
597     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
598   }
599 
600   // The number of parts is a power of 2.  Repeatedly bisect the value using
601   // EXTRACT_ELEMENT.
602   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
603                          EVT::getIntegerVT(*DAG.getContext(),
604                                            ValueVT.getSizeInBits()),
605                          Val);
606 
607   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
608     for (unsigned i = 0; i < NumParts; i += StepSize) {
609       unsigned ThisBits = StepSize * PartBits / 2;
610       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
611       SDValue &Part0 = Parts[i];
612       SDValue &Part1 = Parts[i+StepSize/2];
613 
614       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
615                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
616       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
617                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
618 
619       if (ThisBits == PartBits && ThisVT != PartVT) {
620         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
621         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
622       }
623     }
624   }
625 
626   if (DAG.getDataLayout().isBigEndian())
627     std::reverse(Parts, Parts + OrigNumParts);
628 }
629 
630 static SDValue widenVectorToPartType(SelectionDAG &DAG,
631                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
632   if (!PartVT.isVector())
633     return SDValue();
634 
635   EVT ValueVT = Val.getValueType();
636   unsigned PartNumElts = PartVT.getVectorNumElements();
637   unsigned ValueNumElts = ValueVT.getVectorNumElements();
638   if (PartNumElts > ValueNumElts &&
639       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
640     EVT ElementVT = PartVT.getVectorElementType();
641     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
642     // undef elements.
643     SmallVector<SDValue, 16> Ops;
644     DAG.ExtractVectorElements(Val, Ops);
645     SDValue EltUndef = DAG.getUNDEF(ElementVT);
646     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
647       Ops.push_back(EltUndef);
648 
649     // FIXME: Use CONCAT for 2x -> 4x.
650     return DAG.getBuildVector(PartVT, DL, Ops);
651   }
652 
653   return SDValue();
654 }
655 
656 /// getCopyToPartsVector - Create a series of nodes that contain the specified
657 /// value split into legal parts.
658 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
659                                  SDValue Val, SDValue *Parts, unsigned NumParts,
660                                  MVT PartVT, const Value *V,
661                                  Optional<CallingConv::ID> CallConv) {
662   EVT ValueVT = Val.getValueType();
663   assert(ValueVT.isVector() && "Not a vector");
664   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
665   const bool IsABIRegCopy = CallConv.hasValue();
666 
667   if (NumParts == 1) {
668     EVT PartEVT = PartVT;
669     if (PartEVT == ValueVT) {
670       // Nothing to do.
671     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
672       // Bitconvert vector->vector case.
673       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
674     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
675       Val = Widened;
676     } else if (PartVT.isVector() &&
677                PartEVT.getVectorElementType().bitsGE(
678                  ValueVT.getVectorElementType()) &&
679                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
680 
681       // Promoted vector extract
682       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
683     } else {
684       if (ValueVT.getVectorNumElements() == 1) {
685         Val = DAG.getNode(
686             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
687             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
688       } else {
689         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
690                "lossy conversion of vector to scalar type");
691         EVT IntermediateType =
692             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
693         Val = DAG.getBitcast(IntermediateType, Val);
694         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
695       }
696     }
697 
698     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
699     Parts[0] = Val;
700     return;
701   }
702 
703   // Handle a multi-element vector.
704   EVT IntermediateVT;
705   MVT RegisterVT;
706   unsigned NumIntermediates;
707   unsigned NumRegs;
708   if (IsABIRegCopy) {
709     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
710         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
711         NumIntermediates, RegisterVT);
712   } else {
713     NumRegs =
714         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
715                                    NumIntermediates, RegisterVT);
716   }
717 
718   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
719   NumParts = NumRegs; // Silence a compiler warning.
720   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
721 
722   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
723     IntermediateVT.getVectorNumElements() : 1;
724 
725   // Convert the vector to the appropiate type if necessary.
726   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
727 
728   EVT BuiltVectorTy = EVT::getVectorVT(
729       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
730   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
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] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
743                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
744     } else {
745       Ops[i] = DAG.getNode(
746           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
747           DAG.getConstant(i, DL, IdxVT));
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 (!TargetRegisterInfo::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() &&
952            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
953     // Put the register class of the virtual registers in the flag word.  That
954     // way, later passes can recompute register class constraints for inline
955     // assembly as well as normal instructions.
956     // Don't do this for tied operands that can use the regclass information
957     // from the def.
958     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
959     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
960     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
961   }
962 
963   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
964   Ops.push_back(Res);
965 
966   if (Code == InlineAsm::Kind_Clobber) {
967     // Clobbers should always have a 1:1 mapping with registers, and may
968     // reference registers that have illegal (e.g. vector) types. Hence, we
969     // shouldn't try to apply any sort of splitting logic to them.
970     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
971            "No 1:1 mapping from clobbers to regs?");
972     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
973     (void)SP;
974     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
975       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
976       assert(
977           (Regs[I] != SP ||
978            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
979           "If we clobbered the stack pointer, MFI should know about it.");
980     }
981     return;
982   }
983 
984   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
985     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
986     MVT RegisterVT = RegVTs[Value];
987     for (unsigned i = 0; i != NumRegs; ++i) {
988       assert(Reg < Regs.size() && "Mismatch in # registers expected");
989       unsigned TheReg = Regs[Reg++];
990       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
991     }
992   }
993 }
994 
995 SmallVector<std::pair<unsigned, unsigned>, 4>
996 RegsForValue::getRegsAndSizes() const {
997   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
998   unsigned I = 0;
999   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1000     unsigned RegCount = std::get<0>(CountAndVT);
1001     MVT RegisterVT = std::get<1>(CountAndVT);
1002     unsigned RegisterSize = RegisterVT.getSizeInBits();
1003     for (unsigned E = I + RegCount; I != E; ++I)
1004       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1005   }
1006   return OutVec;
1007 }
1008 
1009 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1010                                const TargetLibraryInfo *li) {
1011   AA = aa;
1012   GFI = gfi;
1013   LibInfo = li;
1014   DL = &DAG.getDataLayout();
1015   Context = DAG.getContext();
1016   LPadToCallSiteMap.clear();
1017   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1018 }
1019 
1020 void SelectionDAGBuilder::clear() {
1021   NodeMap.clear();
1022   UnusedArgNodeMap.clear();
1023   PendingLoads.clear();
1024   PendingExports.clear();
1025   CurInst = nullptr;
1026   HasTailCall = false;
1027   SDNodeOrder = LowestSDNodeOrder;
1028   StatepointLowering.clear();
1029 }
1030 
1031 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1032   DanglingDebugInfoMap.clear();
1033 }
1034 
1035 SDValue SelectionDAGBuilder::getRoot() {
1036   if (PendingLoads.empty())
1037     return DAG.getRoot();
1038 
1039   if (PendingLoads.size() == 1) {
1040     SDValue Root = PendingLoads[0];
1041     DAG.setRoot(Root);
1042     PendingLoads.clear();
1043     return Root;
1044   }
1045 
1046   // Otherwise, we have to make a token factor node.
1047   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1048   PendingLoads.clear();
1049   DAG.setRoot(Root);
1050   return Root;
1051 }
1052 
1053 SDValue SelectionDAGBuilder::getControlRoot() {
1054   SDValue Root = DAG.getRoot();
1055 
1056   if (PendingExports.empty())
1057     return Root;
1058 
1059   // Turn all of the CopyToReg chains into one factored node.
1060   if (Root.getOpcode() != ISD::EntryToken) {
1061     unsigned i = 0, e = PendingExports.size();
1062     for (; i != e; ++i) {
1063       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1064       if (PendingExports[i].getNode()->getOperand(0) == Root)
1065         break;  // Don't add the root if we already indirectly depend on it.
1066     }
1067 
1068     if (i == e)
1069       PendingExports.push_back(Root);
1070   }
1071 
1072   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1073                      PendingExports);
1074   PendingExports.clear();
1075   DAG.setRoot(Root);
1076   return Root;
1077 }
1078 
1079 void SelectionDAGBuilder::visit(const Instruction &I) {
1080   // Set up outgoing PHI node register values before emitting the terminator.
1081   if (I.isTerminator()) {
1082     HandlePHINodesInSuccessorBlocks(I.getParent());
1083   }
1084 
1085   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1086   if (!isa<DbgInfoIntrinsic>(I))
1087     ++SDNodeOrder;
1088 
1089   CurInst = &I;
1090 
1091   visit(I.getOpcode(), I);
1092 
1093   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1094     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1095     // maps to this instruction.
1096     // TODO: We could handle all flags (nsw, etc) here.
1097     // TODO: If an IR instruction maps to >1 node, only the final node will have
1098     //       flags set.
1099     if (SDNode *Node = getNodeForIRValue(&I)) {
1100       SDNodeFlags IncomingFlags;
1101       IncomingFlags.copyFMF(*FPMO);
1102       if (!Node->getFlags().isDefined())
1103         Node->setFlags(IncomingFlags);
1104       else
1105         Node->intersectFlagsWith(IncomingFlags);
1106     }
1107   }
1108 
1109   if (!I.isTerminator() && !HasTailCall &&
1110       !isStatepoint(&I)) // statepoints handle their exports internally
1111     CopyToExportRegsIfNeeded(&I);
1112 
1113   CurInst = nullptr;
1114 }
1115 
1116 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1117   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1118 }
1119 
1120 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1121   // Note: this doesn't use InstVisitor, because it has to work with
1122   // ConstantExpr's in addition to instructions.
1123   switch (Opcode) {
1124   default: llvm_unreachable("Unknown instruction type encountered!");
1125     // Build the switch statement using the Instruction.def file.
1126 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1127     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1128 #include "llvm/IR/Instruction.def"
1129   }
1130 }
1131 
1132 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1133                                                 const DIExpression *Expr) {
1134   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1135     const DbgValueInst *DI = DDI.getDI();
1136     DIVariable *DanglingVariable = DI->getVariable();
1137     DIExpression *DanglingExpr = DI->getExpression();
1138     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1139       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1140       return true;
1141     }
1142     return false;
1143   };
1144 
1145   for (auto &DDIMI : DanglingDebugInfoMap) {
1146     DanglingDebugInfoVector &DDIV = DDIMI.second;
1147 
1148     // If debug info is to be dropped, run it through final checks to see
1149     // whether it can be salvaged.
1150     for (auto &DDI : DDIV)
1151       if (isMatchingDbgValue(DDI))
1152         salvageUnresolvedDbgValue(DDI);
1153 
1154     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1155   }
1156 }
1157 
1158 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1159 // generate the debug data structures now that we've seen its definition.
1160 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1161                                                    SDValue Val) {
1162   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1163   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1164     return;
1165 
1166   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1167   for (auto &DDI : DDIV) {
1168     const DbgValueInst *DI = DDI.getDI();
1169     assert(DI && "Ill-formed DanglingDebugInfo");
1170     DebugLoc dl = DDI.getdl();
1171     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1172     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1173     DILocalVariable *Variable = DI->getVariable();
1174     DIExpression *Expr = DI->getExpression();
1175     assert(Variable->isValidLocationForIntrinsic(dl) &&
1176            "Expected inlined-at fields to agree");
1177     SDDbgValue *SDV;
1178     if (Val.getNode()) {
1179       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1180       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1181       // we couldn't resolve it directly when examining the DbgValue intrinsic
1182       // in the first place we should not be more successful here). Unless we
1183       // have some test case that prove this to be correct we should avoid
1184       // calling EmitFuncArgumentDbgValue here.
1185       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1186         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1187                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1188         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1189         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1190         // inserted after the definition of Val when emitting the instructions
1191         // after ISel. An alternative could be to teach
1192         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1193         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1194                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1195                    << ValSDNodeOrder << "\n");
1196         SDV = getDbgValue(Val, Variable, Expr, dl,
1197                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1198         DAG.AddDbgValue(SDV, Val.getNode(), false);
1199       } else
1200         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1201                           << "in EmitFuncArgumentDbgValue\n");
1202     } else {
1203       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1204       auto Undef =
1205           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1206       auto SDV =
1207           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1208       DAG.AddDbgValue(SDV, nullptr, false);
1209     }
1210   }
1211   DDIV.clear();
1212 }
1213 
1214 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1215   Value *V = DDI.getDI()->getValue();
1216   DILocalVariable *Var = DDI.getDI()->getVariable();
1217   DIExpression *Expr = DDI.getDI()->getExpression();
1218   DebugLoc DL = DDI.getdl();
1219   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1220   unsigned SDOrder = DDI.getSDNodeOrder();
1221 
1222   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1223   // that DW_OP_stack_value is desired.
1224   assert(isa<DbgValueInst>(DDI.getDI()));
1225   bool StackValue = true;
1226 
1227   // Can this Value can be encoded without any further work?
1228   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1229     return;
1230 
1231   // Attempt to salvage back through as many instructions as possible. Bail if
1232   // a non-instruction is seen, such as a constant expression or global
1233   // variable. FIXME: Further work could recover those too.
1234   while (isa<Instruction>(V)) {
1235     Instruction &VAsInst = *cast<Instruction>(V);
1236     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1237 
1238     // If we cannot salvage any further, and haven't yet found a suitable debug
1239     // expression, bail out.
1240     if (!NewExpr)
1241       break;
1242 
1243     // New value and expr now represent this debuginfo.
1244     V = VAsInst.getOperand(0);
1245     Expr = NewExpr;
1246 
1247     // Some kind of simplification occurred: check whether the operand of the
1248     // salvaged debug expression can be encoded in this DAG.
1249     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1250       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1251                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1252       return;
1253     }
1254   }
1255 
1256   // This was the final opportunity to salvage this debug information, and it
1257   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1258   // any earlier variable location.
1259   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1260   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1261   DAG.AddDbgValue(SDV, nullptr, false);
1262 
1263   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1264                     << "\n");
1265   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1266                     << "\n");
1267 }
1268 
1269 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1270                                            DIExpression *Expr, DebugLoc dl,
1271                                            DebugLoc InstDL, unsigned Order) {
1272   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1273   SDDbgValue *SDV;
1274   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1275       isa<ConstantPointerNull>(V)) {
1276     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1277     DAG.AddDbgValue(SDV, nullptr, false);
1278     return true;
1279   }
1280 
1281   // If the Value is a frame index, we can create a FrameIndex debug value
1282   // without relying on the DAG at all.
1283   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1284     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1285     if (SI != FuncInfo.StaticAllocaMap.end()) {
1286       auto SDV =
1287           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1288                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1289       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1290       // is still available even if the SDNode gets optimized out.
1291       DAG.AddDbgValue(SDV, nullptr, false);
1292       return true;
1293     }
1294   }
1295 
1296   // Do not use getValue() in here; we don't want to generate code at
1297   // this point if it hasn't been done yet.
1298   SDValue N = NodeMap[V];
1299   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1300     N = UnusedArgNodeMap[V];
1301   if (N.getNode()) {
1302     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1303       return true;
1304     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1305     DAG.AddDbgValue(SDV, N.getNode(), false);
1306     return true;
1307   }
1308 
1309   // Special rules apply for the first dbg.values of parameter variables in a
1310   // function. Identify them by the fact they reference Argument Values, that
1311   // they're parameters, and they are parameters of the current function. We
1312   // need to let them dangle until they get an SDNode.
1313   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1314                        !InstDL.getInlinedAt();
1315   if (!IsParamOfFunc) {
1316     // The value is not used in this block yet (or it would have an SDNode).
1317     // We still want the value to appear for the user if possible -- if it has
1318     // an associated VReg, we can refer to that instead.
1319     auto VMI = FuncInfo.ValueMap.find(V);
1320     if (VMI != FuncInfo.ValueMap.end()) {
1321       unsigned Reg = VMI->second;
1322       // If this is a PHI node, it may be split up into several MI PHI nodes
1323       // (in FunctionLoweringInfo::set).
1324       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1325                        V->getType(), None);
1326       if (RFV.occupiesMultipleRegs()) {
1327         unsigned Offset = 0;
1328         unsigned BitsToDescribe = 0;
1329         if (auto VarSize = Var->getSizeInBits())
1330           BitsToDescribe = *VarSize;
1331         if (auto Fragment = Expr->getFragmentInfo())
1332           BitsToDescribe = Fragment->SizeInBits;
1333         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1334           unsigned RegisterSize = RegAndSize.second;
1335           // Bail out if all bits are described already.
1336           if (Offset >= BitsToDescribe)
1337             break;
1338           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1339               ? BitsToDescribe - Offset
1340               : RegisterSize;
1341           auto FragmentExpr = DIExpression::createFragmentExpression(
1342               Expr, Offset, FragmentSize);
1343           if (!FragmentExpr)
1344               continue;
1345           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1346                                     false, dl, SDNodeOrder);
1347           DAG.AddDbgValue(SDV, nullptr, false);
1348           Offset += RegisterSize;
1349         }
1350       } else {
1351         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1352         DAG.AddDbgValue(SDV, nullptr, false);
1353       }
1354       return true;
1355     }
1356   }
1357 
1358   return false;
1359 }
1360 
1361 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1362   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1363   for (auto &Pair : DanglingDebugInfoMap)
1364     for (auto &DDI : Pair.second)
1365       salvageUnresolvedDbgValue(DDI);
1366   clearDanglingDebugInfo();
1367 }
1368 
1369 /// getCopyFromRegs - If there was virtual register allocated for the value V
1370 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1371 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1372   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1373   SDValue Result;
1374 
1375   if (It != FuncInfo.ValueMap.end()) {
1376     unsigned InReg = It->second;
1377 
1378     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1379                      DAG.getDataLayout(), InReg, Ty,
1380                      None); // This is not an ABI copy.
1381     SDValue Chain = DAG.getEntryNode();
1382     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1383                                  V);
1384     resolveDanglingDebugInfo(V, Result);
1385   }
1386 
1387   return Result;
1388 }
1389 
1390 /// getValue - Return an SDValue for the given Value.
1391 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1392   // If we already have an SDValue for this value, use it. It's important
1393   // to do this first, so that we don't create a CopyFromReg if we already
1394   // have a regular SDValue.
1395   SDValue &N = NodeMap[V];
1396   if (N.getNode()) return N;
1397 
1398   // If there's a virtual register allocated and initialized for this
1399   // value, use it.
1400   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1401     return copyFromReg;
1402 
1403   // Otherwise create a new SDValue and remember it.
1404   SDValue Val = getValueImpl(V);
1405   NodeMap[V] = Val;
1406   resolveDanglingDebugInfo(V, Val);
1407   return Val;
1408 }
1409 
1410 // Return true if SDValue exists for the given Value
1411 bool SelectionDAGBuilder::findValue(const Value *V) const {
1412   return (NodeMap.find(V) != NodeMap.end()) ||
1413     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1414 }
1415 
1416 /// getNonRegisterValue - Return an SDValue for the given Value, but
1417 /// don't look in FuncInfo.ValueMap for a virtual register.
1418 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1419   // If we already have an SDValue for this value, use it.
1420   SDValue &N = NodeMap[V];
1421   if (N.getNode()) {
1422     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1423       // Remove the debug location from the node as the node is about to be used
1424       // in a location which may differ from the original debug location.  This
1425       // is relevant to Constant and ConstantFP nodes because they can appear
1426       // as constant expressions inside PHI nodes.
1427       N->setDebugLoc(DebugLoc());
1428     }
1429     return N;
1430   }
1431 
1432   // Otherwise create a new SDValue and remember it.
1433   SDValue Val = getValueImpl(V);
1434   NodeMap[V] = Val;
1435   resolveDanglingDebugInfo(V, Val);
1436   return Val;
1437 }
1438 
1439 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1440 /// Create an SDValue for the given value.
1441 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1443 
1444   if (const Constant *C = dyn_cast<Constant>(V)) {
1445     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1446 
1447     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1448       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1449 
1450     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1451       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1452 
1453     if (isa<ConstantPointerNull>(C)) {
1454       unsigned AS = V->getType()->getPointerAddressSpace();
1455       return DAG.getConstant(0, getCurSDLoc(),
1456                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1457     }
1458 
1459     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1460       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1461 
1462     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1463       return DAG.getUNDEF(VT);
1464 
1465     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1466       visit(CE->getOpcode(), *CE);
1467       SDValue N1 = NodeMap[V];
1468       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1469       return N1;
1470     }
1471 
1472     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1473       SmallVector<SDValue, 4> Constants;
1474       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1475            OI != OE; ++OI) {
1476         SDNode *Val = getValue(*OI).getNode();
1477         // If the operand is an empty aggregate, there are no values.
1478         if (!Val) continue;
1479         // Add each leaf value from the operand to the Constants list
1480         // to form a flattened list of all the values.
1481         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1482           Constants.push_back(SDValue(Val, i));
1483       }
1484 
1485       return DAG.getMergeValues(Constants, getCurSDLoc());
1486     }
1487 
1488     if (const ConstantDataSequential *CDS =
1489           dyn_cast<ConstantDataSequential>(C)) {
1490       SmallVector<SDValue, 4> Ops;
1491       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1492         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1493         // Add each leaf value from the operand to the Constants list
1494         // to form a flattened list of all the values.
1495         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1496           Ops.push_back(SDValue(Val, i));
1497       }
1498 
1499       if (isa<ArrayType>(CDS->getType()))
1500         return DAG.getMergeValues(Ops, getCurSDLoc());
1501       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1502     }
1503 
1504     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1505       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1506              "Unknown struct or array constant!");
1507 
1508       SmallVector<EVT, 4> ValueVTs;
1509       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1510       unsigned NumElts = ValueVTs.size();
1511       if (NumElts == 0)
1512         return SDValue(); // empty struct
1513       SmallVector<SDValue, 4> Constants(NumElts);
1514       for (unsigned i = 0; i != NumElts; ++i) {
1515         EVT EltVT = ValueVTs[i];
1516         if (isa<UndefValue>(C))
1517           Constants[i] = DAG.getUNDEF(EltVT);
1518         else if (EltVT.isFloatingPoint())
1519           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1520         else
1521           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1522       }
1523 
1524       return DAG.getMergeValues(Constants, getCurSDLoc());
1525     }
1526 
1527     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1528       return DAG.getBlockAddress(BA, VT);
1529 
1530     VectorType *VecTy = cast<VectorType>(V->getType());
1531     unsigned NumElements = VecTy->getNumElements();
1532 
1533     // Now that we know the number and type of the elements, get that number of
1534     // elements into the Ops array based on what kind of constant it is.
1535     SmallVector<SDValue, 16> Ops;
1536     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1537       for (unsigned i = 0; i != NumElements; ++i)
1538         Ops.push_back(getValue(CV->getOperand(i)));
1539     } else {
1540       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1541       EVT EltVT =
1542           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1543 
1544       SDValue Op;
1545       if (EltVT.isFloatingPoint())
1546         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1547       else
1548         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1549       Ops.assign(NumElements, Op);
1550     }
1551 
1552     // Create a BUILD_VECTOR node.
1553     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1554   }
1555 
1556   // If this is a static alloca, generate it as the frameindex instead of
1557   // computation.
1558   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1559     DenseMap<const AllocaInst*, int>::iterator SI =
1560       FuncInfo.StaticAllocaMap.find(AI);
1561     if (SI != FuncInfo.StaticAllocaMap.end())
1562       return DAG.getFrameIndex(SI->second,
1563                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1564   }
1565 
1566   // If this is an instruction which fast-isel has deferred, select it now.
1567   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1568     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1569 
1570     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1571                      Inst->getType(), getABIRegCopyCC(V));
1572     SDValue Chain = DAG.getEntryNode();
1573     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1574   }
1575 
1576   llvm_unreachable("Can't get register for value!");
1577 }
1578 
1579 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1580   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1581   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1582   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1583   bool IsSEH = isAsynchronousEHPersonality(Pers);
1584   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1585   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1586   if (!IsSEH)
1587     CatchPadMBB->setIsEHScopeEntry();
1588   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1589   if (IsMSVCCXX || IsCoreCLR)
1590     CatchPadMBB->setIsEHFuncletEntry();
1591   // Wasm does not need catchpads anymore
1592   if (!IsWasmCXX)
1593     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1594                             getControlRoot()));
1595 }
1596 
1597 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1598   // Update machine-CFG edge.
1599   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1600   FuncInfo.MBB->addSuccessor(TargetMBB);
1601 
1602   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1603   bool IsSEH = isAsynchronousEHPersonality(Pers);
1604   if (IsSEH) {
1605     // If this is not a fall-through branch or optimizations are switched off,
1606     // emit the branch.
1607     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1608         TM.getOptLevel() == CodeGenOpt::None)
1609       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1610                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1611     return;
1612   }
1613 
1614   // Figure out the funclet membership for the catchret's successor.
1615   // This will be used by the FuncletLayout pass to determine how to order the
1616   // BB's.
1617   // A 'catchret' returns to the outer scope's color.
1618   Value *ParentPad = I.getCatchSwitchParentPad();
1619   const BasicBlock *SuccessorColor;
1620   if (isa<ConstantTokenNone>(ParentPad))
1621     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1622   else
1623     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1624   assert(SuccessorColor && "No parent funclet for catchret!");
1625   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1626   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1627 
1628   // Create the terminator node.
1629   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1630                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1631                             DAG.getBasicBlock(SuccessorColorMBB));
1632   DAG.setRoot(Ret);
1633 }
1634 
1635 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1636   // Don't emit any special code for the cleanuppad instruction. It just marks
1637   // the start of an EH scope/funclet.
1638   FuncInfo.MBB->setIsEHScopeEntry();
1639   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1640   if (Pers != EHPersonality::Wasm_CXX) {
1641     FuncInfo.MBB->setIsEHFuncletEntry();
1642     FuncInfo.MBB->setIsCleanupFuncletEntry();
1643   }
1644 }
1645 
1646 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1647 // the control flow always stops at the single catch pad, as it does for a
1648 // cleanup pad. In case the exception caught is not of the types the catch pad
1649 // catches, it will be rethrown by a rethrow.
1650 static void findWasmUnwindDestinations(
1651     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1652     BranchProbability Prob,
1653     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1654         &UnwindDests) {
1655   while (EHPadBB) {
1656     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1657     if (isa<CleanupPadInst>(Pad)) {
1658       // Stop on cleanup pads.
1659       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1660       UnwindDests.back().first->setIsEHScopeEntry();
1661       break;
1662     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1663       // Add the catchpad handlers to the possible destinations. We don't
1664       // continue to the unwind destination of the catchswitch for wasm.
1665       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1666         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1667         UnwindDests.back().first->setIsEHScopeEntry();
1668       }
1669       break;
1670     } else {
1671       continue;
1672     }
1673   }
1674 }
1675 
1676 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1677 /// many places it could ultimately go. In the IR, we have a single unwind
1678 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1679 /// This function skips over imaginary basic blocks that hold catchswitch
1680 /// instructions, and finds all the "real" machine
1681 /// basic block destinations. As those destinations may not be successors of
1682 /// EHPadBB, here we also calculate the edge probability to those destinations.
1683 /// The passed-in Prob is the edge probability to EHPadBB.
1684 static void findUnwindDestinations(
1685     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1686     BranchProbability Prob,
1687     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1688         &UnwindDests) {
1689   EHPersonality Personality =
1690     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1691   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1692   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1693   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1694   bool IsSEH = isAsynchronousEHPersonality(Personality);
1695 
1696   if (IsWasmCXX) {
1697     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1698     assert(UnwindDests.size() <= 1 &&
1699            "There should be at most one unwind destination for wasm");
1700     return;
1701   }
1702 
1703   while (EHPadBB) {
1704     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1705     BasicBlock *NewEHPadBB = nullptr;
1706     if (isa<LandingPadInst>(Pad)) {
1707       // Stop on landingpads. They are not funclets.
1708       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1709       break;
1710     } else if (isa<CleanupPadInst>(Pad)) {
1711       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1712       // personalities.
1713       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1714       UnwindDests.back().first->setIsEHScopeEntry();
1715       UnwindDests.back().first->setIsEHFuncletEntry();
1716       break;
1717     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1718       // Add the catchpad handlers to the possible destinations.
1719       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1720         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1721         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1722         if (IsMSVCCXX || IsCoreCLR)
1723           UnwindDests.back().first->setIsEHFuncletEntry();
1724         if (!IsSEH)
1725           UnwindDests.back().first->setIsEHScopeEntry();
1726       }
1727       NewEHPadBB = CatchSwitch->getUnwindDest();
1728     } else {
1729       continue;
1730     }
1731 
1732     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1733     if (BPI && NewEHPadBB)
1734       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1735     EHPadBB = NewEHPadBB;
1736   }
1737 }
1738 
1739 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1740   // Update successor info.
1741   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1742   auto UnwindDest = I.getUnwindDest();
1743   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1744   BranchProbability UnwindDestProb =
1745       (BPI && UnwindDest)
1746           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1747           : BranchProbability::getZero();
1748   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1749   for (auto &UnwindDest : UnwindDests) {
1750     UnwindDest.first->setIsEHPad();
1751     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1752   }
1753   FuncInfo.MBB->normalizeSuccProbs();
1754 
1755   // Create the terminator node.
1756   SDValue Ret =
1757       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1758   DAG.setRoot(Ret);
1759 }
1760 
1761 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1762   report_fatal_error("visitCatchSwitch not yet implemented!");
1763 }
1764 
1765 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1766   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1767   auto &DL = DAG.getDataLayout();
1768   SDValue Chain = getControlRoot();
1769   SmallVector<ISD::OutputArg, 8> Outs;
1770   SmallVector<SDValue, 8> OutVals;
1771 
1772   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1773   // lower
1774   //
1775   //   %val = call <ty> @llvm.experimental.deoptimize()
1776   //   ret <ty> %val
1777   //
1778   // differently.
1779   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1780     LowerDeoptimizingReturn();
1781     return;
1782   }
1783 
1784   if (!FuncInfo.CanLowerReturn) {
1785     unsigned DemoteReg = FuncInfo.DemoteRegister;
1786     const Function *F = I.getParent()->getParent();
1787 
1788     // Emit a store of the return value through the virtual register.
1789     // Leave Outs empty so that LowerReturn won't try to load return
1790     // registers the usual way.
1791     SmallVector<EVT, 1> PtrValueVTs;
1792     ComputeValueVTs(TLI, DL,
1793                     F->getReturnType()->getPointerTo(
1794                         DAG.getDataLayout().getAllocaAddrSpace()),
1795                     PtrValueVTs);
1796 
1797     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1798                                         DemoteReg, PtrValueVTs[0]);
1799     SDValue RetOp = getValue(I.getOperand(0));
1800 
1801     SmallVector<EVT, 4> ValueVTs, MemVTs;
1802     SmallVector<uint64_t, 4> Offsets;
1803     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1804                     &Offsets);
1805     unsigned NumValues = ValueVTs.size();
1806 
1807     SmallVector<SDValue, 4> Chains(NumValues);
1808     for (unsigned i = 0; i != NumValues; ++i) {
1809       // An aggregate return value cannot wrap around the address space, so
1810       // offsets to its parts don't wrap either.
1811       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1812 
1813       SDValue Val = RetOp.getValue(i);
1814       if (MemVTs[i] != ValueVTs[i])
1815         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1816       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1817           // FIXME: better loc info would be nice.
1818           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1819     }
1820 
1821     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1822                         MVT::Other, Chains);
1823   } else if (I.getNumOperands() != 0) {
1824     SmallVector<EVT, 4> ValueVTs;
1825     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1826     unsigned NumValues = ValueVTs.size();
1827     if (NumValues) {
1828       SDValue RetOp = getValue(I.getOperand(0));
1829 
1830       const Function *F = I.getParent()->getParent();
1831 
1832       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1833           I.getOperand(0)->getType(), F->getCallingConv(),
1834           /*IsVarArg*/ false);
1835 
1836       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1837       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1838                                           Attribute::SExt))
1839         ExtendKind = ISD::SIGN_EXTEND;
1840       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1841                                                Attribute::ZExt))
1842         ExtendKind = ISD::ZERO_EXTEND;
1843 
1844       LLVMContext &Context = F->getContext();
1845       bool RetInReg = F->getAttributes().hasAttribute(
1846           AttributeList::ReturnIndex, Attribute::InReg);
1847 
1848       for (unsigned j = 0; j != NumValues; ++j) {
1849         EVT VT = ValueVTs[j];
1850 
1851         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1852           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1853 
1854         CallingConv::ID CC = F->getCallingConv();
1855 
1856         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1857         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1858         SmallVector<SDValue, 4> Parts(NumParts);
1859         getCopyToParts(DAG, getCurSDLoc(),
1860                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1861                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1862 
1863         // 'inreg' on function refers to return value
1864         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1865         if (RetInReg)
1866           Flags.setInReg();
1867 
1868         if (I.getOperand(0)->getType()->isPointerTy()) {
1869           Flags.setPointer();
1870           Flags.setPointerAddrSpace(
1871               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1872         }
1873 
1874         if (NeedsRegBlock) {
1875           Flags.setInConsecutiveRegs();
1876           if (j == NumValues - 1)
1877             Flags.setInConsecutiveRegsLast();
1878         }
1879 
1880         // Propagate extension type if any
1881         if (ExtendKind == ISD::SIGN_EXTEND)
1882           Flags.setSExt();
1883         else if (ExtendKind == ISD::ZERO_EXTEND)
1884           Flags.setZExt();
1885 
1886         for (unsigned i = 0; i < NumParts; ++i) {
1887           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1888                                         VT, /*isfixed=*/true, 0, 0));
1889           OutVals.push_back(Parts[i]);
1890         }
1891       }
1892     }
1893   }
1894 
1895   // Push in swifterror virtual register as the last element of Outs. This makes
1896   // sure swifterror virtual register will be returned in the swifterror
1897   // physical register.
1898   const Function *F = I.getParent()->getParent();
1899   if (TLI.supportSwiftError() &&
1900       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1901     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1902     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1903     Flags.setSwiftError();
1904     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1905                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1906                                   true /*isfixed*/, 1 /*origidx*/,
1907                                   0 /*partOffs*/));
1908     // Create SDNode for the swifterror virtual register.
1909     OutVals.push_back(
1910         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1911                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1912                         EVT(TLI.getPointerTy(DL))));
1913   }
1914 
1915   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1916   CallingConv::ID CallConv =
1917     DAG.getMachineFunction().getFunction().getCallingConv();
1918   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1919       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1920 
1921   // Verify that the target's LowerReturn behaved as expected.
1922   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1923          "LowerReturn didn't return a valid chain!");
1924 
1925   // Update the DAG with the new chain value resulting from return lowering.
1926   DAG.setRoot(Chain);
1927 }
1928 
1929 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1930 /// created for it, emit nodes to copy the value into the virtual
1931 /// registers.
1932 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1933   // Skip empty types
1934   if (V->getType()->isEmptyTy())
1935     return;
1936 
1937   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1938   if (VMI != FuncInfo.ValueMap.end()) {
1939     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1940     CopyValueToVirtualRegister(V, VMI->second);
1941   }
1942 }
1943 
1944 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1945 /// the current basic block, add it to ValueMap now so that we'll get a
1946 /// CopyTo/FromReg.
1947 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1948   // No need to export constants.
1949   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1950 
1951   // Already exported?
1952   if (FuncInfo.isExportedInst(V)) return;
1953 
1954   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1955   CopyValueToVirtualRegister(V, Reg);
1956 }
1957 
1958 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1959                                                      const BasicBlock *FromBB) {
1960   // The operands of the setcc have to be in this block.  We don't know
1961   // how to export them from some other block.
1962   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1963     // Can export from current BB.
1964     if (VI->getParent() == FromBB)
1965       return true;
1966 
1967     // Is already exported, noop.
1968     return FuncInfo.isExportedInst(V);
1969   }
1970 
1971   // If this is an argument, we can export it if the BB is the entry block or
1972   // if it is already exported.
1973   if (isa<Argument>(V)) {
1974     if (FromBB == &FromBB->getParent()->getEntryBlock())
1975       return true;
1976 
1977     // Otherwise, can only export this if it is already exported.
1978     return FuncInfo.isExportedInst(V);
1979   }
1980 
1981   // Otherwise, constants can always be exported.
1982   return true;
1983 }
1984 
1985 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1986 BranchProbability
1987 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1988                                         const MachineBasicBlock *Dst) const {
1989   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1990   const BasicBlock *SrcBB = Src->getBasicBlock();
1991   const BasicBlock *DstBB = Dst->getBasicBlock();
1992   if (!BPI) {
1993     // If BPI is not available, set the default probability as 1 / N, where N is
1994     // the number of successors.
1995     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1996     return BranchProbability(1, SuccSize);
1997   }
1998   return BPI->getEdgeProbability(SrcBB, DstBB);
1999 }
2000 
2001 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2002                                                MachineBasicBlock *Dst,
2003                                                BranchProbability Prob) {
2004   if (!FuncInfo.BPI)
2005     Src->addSuccessorWithoutProb(Dst);
2006   else {
2007     if (Prob.isUnknown())
2008       Prob = getEdgeProbability(Src, Dst);
2009     Src->addSuccessor(Dst, Prob);
2010   }
2011 }
2012 
2013 static bool InBlock(const Value *V, const BasicBlock *BB) {
2014   if (const Instruction *I = dyn_cast<Instruction>(V))
2015     return I->getParent() == BB;
2016   return true;
2017 }
2018 
2019 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2020 /// This function emits a branch and is used at the leaves of an OR or an
2021 /// AND operator tree.
2022 void
2023 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2024                                                   MachineBasicBlock *TBB,
2025                                                   MachineBasicBlock *FBB,
2026                                                   MachineBasicBlock *CurBB,
2027                                                   MachineBasicBlock *SwitchBB,
2028                                                   BranchProbability TProb,
2029                                                   BranchProbability FProb,
2030                                                   bool InvertCond) {
2031   const BasicBlock *BB = CurBB->getBasicBlock();
2032 
2033   // If the leaf of the tree is a comparison, merge the condition into
2034   // the caseblock.
2035   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2036     // The operands of the cmp have to be in this block.  We don't know
2037     // how to export them from some other block.  If this is the first block
2038     // of the sequence, no exporting is needed.
2039     if (CurBB == SwitchBB ||
2040         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2041          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2042       ISD::CondCode Condition;
2043       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2044         ICmpInst::Predicate Pred =
2045             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2046         Condition = getICmpCondCode(Pred);
2047       } else {
2048         const FCmpInst *FC = cast<FCmpInst>(Cond);
2049         FCmpInst::Predicate Pred =
2050             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2051         Condition = getFCmpCondCode(Pred);
2052         if (TM.Options.NoNaNsFPMath)
2053           Condition = getFCmpCodeWithoutNaN(Condition);
2054       }
2055 
2056       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2057                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2058       SL->SwitchCases.push_back(CB);
2059       return;
2060     }
2061   }
2062 
2063   // Create a CaseBlock record representing this branch.
2064   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2065   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2066                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2067   SL->SwitchCases.push_back(CB);
2068 }
2069 
2070 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2071                                                MachineBasicBlock *TBB,
2072                                                MachineBasicBlock *FBB,
2073                                                MachineBasicBlock *CurBB,
2074                                                MachineBasicBlock *SwitchBB,
2075                                                Instruction::BinaryOps Opc,
2076                                                BranchProbability TProb,
2077                                                BranchProbability FProb,
2078                                                bool InvertCond) {
2079   // Skip over not part of the tree and remember to invert op and operands at
2080   // next level.
2081   Value *NotCond;
2082   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2083       InBlock(NotCond, CurBB->getBasicBlock())) {
2084     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2085                          !InvertCond);
2086     return;
2087   }
2088 
2089   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2090   // Compute the effective opcode for Cond, taking into account whether it needs
2091   // to be inverted, e.g.
2092   //   and (not (or A, B)), C
2093   // gets lowered as
2094   //   and (and (not A, not B), C)
2095   unsigned BOpc = 0;
2096   if (BOp) {
2097     BOpc = BOp->getOpcode();
2098     if (InvertCond) {
2099       if (BOpc == Instruction::And)
2100         BOpc = Instruction::Or;
2101       else if (BOpc == Instruction::Or)
2102         BOpc = Instruction::And;
2103     }
2104   }
2105 
2106   // If this node is not part of the or/and tree, emit it as a branch.
2107   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2108       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2109       BOp->getParent() != CurBB->getBasicBlock() ||
2110       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2111       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2112     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2113                                  TProb, FProb, InvertCond);
2114     return;
2115   }
2116 
2117   //  Create TmpBB after CurBB.
2118   MachineFunction::iterator BBI(CurBB);
2119   MachineFunction &MF = DAG.getMachineFunction();
2120   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2121   CurBB->getParent()->insert(++BBI, TmpBB);
2122 
2123   if (Opc == Instruction::Or) {
2124     // Codegen X | Y as:
2125     // BB1:
2126     //   jmp_if_X TBB
2127     //   jmp TmpBB
2128     // TmpBB:
2129     //   jmp_if_Y TBB
2130     //   jmp FBB
2131     //
2132 
2133     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2134     // The requirement is that
2135     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2136     //     = TrueProb for original BB.
2137     // Assuming the original probabilities are A and B, one choice is to set
2138     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2139     // A/(1+B) and 2B/(1+B). This choice assumes that
2140     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2141     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2142     // TmpBB, but the math is more complicated.
2143 
2144     auto NewTrueProb = TProb / 2;
2145     auto NewFalseProb = TProb / 2 + FProb;
2146     // Emit the LHS condition.
2147     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2148                          NewTrueProb, NewFalseProb, InvertCond);
2149 
2150     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2151     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2152     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2153     // Emit the RHS condition into TmpBB.
2154     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2155                          Probs[0], Probs[1], InvertCond);
2156   } else {
2157     assert(Opc == Instruction::And && "Unknown merge op!");
2158     // Codegen X & Y as:
2159     // BB1:
2160     //   jmp_if_X TmpBB
2161     //   jmp FBB
2162     // TmpBB:
2163     //   jmp_if_Y TBB
2164     //   jmp FBB
2165     //
2166     //  This requires creation of TmpBB after CurBB.
2167 
2168     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2169     // The requirement is that
2170     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2171     //     = FalseProb for original BB.
2172     // Assuming the original probabilities are A and B, one choice is to set
2173     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2174     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2175     // TrueProb for BB1 * FalseProb for TmpBB.
2176 
2177     auto NewTrueProb = TProb + FProb / 2;
2178     auto NewFalseProb = FProb / 2;
2179     // Emit the LHS condition.
2180     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2181                          NewTrueProb, NewFalseProb, InvertCond);
2182 
2183     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2184     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2185     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2186     // Emit the RHS condition into TmpBB.
2187     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2188                          Probs[0], Probs[1], InvertCond);
2189   }
2190 }
2191 
2192 /// If the set of cases should be emitted as a series of branches, return true.
2193 /// If we should emit this as a bunch of and/or'd together conditions, return
2194 /// false.
2195 bool
2196 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2197   if (Cases.size() != 2) return true;
2198 
2199   // If this is two comparisons of the same values or'd or and'd together, they
2200   // will get folded into a single comparison, so don't emit two blocks.
2201   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2202        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2203       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2204        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2205     return false;
2206   }
2207 
2208   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2209   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2210   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2211       Cases[0].CC == Cases[1].CC &&
2212       isa<Constant>(Cases[0].CmpRHS) &&
2213       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2214     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2215       return false;
2216     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2217       return false;
2218   }
2219 
2220   return true;
2221 }
2222 
2223 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2224   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2225 
2226   // Update machine-CFG edges.
2227   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2228 
2229   if (I.isUnconditional()) {
2230     // Update machine-CFG edges.
2231     BrMBB->addSuccessor(Succ0MBB);
2232 
2233     // If this is not a fall-through branch or optimizations are switched off,
2234     // emit the branch.
2235     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2236       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2237                               MVT::Other, getControlRoot(),
2238                               DAG.getBasicBlock(Succ0MBB)));
2239 
2240     return;
2241   }
2242 
2243   // If this condition is one of the special cases we handle, do special stuff
2244   // now.
2245   const Value *CondVal = I.getCondition();
2246   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2247 
2248   // If this is a series of conditions that are or'd or and'd together, emit
2249   // this as a sequence of branches instead of setcc's with and/or operations.
2250   // As long as jumps are not expensive, this should improve performance.
2251   // For example, instead of something like:
2252   //     cmp A, B
2253   //     C = seteq
2254   //     cmp D, E
2255   //     F = setle
2256   //     or C, F
2257   //     jnz foo
2258   // Emit:
2259   //     cmp A, B
2260   //     je foo
2261   //     cmp D, E
2262   //     jle foo
2263   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2264     Instruction::BinaryOps Opcode = BOp->getOpcode();
2265     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2266         !I.getMetadata(LLVMContext::MD_unpredictable) &&
2267         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2268       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2269                            Opcode,
2270                            getEdgeProbability(BrMBB, Succ0MBB),
2271                            getEdgeProbability(BrMBB, Succ1MBB),
2272                            /*InvertCond=*/false);
2273       // If the compares in later blocks need to use values not currently
2274       // exported from this block, export them now.  This block should always
2275       // be the first entry.
2276       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2277 
2278       // Allow some cases to be rejected.
2279       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2280         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2281           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2282           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2283         }
2284 
2285         // Emit the branch for this block.
2286         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2287         SL->SwitchCases.erase(SL->SwitchCases.begin());
2288         return;
2289       }
2290 
2291       // Okay, we decided not to do this, remove any inserted MBB's and clear
2292       // SwitchCases.
2293       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2294         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2295 
2296       SL->SwitchCases.clear();
2297     }
2298   }
2299 
2300   // Create a CaseBlock record representing this branch.
2301   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2302                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2303 
2304   // Use visitSwitchCase to actually insert the fast branch sequence for this
2305   // cond branch.
2306   visitSwitchCase(CB, BrMBB);
2307 }
2308 
2309 /// visitSwitchCase - Emits the necessary code to represent a single node in
2310 /// the binary search tree resulting from lowering a switch instruction.
2311 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2312                                           MachineBasicBlock *SwitchBB) {
2313   SDValue Cond;
2314   SDValue CondLHS = getValue(CB.CmpLHS);
2315   SDLoc dl = CB.DL;
2316 
2317   if (CB.CC == ISD::SETTRUE) {
2318     // Branch or fall through to TrueBB.
2319     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2320     SwitchBB->normalizeSuccProbs();
2321     if (CB.TrueBB != NextBlock(SwitchBB)) {
2322       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2323                               DAG.getBasicBlock(CB.TrueBB)));
2324     }
2325     return;
2326   }
2327 
2328   auto &TLI = DAG.getTargetLoweringInfo();
2329   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2330 
2331   // Build the setcc now.
2332   if (!CB.CmpMHS) {
2333     // Fold "(X == true)" to X and "(X == false)" to !X to
2334     // handle common cases produced by branch lowering.
2335     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2336         CB.CC == ISD::SETEQ)
2337       Cond = CondLHS;
2338     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2339              CB.CC == ISD::SETEQ) {
2340       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2341       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2342     } else {
2343       SDValue CondRHS = getValue(CB.CmpRHS);
2344 
2345       // If a pointer's DAG type is larger than its memory type then the DAG
2346       // values are zero-extended. This breaks signed comparisons so truncate
2347       // back to the underlying type before doing the compare.
2348       if (CondLHS.getValueType() != MemVT) {
2349         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2350         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2351       }
2352       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2353     }
2354   } else {
2355     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2356 
2357     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2358     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2359 
2360     SDValue CmpOp = getValue(CB.CmpMHS);
2361     EVT VT = CmpOp.getValueType();
2362 
2363     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2364       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2365                           ISD::SETLE);
2366     } else {
2367       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2368                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2369       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2370                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2371     }
2372   }
2373 
2374   // Update successor info
2375   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2376   // TrueBB and FalseBB are always different unless the incoming IR is
2377   // degenerate. This only happens when running llc on weird IR.
2378   if (CB.TrueBB != CB.FalseBB)
2379     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2380   SwitchBB->normalizeSuccProbs();
2381 
2382   // If the lhs block is the next block, invert the condition so that we can
2383   // fall through to the lhs instead of the rhs block.
2384   if (CB.TrueBB == NextBlock(SwitchBB)) {
2385     std::swap(CB.TrueBB, CB.FalseBB);
2386     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2387     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2388   }
2389 
2390   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2391                                MVT::Other, getControlRoot(), Cond,
2392                                DAG.getBasicBlock(CB.TrueBB));
2393 
2394   // Insert the false branch. Do this even if it's a fall through branch,
2395   // this makes it easier to do DAG optimizations which require inverting
2396   // the branch condition.
2397   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2398                        DAG.getBasicBlock(CB.FalseBB));
2399 
2400   DAG.setRoot(BrCond);
2401 }
2402 
2403 /// visitJumpTable - Emit JumpTable node in the current MBB
2404 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2405   // Emit the code for the jump table
2406   assert(JT.Reg != -1U && "Should lower JT Header first!");
2407   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2408   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2409                                      JT.Reg, PTy);
2410   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2411   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2412                                     MVT::Other, Index.getValue(1),
2413                                     Table, Index);
2414   DAG.setRoot(BrJumpTable);
2415 }
2416 
2417 /// visitJumpTableHeader - This function emits necessary code to produce index
2418 /// in the JumpTable from switch case.
2419 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2420                                                JumpTableHeader &JTH,
2421                                                MachineBasicBlock *SwitchBB) {
2422   SDLoc dl = getCurSDLoc();
2423 
2424   // Subtract the lowest switch case value from the value being switched on.
2425   SDValue SwitchOp = getValue(JTH.SValue);
2426   EVT VT = SwitchOp.getValueType();
2427   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2428                             DAG.getConstant(JTH.First, dl, VT));
2429 
2430   // The SDNode we just created, which holds the value being switched on minus
2431   // the smallest case value, needs to be copied to a virtual register so it
2432   // can be used as an index into the jump table in a subsequent basic block.
2433   // This value may be smaller or larger than the target's pointer type, and
2434   // therefore require extension or truncating.
2435   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2436   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2437 
2438   unsigned JumpTableReg =
2439       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2440   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2441                                     JumpTableReg, SwitchOp);
2442   JT.Reg = JumpTableReg;
2443 
2444   if (!JTH.OmitRangeCheck) {
2445     // Emit the range check for the jump table, and branch to the default block
2446     // for the switch statement if the value being switched on exceeds the
2447     // largest case in the switch.
2448     SDValue CMP = DAG.getSetCC(
2449         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2450                                    Sub.getValueType()),
2451         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2452 
2453     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2454                                  MVT::Other, CopyTo, CMP,
2455                                  DAG.getBasicBlock(JT.Default));
2456 
2457     // Avoid emitting unnecessary branches to the next block.
2458     if (JT.MBB != NextBlock(SwitchBB))
2459       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2460                            DAG.getBasicBlock(JT.MBB));
2461 
2462     DAG.setRoot(BrCond);
2463   } else {
2464     // Avoid emitting unnecessary branches to the next block.
2465     if (JT.MBB != NextBlock(SwitchBB))
2466       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2467                               DAG.getBasicBlock(JT.MBB)));
2468     else
2469       DAG.setRoot(CopyTo);
2470   }
2471 }
2472 
2473 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2474 /// variable if there exists one.
2475 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2476                                  SDValue &Chain) {
2477   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2478   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2479   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2480   MachineFunction &MF = DAG.getMachineFunction();
2481   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2482   MachineSDNode *Node =
2483       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2484   if (Global) {
2485     MachinePointerInfo MPInfo(Global);
2486     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2487                  MachineMemOperand::MODereferenceable;
2488     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2489         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2490     DAG.setNodeMemRefs(Node, {MemRef});
2491   }
2492   if (PtrTy != PtrMemTy)
2493     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2494   return SDValue(Node, 0);
2495 }
2496 
2497 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2498 /// tail spliced into a stack protector check success bb.
2499 ///
2500 /// For a high level explanation of how this fits into the stack protector
2501 /// generation see the comment on the declaration of class
2502 /// StackProtectorDescriptor.
2503 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2504                                                   MachineBasicBlock *ParentBB) {
2505 
2506   // First create the loads to the guard/stack slot for the comparison.
2507   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2508   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2509   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2510 
2511   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2512   int FI = MFI.getStackProtectorIndex();
2513 
2514   SDValue Guard;
2515   SDLoc dl = getCurSDLoc();
2516   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2517   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2518   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2519 
2520   // Generate code to load the content of the guard slot.
2521   SDValue GuardVal = DAG.getLoad(
2522       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2523       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2524       MachineMemOperand::MOVolatile);
2525 
2526   if (TLI.useStackGuardXorFP())
2527     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2528 
2529   // Retrieve guard check function, nullptr if instrumentation is inlined.
2530   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2531     // The target provides a guard check function to validate the guard value.
2532     // Generate a call to that function with the content of the guard slot as
2533     // argument.
2534     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2535     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2536 
2537     TargetLowering::ArgListTy Args;
2538     TargetLowering::ArgListEntry Entry;
2539     Entry.Node = GuardVal;
2540     Entry.Ty = FnTy->getParamType(0);
2541     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2542       Entry.IsInReg = true;
2543     Args.push_back(Entry);
2544 
2545     TargetLowering::CallLoweringInfo CLI(DAG);
2546     CLI.setDebugLoc(getCurSDLoc())
2547         .setChain(DAG.getEntryNode())
2548         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2549                    getValue(GuardCheckFn), std::move(Args));
2550 
2551     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2552     DAG.setRoot(Result.second);
2553     return;
2554   }
2555 
2556   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2557   // Otherwise, emit a volatile load to retrieve the stack guard value.
2558   SDValue Chain = DAG.getEntryNode();
2559   if (TLI.useLoadStackGuardNode()) {
2560     Guard = getLoadStackGuard(DAG, dl, Chain);
2561   } else {
2562     const Value *IRGuard = TLI.getSDagStackGuard(M);
2563     SDValue GuardPtr = getValue(IRGuard);
2564 
2565     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2566                         MachinePointerInfo(IRGuard, 0), Align,
2567                         MachineMemOperand::MOVolatile);
2568   }
2569 
2570   // Perform the comparison via a subtract/getsetcc.
2571   EVT VT = Guard.getValueType();
2572   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2573 
2574   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2575                                                         *DAG.getContext(),
2576                                                         Sub.getValueType()),
2577                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2578 
2579   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2580   // branch to failure MBB.
2581   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2582                                MVT::Other, GuardVal.getOperand(0),
2583                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2584   // Otherwise branch to success MBB.
2585   SDValue Br = DAG.getNode(ISD::BR, dl,
2586                            MVT::Other, BrCond,
2587                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2588 
2589   DAG.setRoot(Br);
2590 }
2591 
2592 /// Codegen the failure basic block for a stack protector check.
2593 ///
2594 /// A failure stack protector machine basic block consists simply of a call to
2595 /// __stack_chk_fail().
2596 ///
2597 /// For a high level explanation of how this fits into the stack protector
2598 /// generation see the comment on the declaration of class
2599 /// StackProtectorDescriptor.
2600 void
2601 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2602   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2603   SDValue Chain =
2604       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2605                       None, false, getCurSDLoc(), false, false).second;
2606   // On PS4, the "return address" must still be within the calling function,
2607   // even if it's at the very end, so emit an explicit TRAP here.
2608   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2609   if (TM.getTargetTriple().isPS4CPU())
2610     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2611 
2612   DAG.setRoot(Chain);
2613 }
2614 
2615 /// visitBitTestHeader - This function emits necessary code to produce value
2616 /// suitable for "bit tests"
2617 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2618                                              MachineBasicBlock *SwitchBB) {
2619   SDLoc dl = getCurSDLoc();
2620 
2621   // Subtract the minimum value
2622   SDValue SwitchOp = getValue(B.SValue);
2623   EVT VT = SwitchOp.getValueType();
2624   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2625                             DAG.getConstant(B.First, dl, VT));
2626 
2627   // Check range
2628   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2629   SDValue RangeCmp = DAG.getSetCC(
2630       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2631                                  Sub.getValueType()),
2632       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2633 
2634   // Determine the type of the test operands.
2635   bool UsePtrType = false;
2636   if (!TLI.isTypeLegal(VT))
2637     UsePtrType = true;
2638   else {
2639     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2640       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2641         // Switch table case range are encoded into series of masks.
2642         // Just use pointer type, it's guaranteed to fit.
2643         UsePtrType = true;
2644         break;
2645       }
2646   }
2647   if (UsePtrType) {
2648     VT = TLI.getPointerTy(DAG.getDataLayout());
2649     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2650   }
2651 
2652   B.RegVT = VT.getSimpleVT();
2653   B.Reg = FuncInfo.CreateReg(B.RegVT);
2654   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2655 
2656   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2657 
2658   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2659   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2660   SwitchBB->normalizeSuccProbs();
2661 
2662   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2663                                 MVT::Other, CopyTo, RangeCmp,
2664                                 DAG.getBasicBlock(B.Default));
2665 
2666   // Avoid emitting unnecessary branches to the next block.
2667   if (MBB != NextBlock(SwitchBB))
2668     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2669                           DAG.getBasicBlock(MBB));
2670 
2671   DAG.setRoot(BrRange);
2672 }
2673 
2674 /// visitBitTestCase - this function produces one "bit test"
2675 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2676                                            MachineBasicBlock* NextMBB,
2677                                            BranchProbability BranchProbToNext,
2678                                            unsigned Reg,
2679                                            BitTestCase &B,
2680                                            MachineBasicBlock *SwitchBB) {
2681   SDLoc dl = getCurSDLoc();
2682   MVT VT = BB.RegVT;
2683   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2684   SDValue Cmp;
2685   unsigned PopCount = countPopulation(B.Mask);
2686   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2687   if (PopCount == 1) {
2688     // Testing for a single bit; just compare the shift count with what it
2689     // would need to be to shift a 1 bit in that position.
2690     Cmp = DAG.getSetCC(
2691         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2692         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2693         ISD::SETEQ);
2694   } else if (PopCount == BB.Range) {
2695     // There is only one zero bit in the range, test for it directly.
2696     Cmp = DAG.getSetCC(
2697         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2698         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2699         ISD::SETNE);
2700   } else {
2701     // Make desired shift
2702     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2703                                     DAG.getConstant(1, dl, VT), ShiftOp);
2704 
2705     // Emit bit tests and jumps
2706     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2707                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2708     Cmp = DAG.getSetCC(
2709         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2710         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2711   }
2712 
2713   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2714   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2715   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2716   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2717   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2718   // one as they are relative probabilities (and thus work more like weights),
2719   // and hence we need to normalize them to let the sum of them become one.
2720   SwitchBB->normalizeSuccProbs();
2721 
2722   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2723                               MVT::Other, getControlRoot(),
2724                               Cmp, DAG.getBasicBlock(B.TargetBB));
2725 
2726   // Avoid emitting unnecessary branches to the next block.
2727   if (NextMBB != NextBlock(SwitchBB))
2728     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2729                         DAG.getBasicBlock(NextMBB));
2730 
2731   DAG.setRoot(BrAnd);
2732 }
2733 
2734 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2735   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2736 
2737   // Retrieve successors. Look through artificial IR level blocks like
2738   // catchswitch for successors.
2739   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2740   const BasicBlock *EHPadBB = I.getSuccessor(1);
2741 
2742   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2743   // have to do anything here to lower funclet bundles.
2744   assert(!I.hasOperandBundlesOtherThan(
2745              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2746          "Cannot lower invokes with arbitrary operand bundles yet!");
2747 
2748   const Value *Callee(I.getCalledValue());
2749   const Function *Fn = dyn_cast<Function>(Callee);
2750   if (isa<InlineAsm>(Callee))
2751     visitInlineAsm(&I);
2752   else if (Fn && Fn->isIntrinsic()) {
2753     switch (Fn->getIntrinsicID()) {
2754     default:
2755       llvm_unreachable("Cannot invoke this intrinsic");
2756     case Intrinsic::donothing:
2757       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2758       break;
2759     case Intrinsic::experimental_patchpoint_void:
2760     case Intrinsic::experimental_patchpoint_i64:
2761       visitPatchpoint(&I, EHPadBB);
2762       break;
2763     case Intrinsic::experimental_gc_statepoint:
2764       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2765       break;
2766     case Intrinsic::wasm_rethrow_in_catch: {
2767       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2768       // special because it can be invoked, so we manually lower it to a DAG
2769       // node here.
2770       SmallVector<SDValue, 8> Ops;
2771       Ops.push_back(getRoot()); // inchain
2772       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2773       Ops.push_back(
2774           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2775                                 TLI.getPointerTy(DAG.getDataLayout())));
2776       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2777       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2778       break;
2779     }
2780     }
2781   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2782     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2783     // Eventually we will support lowering the @llvm.experimental.deoptimize
2784     // intrinsic, and right now there are no plans to support other intrinsics
2785     // with deopt state.
2786     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2787   } else {
2788     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2789   }
2790 
2791   // If the value of the invoke is used outside of its defining block, make it
2792   // available as a virtual register.
2793   // We already took care of the exported value for the statepoint instruction
2794   // during call to the LowerStatepoint.
2795   if (!isStatepoint(I)) {
2796     CopyToExportRegsIfNeeded(&I);
2797   }
2798 
2799   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2800   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2801   BranchProbability EHPadBBProb =
2802       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2803           : BranchProbability::getZero();
2804   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2805 
2806   // Update successor info.
2807   addSuccessorWithProb(InvokeMBB, Return);
2808   for (auto &UnwindDest : UnwindDests) {
2809     UnwindDest.first->setIsEHPad();
2810     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2811   }
2812   InvokeMBB->normalizeSuccProbs();
2813 
2814   // Drop into normal successor.
2815   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2816                           DAG.getBasicBlock(Return)));
2817 }
2818 
2819 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2820   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2821 
2822   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2823   // have to do anything here to lower funclet bundles.
2824   assert(!I.hasOperandBundlesOtherThan(
2825              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2826          "Cannot lower callbrs with arbitrary operand bundles yet!");
2827 
2828   assert(isa<InlineAsm>(I.getCalledValue()) &&
2829          "Only know how to handle inlineasm callbr");
2830   visitInlineAsm(&I);
2831 
2832   // Retrieve successors.
2833   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2834 
2835   // Update successor info.
2836   addSuccessorWithProb(CallBrMBB, Return);
2837   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2838     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2839     addSuccessorWithProb(CallBrMBB, Target);
2840   }
2841   CallBrMBB->normalizeSuccProbs();
2842 
2843   // Drop into default successor.
2844   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2845                           MVT::Other, getControlRoot(),
2846                           DAG.getBasicBlock(Return)));
2847 }
2848 
2849 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2850   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2851 }
2852 
2853 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2854   assert(FuncInfo.MBB->isEHPad() &&
2855          "Call to landingpad not in landing pad!");
2856 
2857   // If there aren't registers to copy the values into (e.g., during SjLj
2858   // exceptions), then don't bother to create these DAG nodes.
2859   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2860   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2861   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2862       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2863     return;
2864 
2865   // If landingpad's return type is token type, we don't create DAG nodes
2866   // for its exception pointer and selector value. The extraction of exception
2867   // pointer or selector value from token type landingpads is not currently
2868   // supported.
2869   if (LP.getType()->isTokenTy())
2870     return;
2871 
2872   SmallVector<EVT, 2> ValueVTs;
2873   SDLoc dl = getCurSDLoc();
2874   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2875   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2876 
2877   // Get the two live-in registers as SDValues. The physregs have already been
2878   // copied into virtual registers.
2879   SDValue Ops[2];
2880   if (FuncInfo.ExceptionPointerVirtReg) {
2881     Ops[0] = DAG.getZExtOrTrunc(
2882         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2883                            FuncInfo.ExceptionPointerVirtReg,
2884                            TLI.getPointerTy(DAG.getDataLayout())),
2885         dl, ValueVTs[0]);
2886   } else {
2887     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2888   }
2889   Ops[1] = DAG.getZExtOrTrunc(
2890       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2891                          FuncInfo.ExceptionSelectorVirtReg,
2892                          TLI.getPointerTy(DAG.getDataLayout())),
2893       dl, ValueVTs[1]);
2894 
2895   // Merge into one.
2896   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2897                             DAG.getVTList(ValueVTs), Ops);
2898   setValue(&LP, Res);
2899 }
2900 
2901 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2902                                            MachineBasicBlock *Last) {
2903   // Update JTCases.
2904   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2905     if (SL->JTCases[i].first.HeaderBB == First)
2906       SL->JTCases[i].first.HeaderBB = Last;
2907 
2908   // Update BitTestCases.
2909   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2910     if (SL->BitTestCases[i].Parent == First)
2911       SL->BitTestCases[i].Parent = Last;
2912 }
2913 
2914 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2915   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2916 
2917   // Update machine-CFG edges with unique successors.
2918   SmallSet<BasicBlock*, 32> Done;
2919   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2920     BasicBlock *BB = I.getSuccessor(i);
2921     bool Inserted = Done.insert(BB).second;
2922     if (!Inserted)
2923         continue;
2924 
2925     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2926     addSuccessorWithProb(IndirectBrMBB, Succ);
2927   }
2928   IndirectBrMBB->normalizeSuccProbs();
2929 
2930   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2931                           MVT::Other, getControlRoot(),
2932                           getValue(I.getAddress())));
2933 }
2934 
2935 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2936   if (!DAG.getTarget().Options.TrapUnreachable)
2937     return;
2938 
2939   // We may be able to ignore unreachable behind a noreturn call.
2940   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2941     const BasicBlock &BB = *I.getParent();
2942     if (&I != &BB.front()) {
2943       BasicBlock::const_iterator PredI =
2944         std::prev(BasicBlock::const_iterator(&I));
2945       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2946         if (Call->doesNotReturn())
2947           return;
2948       }
2949     }
2950   }
2951 
2952   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2953 }
2954 
2955 void SelectionDAGBuilder::visitFSub(const User &I) {
2956   // -0.0 - X --> fneg
2957   Type *Ty = I.getType();
2958   if (isa<Constant>(I.getOperand(0)) &&
2959       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2960     SDValue Op2 = getValue(I.getOperand(1));
2961     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2962                              Op2.getValueType(), Op2));
2963     return;
2964   }
2965 
2966   visitBinary(I, ISD::FSUB);
2967 }
2968 
2969 /// Checks if the given instruction performs a vector reduction, in which case
2970 /// we have the freedom to alter the elements in the result as long as the
2971 /// reduction of them stays unchanged.
2972 static bool isVectorReductionOp(const User *I) {
2973   const Instruction *Inst = dyn_cast<Instruction>(I);
2974   if (!Inst || !Inst->getType()->isVectorTy())
2975     return false;
2976 
2977   auto OpCode = Inst->getOpcode();
2978   switch (OpCode) {
2979   case Instruction::Add:
2980   case Instruction::Mul:
2981   case Instruction::And:
2982   case Instruction::Or:
2983   case Instruction::Xor:
2984     break;
2985   case Instruction::FAdd:
2986   case Instruction::FMul:
2987     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2988       if (FPOp->getFastMathFlags().isFast())
2989         break;
2990     LLVM_FALLTHROUGH;
2991   default:
2992     return false;
2993   }
2994 
2995   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2996   // Ensure the reduction size is a power of 2.
2997   if (!isPowerOf2_32(ElemNum))
2998     return false;
2999 
3000   unsigned ElemNumToReduce = ElemNum;
3001 
3002   // Do DFS search on the def-use chain from the given instruction. We only
3003   // allow four kinds of operations during the search until we reach the
3004   // instruction that extracts the first element from the vector:
3005   //
3006   //   1. The reduction operation of the same opcode as the given instruction.
3007   //
3008   //   2. PHI node.
3009   //
3010   //   3. ShuffleVector instruction together with a reduction operation that
3011   //      does a partial reduction.
3012   //
3013   //   4. ExtractElement that extracts the first element from the vector, and we
3014   //      stop searching the def-use chain here.
3015   //
3016   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3017   // from 1-3 to the stack to continue the DFS. The given instruction is not
3018   // a reduction operation if we meet any other instructions other than those
3019   // listed above.
3020 
3021   SmallVector<const User *, 16> UsersToVisit{Inst};
3022   SmallPtrSet<const User *, 16> Visited;
3023   bool ReduxExtracted = false;
3024 
3025   while (!UsersToVisit.empty()) {
3026     auto User = UsersToVisit.back();
3027     UsersToVisit.pop_back();
3028     if (!Visited.insert(User).second)
3029       continue;
3030 
3031     for (const auto &U : User->users()) {
3032       auto Inst = dyn_cast<Instruction>(U);
3033       if (!Inst)
3034         return false;
3035 
3036       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3037         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3038           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3039             return false;
3040         UsersToVisit.push_back(U);
3041       } else if (const ShuffleVectorInst *ShufInst =
3042                      dyn_cast<ShuffleVectorInst>(U)) {
3043         // Detect the following pattern: A ShuffleVector instruction together
3044         // with a reduction that do partial reduction on the first and second
3045         // ElemNumToReduce / 2 elements, and store the result in
3046         // ElemNumToReduce / 2 elements in another vector.
3047 
3048         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3049         if (ResultElements < ElemNum)
3050           return false;
3051 
3052         if (ElemNumToReduce == 1)
3053           return false;
3054         if (!isa<UndefValue>(U->getOperand(1)))
3055           return false;
3056         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3057           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3058             return false;
3059         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3060           if (ShufInst->getMaskValue(i) != -1)
3061             return false;
3062 
3063         // There is only one user of this ShuffleVector instruction, which
3064         // must be a reduction operation.
3065         if (!U->hasOneUse())
3066           return false;
3067 
3068         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3069         if (!U2 || U2->getOpcode() != OpCode)
3070           return false;
3071 
3072         // Check operands of the reduction operation.
3073         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3074             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3075           UsersToVisit.push_back(U2);
3076           ElemNumToReduce /= 2;
3077         } else
3078           return false;
3079       } else if (isa<ExtractElementInst>(U)) {
3080         // At this moment we should have reduced all elements in the vector.
3081         if (ElemNumToReduce != 1)
3082           return false;
3083 
3084         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3085         if (!Val || !Val->isZero())
3086           return false;
3087 
3088         ReduxExtracted = true;
3089       } else
3090         return false;
3091     }
3092   }
3093   return ReduxExtracted;
3094 }
3095 
3096 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3097   SDNodeFlags Flags;
3098 
3099   SDValue Op = getValue(I.getOperand(0));
3100   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3101                                     Op, Flags);
3102   setValue(&I, UnNodeValue);
3103 }
3104 
3105 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3106   SDNodeFlags Flags;
3107   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3108     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3109     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3110   }
3111   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3112     Flags.setExact(ExactOp->isExact());
3113   }
3114   if (isVectorReductionOp(&I)) {
3115     Flags.setVectorReduction(true);
3116     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3117   }
3118 
3119   SDValue Op1 = getValue(I.getOperand(0));
3120   SDValue Op2 = getValue(I.getOperand(1));
3121   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3122                                      Op1, Op2, Flags);
3123   setValue(&I, BinNodeValue);
3124 }
3125 
3126 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3127   SDValue Op1 = getValue(I.getOperand(0));
3128   SDValue Op2 = getValue(I.getOperand(1));
3129 
3130   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3131       Op1.getValueType(), DAG.getDataLayout());
3132 
3133   // Coerce the shift amount to the right type if we can.
3134   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3135     unsigned ShiftSize = ShiftTy.getSizeInBits();
3136     unsigned Op2Size = Op2.getValueSizeInBits();
3137     SDLoc DL = getCurSDLoc();
3138 
3139     // If the operand is smaller than the shift count type, promote it.
3140     if (ShiftSize > Op2Size)
3141       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3142 
3143     // If the operand is larger than the shift count type but the shift
3144     // count type has enough bits to represent any shift value, truncate
3145     // it now. This is a common case and it exposes the truncate to
3146     // optimization early.
3147     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3148       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3149     // Otherwise we'll need to temporarily settle for some other convenient
3150     // type.  Type legalization will make adjustments once the shiftee is split.
3151     else
3152       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3153   }
3154 
3155   bool nuw = false;
3156   bool nsw = false;
3157   bool exact = false;
3158 
3159   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3160 
3161     if (const OverflowingBinaryOperator *OFBinOp =
3162             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3163       nuw = OFBinOp->hasNoUnsignedWrap();
3164       nsw = OFBinOp->hasNoSignedWrap();
3165     }
3166     if (const PossiblyExactOperator *ExactOp =
3167             dyn_cast<const PossiblyExactOperator>(&I))
3168       exact = ExactOp->isExact();
3169   }
3170   SDNodeFlags Flags;
3171   Flags.setExact(exact);
3172   Flags.setNoSignedWrap(nsw);
3173   Flags.setNoUnsignedWrap(nuw);
3174   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3175                             Flags);
3176   setValue(&I, Res);
3177 }
3178 
3179 void SelectionDAGBuilder::visitSDiv(const User &I) {
3180   SDValue Op1 = getValue(I.getOperand(0));
3181   SDValue Op2 = getValue(I.getOperand(1));
3182 
3183   SDNodeFlags Flags;
3184   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3185                  cast<PossiblyExactOperator>(&I)->isExact());
3186   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3187                            Op2, Flags));
3188 }
3189 
3190 void SelectionDAGBuilder::visitICmp(const User &I) {
3191   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3192   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3193     predicate = IC->getPredicate();
3194   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3195     predicate = ICmpInst::Predicate(IC->getPredicate());
3196   SDValue Op1 = getValue(I.getOperand(0));
3197   SDValue Op2 = getValue(I.getOperand(1));
3198   ISD::CondCode Opcode = getICmpCondCode(predicate);
3199 
3200   auto &TLI = DAG.getTargetLoweringInfo();
3201   EVT MemVT =
3202       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3203 
3204   // If a pointer's DAG type is larger than its memory type then the DAG values
3205   // are zero-extended. This breaks signed comparisons so truncate back to the
3206   // underlying type before doing the compare.
3207   if (Op1.getValueType() != MemVT) {
3208     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3209     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3210   }
3211 
3212   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3213                                                         I.getType());
3214   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3215 }
3216 
3217 void SelectionDAGBuilder::visitFCmp(const User &I) {
3218   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3219   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3220     predicate = FC->getPredicate();
3221   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3222     predicate = FCmpInst::Predicate(FC->getPredicate());
3223   SDValue Op1 = getValue(I.getOperand(0));
3224   SDValue Op2 = getValue(I.getOperand(1));
3225 
3226   ISD::CondCode Condition = getFCmpCondCode(predicate);
3227   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3228   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3229     Condition = getFCmpCodeWithoutNaN(Condition);
3230 
3231   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3232                                                         I.getType());
3233   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3234 }
3235 
3236 // Check if the condition of the select has one use or two users that are both
3237 // selects with the same condition.
3238 static bool hasOnlySelectUsers(const Value *Cond) {
3239   return llvm::all_of(Cond->users(), [](const Value *V) {
3240     return isa<SelectInst>(V);
3241   });
3242 }
3243 
3244 void SelectionDAGBuilder::visitSelect(const User &I) {
3245   SmallVector<EVT, 4> ValueVTs;
3246   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3247                   ValueVTs);
3248   unsigned NumValues = ValueVTs.size();
3249   if (NumValues == 0) return;
3250 
3251   SmallVector<SDValue, 4> Values(NumValues);
3252   SDValue Cond     = getValue(I.getOperand(0));
3253   SDValue LHSVal   = getValue(I.getOperand(1));
3254   SDValue RHSVal   = getValue(I.getOperand(2));
3255   auto BaseOps = {Cond};
3256   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3257     ISD::VSELECT : ISD::SELECT;
3258 
3259   bool IsUnaryAbs = false;
3260 
3261   // Min/max matching is only viable if all output VTs are the same.
3262   if (is_splat(ValueVTs)) {
3263     EVT VT = ValueVTs[0];
3264     LLVMContext &Ctx = *DAG.getContext();
3265     auto &TLI = DAG.getTargetLoweringInfo();
3266 
3267     // We care about the legality of the operation after it has been type
3268     // legalized.
3269     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
3270            VT != TLI.getTypeToTransformTo(Ctx, VT))
3271       VT = TLI.getTypeToTransformTo(Ctx, VT);
3272 
3273     // If the vselect is legal, assume we want to leave this as a vector setcc +
3274     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3275     // min/max is legal on the scalar type.
3276     bool UseScalarMinMax = VT.isVector() &&
3277       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3278 
3279     Value *LHS, *RHS;
3280     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3281     ISD::NodeType Opc = ISD::DELETED_NODE;
3282     switch (SPR.Flavor) {
3283     case SPF_UMAX:    Opc = ISD::UMAX; break;
3284     case SPF_UMIN:    Opc = ISD::UMIN; break;
3285     case SPF_SMAX:    Opc = ISD::SMAX; break;
3286     case SPF_SMIN:    Opc = ISD::SMIN; break;
3287     case SPF_FMINNUM:
3288       switch (SPR.NaNBehavior) {
3289       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3290       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3291       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3292       case SPNB_RETURNS_ANY: {
3293         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3294           Opc = ISD::FMINNUM;
3295         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3296           Opc = ISD::FMINIMUM;
3297         else if (UseScalarMinMax)
3298           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3299             ISD::FMINNUM : ISD::FMINIMUM;
3300         break;
3301       }
3302       }
3303       break;
3304     case SPF_FMAXNUM:
3305       switch (SPR.NaNBehavior) {
3306       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3307       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3308       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3309       case SPNB_RETURNS_ANY:
3310 
3311         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3312           Opc = ISD::FMAXNUM;
3313         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3314           Opc = ISD::FMAXIMUM;
3315         else if (UseScalarMinMax)
3316           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3317             ISD::FMAXNUM : ISD::FMAXIMUM;
3318         break;
3319       }
3320       break;
3321     case SPF_ABS:
3322       IsUnaryAbs = true;
3323       Opc = ISD::ABS;
3324       break;
3325     case SPF_NABS:
3326       // TODO: we need to produce sub(0, abs(X)).
3327     default: break;
3328     }
3329 
3330     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3331         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3332          (UseScalarMinMax &&
3333           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3334         // If the underlying comparison instruction is used by any other
3335         // instruction, the consumed instructions won't be destroyed, so it is
3336         // not profitable to convert to a min/max.
3337         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3338       OpCode = Opc;
3339       LHSVal = getValue(LHS);
3340       RHSVal = getValue(RHS);
3341       BaseOps = {};
3342     }
3343 
3344     if (IsUnaryAbs) {
3345       OpCode = Opc;
3346       LHSVal = getValue(LHS);
3347       BaseOps = {};
3348     }
3349   }
3350 
3351   if (IsUnaryAbs) {
3352     for (unsigned i = 0; i != NumValues; ++i) {
3353       Values[i] =
3354           DAG.getNode(OpCode, getCurSDLoc(),
3355                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3356                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3357     }
3358   } else {
3359     for (unsigned i = 0; i != NumValues; ++i) {
3360       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3361       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3362       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3363       Values[i] = DAG.getNode(
3364           OpCode, getCurSDLoc(),
3365           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3366     }
3367   }
3368 
3369   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3370                            DAG.getVTList(ValueVTs), Values));
3371 }
3372 
3373 void SelectionDAGBuilder::visitTrunc(const User &I) {
3374   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3375   SDValue N = getValue(I.getOperand(0));
3376   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3377                                                         I.getType());
3378   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3379 }
3380 
3381 void SelectionDAGBuilder::visitZExt(const User &I) {
3382   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3383   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3384   SDValue N = getValue(I.getOperand(0));
3385   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3386                                                         I.getType());
3387   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3388 }
3389 
3390 void SelectionDAGBuilder::visitSExt(const User &I) {
3391   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3392   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3393   SDValue N = getValue(I.getOperand(0));
3394   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3395                                                         I.getType());
3396   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3397 }
3398 
3399 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3400   // FPTrunc is never a no-op cast, no need to check
3401   SDValue N = getValue(I.getOperand(0));
3402   SDLoc dl = getCurSDLoc();
3403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3404   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3405   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3406                            DAG.getTargetConstant(
3407                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3408 }
3409 
3410 void SelectionDAGBuilder::visitFPExt(const User &I) {
3411   // FPExt is never a no-op cast, no need to check
3412   SDValue N = getValue(I.getOperand(0));
3413   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3414                                                         I.getType());
3415   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3416 }
3417 
3418 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3419   // FPToUI is never a no-op cast, no need to check
3420   SDValue N = getValue(I.getOperand(0));
3421   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3422                                                         I.getType());
3423   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3424 }
3425 
3426 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3427   // FPToSI is never a no-op cast, no need to check
3428   SDValue N = getValue(I.getOperand(0));
3429   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3430                                                         I.getType());
3431   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3432 }
3433 
3434 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3435   // UIToFP is never a no-op cast, no need to check
3436   SDValue N = getValue(I.getOperand(0));
3437   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3438                                                         I.getType());
3439   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3440 }
3441 
3442 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3443   // SIToFP is never a no-op cast, no need to check
3444   SDValue N = getValue(I.getOperand(0));
3445   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3446                                                         I.getType());
3447   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3448 }
3449 
3450 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3451   // What to do depends on the size of the integer and the size of the pointer.
3452   // We can either truncate, zero extend, or no-op, accordingly.
3453   SDValue N = getValue(I.getOperand(0));
3454   auto &TLI = DAG.getTargetLoweringInfo();
3455   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3456                                                         I.getType());
3457   EVT PtrMemVT =
3458       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3459   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3460   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3461   setValue(&I, N);
3462 }
3463 
3464 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3465   // What to do depends on the size of the integer and the size of the pointer.
3466   // We can either truncate, zero extend, or no-op, accordingly.
3467   SDValue N = getValue(I.getOperand(0));
3468   auto &TLI = DAG.getTargetLoweringInfo();
3469   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3470   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3471   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3472   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3473   setValue(&I, N);
3474 }
3475 
3476 void SelectionDAGBuilder::visitBitCast(const User &I) {
3477   SDValue N = getValue(I.getOperand(0));
3478   SDLoc dl = getCurSDLoc();
3479   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3480                                                         I.getType());
3481 
3482   // BitCast assures us that source and destination are the same size so this is
3483   // either a BITCAST or a no-op.
3484   if (DestVT != N.getValueType())
3485     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3486                              DestVT, N)); // convert types.
3487   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3488   // might fold any kind of constant expression to an integer constant and that
3489   // is not what we are looking for. Only recognize a bitcast of a genuine
3490   // constant integer as an opaque constant.
3491   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3492     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3493                                  /*isOpaque*/true));
3494   else
3495     setValue(&I, N);            // noop cast.
3496 }
3497 
3498 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3499   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3500   const Value *SV = I.getOperand(0);
3501   SDValue N = getValue(SV);
3502   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3503 
3504   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3505   unsigned DestAS = I.getType()->getPointerAddressSpace();
3506 
3507   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3508     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3509 
3510   setValue(&I, N);
3511 }
3512 
3513 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3514   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3515   SDValue InVec = getValue(I.getOperand(0));
3516   SDValue InVal = getValue(I.getOperand(1));
3517   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3518                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3519   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3520                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3521                            InVec, InVal, InIdx));
3522 }
3523 
3524 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3525   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3526   SDValue InVec = getValue(I.getOperand(0));
3527   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3528                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3529   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3530                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3531                            InVec, InIdx));
3532 }
3533 
3534 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3535   SDValue Src1 = getValue(I.getOperand(0));
3536   SDValue Src2 = getValue(I.getOperand(1));
3537   SDLoc DL = getCurSDLoc();
3538 
3539   SmallVector<int, 8> Mask;
3540   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3541   unsigned MaskNumElts = Mask.size();
3542 
3543   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3544   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3545   EVT SrcVT = Src1.getValueType();
3546   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3547 
3548   if (SrcNumElts == MaskNumElts) {
3549     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3550     return;
3551   }
3552 
3553   // Normalize the shuffle vector since mask and vector length don't match.
3554   if (SrcNumElts < MaskNumElts) {
3555     // Mask is longer than the source vectors. We can use concatenate vector to
3556     // make the mask and vectors lengths match.
3557 
3558     if (MaskNumElts % SrcNumElts == 0) {
3559       // Mask length is a multiple of the source vector length.
3560       // Check if the shuffle is some kind of concatenation of the input
3561       // vectors.
3562       unsigned NumConcat = MaskNumElts / SrcNumElts;
3563       bool IsConcat = true;
3564       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3565       for (unsigned i = 0; i != MaskNumElts; ++i) {
3566         int Idx = Mask[i];
3567         if (Idx < 0)
3568           continue;
3569         // Ensure the indices in each SrcVT sized piece are sequential and that
3570         // the same source is used for the whole piece.
3571         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3572             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3573              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3574           IsConcat = false;
3575           break;
3576         }
3577         // Remember which source this index came from.
3578         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3579       }
3580 
3581       // The shuffle is concatenating multiple vectors together. Just emit
3582       // a CONCAT_VECTORS operation.
3583       if (IsConcat) {
3584         SmallVector<SDValue, 8> ConcatOps;
3585         for (auto Src : ConcatSrcs) {
3586           if (Src < 0)
3587             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3588           else if (Src == 0)
3589             ConcatOps.push_back(Src1);
3590           else
3591             ConcatOps.push_back(Src2);
3592         }
3593         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3594         return;
3595       }
3596     }
3597 
3598     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3599     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3600     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3601                                     PaddedMaskNumElts);
3602 
3603     // Pad both vectors with undefs to make them the same length as the mask.
3604     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3605 
3606     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3607     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3608     MOps1[0] = Src1;
3609     MOps2[0] = Src2;
3610 
3611     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3612     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3613 
3614     // Readjust mask for new input vector length.
3615     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3616     for (unsigned i = 0; i != MaskNumElts; ++i) {
3617       int Idx = Mask[i];
3618       if (Idx >= (int)SrcNumElts)
3619         Idx -= SrcNumElts - PaddedMaskNumElts;
3620       MappedOps[i] = Idx;
3621     }
3622 
3623     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3624 
3625     // If the concatenated vector was padded, extract a subvector with the
3626     // correct number of elements.
3627     if (MaskNumElts != PaddedMaskNumElts)
3628       Result = DAG.getNode(
3629           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3630           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3631 
3632     setValue(&I, Result);
3633     return;
3634   }
3635 
3636   if (SrcNumElts > MaskNumElts) {
3637     // Analyze the access pattern of the vector to see if we can extract
3638     // two subvectors and do the shuffle.
3639     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3640     bool CanExtract = true;
3641     for (int Idx : Mask) {
3642       unsigned Input = 0;
3643       if (Idx < 0)
3644         continue;
3645 
3646       if (Idx >= (int)SrcNumElts) {
3647         Input = 1;
3648         Idx -= SrcNumElts;
3649       }
3650 
3651       // If all the indices come from the same MaskNumElts sized portion of
3652       // the sources we can use extract. Also make sure the extract wouldn't
3653       // extract past the end of the source.
3654       int NewStartIdx = alignDown(Idx, MaskNumElts);
3655       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3656           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3657         CanExtract = false;
3658       // Make sure we always update StartIdx as we use it to track if all
3659       // elements are undef.
3660       StartIdx[Input] = NewStartIdx;
3661     }
3662 
3663     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3664       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3665       return;
3666     }
3667     if (CanExtract) {
3668       // Extract appropriate subvector and generate a vector shuffle
3669       for (unsigned Input = 0; Input < 2; ++Input) {
3670         SDValue &Src = Input == 0 ? Src1 : Src2;
3671         if (StartIdx[Input] < 0)
3672           Src = DAG.getUNDEF(VT);
3673         else {
3674           Src = DAG.getNode(
3675               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3676               DAG.getConstant(StartIdx[Input], DL,
3677                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3678         }
3679       }
3680 
3681       // Calculate new mask.
3682       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3683       for (int &Idx : MappedOps) {
3684         if (Idx >= (int)SrcNumElts)
3685           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3686         else if (Idx >= 0)
3687           Idx -= StartIdx[0];
3688       }
3689 
3690       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3691       return;
3692     }
3693   }
3694 
3695   // We can't use either concat vectors or extract subvectors so fall back to
3696   // replacing the shuffle with extract and build vector.
3697   // to insert and build vector.
3698   EVT EltVT = VT.getVectorElementType();
3699   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3700   SmallVector<SDValue,8> Ops;
3701   for (int Idx : Mask) {
3702     SDValue Res;
3703 
3704     if (Idx < 0) {
3705       Res = DAG.getUNDEF(EltVT);
3706     } else {
3707       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3708       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3709 
3710       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3711                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3712     }
3713 
3714     Ops.push_back(Res);
3715   }
3716 
3717   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3718 }
3719 
3720 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3721   ArrayRef<unsigned> Indices;
3722   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3723     Indices = IV->getIndices();
3724   else
3725     Indices = cast<ConstantExpr>(&I)->getIndices();
3726 
3727   const Value *Op0 = I.getOperand(0);
3728   const Value *Op1 = I.getOperand(1);
3729   Type *AggTy = I.getType();
3730   Type *ValTy = Op1->getType();
3731   bool IntoUndef = isa<UndefValue>(Op0);
3732   bool FromUndef = isa<UndefValue>(Op1);
3733 
3734   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3735 
3736   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3737   SmallVector<EVT, 4> AggValueVTs;
3738   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3739   SmallVector<EVT, 4> ValValueVTs;
3740   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3741 
3742   unsigned NumAggValues = AggValueVTs.size();
3743   unsigned NumValValues = ValValueVTs.size();
3744   SmallVector<SDValue, 4> Values(NumAggValues);
3745 
3746   // Ignore an insertvalue that produces an empty object
3747   if (!NumAggValues) {
3748     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3749     return;
3750   }
3751 
3752   SDValue Agg = getValue(Op0);
3753   unsigned i = 0;
3754   // Copy the beginning value(s) from the original aggregate.
3755   for (; i != LinearIndex; ++i)
3756     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3757                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3758   // Copy values from the inserted value(s).
3759   if (NumValValues) {
3760     SDValue Val = getValue(Op1);
3761     for (; i != LinearIndex + NumValValues; ++i)
3762       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3763                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3764   }
3765   // Copy remaining value(s) from the original aggregate.
3766   for (; i != NumAggValues; ++i)
3767     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3768                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3769 
3770   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3771                            DAG.getVTList(AggValueVTs), Values));
3772 }
3773 
3774 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3775   ArrayRef<unsigned> Indices;
3776   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3777     Indices = EV->getIndices();
3778   else
3779     Indices = cast<ConstantExpr>(&I)->getIndices();
3780 
3781   const Value *Op0 = I.getOperand(0);
3782   Type *AggTy = Op0->getType();
3783   Type *ValTy = I.getType();
3784   bool OutOfUndef = isa<UndefValue>(Op0);
3785 
3786   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3787 
3788   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3789   SmallVector<EVT, 4> ValValueVTs;
3790   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3791 
3792   unsigned NumValValues = ValValueVTs.size();
3793 
3794   // Ignore a extractvalue that produces an empty object
3795   if (!NumValValues) {
3796     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3797     return;
3798   }
3799 
3800   SmallVector<SDValue, 4> Values(NumValValues);
3801 
3802   SDValue Agg = getValue(Op0);
3803   // Copy out the selected value(s).
3804   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3805     Values[i - LinearIndex] =
3806       OutOfUndef ?
3807         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3808         SDValue(Agg.getNode(), Agg.getResNo() + i);
3809 
3810   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3811                            DAG.getVTList(ValValueVTs), Values));
3812 }
3813 
3814 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3815   Value *Op0 = I.getOperand(0);
3816   // Note that the pointer operand may be a vector of pointers. Take the scalar
3817   // element which holds a pointer.
3818   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3819   SDValue N = getValue(Op0);
3820   SDLoc dl = getCurSDLoc();
3821   auto &TLI = DAG.getTargetLoweringInfo();
3822   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3823   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3824 
3825   // Normalize Vector GEP - all scalar operands should be converted to the
3826   // splat vector.
3827   unsigned VectorWidth = I.getType()->isVectorTy() ?
3828     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3829 
3830   if (VectorWidth && !N.getValueType().isVector()) {
3831     LLVMContext &Context = *DAG.getContext();
3832     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3833     N = DAG.getSplatBuildVector(VT, dl, N);
3834   }
3835 
3836   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3837        GTI != E; ++GTI) {
3838     const Value *Idx = GTI.getOperand();
3839     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3840       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3841       if (Field) {
3842         // N = N + Offset
3843         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3844 
3845         // In an inbounds GEP with an offset that is nonnegative even when
3846         // interpreted as signed, assume there is no unsigned overflow.
3847         SDNodeFlags Flags;
3848         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3849           Flags.setNoUnsignedWrap(true);
3850 
3851         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3852                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3853       }
3854     } else {
3855       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3856       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3857       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3858 
3859       // If this is a scalar constant or a splat vector of constants,
3860       // handle it quickly.
3861       const auto *CI = dyn_cast<ConstantInt>(Idx);
3862       if (!CI && isa<ConstantDataVector>(Idx) &&
3863           cast<ConstantDataVector>(Idx)->getSplatValue())
3864         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3865 
3866       if (CI) {
3867         if (CI->isZero())
3868           continue;
3869         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3870         LLVMContext &Context = *DAG.getContext();
3871         SDValue OffsVal = VectorWidth ?
3872           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3873           DAG.getConstant(Offs, dl, IdxTy);
3874 
3875         // In an inbouds GEP with an offset that is nonnegative even when
3876         // interpreted as signed, assume there is no unsigned overflow.
3877         SDNodeFlags Flags;
3878         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3879           Flags.setNoUnsignedWrap(true);
3880 
3881         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3882 
3883         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3884         continue;
3885       }
3886 
3887       // N = N + Idx * ElementSize;
3888       SDValue IdxN = getValue(Idx);
3889 
3890       if (!IdxN.getValueType().isVector() && VectorWidth) {
3891         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3892         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3893       }
3894 
3895       // If the index is smaller or larger than intptr_t, truncate or extend
3896       // it.
3897       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3898 
3899       // If this is a multiply by a power of two, turn it into a shl
3900       // immediately.  This is a very common case.
3901       if (ElementSize != 1) {
3902         if (ElementSize.isPowerOf2()) {
3903           unsigned Amt = ElementSize.logBase2();
3904           IdxN = DAG.getNode(ISD::SHL, dl,
3905                              N.getValueType(), IdxN,
3906                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3907         } else {
3908           SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
3909                                           IdxN.getValueType());
3910           IdxN = DAG.getNode(ISD::MUL, dl,
3911                              N.getValueType(), IdxN, Scale);
3912         }
3913       }
3914 
3915       N = DAG.getNode(ISD::ADD, dl,
3916                       N.getValueType(), N, IdxN);
3917     }
3918   }
3919 
3920   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3921     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3922 
3923   setValue(&I, N);
3924 }
3925 
3926 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3927   // If this is a fixed sized alloca in the entry block of the function,
3928   // allocate it statically on the stack.
3929   if (FuncInfo.StaticAllocaMap.count(&I))
3930     return;   // getValue will auto-populate this.
3931 
3932   SDLoc dl = getCurSDLoc();
3933   Type *Ty = I.getAllocatedType();
3934   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3935   auto &DL = DAG.getDataLayout();
3936   uint64_t TySize = DL.getTypeAllocSize(Ty);
3937   unsigned Align =
3938       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3939 
3940   SDValue AllocSize = getValue(I.getArraySize());
3941 
3942   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3943   if (AllocSize.getValueType() != IntPtr)
3944     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3945 
3946   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3947                           AllocSize,
3948                           DAG.getConstant(TySize, dl, IntPtr));
3949 
3950   // Handle alignment.  If the requested alignment is less than or equal to
3951   // the stack alignment, ignore it.  If the size is greater than or equal to
3952   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3953   unsigned StackAlign =
3954       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3955   if (Align <= StackAlign)
3956     Align = 0;
3957 
3958   // Round the size of the allocation up to the stack alignment size
3959   // by add SA-1 to the size. This doesn't overflow because we're computing
3960   // an address inside an alloca.
3961   SDNodeFlags Flags;
3962   Flags.setNoUnsignedWrap(true);
3963   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3964                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3965 
3966   // Mask out the low bits for alignment purposes.
3967   AllocSize =
3968       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3969                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3970 
3971   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3972   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3973   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3974   setValue(&I, DSA);
3975   DAG.setRoot(DSA.getValue(1));
3976 
3977   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3978 }
3979 
3980 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3981   if (I.isAtomic())
3982     return visitAtomicLoad(I);
3983 
3984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3985   const Value *SV = I.getOperand(0);
3986   if (TLI.supportSwiftError()) {
3987     // Swifterror values can come from either a function parameter with
3988     // swifterror attribute or an alloca with swifterror attribute.
3989     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3990       if (Arg->hasSwiftErrorAttr())
3991         return visitLoadFromSwiftError(I);
3992     }
3993 
3994     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3995       if (Alloca->isSwiftError())
3996         return visitLoadFromSwiftError(I);
3997     }
3998   }
3999 
4000   SDValue Ptr = getValue(SV);
4001 
4002   Type *Ty = I.getType();
4003 
4004   bool isVolatile = I.isVolatile();
4005   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
4006   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
4007   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
4008   unsigned Alignment = I.getAlignment();
4009 
4010   AAMDNodes AAInfo;
4011   I.getAAMetadata(AAInfo);
4012   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4013 
4014   SmallVector<EVT, 4> ValueVTs, MemVTs;
4015   SmallVector<uint64_t, 4> Offsets;
4016   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4017   unsigned NumValues = ValueVTs.size();
4018   if (NumValues == 0)
4019     return;
4020 
4021   SDValue Root;
4022   bool ConstantMemory = false;
4023   if (isVolatile || NumValues > MaxParallelChains)
4024     // Serialize volatile loads with other side effects.
4025     Root = getRoot();
4026   else if (AA &&
4027            AA->pointsToConstantMemory(MemoryLocation(
4028                SV,
4029                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4030                AAInfo))) {
4031     // Do not serialize (non-volatile) loads of constant memory with anything.
4032     Root = DAG.getEntryNode();
4033     ConstantMemory = true;
4034   } else {
4035     // Do not serialize non-volatile loads against each other.
4036     Root = DAG.getRoot();
4037   }
4038 
4039   SDLoc dl = getCurSDLoc();
4040 
4041   if (isVolatile)
4042     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4043 
4044   // An aggregate load cannot wrap around the address space, so offsets to its
4045   // parts don't wrap either.
4046   SDNodeFlags Flags;
4047   Flags.setNoUnsignedWrap(true);
4048 
4049   SmallVector<SDValue, 4> Values(NumValues);
4050   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4051   EVT PtrVT = Ptr.getValueType();
4052   unsigned ChainI = 0;
4053   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4054     // Serializing loads here may result in excessive register pressure, and
4055     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4056     // could recover a bit by hoisting nodes upward in the chain by recognizing
4057     // they are side-effect free or do not alias. The optimizer should really
4058     // avoid this case by converting large object/array copies to llvm.memcpy
4059     // (MaxParallelChains should always remain as failsafe).
4060     if (ChainI == MaxParallelChains) {
4061       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4062       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4063                                   makeArrayRef(Chains.data(), ChainI));
4064       Root = Chain;
4065       ChainI = 0;
4066     }
4067     SDValue A = DAG.getNode(ISD::ADD, dl,
4068                             PtrVT, Ptr,
4069                             DAG.getConstant(Offsets[i], dl, PtrVT),
4070                             Flags);
4071     auto MMOFlags = MachineMemOperand::MONone;
4072     if (isVolatile)
4073       MMOFlags |= MachineMemOperand::MOVolatile;
4074     if (isNonTemporal)
4075       MMOFlags |= MachineMemOperand::MONonTemporal;
4076     if (isInvariant)
4077       MMOFlags |= MachineMemOperand::MOInvariant;
4078     if (isDereferenceable)
4079       MMOFlags |= MachineMemOperand::MODereferenceable;
4080     MMOFlags |= TLI.getMMOFlags(I);
4081 
4082     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4083                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4084                             MMOFlags, AAInfo, Ranges);
4085     Chains[ChainI] = L.getValue(1);
4086 
4087     if (MemVTs[i] != ValueVTs[i])
4088       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4089 
4090     Values[i] = L;
4091   }
4092 
4093   if (!ConstantMemory) {
4094     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4095                                 makeArrayRef(Chains.data(), ChainI));
4096     if (isVolatile)
4097       DAG.setRoot(Chain);
4098     else
4099       PendingLoads.push_back(Chain);
4100   }
4101 
4102   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4103                            DAG.getVTList(ValueVTs), Values));
4104 }
4105 
4106 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4107   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4108          "call visitStoreToSwiftError when backend supports swifterror");
4109 
4110   SmallVector<EVT, 4> ValueVTs;
4111   SmallVector<uint64_t, 4> Offsets;
4112   const Value *SrcV = I.getOperand(0);
4113   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4114                   SrcV->getType(), ValueVTs, &Offsets);
4115   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4116          "expect a single EVT for swifterror");
4117 
4118   SDValue Src = getValue(SrcV);
4119   // Create a virtual register, then update the virtual register.
4120   unsigned VReg =
4121       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4122   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4123   // Chain can be getRoot or getControlRoot.
4124   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4125                                       SDValue(Src.getNode(), Src.getResNo()));
4126   DAG.setRoot(CopyNode);
4127 }
4128 
4129 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4130   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4131          "call visitLoadFromSwiftError when backend supports swifterror");
4132 
4133   assert(!I.isVolatile() &&
4134          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
4135          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
4136          "Support volatile, non temporal, invariant for load_from_swift_error");
4137 
4138   const Value *SV = I.getOperand(0);
4139   Type *Ty = I.getType();
4140   AAMDNodes AAInfo;
4141   I.getAAMetadata(AAInfo);
4142   assert(
4143       (!AA ||
4144        !AA->pointsToConstantMemory(MemoryLocation(
4145            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4146            AAInfo))) &&
4147       "load_from_swift_error should not be constant memory");
4148 
4149   SmallVector<EVT, 4> ValueVTs;
4150   SmallVector<uint64_t, 4> Offsets;
4151   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4152                   ValueVTs, &Offsets);
4153   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4154          "expect a single EVT for swifterror");
4155 
4156   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4157   SDValue L = DAG.getCopyFromReg(
4158       getRoot(), getCurSDLoc(),
4159       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4160 
4161   setValue(&I, L);
4162 }
4163 
4164 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4165   if (I.isAtomic())
4166     return visitAtomicStore(I);
4167 
4168   const Value *SrcV = I.getOperand(0);
4169   const Value *PtrV = I.getOperand(1);
4170 
4171   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4172   if (TLI.supportSwiftError()) {
4173     // Swifterror values can come from either a function parameter with
4174     // swifterror attribute or an alloca with swifterror attribute.
4175     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4176       if (Arg->hasSwiftErrorAttr())
4177         return visitStoreToSwiftError(I);
4178     }
4179 
4180     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4181       if (Alloca->isSwiftError())
4182         return visitStoreToSwiftError(I);
4183     }
4184   }
4185 
4186   SmallVector<EVT, 4> ValueVTs, MemVTs;
4187   SmallVector<uint64_t, 4> Offsets;
4188   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4189                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4190   unsigned NumValues = ValueVTs.size();
4191   if (NumValues == 0)
4192     return;
4193 
4194   // Get the lowered operands. Note that we do this after
4195   // checking if NumResults is zero, because with zero results
4196   // the operands won't have values in the map.
4197   SDValue Src = getValue(SrcV);
4198   SDValue Ptr = getValue(PtrV);
4199 
4200   SDValue Root = getRoot();
4201   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4202   SDLoc dl = getCurSDLoc();
4203   EVT PtrVT = Ptr.getValueType();
4204   unsigned Alignment = I.getAlignment();
4205   AAMDNodes AAInfo;
4206   I.getAAMetadata(AAInfo);
4207 
4208   auto MMOFlags = MachineMemOperand::MONone;
4209   if (I.isVolatile())
4210     MMOFlags |= MachineMemOperand::MOVolatile;
4211   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
4212     MMOFlags |= MachineMemOperand::MONonTemporal;
4213   MMOFlags |= TLI.getMMOFlags(I);
4214 
4215   // An aggregate load cannot wrap around the address space, so offsets to its
4216   // parts don't wrap either.
4217   SDNodeFlags Flags;
4218   Flags.setNoUnsignedWrap(true);
4219 
4220   unsigned ChainI = 0;
4221   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4222     // See visitLoad comments.
4223     if (ChainI == MaxParallelChains) {
4224       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4225                                   makeArrayRef(Chains.data(), ChainI));
4226       Root = Chain;
4227       ChainI = 0;
4228     }
4229     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
4230                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
4231     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4232     if (MemVTs[i] != ValueVTs[i])
4233       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4234     SDValue St =
4235         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4236                      Alignment, MMOFlags, AAInfo);
4237     Chains[ChainI] = St;
4238   }
4239 
4240   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4241                                   makeArrayRef(Chains.data(), ChainI));
4242   DAG.setRoot(StoreNode);
4243 }
4244 
4245 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4246                                            bool IsCompressing) {
4247   SDLoc sdl = getCurSDLoc();
4248 
4249   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4250                            unsigned& Alignment) {
4251     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4252     Src0 = I.getArgOperand(0);
4253     Ptr = I.getArgOperand(1);
4254     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4255     Mask = I.getArgOperand(3);
4256   };
4257   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4258                            unsigned& Alignment) {
4259     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4260     Src0 = I.getArgOperand(0);
4261     Ptr = I.getArgOperand(1);
4262     Mask = I.getArgOperand(2);
4263     Alignment = 0;
4264   };
4265 
4266   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4267   unsigned Alignment;
4268   if (IsCompressing)
4269     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4270   else
4271     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4272 
4273   SDValue Ptr = getValue(PtrOperand);
4274   SDValue Src0 = getValue(Src0Operand);
4275   SDValue Mask = getValue(MaskOperand);
4276 
4277   EVT VT = Src0.getValueType();
4278   if (!Alignment)
4279     Alignment = DAG.getEVTAlignment(VT);
4280 
4281   AAMDNodes AAInfo;
4282   I.getAAMetadata(AAInfo);
4283 
4284   MachineMemOperand *MMO =
4285     DAG.getMachineFunction().
4286     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4287                           MachineMemOperand::MOStore,  VT.getStoreSize(),
4288                           Alignment, AAInfo);
4289   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
4290                                          MMO, false /* Truncating */,
4291                                          IsCompressing);
4292   DAG.setRoot(StoreNode);
4293   setValue(&I, StoreNode);
4294 }
4295 
4296 // Get a uniform base for the Gather/Scatter intrinsic.
4297 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4298 // We try to represent it as a base pointer + vector of indices.
4299 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4300 // The first operand of the GEP may be a single pointer or a vector of pointers
4301 // Example:
4302 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4303 //  or
4304 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4305 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4306 //
4307 // When the first GEP operand is a single pointer - it is the uniform base we
4308 // are looking for. If first operand of the GEP is a splat vector - we
4309 // extract the splat value and use it as a uniform base.
4310 // In all other cases the function returns 'false'.
4311 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
4312                            SDValue &Scale, SelectionDAGBuilder* SDB) {
4313   SelectionDAG& DAG = SDB->DAG;
4314   LLVMContext &Context = *DAG.getContext();
4315 
4316   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4317   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4318   if (!GEP)
4319     return false;
4320 
4321   const Value *GEPPtr = GEP->getPointerOperand();
4322   if (!GEPPtr->getType()->isVectorTy())
4323     Ptr = GEPPtr;
4324   else if (!(Ptr = getSplatValue(GEPPtr)))
4325     return false;
4326 
4327   unsigned FinalIndex = GEP->getNumOperands() - 1;
4328   Value *IndexVal = GEP->getOperand(FinalIndex);
4329 
4330   // Ensure all the other indices are 0.
4331   for (unsigned i = 1; i < FinalIndex; ++i) {
4332     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
4333     if (!C || !C->isZero())
4334       return false;
4335   }
4336 
4337   // The operands of the GEP may be defined in another basic block.
4338   // In this case we'll not find nodes for the operands.
4339   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
4340     return false;
4341 
4342   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4343   const DataLayout &DL = DAG.getDataLayout();
4344   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4345                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4346   Base = SDB->getValue(Ptr);
4347   Index = SDB->getValue(IndexVal);
4348 
4349   if (!Index.getValueType().isVector()) {
4350     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4351     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4352     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4353   }
4354   return true;
4355 }
4356 
4357 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4358   SDLoc sdl = getCurSDLoc();
4359 
4360   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4361   const Value *Ptr = I.getArgOperand(1);
4362   SDValue Src0 = getValue(I.getArgOperand(0));
4363   SDValue Mask = getValue(I.getArgOperand(3));
4364   EVT VT = Src0.getValueType();
4365   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4366   if (!Alignment)
4367     Alignment = DAG.getEVTAlignment(VT);
4368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4369 
4370   AAMDNodes AAInfo;
4371   I.getAAMetadata(AAInfo);
4372 
4373   SDValue Base;
4374   SDValue Index;
4375   SDValue Scale;
4376   const Value *BasePtr = Ptr;
4377   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4378 
4379   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4380   MachineMemOperand *MMO = DAG.getMachineFunction().
4381     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4382                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4383                          Alignment, AAInfo);
4384   if (!UniformBase) {
4385     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4386     Index = getValue(Ptr);
4387     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4388   }
4389   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4390   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4391                                          Ops, MMO);
4392   DAG.setRoot(Scatter);
4393   setValue(&I, Scatter);
4394 }
4395 
4396 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4397   SDLoc sdl = getCurSDLoc();
4398 
4399   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4400                            unsigned& Alignment) {
4401     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4402     Ptr = I.getArgOperand(0);
4403     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4404     Mask = I.getArgOperand(2);
4405     Src0 = I.getArgOperand(3);
4406   };
4407   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4408                            unsigned& Alignment) {
4409     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4410     Ptr = I.getArgOperand(0);
4411     Alignment = 0;
4412     Mask = I.getArgOperand(1);
4413     Src0 = I.getArgOperand(2);
4414   };
4415 
4416   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4417   unsigned Alignment;
4418   if (IsExpanding)
4419     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4420   else
4421     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4422 
4423   SDValue Ptr = getValue(PtrOperand);
4424   SDValue Src0 = getValue(Src0Operand);
4425   SDValue Mask = getValue(MaskOperand);
4426 
4427   EVT VT = Src0.getValueType();
4428   if (!Alignment)
4429     Alignment = DAG.getEVTAlignment(VT);
4430 
4431   AAMDNodes AAInfo;
4432   I.getAAMetadata(AAInfo);
4433   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4434 
4435   // Do not serialize masked loads of constant memory with anything.
4436   bool AddToChain =
4437       !AA || !AA->pointsToConstantMemory(MemoryLocation(
4438                  PtrOperand,
4439                  LocationSize::precise(
4440                      DAG.getDataLayout().getTypeStoreSize(I.getType())),
4441                  AAInfo));
4442   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4443 
4444   MachineMemOperand *MMO =
4445     DAG.getMachineFunction().
4446     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4447                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4448                           Alignment, AAInfo, Ranges);
4449 
4450   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4451                                    ISD::NON_EXTLOAD, IsExpanding);
4452   if (AddToChain)
4453     PendingLoads.push_back(Load.getValue(1));
4454   setValue(&I, Load);
4455 }
4456 
4457 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4458   SDLoc sdl = getCurSDLoc();
4459 
4460   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4461   const Value *Ptr = I.getArgOperand(0);
4462   SDValue Src0 = getValue(I.getArgOperand(3));
4463   SDValue Mask = getValue(I.getArgOperand(2));
4464 
4465   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4466   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4467   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4468   if (!Alignment)
4469     Alignment = DAG.getEVTAlignment(VT);
4470 
4471   AAMDNodes AAInfo;
4472   I.getAAMetadata(AAInfo);
4473   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4474 
4475   SDValue Root = DAG.getRoot();
4476   SDValue Base;
4477   SDValue Index;
4478   SDValue Scale;
4479   const Value *BasePtr = Ptr;
4480   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4481   bool ConstantMemory = false;
4482   if (UniformBase && AA &&
4483       AA->pointsToConstantMemory(
4484           MemoryLocation(BasePtr,
4485                          LocationSize::precise(
4486                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4487                          AAInfo))) {
4488     // Do not serialize (non-volatile) loads of constant memory with anything.
4489     Root = DAG.getEntryNode();
4490     ConstantMemory = true;
4491   }
4492 
4493   MachineMemOperand *MMO =
4494     DAG.getMachineFunction().
4495     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4496                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4497                          Alignment, AAInfo, Ranges);
4498 
4499   if (!UniformBase) {
4500     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4501     Index = getValue(Ptr);
4502     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4503   }
4504   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4505   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4506                                        Ops, MMO);
4507 
4508   SDValue OutChain = Gather.getValue(1);
4509   if (!ConstantMemory)
4510     PendingLoads.push_back(OutChain);
4511   setValue(&I, Gather);
4512 }
4513 
4514 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4515   SDLoc dl = getCurSDLoc();
4516   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4517   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4518   SyncScope::ID SSID = I.getSyncScopeID();
4519 
4520   SDValue InChain = getRoot();
4521 
4522   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4523   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4524 
4525   auto Alignment = DAG.getEVTAlignment(MemVT);
4526 
4527   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4528   if (I.isVolatile())
4529     Flags |= MachineMemOperand::MOVolatile;
4530   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4531 
4532   MachineFunction &MF = DAG.getMachineFunction();
4533   MachineMemOperand *MMO =
4534     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4535                             Flags, MemVT.getStoreSize(), Alignment,
4536                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4537                             FailureOrdering);
4538 
4539   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4540                                    dl, MemVT, VTs, InChain,
4541                                    getValue(I.getPointerOperand()),
4542                                    getValue(I.getCompareOperand()),
4543                                    getValue(I.getNewValOperand()), MMO);
4544 
4545   SDValue OutChain = L.getValue(2);
4546 
4547   setValue(&I, L);
4548   DAG.setRoot(OutChain);
4549 }
4550 
4551 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4552   SDLoc dl = getCurSDLoc();
4553   ISD::NodeType NT;
4554   switch (I.getOperation()) {
4555   default: llvm_unreachable("Unknown atomicrmw operation");
4556   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4557   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4558   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4559   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4560   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4561   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4562   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4563   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4564   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4565   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4566   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4567   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4568   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4569   }
4570   AtomicOrdering Ordering = I.getOrdering();
4571   SyncScope::ID SSID = I.getSyncScopeID();
4572 
4573   SDValue InChain = getRoot();
4574 
4575   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4576   auto Alignment = DAG.getEVTAlignment(MemVT);
4577 
4578   auto Flags = MachineMemOperand::MOLoad |  MachineMemOperand::MOStore;
4579   if (I.isVolatile())
4580     Flags |= MachineMemOperand::MOVolatile;
4581   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4582 
4583   MachineFunction &MF = DAG.getMachineFunction();
4584   MachineMemOperand *MMO =
4585     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4586                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4587                             nullptr, SSID, Ordering);
4588 
4589   SDValue L =
4590     DAG.getAtomic(NT, dl, MemVT, InChain,
4591                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4592                   MMO);
4593 
4594   SDValue OutChain = L.getValue(1);
4595 
4596   setValue(&I, L);
4597   DAG.setRoot(OutChain);
4598 }
4599 
4600 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4601   SDLoc dl = getCurSDLoc();
4602   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4603   SDValue Ops[3];
4604   Ops[0] = getRoot();
4605   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4606                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4607   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4608                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4609   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4610 }
4611 
4612 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4613   SDLoc dl = getCurSDLoc();
4614   AtomicOrdering Order = I.getOrdering();
4615   SyncScope::ID SSID = I.getSyncScopeID();
4616 
4617   SDValue InChain = getRoot();
4618 
4619   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4620   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4621   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4622 
4623   if (!TLI.supportsUnalignedAtomics() &&
4624       I.getAlignment() < MemVT.getSizeInBits() / 8)
4625     report_fatal_error("Cannot generate unaligned atomic load");
4626 
4627   auto Flags = MachineMemOperand::MOLoad;
4628   if (I.isVolatile())
4629     Flags |= MachineMemOperand::MOVolatile;
4630   if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr)
4631     Flags |= MachineMemOperand::MOInvariant;
4632   if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout()))
4633     Flags |= MachineMemOperand::MODereferenceable;
4634 
4635   Flags |= TLI.getMMOFlags(I);
4636 
4637   MachineMemOperand *MMO =
4638       DAG.getMachineFunction().
4639       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4640                            Flags, MemVT.getStoreSize(),
4641                            I.getAlignment() ? I.getAlignment() :
4642                                               DAG.getEVTAlignment(MemVT),
4643                            AAMDNodes(), nullptr, SSID, Order);
4644 
4645   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4646   SDValue L =
4647       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4648                     getValue(I.getPointerOperand()), MMO);
4649 
4650   SDValue OutChain = L.getValue(1);
4651   if (MemVT != VT)
4652     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4653 
4654   setValue(&I, L);
4655   DAG.setRoot(OutChain);
4656 }
4657 
4658 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4659   SDLoc dl = getCurSDLoc();
4660 
4661   AtomicOrdering Ordering = I.getOrdering();
4662   SyncScope::ID SSID = I.getSyncScopeID();
4663 
4664   SDValue InChain = getRoot();
4665 
4666   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4667   EVT MemVT =
4668       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4669 
4670   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4671     report_fatal_error("Cannot generate unaligned atomic store");
4672 
4673   auto Flags = MachineMemOperand::MOStore;
4674   if (I.isVolatile())
4675     Flags |= MachineMemOperand::MOVolatile;
4676   Flags |= TLI.getMMOFlags(I);
4677 
4678   MachineFunction &MF = DAG.getMachineFunction();
4679   MachineMemOperand *MMO =
4680     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4681                             MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4682                             nullptr, SSID, Ordering);
4683 
4684   SDValue Val = getValue(I.getValueOperand());
4685   if (Val.getValueType() != MemVT)
4686     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4687 
4688   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4689                                    getValue(I.getPointerOperand()), Val, MMO);
4690 
4691 
4692   DAG.setRoot(OutChain);
4693 }
4694 
4695 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4696 /// node.
4697 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4698                                                unsigned Intrinsic) {
4699   // Ignore the callsite's attributes. A specific call site may be marked with
4700   // readnone, but the lowering code will expect the chain based on the
4701   // definition.
4702   const Function *F = I.getCalledFunction();
4703   bool HasChain = !F->doesNotAccessMemory();
4704   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4705 
4706   // Build the operand list.
4707   SmallVector<SDValue, 8> Ops;
4708   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4709     if (OnlyLoad) {
4710       // We don't need to serialize loads against other loads.
4711       Ops.push_back(DAG.getRoot());
4712     } else {
4713       Ops.push_back(getRoot());
4714     }
4715   }
4716 
4717   // Info is set by getTgtMemInstrinsic
4718   TargetLowering::IntrinsicInfo Info;
4719   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4720   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4721                                                DAG.getMachineFunction(),
4722                                                Intrinsic);
4723 
4724   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4725   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4726       Info.opc == ISD::INTRINSIC_W_CHAIN)
4727     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4728                                         TLI.getPointerTy(DAG.getDataLayout())));
4729 
4730   // Add all operands of the call to the operand list.
4731   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4732     SDValue Op = getValue(I.getArgOperand(i));
4733     Ops.push_back(Op);
4734   }
4735 
4736   SmallVector<EVT, 4> ValueVTs;
4737   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4738 
4739   if (HasChain)
4740     ValueVTs.push_back(MVT::Other);
4741 
4742   SDVTList VTs = DAG.getVTList(ValueVTs);
4743 
4744   // Create the node.
4745   SDValue Result;
4746   if (IsTgtIntrinsic) {
4747     // This is target intrinsic that touches memory
4748     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4749       Ops, Info.memVT,
4750       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4751       Info.flags, Info.size);
4752   } else if (!HasChain) {
4753     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4754   } else if (!I.getType()->isVoidTy()) {
4755     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4756   } else {
4757     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4758   }
4759 
4760   if (HasChain) {
4761     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4762     if (OnlyLoad)
4763       PendingLoads.push_back(Chain);
4764     else
4765       DAG.setRoot(Chain);
4766   }
4767 
4768   if (!I.getType()->isVoidTy()) {
4769     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4770       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4771       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4772     } else
4773       Result = lowerRangeToAssertZExt(DAG, I, Result);
4774 
4775     setValue(&I, Result);
4776   }
4777 }
4778 
4779 /// GetSignificand - Get the significand and build it into a floating-point
4780 /// number with exponent of 1:
4781 ///
4782 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4783 ///
4784 /// where Op is the hexadecimal representation of floating point value.
4785 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4786   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4787                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4788   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4789                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4790   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4791 }
4792 
4793 /// GetExponent - Get the exponent:
4794 ///
4795 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4796 ///
4797 /// where Op is the hexadecimal representation of floating point value.
4798 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4799                            const TargetLowering &TLI, const SDLoc &dl) {
4800   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4801                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4802   SDValue t1 = DAG.getNode(
4803       ISD::SRL, dl, MVT::i32, t0,
4804       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4805   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4806                            DAG.getConstant(127, dl, MVT::i32));
4807   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4808 }
4809 
4810 /// getF32Constant - Get 32-bit floating point constant.
4811 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4812                               const SDLoc &dl) {
4813   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4814                            MVT::f32);
4815 }
4816 
4817 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4818                                        SelectionDAG &DAG) {
4819   // TODO: What fast-math-flags should be set on the floating-point nodes?
4820 
4821   //   IntegerPartOfX = ((int32_t)(t0);
4822   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4823 
4824   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4825   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4826   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4827 
4828   //   IntegerPartOfX <<= 23;
4829   IntegerPartOfX = DAG.getNode(
4830       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4831       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4832                                   DAG.getDataLayout())));
4833 
4834   SDValue TwoToFractionalPartOfX;
4835   if (LimitFloatPrecision <= 6) {
4836     // For floating-point precision of 6:
4837     //
4838     //   TwoToFractionalPartOfX =
4839     //     0.997535578f +
4840     //       (0.735607626f + 0.252464424f * x) * x;
4841     //
4842     // error 0.0144103317, which is 6 bits
4843     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4844                              getF32Constant(DAG, 0x3e814304, dl));
4845     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4846                              getF32Constant(DAG, 0x3f3c50c8, dl));
4847     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4848     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4849                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4850   } else if (LimitFloatPrecision <= 12) {
4851     // For floating-point precision of 12:
4852     //
4853     //   TwoToFractionalPartOfX =
4854     //     0.999892986f +
4855     //       (0.696457318f +
4856     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4857     //
4858     // error 0.000107046256, which is 13 to 14 bits
4859     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4860                              getF32Constant(DAG, 0x3da235e3, dl));
4861     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4862                              getF32Constant(DAG, 0x3e65b8f3, dl));
4863     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4864     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4865                              getF32Constant(DAG, 0x3f324b07, dl));
4866     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4867     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4868                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4869   } else { // LimitFloatPrecision <= 18
4870     // For floating-point precision of 18:
4871     //
4872     //   TwoToFractionalPartOfX =
4873     //     0.999999982f +
4874     //       (0.693148872f +
4875     //         (0.240227044f +
4876     //           (0.554906021e-1f +
4877     //             (0.961591928e-2f +
4878     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4879     // error 2.47208000*10^(-7), which is better than 18 bits
4880     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4881                              getF32Constant(DAG, 0x3924b03e, dl));
4882     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4883                              getF32Constant(DAG, 0x3ab24b87, dl));
4884     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4885     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4886                              getF32Constant(DAG, 0x3c1d8c17, dl));
4887     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4888     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4889                              getF32Constant(DAG, 0x3d634a1d, dl));
4890     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4891     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4892                              getF32Constant(DAG, 0x3e75fe14, dl));
4893     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4894     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4895                               getF32Constant(DAG, 0x3f317234, dl));
4896     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4897     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4898                                          getF32Constant(DAG, 0x3f800000, dl));
4899   }
4900 
4901   // Add the exponent into the result in integer domain.
4902   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4903   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4904                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4905 }
4906 
4907 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4908 /// limited-precision mode.
4909 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4910                          const TargetLowering &TLI) {
4911   if (Op.getValueType() == MVT::f32 &&
4912       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4913 
4914     // Put the exponent in the right bit position for later addition to the
4915     // final result:
4916     //
4917     //   #define LOG2OFe 1.4426950f
4918     //   t0 = Op * LOG2OFe
4919 
4920     // TODO: What fast-math-flags should be set here?
4921     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4922                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4923     return getLimitedPrecisionExp2(t0, dl, DAG);
4924   }
4925 
4926   // No special expansion.
4927   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4928 }
4929 
4930 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4931 /// limited-precision mode.
4932 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4933                          const TargetLowering &TLI) {
4934   // TODO: What fast-math-flags should be set on the floating-point nodes?
4935 
4936   if (Op.getValueType() == MVT::f32 &&
4937       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4938     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4939 
4940     // Scale the exponent by log(2) [0.69314718f].
4941     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4942     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4943                                         getF32Constant(DAG, 0x3f317218, dl));
4944 
4945     // Get the significand and build it into a floating-point number with
4946     // exponent of 1.
4947     SDValue X = GetSignificand(DAG, Op1, dl);
4948 
4949     SDValue LogOfMantissa;
4950     if (LimitFloatPrecision <= 6) {
4951       // For floating-point precision of 6:
4952       //
4953       //   LogofMantissa =
4954       //     -1.1609546f +
4955       //       (1.4034025f - 0.23903021f * x) * x;
4956       //
4957       // error 0.0034276066, which is better than 8 bits
4958       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4959                                getF32Constant(DAG, 0xbe74c456, dl));
4960       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4961                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4962       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4963       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4964                                   getF32Constant(DAG, 0x3f949a29, dl));
4965     } else if (LimitFloatPrecision <= 12) {
4966       // For floating-point precision of 12:
4967       //
4968       //   LogOfMantissa =
4969       //     -1.7417939f +
4970       //       (2.8212026f +
4971       //         (-1.4699568f +
4972       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4973       //
4974       // error 0.000061011436, which is 14 bits
4975       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4976                                getF32Constant(DAG, 0xbd67b6d6, dl));
4977       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4978                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4979       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4980       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4981                                getF32Constant(DAG, 0x3fbc278b, dl));
4982       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4983       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4984                                getF32Constant(DAG, 0x40348e95, dl));
4985       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4986       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4987                                   getF32Constant(DAG, 0x3fdef31a, dl));
4988     } else { // LimitFloatPrecision <= 18
4989       // For floating-point precision of 18:
4990       //
4991       //   LogOfMantissa =
4992       //     -2.1072184f +
4993       //       (4.2372794f +
4994       //         (-3.7029485f +
4995       //           (2.2781945f +
4996       //             (-0.87823314f +
4997       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4998       //
4999       // error 0.0000023660568, which is better than 18 bits
5000       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5001                                getF32Constant(DAG, 0xbc91e5ac, dl));
5002       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5003                                getF32Constant(DAG, 0x3e4350aa, dl));
5004       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5005       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5006                                getF32Constant(DAG, 0x3f60d3e3, dl));
5007       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5008       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5009                                getF32Constant(DAG, 0x4011cdf0, dl));
5010       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5011       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5012                                getF32Constant(DAG, 0x406cfd1c, dl));
5013       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5014       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5015                                getF32Constant(DAG, 0x408797cb, dl));
5016       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5017       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5018                                   getF32Constant(DAG, 0x4006dcab, dl));
5019     }
5020 
5021     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5022   }
5023 
5024   // No special expansion.
5025   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5026 }
5027 
5028 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5029 /// limited-precision mode.
5030 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5031                           const TargetLowering &TLI) {
5032   // TODO: What fast-math-flags should be set on the floating-point nodes?
5033 
5034   if (Op.getValueType() == MVT::f32 &&
5035       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5036     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5037 
5038     // Get the exponent.
5039     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5040 
5041     // Get the significand and build it into a floating-point number with
5042     // exponent of 1.
5043     SDValue X = GetSignificand(DAG, Op1, dl);
5044 
5045     // Different possible minimax approximations of significand in
5046     // floating-point for various degrees of accuracy over [1,2].
5047     SDValue Log2ofMantissa;
5048     if (LimitFloatPrecision <= 6) {
5049       // For floating-point precision of 6:
5050       //
5051       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5052       //
5053       // error 0.0049451742, which is more than 7 bits
5054       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5055                                getF32Constant(DAG, 0xbeb08fe0, dl));
5056       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5057                                getF32Constant(DAG, 0x40019463, dl));
5058       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5059       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5060                                    getF32Constant(DAG, 0x3fd6633d, dl));
5061     } else if (LimitFloatPrecision <= 12) {
5062       // For floating-point precision of 12:
5063       //
5064       //   Log2ofMantissa =
5065       //     -2.51285454f +
5066       //       (4.07009056f +
5067       //         (-2.12067489f +
5068       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5069       //
5070       // error 0.0000876136000, which is better than 13 bits
5071       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5072                                getF32Constant(DAG, 0xbda7262e, dl));
5073       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5074                                getF32Constant(DAG, 0x3f25280b, dl));
5075       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5076       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5077                                getF32Constant(DAG, 0x4007b923, dl));
5078       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5079       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5080                                getF32Constant(DAG, 0x40823e2f, dl));
5081       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5082       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5083                                    getF32Constant(DAG, 0x4020d29c, dl));
5084     } else { // LimitFloatPrecision <= 18
5085       // For floating-point precision of 18:
5086       //
5087       //   Log2ofMantissa =
5088       //     -3.0400495f +
5089       //       (6.1129976f +
5090       //         (-5.3420409f +
5091       //           (3.2865683f +
5092       //             (-1.2669343f +
5093       //               (0.27515199f -
5094       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5095       //
5096       // error 0.0000018516, which is better than 18 bits
5097       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5098                                getF32Constant(DAG, 0xbcd2769e, dl));
5099       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5100                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5101       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5102       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5103                                getF32Constant(DAG, 0x3fa22ae7, dl));
5104       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5105       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5106                                getF32Constant(DAG, 0x40525723, dl));
5107       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5108       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5109                                getF32Constant(DAG, 0x40aaf200, dl));
5110       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5111       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5112                                getF32Constant(DAG, 0x40c39dad, dl));
5113       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5114       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5115                                    getF32Constant(DAG, 0x4042902c, dl));
5116     }
5117 
5118     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5119   }
5120 
5121   // No special expansion.
5122   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5123 }
5124 
5125 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5126 /// limited-precision mode.
5127 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5128                            const TargetLowering &TLI) {
5129   // TODO: What fast-math-flags should be set on the floating-point nodes?
5130 
5131   if (Op.getValueType() == MVT::f32 &&
5132       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5133     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5134 
5135     // Scale the exponent by log10(2) [0.30102999f].
5136     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5137     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5138                                         getF32Constant(DAG, 0x3e9a209a, dl));
5139 
5140     // Get the significand and build it into a floating-point number with
5141     // exponent of 1.
5142     SDValue X = GetSignificand(DAG, Op1, dl);
5143 
5144     SDValue Log10ofMantissa;
5145     if (LimitFloatPrecision <= 6) {
5146       // For floating-point precision of 6:
5147       //
5148       //   Log10ofMantissa =
5149       //     -0.50419619f +
5150       //       (0.60948995f - 0.10380950f * x) * x;
5151       //
5152       // error 0.0014886165, which is 6 bits
5153       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5154                                getF32Constant(DAG, 0xbdd49a13, dl));
5155       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5156                                getF32Constant(DAG, 0x3f1c0789, dl));
5157       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5158       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5159                                     getF32Constant(DAG, 0x3f011300, dl));
5160     } else if (LimitFloatPrecision <= 12) {
5161       // For floating-point precision of 12:
5162       //
5163       //   Log10ofMantissa =
5164       //     -0.64831180f +
5165       //       (0.91751397f +
5166       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5167       //
5168       // error 0.00019228036, which is better than 12 bits
5169       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5170                                getF32Constant(DAG, 0x3d431f31, dl));
5171       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5172                                getF32Constant(DAG, 0x3ea21fb2, dl));
5173       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5174       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5175                                getF32Constant(DAG, 0x3f6ae232, dl));
5176       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5177       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5178                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5179     } else { // LimitFloatPrecision <= 18
5180       // For floating-point precision of 18:
5181       //
5182       //   Log10ofMantissa =
5183       //     -0.84299375f +
5184       //       (1.5327582f +
5185       //         (-1.0688956f +
5186       //           (0.49102474f +
5187       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5188       //
5189       // error 0.0000037995730, which is better than 18 bits
5190       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5191                                getF32Constant(DAG, 0x3c5d51ce, dl));
5192       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5193                                getF32Constant(DAG, 0x3e00685a, dl));
5194       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5195       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5196                                getF32Constant(DAG, 0x3efb6798, dl));
5197       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5198       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5199                                getF32Constant(DAG, 0x3f88d192, dl));
5200       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5201       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5202                                getF32Constant(DAG, 0x3fc4316c, dl));
5203       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5204       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5205                                     getF32Constant(DAG, 0x3f57ce70, dl));
5206     }
5207 
5208     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5209   }
5210 
5211   // No special expansion.
5212   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5213 }
5214 
5215 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5216 /// limited-precision mode.
5217 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5218                           const TargetLowering &TLI) {
5219   if (Op.getValueType() == MVT::f32 &&
5220       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5221     return getLimitedPrecisionExp2(Op, dl, DAG);
5222 
5223   // No special expansion.
5224   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5225 }
5226 
5227 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5228 /// limited-precision mode with x == 10.0f.
5229 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5230                          SelectionDAG &DAG, const TargetLowering &TLI) {
5231   bool IsExp10 = false;
5232   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5233       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5234     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5235       APFloat Ten(10.0f);
5236       IsExp10 = LHSC->isExactlyValue(Ten);
5237     }
5238   }
5239 
5240   // TODO: What fast-math-flags should be set on the FMUL node?
5241   if (IsExp10) {
5242     // Put the exponent in the right bit position for later addition to the
5243     // final result:
5244     //
5245     //   #define LOG2OF10 3.3219281f
5246     //   t0 = Op * LOG2OF10;
5247     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5248                              getF32Constant(DAG, 0x40549a78, dl));
5249     return getLimitedPrecisionExp2(t0, dl, DAG);
5250   }
5251 
5252   // No special expansion.
5253   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5254 }
5255 
5256 /// ExpandPowI - Expand a llvm.powi intrinsic.
5257 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5258                           SelectionDAG &DAG) {
5259   // If RHS is a constant, we can expand this out to a multiplication tree,
5260   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5261   // optimizing for size, we only want to do this if the expansion would produce
5262   // a small number of multiplies, otherwise we do the full expansion.
5263   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5264     // Get the exponent as a positive value.
5265     unsigned Val = RHSC->getSExtValue();
5266     if ((int)Val < 0) Val = -Val;
5267 
5268     // powi(x, 0) -> 1.0
5269     if (Val == 0)
5270       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5271 
5272     const Function &F = DAG.getMachineFunction().getFunction();
5273     if (!F.hasOptSize() ||
5274         // If optimizing for size, don't insert too many multiplies.
5275         // This inserts up to 5 multiplies.
5276         countPopulation(Val) + Log2_32(Val) < 7) {
5277       // We use the simple binary decomposition method to generate the multiply
5278       // sequence.  There are more optimal ways to do this (for example,
5279       // powi(x,15) generates one more multiply than it should), but this has
5280       // the benefit of being both really simple and much better than a libcall.
5281       SDValue Res;  // Logically starts equal to 1.0
5282       SDValue CurSquare = LHS;
5283       // TODO: Intrinsics should have fast-math-flags that propagate to these
5284       // nodes.
5285       while (Val) {
5286         if (Val & 1) {
5287           if (Res.getNode())
5288             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5289           else
5290             Res = CurSquare;  // 1.0*CurSquare.
5291         }
5292 
5293         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5294                                 CurSquare, CurSquare);
5295         Val >>= 1;
5296       }
5297 
5298       // If the original was negative, invert the result, producing 1/(x*x*x).
5299       if (RHSC->getSExtValue() < 0)
5300         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5301                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5302       return Res;
5303     }
5304   }
5305 
5306   // Otherwise, expand to a libcall.
5307   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5308 }
5309 
5310 // getUnderlyingArgReg - Find underlying register used for a truncated or
5311 // bitcasted argument.
5312 static unsigned getUnderlyingArgReg(const SDValue &N) {
5313   switch (N.getOpcode()) {
5314   case ISD::CopyFromReg:
5315     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
5316   case ISD::BITCAST:
5317   case ISD::AssertZext:
5318   case ISD::AssertSext:
5319   case ISD::TRUNCATE:
5320     return getUnderlyingArgReg(N.getOperand(0));
5321   default:
5322     return 0;
5323   }
5324 }
5325 
5326 /// If the DbgValueInst is a dbg_value of a function argument, create the
5327 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5328 /// instruction selection, they will be inserted to the entry BB.
5329 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5330     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5331     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5332   const Argument *Arg = dyn_cast<Argument>(V);
5333   if (!Arg)
5334     return false;
5335 
5336   if (!IsDbgDeclare) {
5337     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5338     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5339     // the entry block.
5340     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5341     if (!IsInEntryBlock)
5342       return false;
5343 
5344     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5345     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5346     // variable that also is a param.
5347     //
5348     // Although, if we are at the top of the entry block already, we can still
5349     // emit using ArgDbgValue. This might catch some situations when the
5350     // dbg.value refers to an argument that isn't used in the entry block, so
5351     // any CopyToReg node would be optimized out and the only way to express
5352     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5353     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5354     // we should only emit as ArgDbgValue if the Variable is an argument to the
5355     // current function, and the dbg.value intrinsic is found in the entry
5356     // block.
5357     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5358         !DL->getInlinedAt();
5359     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5360     if (!IsInPrologue && !VariableIsFunctionInputArg)
5361       return false;
5362 
5363     // Here we assume that a function argument on IR level only can be used to
5364     // describe one input parameter on source level. If we for example have
5365     // source code like this
5366     //
5367     //    struct A { long x, y; };
5368     //    void foo(struct A a, long b) {
5369     //      ...
5370     //      b = a.x;
5371     //      ...
5372     //    }
5373     //
5374     // and IR like this
5375     //
5376     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5377     //  entry:
5378     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5379     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5380     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5381     //    ...
5382     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5383     //    ...
5384     //
5385     // then the last dbg.value is describing a parameter "b" using a value that
5386     // is an argument. But since we already has used %a1 to describe a parameter
5387     // we should not handle that last dbg.value here (that would result in an
5388     // incorrect hoisting of the DBG_VALUE to the function entry).
5389     // Notice that we allow one dbg.value per IR level argument, to accomodate
5390     // for the situation with fragments above.
5391     if (VariableIsFunctionInputArg) {
5392       unsigned ArgNo = Arg->getArgNo();
5393       if (ArgNo >= FuncInfo.DescribedArgs.size())
5394         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5395       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5396         return false;
5397       FuncInfo.DescribedArgs.set(ArgNo);
5398     }
5399   }
5400 
5401   MachineFunction &MF = DAG.getMachineFunction();
5402   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5403 
5404   bool IsIndirect = false;
5405   Optional<MachineOperand> Op;
5406   // Some arguments' frame index is recorded during argument lowering.
5407   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5408   if (FI != std::numeric_limits<int>::max())
5409     Op = MachineOperand::CreateFI(FI);
5410 
5411   if (!Op && N.getNode()) {
5412     unsigned Reg = getUnderlyingArgReg(N);
5413     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
5414       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5415       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
5416       if (PR)
5417         Reg = PR;
5418     }
5419     if (Reg) {
5420       Op = MachineOperand::CreateReg(Reg, false);
5421       IsIndirect = IsDbgDeclare;
5422     }
5423   }
5424 
5425   if (!Op && N.getNode()) {
5426     // Check if frame index is available.
5427     SDValue LCandidate = peekThroughBitcasts(N);
5428     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5429       if (FrameIndexSDNode *FINode =
5430           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5431         Op = MachineOperand::CreateFI(FINode->getIndex());
5432   }
5433 
5434   if (!Op) {
5435     // Check if ValueMap has reg number.
5436     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
5437     if (VMI != FuncInfo.ValueMap.end()) {
5438       const auto &TLI = DAG.getTargetLoweringInfo();
5439       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5440                        V->getType(), getABIRegCopyCC(V));
5441       if (RFV.occupiesMultipleRegs()) {
5442         unsigned Offset = 0;
5443         for (auto RegAndSize : RFV.getRegsAndSizes()) {
5444           Op = MachineOperand::CreateReg(RegAndSize.first, false);
5445           auto FragmentExpr = DIExpression::createFragmentExpression(
5446               Expr, Offset, RegAndSize.second);
5447           if (!FragmentExpr)
5448             continue;
5449           FuncInfo.ArgDbgValues.push_back(
5450               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5451                       Op->getReg(), Variable, *FragmentExpr));
5452           Offset += RegAndSize.second;
5453         }
5454         return true;
5455       }
5456       Op = MachineOperand::CreateReg(VMI->second, false);
5457       IsIndirect = IsDbgDeclare;
5458     }
5459   }
5460 
5461   if (!Op)
5462     return false;
5463 
5464   assert(Variable->isValidLocationForIntrinsic(DL) &&
5465          "Expected inlined-at fields to agree");
5466   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5467   FuncInfo.ArgDbgValues.push_back(
5468       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5469               *Op, Variable, Expr));
5470 
5471   return true;
5472 }
5473 
5474 /// Return the appropriate SDDbgValue based on N.
5475 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5476                                              DILocalVariable *Variable,
5477                                              DIExpression *Expr,
5478                                              const DebugLoc &dl,
5479                                              unsigned DbgSDNodeOrder) {
5480   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5481     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5482     // stack slot locations.
5483     //
5484     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5485     // debug values here after optimization:
5486     //
5487     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5488     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5489     //
5490     // Both describe the direct values of their associated variables.
5491     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5492                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5493   }
5494   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5495                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5496 }
5497 
5498 // VisualStudio defines setjmp as _setjmp
5499 #if defined(_MSC_VER) && defined(setjmp) && \
5500                          !defined(setjmp_undefined_for_msvc)
5501 #  pragma push_macro("setjmp")
5502 #  undef setjmp
5503 #  define setjmp_undefined_for_msvc
5504 #endif
5505 
5506 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5507   switch (Intrinsic) {
5508   case Intrinsic::smul_fix:
5509     return ISD::SMULFIX;
5510   case Intrinsic::umul_fix:
5511     return ISD::UMULFIX;
5512   default:
5513     llvm_unreachable("Unhandled fixed point intrinsic");
5514   }
5515 }
5516 
5517 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5518                                            const char *FunctionName) {
5519   assert(FunctionName && "FunctionName must not be nullptr");
5520   SDValue Callee = DAG.getExternalSymbol(
5521       FunctionName,
5522       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5523   LowerCallTo(&I, Callee, I.isTailCall());
5524 }
5525 
5526 /// Lower the call to the specified intrinsic function.
5527 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5528                                              unsigned Intrinsic) {
5529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5530   SDLoc sdl = getCurSDLoc();
5531   DebugLoc dl = getCurDebugLoc();
5532   SDValue Res;
5533 
5534   switch (Intrinsic) {
5535   default:
5536     // By default, turn this into a target intrinsic node.
5537     visitTargetIntrinsic(I, Intrinsic);
5538     return;
5539   case Intrinsic::vastart:  visitVAStart(I); return;
5540   case Intrinsic::vaend:    visitVAEnd(I); return;
5541   case Intrinsic::vacopy:   visitVACopy(I); return;
5542   case Intrinsic::returnaddress:
5543     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5544                              TLI.getPointerTy(DAG.getDataLayout()),
5545                              getValue(I.getArgOperand(0))));
5546     return;
5547   case Intrinsic::addressofreturnaddress:
5548     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5549                              TLI.getPointerTy(DAG.getDataLayout())));
5550     return;
5551   case Intrinsic::sponentry:
5552     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5553                              TLI.getPointerTy(DAG.getDataLayout())));
5554     return;
5555   case Intrinsic::frameaddress:
5556     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5557                              TLI.getPointerTy(DAG.getDataLayout()),
5558                              getValue(I.getArgOperand(0))));
5559     return;
5560   case Intrinsic::read_register: {
5561     Value *Reg = I.getArgOperand(0);
5562     SDValue Chain = getRoot();
5563     SDValue RegName =
5564         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5565     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5566     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5567       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5568     setValue(&I, Res);
5569     DAG.setRoot(Res.getValue(1));
5570     return;
5571   }
5572   case Intrinsic::write_register: {
5573     Value *Reg = I.getArgOperand(0);
5574     Value *RegValue = I.getArgOperand(1);
5575     SDValue Chain = getRoot();
5576     SDValue RegName =
5577         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5578     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5579                             RegName, getValue(RegValue)));
5580     return;
5581   }
5582   case Intrinsic::setjmp:
5583     lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
5584     return;
5585   case Intrinsic::longjmp:
5586     lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
5587     return;
5588   case Intrinsic::memcpy: {
5589     const auto &MCI = cast<MemCpyInst>(I);
5590     SDValue Op1 = getValue(I.getArgOperand(0));
5591     SDValue Op2 = getValue(I.getArgOperand(1));
5592     SDValue Op3 = getValue(I.getArgOperand(2));
5593     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5594     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5595     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5596     unsigned Align = MinAlign(DstAlign, SrcAlign);
5597     bool isVol = MCI.isVolatile();
5598     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5599     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5600     // node.
5601     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5602                                false, isTC,
5603                                MachinePointerInfo(I.getArgOperand(0)),
5604                                MachinePointerInfo(I.getArgOperand(1)));
5605     updateDAGForMaybeTailCall(MC);
5606     return;
5607   }
5608   case Intrinsic::memset: {
5609     const auto &MSI = cast<MemSetInst>(I);
5610     SDValue Op1 = getValue(I.getArgOperand(0));
5611     SDValue Op2 = getValue(I.getArgOperand(1));
5612     SDValue Op3 = getValue(I.getArgOperand(2));
5613     // @llvm.memset defines 0 and 1 to both mean no alignment.
5614     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5615     bool isVol = MSI.isVolatile();
5616     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5617     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5618                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5619     updateDAGForMaybeTailCall(MS);
5620     return;
5621   }
5622   case Intrinsic::memmove: {
5623     const auto &MMI = cast<MemMoveInst>(I);
5624     SDValue Op1 = getValue(I.getArgOperand(0));
5625     SDValue Op2 = getValue(I.getArgOperand(1));
5626     SDValue Op3 = getValue(I.getArgOperand(2));
5627     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5628     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5629     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5630     unsigned Align = MinAlign(DstAlign, SrcAlign);
5631     bool isVol = MMI.isVolatile();
5632     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5633     // FIXME: Support passing different dest/src alignments to the memmove DAG
5634     // node.
5635     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5636                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5637                                 MachinePointerInfo(I.getArgOperand(1)));
5638     updateDAGForMaybeTailCall(MM);
5639     return;
5640   }
5641   case Intrinsic::memcpy_element_unordered_atomic: {
5642     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5643     SDValue Dst = getValue(MI.getRawDest());
5644     SDValue Src = getValue(MI.getRawSource());
5645     SDValue Length = getValue(MI.getLength());
5646 
5647     unsigned DstAlign = MI.getDestAlignment();
5648     unsigned SrcAlign = MI.getSourceAlignment();
5649     Type *LengthTy = MI.getLength()->getType();
5650     unsigned ElemSz = MI.getElementSizeInBytes();
5651     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5652     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5653                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5654                                      MachinePointerInfo(MI.getRawDest()),
5655                                      MachinePointerInfo(MI.getRawSource()));
5656     updateDAGForMaybeTailCall(MC);
5657     return;
5658   }
5659   case Intrinsic::memmove_element_unordered_atomic: {
5660     auto &MI = cast<AtomicMemMoveInst>(I);
5661     SDValue Dst = getValue(MI.getRawDest());
5662     SDValue Src = getValue(MI.getRawSource());
5663     SDValue Length = getValue(MI.getLength());
5664 
5665     unsigned DstAlign = MI.getDestAlignment();
5666     unsigned SrcAlign = MI.getSourceAlignment();
5667     Type *LengthTy = MI.getLength()->getType();
5668     unsigned ElemSz = MI.getElementSizeInBytes();
5669     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5670     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5671                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5672                                       MachinePointerInfo(MI.getRawDest()),
5673                                       MachinePointerInfo(MI.getRawSource()));
5674     updateDAGForMaybeTailCall(MC);
5675     return;
5676   }
5677   case Intrinsic::memset_element_unordered_atomic: {
5678     auto &MI = cast<AtomicMemSetInst>(I);
5679     SDValue Dst = getValue(MI.getRawDest());
5680     SDValue Val = getValue(MI.getValue());
5681     SDValue Length = getValue(MI.getLength());
5682 
5683     unsigned DstAlign = MI.getDestAlignment();
5684     Type *LengthTy = MI.getLength()->getType();
5685     unsigned ElemSz = MI.getElementSizeInBytes();
5686     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5687     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5688                                      LengthTy, ElemSz, isTC,
5689                                      MachinePointerInfo(MI.getRawDest()));
5690     updateDAGForMaybeTailCall(MC);
5691     return;
5692   }
5693   case Intrinsic::dbg_addr:
5694   case Intrinsic::dbg_declare: {
5695     const auto &DI = cast<DbgVariableIntrinsic>(I);
5696     DILocalVariable *Variable = DI.getVariable();
5697     DIExpression *Expression = DI.getExpression();
5698     dropDanglingDebugInfo(Variable, Expression);
5699     assert(Variable && "Missing variable");
5700 
5701     // Check if address has undef value.
5702     const Value *Address = DI.getVariableLocation();
5703     if (!Address || isa<UndefValue>(Address) ||
5704         (Address->use_empty() && !isa<Argument>(Address))) {
5705       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5706       return;
5707     }
5708 
5709     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5710 
5711     // Check if this variable can be described by a frame index, typically
5712     // either as a static alloca or a byval parameter.
5713     int FI = std::numeric_limits<int>::max();
5714     if (const auto *AI =
5715             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5716       if (AI->isStaticAlloca()) {
5717         auto I = FuncInfo.StaticAllocaMap.find(AI);
5718         if (I != FuncInfo.StaticAllocaMap.end())
5719           FI = I->second;
5720       }
5721     } else if (const auto *Arg = dyn_cast<Argument>(
5722                    Address->stripInBoundsConstantOffsets())) {
5723       FI = FuncInfo.getArgumentFrameIndex(Arg);
5724     }
5725 
5726     // llvm.dbg.addr is control dependent and always generates indirect
5727     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5728     // the MachineFunction variable table.
5729     if (FI != std::numeric_limits<int>::max()) {
5730       if (Intrinsic == Intrinsic::dbg_addr) {
5731         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5732             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5733         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5734       }
5735       return;
5736     }
5737 
5738     SDValue &N = NodeMap[Address];
5739     if (!N.getNode() && isa<Argument>(Address))
5740       // Check unused arguments map.
5741       N = UnusedArgNodeMap[Address];
5742     SDDbgValue *SDV;
5743     if (N.getNode()) {
5744       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5745         Address = BCI->getOperand(0);
5746       // Parameters are handled specially.
5747       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5748       if (isParameter && FINode) {
5749         // Byval parameter. We have a frame index at this point.
5750         SDV =
5751             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5752                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5753       } else if (isa<Argument>(Address)) {
5754         // Address is an argument, so try to emit its dbg value using
5755         // virtual register info from the FuncInfo.ValueMap.
5756         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5757         return;
5758       } else {
5759         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5760                               true, dl, SDNodeOrder);
5761       }
5762       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5763     } else {
5764       // If Address is an argument then try to emit its dbg value using
5765       // virtual register info from the FuncInfo.ValueMap.
5766       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5767                                     N)) {
5768         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5769       }
5770     }
5771     return;
5772   }
5773   case Intrinsic::dbg_label: {
5774     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5775     DILabel *Label = DI.getLabel();
5776     assert(Label && "Missing label");
5777 
5778     SDDbgLabel *SDV;
5779     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5780     DAG.AddDbgLabel(SDV);
5781     return;
5782   }
5783   case Intrinsic::dbg_value: {
5784     const DbgValueInst &DI = cast<DbgValueInst>(I);
5785     assert(DI.getVariable() && "Missing variable");
5786 
5787     DILocalVariable *Variable = DI.getVariable();
5788     DIExpression *Expression = DI.getExpression();
5789     dropDanglingDebugInfo(Variable, Expression);
5790     const Value *V = DI.getValue();
5791     if (!V)
5792       return;
5793 
5794     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5795         SDNodeOrder))
5796       return;
5797 
5798     // TODO: Dangling debug info will eventually either be resolved or produce
5799     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5800     // between the original dbg.value location and its resolved DBG_VALUE, which
5801     // we should ideally fill with an extra Undef DBG_VALUE.
5802 
5803     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5804     return;
5805   }
5806 
5807   case Intrinsic::eh_typeid_for: {
5808     // Find the type id for the given typeinfo.
5809     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5810     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5811     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5812     setValue(&I, Res);
5813     return;
5814   }
5815 
5816   case Intrinsic::eh_return_i32:
5817   case Intrinsic::eh_return_i64:
5818     DAG.getMachineFunction().setCallsEHReturn(true);
5819     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5820                             MVT::Other,
5821                             getControlRoot(),
5822                             getValue(I.getArgOperand(0)),
5823                             getValue(I.getArgOperand(1))));
5824     return;
5825   case Intrinsic::eh_unwind_init:
5826     DAG.getMachineFunction().setCallsUnwindInit(true);
5827     return;
5828   case Intrinsic::eh_dwarf_cfa:
5829     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5830                              TLI.getPointerTy(DAG.getDataLayout()),
5831                              getValue(I.getArgOperand(0))));
5832     return;
5833   case Intrinsic::eh_sjlj_callsite: {
5834     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5835     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5836     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5837     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5838 
5839     MMI.setCurrentCallSite(CI->getZExtValue());
5840     return;
5841   }
5842   case Intrinsic::eh_sjlj_functioncontext: {
5843     // Get and store the index of the function context.
5844     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5845     AllocaInst *FnCtx =
5846       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5847     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5848     MFI.setFunctionContextIndex(FI);
5849     return;
5850   }
5851   case Intrinsic::eh_sjlj_setjmp: {
5852     SDValue Ops[2];
5853     Ops[0] = getRoot();
5854     Ops[1] = getValue(I.getArgOperand(0));
5855     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5856                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5857     setValue(&I, Op.getValue(0));
5858     DAG.setRoot(Op.getValue(1));
5859     return;
5860   }
5861   case Intrinsic::eh_sjlj_longjmp:
5862     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5863                             getRoot(), getValue(I.getArgOperand(0))));
5864     return;
5865   case Intrinsic::eh_sjlj_setup_dispatch:
5866     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5867                             getRoot()));
5868     return;
5869   case Intrinsic::masked_gather:
5870     visitMaskedGather(I);
5871     return;
5872   case Intrinsic::masked_load:
5873     visitMaskedLoad(I);
5874     return;
5875   case Intrinsic::masked_scatter:
5876     visitMaskedScatter(I);
5877     return;
5878   case Intrinsic::masked_store:
5879     visitMaskedStore(I);
5880     return;
5881   case Intrinsic::masked_expandload:
5882     visitMaskedLoad(I, true /* IsExpanding */);
5883     return;
5884   case Intrinsic::masked_compressstore:
5885     visitMaskedStore(I, true /* IsCompressing */);
5886     return;
5887   case Intrinsic::x86_mmx_pslli_w:
5888   case Intrinsic::x86_mmx_pslli_d:
5889   case Intrinsic::x86_mmx_pslli_q:
5890   case Intrinsic::x86_mmx_psrli_w:
5891   case Intrinsic::x86_mmx_psrli_d:
5892   case Intrinsic::x86_mmx_psrli_q:
5893   case Intrinsic::x86_mmx_psrai_w:
5894   case Intrinsic::x86_mmx_psrai_d: {
5895     SDValue ShAmt = getValue(I.getArgOperand(1));
5896     if (isa<ConstantSDNode>(ShAmt)) {
5897       visitTargetIntrinsic(I, Intrinsic);
5898       return;
5899     }
5900     unsigned NewIntrinsic = 0;
5901     EVT ShAmtVT = MVT::v2i32;
5902     switch (Intrinsic) {
5903     case Intrinsic::x86_mmx_pslli_w:
5904       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5905       break;
5906     case Intrinsic::x86_mmx_pslli_d:
5907       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5908       break;
5909     case Intrinsic::x86_mmx_pslli_q:
5910       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5911       break;
5912     case Intrinsic::x86_mmx_psrli_w:
5913       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5914       break;
5915     case Intrinsic::x86_mmx_psrli_d:
5916       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5917       break;
5918     case Intrinsic::x86_mmx_psrli_q:
5919       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5920       break;
5921     case Intrinsic::x86_mmx_psrai_w:
5922       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5923       break;
5924     case Intrinsic::x86_mmx_psrai_d:
5925       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5926       break;
5927     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5928     }
5929 
5930     // The vector shift intrinsics with scalars uses 32b shift amounts but
5931     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5932     // to be zero.
5933     // We must do this early because v2i32 is not a legal type.
5934     SDValue ShOps[2];
5935     ShOps[0] = ShAmt;
5936     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5937     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5938     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5939     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5940     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5941                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5942                        getValue(I.getArgOperand(0)), ShAmt);
5943     setValue(&I, Res);
5944     return;
5945   }
5946   case Intrinsic::powi:
5947     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5948                             getValue(I.getArgOperand(1)), DAG));
5949     return;
5950   case Intrinsic::log:
5951     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5952     return;
5953   case Intrinsic::log2:
5954     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5955     return;
5956   case Intrinsic::log10:
5957     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5958     return;
5959   case Intrinsic::exp:
5960     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5961     return;
5962   case Intrinsic::exp2:
5963     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5964     return;
5965   case Intrinsic::pow:
5966     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5967                            getValue(I.getArgOperand(1)), DAG, TLI));
5968     return;
5969   case Intrinsic::sqrt:
5970   case Intrinsic::fabs:
5971   case Intrinsic::sin:
5972   case Intrinsic::cos:
5973   case Intrinsic::floor:
5974   case Intrinsic::ceil:
5975   case Intrinsic::trunc:
5976   case Intrinsic::rint:
5977   case Intrinsic::nearbyint:
5978   case Intrinsic::round:
5979   case Intrinsic::canonicalize: {
5980     unsigned Opcode;
5981     switch (Intrinsic) {
5982     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5983     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5984     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5985     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5986     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5987     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5988     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5989     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5990     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5991     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5992     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5993     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5994     }
5995 
5996     setValue(&I, DAG.getNode(Opcode, sdl,
5997                              getValue(I.getArgOperand(0)).getValueType(),
5998                              getValue(I.getArgOperand(0))));
5999     return;
6000   }
6001   case Intrinsic::lround:
6002   case Intrinsic::llround:
6003   case Intrinsic::lrint:
6004   case Intrinsic::llrint: {
6005     unsigned Opcode;
6006     switch (Intrinsic) {
6007     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6008     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6009     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6010     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6011     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6012     }
6013 
6014     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6015     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6016                              getValue(I.getArgOperand(0))));
6017     return;
6018   }
6019   case Intrinsic::minnum:
6020     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6021                              getValue(I.getArgOperand(0)).getValueType(),
6022                              getValue(I.getArgOperand(0)),
6023                              getValue(I.getArgOperand(1))));
6024     return;
6025   case Intrinsic::maxnum:
6026     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6027                              getValue(I.getArgOperand(0)).getValueType(),
6028                              getValue(I.getArgOperand(0)),
6029                              getValue(I.getArgOperand(1))));
6030     return;
6031   case Intrinsic::minimum:
6032     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6033                              getValue(I.getArgOperand(0)).getValueType(),
6034                              getValue(I.getArgOperand(0)),
6035                              getValue(I.getArgOperand(1))));
6036     return;
6037   case Intrinsic::maximum:
6038     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6039                              getValue(I.getArgOperand(0)).getValueType(),
6040                              getValue(I.getArgOperand(0)),
6041                              getValue(I.getArgOperand(1))));
6042     return;
6043   case Intrinsic::copysign:
6044     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6045                              getValue(I.getArgOperand(0)).getValueType(),
6046                              getValue(I.getArgOperand(0)),
6047                              getValue(I.getArgOperand(1))));
6048     return;
6049   case Intrinsic::fma:
6050     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6051                              getValue(I.getArgOperand(0)).getValueType(),
6052                              getValue(I.getArgOperand(0)),
6053                              getValue(I.getArgOperand(1)),
6054                              getValue(I.getArgOperand(2))));
6055     return;
6056   case Intrinsic::experimental_constrained_fadd:
6057   case Intrinsic::experimental_constrained_fsub:
6058   case Intrinsic::experimental_constrained_fmul:
6059   case Intrinsic::experimental_constrained_fdiv:
6060   case Intrinsic::experimental_constrained_frem:
6061   case Intrinsic::experimental_constrained_fma:
6062   case Intrinsic::experimental_constrained_fptrunc:
6063   case Intrinsic::experimental_constrained_fpext:
6064   case Intrinsic::experimental_constrained_sqrt:
6065   case Intrinsic::experimental_constrained_pow:
6066   case Intrinsic::experimental_constrained_powi:
6067   case Intrinsic::experimental_constrained_sin:
6068   case Intrinsic::experimental_constrained_cos:
6069   case Intrinsic::experimental_constrained_exp:
6070   case Intrinsic::experimental_constrained_exp2:
6071   case Intrinsic::experimental_constrained_log:
6072   case Intrinsic::experimental_constrained_log10:
6073   case Intrinsic::experimental_constrained_log2:
6074   case Intrinsic::experimental_constrained_rint:
6075   case Intrinsic::experimental_constrained_nearbyint:
6076   case Intrinsic::experimental_constrained_maxnum:
6077   case Intrinsic::experimental_constrained_minnum:
6078   case Intrinsic::experimental_constrained_ceil:
6079   case Intrinsic::experimental_constrained_floor:
6080   case Intrinsic::experimental_constrained_round:
6081   case Intrinsic::experimental_constrained_trunc:
6082     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6083     return;
6084   case Intrinsic::fmuladd: {
6085     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6086     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6087         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
6088       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6089                                getValue(I.getArgOperand(0)).getValueType(),
6090                                getValue(I.getArgOperand(0)),
6091                                getValue(I.getArgOperand(1)),
6092                                getValue(I.getArgOperand(2))));
6093     } else {
6094       // TODO: Intrinsic calls should have fast-math-flags.
6095       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6096                                 getValue(I.getArgOperand(0)).getValueType(),
6097                                 getValue(I.getArgOperand(0)),
6098                                 getValue(I.getArgOperand(1)));
6099       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6100                                 getValue(I.getArgOperand(0)).getValueType(),
6101                                 Mul,
6102                                 getValue(I.getArgOperand(2)));
6103       setValue(&I, Add);
6104     }
6105     return;
6106   }
6107   case Intrinsic::convert_to_fp16:
6108     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6109                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6110                                          getValue(I.getArgOperand(0)),
6111                                          DAG.getTargetConstant(0, sdl,
6112                                                                MVT::i32))));
6113     return;
6114   case Intrinsic::convert_from_fp16:
6115     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6116                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6117                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6118                                          getValue(I.getArgOperand(0)))));
6119     return;
6120   case Intrinsic::pcmarker: {
6121     SDValue Tmp = getValue(I.getArgOperand(0));
6122     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6123     return;
6124   }
6125   case Intrinsic::readcyclecounter: {
6126     SDValue Op = getRoot();
6127     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6128                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6129     setValue(&I, Res);
6130     DAG.setRoot(Res.getValue(1));
6131     return;
6132   }
6133   case Intrinsic::bitreverse:
6134     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6135                              getValue(I.getArgOperand(0)).getValueType(),
6136                              getValue(I.getArgOperand(0))));
6137     return;
6138   case Intrinsic::bswap:
6139     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6140                              getValue(I.getArgOperand(0)).getValueType(),
6141                              getValue(I.getArgOperand(0))));
6142     return;
6143   case Intrinsic::cttz: {
6144     SDValue Arg = getValue(I.getArgOperand(0));
6145     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6146     EVT Ty = Arg.getValueType();
6147     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6148                              sdl, Ty, Arg));
6149     return;
6150   }
6151   case Intrinsic::ctlz: {
6152     SDValue Arg = getValue(I.getArgOperand(0));
6153     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6154     EVT Ty = Arg.getValueType();
6155     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6156                              sdl, Ty, Arg));
6157     return;
6158   }
6159   case Intrinsic::ctpop: {
6160     SDValue Arg = getValue(I.getArgOperand(0));
6161     EVT Ty = Arg.getValueType();
6162     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6163     return;
6164   }
6165   case Intrinsic::fshl:
6166   case Intrinsic::fshr: {
6167     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6168     SDValue X = getValue(I.getArgOperand(0));
6169     SDValue Y = getValue(I.getArgOperand(1));
6170     SDValue Z = getValue(I.getArgOperand(2));
6171     EVT VT = X.getValueType();
6172     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6173     SDValue Zero = DAG.getConstant(0, sdl, VT);
6174     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6175 
6176     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6177     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6178       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6179       return;
6180     }
6181 
6182     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6183     // avoid the select that is necessary in the general case to filter out
6184     // the 0-shift possibility that leads to UB.
6185     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6186       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6187       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6188         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6189         return;
6190       }
6191 
6192       // Some targets only rotate one way. Try the opposite direction.
6193       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6194       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6195         // Negate the shift amount because it is safe to ignore the high bits.
6196         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6197         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6198         return;
6199       }
6200 
6201       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6202       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6203       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6204       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6205       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6206       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6207       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6208       return;
6209     }
6210 
6211     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6212     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6213     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6214     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6215     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6216     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6217 
6218     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6219     // and that is undefined. We must compare and select to avoid UB.
6220     EVT CCVT = MVT::i1;
6221     if (VT.isVector())
6222       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6223 
6224     // For fshl, 0-shift returns the 1st arg (X).
6225     // For fshr, 0-shift returns the 2nd arg (Y).
6226     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6227     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6228     return;
6229   }
6230   case Intrinsic::sadd_sat: {
6231     SDValue Op1 = getValue(I.getArgOperand(0));
6232     SDValue Op2 = getValue(I.getArgOperand(1));
6233     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6234     return;
6235   }
6236   case Intrinsic::uadd_sat: {
6237     SDValue Op1 = getValue(I.getArgOperand(0));
6238     SDValue Op2 = getValue(I.getArgOperand(1));
6239     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6240     return;
6241   }
6242   case Intrinsic::ssub_sat: {
6243     SDValue Op1 = getValue(I.getArgOperand(0));
6244     SDValue Op2 = getValue(I.getArgOperand(1));
6245     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6246     return;
6247   }
6248   case Intrinsic::usub_sat: {
6249     SDValue Op1 = getValue(I.getArgOperand(0));
6250     SDValue Op2 = getValue(I.getArgOperand(1));
6251     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6252     return;
6253   }
6254   case Intrinsic::smul_fix:
6255   case Intrinsic::umul_fix: {
6256     SDValue Op1 = getValue(I.getArgOperand(0));
6257     SDValue Op2 = getValue(I.getArgOperand(1));
6258     SDValue Op3 = getValue(I.getArgOperand(2));
6259     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6260                              Op1.getValueType(), Op1, Op2, Op3));
6261     return;
6262   }
6263   case Intrinsic::smul_fix_sat: {
6264     SDValue Op1 = getValue(I.getArgOperand(0));
6265     SDValue Op2 = getValue(I.getArgOperand(1));
6266     SDValue Op3 = getValue(I.getArgOperand(2));
6267     setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6268                              Op3));
6269     return;
6270   }
6271   case Intrinsic::stacksave: {
6272     SDValue Op = getRoot();
6273     Res = DAG.getNode(
6274         ISD::STACKSAVE, sdl,
6275         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6276     setValue(&I, Res);
6277     DAG.setRoot(Res.getValue(1));
6278     return;
6279   }
6280   case Intrinsic::stackrestore:
6281     Res = getValue(I.getArgOperand(0));
6282     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6283     return;
6284   case Intrinsic::get_dynamic_area_offset: {
6285     SDValue Op = getRoot();
6286     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6287     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6288     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6289     // target.
6290     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6291       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6292                          " intrinsic!");
6293     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6294                       Op);
6295     DAG.setRoot(Op);
6296     setValue(&I, Res);
6297     return;
6298   }
6299   case Intrinsic::stackguard: {
6300     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6301     MachineFunction &MF = DAG.getMachineFunction();
6302     const Module &M = *MF.getFunction().getParent();
6303     SDValue Chain = getRoot();
6304     if (TLI.useLoadStackGuardNode()) {
6305       Res = getLoadStackGuard(DAG, sdl, Chain);
6306     } else {
6307       const Value *Global = TLI.getSDagStackGuard(M);
6308       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6309       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6310                         MachinePointerInfo(Global, 0), Align,
6311                         MachineMemOperand::MOVolatile);
6312     }
6313     if (TLI.useStackGuardXorFP())
6314       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6315     DAG.setRoot(Chain);
6316     setValue(&I, Res);
6317     return;
6318   }
6319   case Intrinsic::stackprotector: {
6320     // Emit code into the DAG to store the stack guard onto the stack.
6321     MachineFunction &MF = DAG.getMachineFunction();
6322     MachineFrameInfo &MFI = MF.getFrameInfo();
6323     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6324     SDValue Src, Chain = getRoot();
6325 
6326     if (TLI.useLoadStackGuardNode())
6327       Src = getLoadStackGuard(DAG, sdl, Chain);
6328     else
6329       Src = getValue(I.getArgOperand(0));   // The guard's value.
6330 
6331     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6332 
6333     int FI = FuncInfo.StaticAllocaMap[Slot];
6334     MFI.setStackProtectorIndex(FI);
6335 
6336     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6337 
6338     // Store the stack protector onto the stack.
6339     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6340                                                  DAG.getMachineFunction(), FI),
6341                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6342     setValue(&I, Res);
6343     DAG.setRoot(Res);
6344     return;
6345   }
6346   case Intrinsic::objectsize: {
6347     // If we don't know by now, we're never going to know.
6348     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
6349 
6350     assert(CI && "Non-constant type in __builtin_object_size?");
6351 
6352     SDValue Arg = getValue(I.getCalledValue());
6353     EVT Ty = Arg.getValueType();
6354 
6355     if (CI->isZero())
6356       Res = DAG.getConstant(-1ULL, sdl, Ty);
6357     else
6358       Res = DAG.getConstant(0, sdl, Ty);
6359 
6360     setValue(&I, Res);
6361     return;
6362   }
6363 
6364   case Intrinsic::is_constant:
6365     // If this wasn't constant-folded away by now, then it's not a
6366     // constant.
6367     setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
6368     return;
6369 
6370   case Intrinsic::annotation:
6371   case Intrinsic::ptr_annotation:
6372   case Intrinsic::launder_invariant_group:
6373   case Intrinsic::strip_invariant_group:
6374     // Drop the intrinsic, but forward the value
6375     setValue(&I, getValue(I.getOperand(0)));
6376     return;
6377   case Intrinsic::assume:
6378   case Intrinsic::var_annotation:
6379   case Intrinsic::sideeffect:
6380     // Discard annotate attributes, assumptions, and artificial side-effects.
6381     return;
6382 
6383   case Intrinsic::codeview_annotation: {
6384     // Emit a label associated with this metadata.
6385     MachineFunction &MF = DAG.getMachineFunction();
6386     MCSymbol *Label =
6387         MF.getMMI().getContext().createTempSymbol("annotation", true);
6388     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6389     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6390     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6391     DAG.setRoot(Res);
6392     return;
6393   }
6394 
6395   case Intrinsic::init_trampoline: {
6396     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6397 
6398     SDValue Ops[6];
6399     Ops[0] = getRoot();
6400     Ops[1] = getValue(I.getArgOperand(0));
6401     Ops[2] = getValue(I.getArgOperand(1));
6402     Ops[3] = getValue(I.getArgOperand(2));
6403     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6404     Ops[5] = DAG.getSrcValue(F);
6405 
6406     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6407 
6408     DAG.setRoot(Res);
6409     return;
6410   }
6411   case Intrinsic::adjust_trampoline:
6412     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6413                              TLI.getPointerTy(DAG.getDataLayout()),
6414                              getValue(I.getArgOperand(0))));
6415     return;
6416   case Intrinsic::gcroot: {
6417     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6418            "only valid in functions with gc specified, enforced by Verifier");
6419     assert(GFI && "implied by previous");
6420     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6421     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6422 
6423     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6424     GFI->addStackRoot(FI->getIndex(), TypeMap);
6425     return;
6426   }
6427   case Intrinsic::gcread:
6428   case Intrinsic::gcwrite:
6429     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6430   case Intrinsic::flt_rounds:
6431     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6432     return;
6433 
6434   case Intrinsic::expect:
6435     // Just replace __builtin_expect(exp, c) with EXP.
6436     setValue(&I, getValue(I.getArgOperand(0)));
6437     return;
6438 
6439   case Intrinsic::debugtrap:
6440   case Intrinsic::trap: {
6441     StringRef TrapFuncName =
6442         I.getAttributes()
6443             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6444             .getValueAsString();
6445     if (TrapFuncName.empty()) {
6446       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6447         ISD::TRAP : ISD::DEBUGTRAP;
6448       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6449       return;
6450     }
6451     TargetLowering::ArgListTy Args;
6452 
6453     TargetLowering::CallLoweringInfo CLI(DAG);
6454     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6455         CallingConv::C, I.getType(),
6456         DAG.getExternalSymbol(TrapFuncName.data(),
6457                               TLI.getPointerTy(DAG.getDataLayout())),
6458         std::move(Args));
6459 
6460     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6461     DAG.setRoot(Result.second);
6462     return;
6463   }
6464 
6465   case Intrinsic::uadd_with_overflow:
6466   case Intrinsic::sadd_with_overflow:
6467   case Intrinsic::usub_with_overflow:
6468   case Intrinsic::ssub_with_overflow:
6469   case Intrinsic::umul_with_overflow:
6470   case Intrinsic::smul_with_overflow: {
6471     ISD::NodeType Op;
6472     switch (Intrinsic) {
6473     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6474     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6475     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6476     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6477     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6478     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6479     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6480     }
6481     SDValue Op1 = getValue(I.getArgOperand(0));
6482     SDValue Op2 = getValue(I.getArgOperand(1));
6483 
6484     EVT ResultVT = Op1.getValueType();
6485     EVT OverflowVT = MVT::i1;
6486     if (ResultVT.isVector())
6487       OverflowVT = EVT::getVectorVT(
6488           *Context, OverflowVT, ResultVT.getVectorNumElements());
6489 
6490     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6491     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6492     return;
6493   }
6494   case Intrinsic::prefetch: {
6495     SDValue Ops[5];
6496     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6497     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6498     Ops[0] = DAG.getRoot();
6499     Ops[1] = getValue(I.getArgOperand(0));
6500     Ops[2] = getValue(I.getArgOperand(1));
6501     Ops[3] = getValue(I.getArgOperand(2));
6502     Ops[4] = getValue(I.getArgOperand(3));
6503     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6504                                              DAG.getVTList(MVT::Other), Ops,
6505                                              EVT::getIntegerVT(*Context, 8),
6506                                              MachinePointerInfo(I.getArgOperand(0)),
6507                                              0, /* align */
6508                                              Flags);
6509 
6510     // Chain the prefetch in parallell with any pending loads, to stay out of
6511     // the way of later optimizations.
6512     PendingLoads.push_back(Result);
6513     Result = getRoot();
6514     DAG.setRoot(Result);
6515     return;
6516   }
6517   case Intrinsic::lifetime_start:
6518   case Intrinsic::lifetime_end: {
6519     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6520     // Stack coloring is not enabled in O0, discard region information.
6521     if (TM.getOptLevel() == CodeGenOpt::None)
6522       return;
6523 
6524     const int64_t ObjectSize =
6525         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6526     Value *const ObjectPtr = I.getArgOperand(1);
6527     SmallVector<const Value *, 4> Allocas;
6528     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6529 
6530     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6531            E = Allocas.end(); Object != E; ++Object) {
6532       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6533 
6534       // Could not find an Alloca.
6535       if (!LifetimeObject)
6536         continue;
6537 
6538       // First check that the Alloca is static, otherwise it won't have a
6539       // valid frame index.
6540       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6541       if (SI == FuncInfo.StaticAllocaMap.end())
6542         return;
6543 
6544       const int FrameIndex = SI->second;
6545       int64_t Offset;
6546       if (GetPointerBaseWithConstantOffset(
6547               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6548         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6549       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6550                                 Offset);
6551       DAG.setRoot(Res);
6552     }
6553     return;
6554   }
6555   case Intrinsic::invariant_start:
6556     // Discard region information.
6557     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6558     return;
6559   case Intrinsic::invariant_end:
6560     // Discard region information.
6561     return;
6562   case Intrinsic::clear_cache:
6563     /// FunctionName may be null.
6564     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6565       lowerCallToExternalSymbol(I, FunctionName);
6566     return;
6567   case Intrinsic::donothing:
6568     // ignore
6569     return;
6570   case Intrinsic::experimental_stackmap:
6571     visitStackmap(I);
6572     return;
6573   case Intrinsic::experimental_patchpoint_void:
6574   case Intrinsic::experimental_patchpoint_i64:
6575     visitPatchpoint(&I);
6576     return;
6577   case Intrinsic::experimental_gc_statepoint:
6578     LowerStatepoint(ImmutableStatepoint(&I));
6579     return;
6580   case Intrinsic::experimental_gc_result:
6581     visitGCResult(cast<GCResultInst>(I));
6582     return;
6583   case Intrinsic::experimental_gc_relocate:
6584     visitGCRelocate(cast<GCRelocateInst>(I));
6585     return;
6586   case Intrinsic::instrprof_increment:
6587     llvm_unreachable("instrprof failed to lower an increment");
6588   case Intrinsic::instrprof_value_profile:
6589     llvm_unreachable("instrprof failed to lower a value profiling call");
6590   case Intrinsic::localescape: {
6591     MachineFunction &MF = DAG.getMachineFunction();
6592     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6593 
6594     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6595     // is the same on all targets.
6596     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6597       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6598       if (isa<ConstantPointerNull>(Arg))
6599         continue; // Skip null pointers. They represent a hole in index space.
6600       AllocaInst *Slot = cast<AllocaInst>(Arg);
6601       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6602              "can only escape static allocas");
6603       int FI = FuncInfo.StaticAllocaMap[Slot];
6604       MCSymbol *FrameAllocSym =
6605           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6606               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6607       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6608               TII->get(TargetOpcode::LOCAL_ESCAPE))
6609           .addSym(FrameAllocSym)
6610           .addFrameIndex(FI);
6611     }
6612 
6613     return;
6614   }
6615 
6616   case Intrinsic::localrecover: {
6617     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6618     MachineFunction &MF = DAG.getMachineFunction();
6619     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6620 
6621     // Get the symbol that defines the frame offset.
6622     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6623     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6624     unsigned IdxVal =
6625         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6626     MCSymbol *FrameAllocSym =
6627         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6628             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6629 
6630     // Create a MCSymbol for the label to avoid any target lowering
6631     // that would make this PC relative.
6632     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6633     SDValue OffsetVal =
6634         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6635 
6636     // Add the offset to the FP.
6637     Value *FP = I.getArgOperand(1);
6638     SDValue FPVal = getValue(FP);
6639     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6640     setValue(&I, Add);
6641 
6642     return;
6643   }
6644 
6645   case Intrinsic::eh_exceptionpointer:
6646   case Intrinsic::eh_exceptioncode: {
6647     // Get the exception pointer vreg, copy from it, and resize it to fit.
6648     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6649     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6650     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6651     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6652     SDValue N =
6653         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6654     if (Intrinsic == Intrinsic::eh_exceptioncode)
6655       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6656     setValue(&I, N);
6657     return;
6658   }
6659   case Intrinsic::xray_customevent: {
6660     // Here we want to make sure that the intrinsic behaves as if it has a
6661     // specific calling convention, and only for x86_64.
6662     // FIXME: Support other platforms later.
6663     const auto &Triple = DAG.getTarget().getTargetTriple();
6664     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6665       return;
6666 
6667     SDLoc DL = getCurSDLoc();
6668     SmallVector<SDValue, 8> Ops;
6669 
6670     // We want to say that we always want the arguments in registers.
6671     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6672     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6673     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6674     SDValue Chain = getRoot();
6675     Ops.push_back(LogEntryVal);
6676     Ops.push_back(StrSizeVal);
6677     Ops.push_back(Chain);
6678 
6679     // We need to enforce the calling convention for the callsite, so that
6680     // argument ordering is enforced correctly, and that register allocation can
6681     // see that some registers may be assumed clobbered and have to preserve
6682     // them across calls to the intrinsic.
6683     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6684                                            DL, NodeTys, Ops);
6685     SDValue patchableNode = SDValue(MN, 0);
6686     DAG.setRoot(patchableNode);
6687     setValue(&I, patchableNode);
6688     return;
6689   }
6690   case Intrinsic::xray_typedevent: {
6691     // Here we want to make sure that the intrinsic behaves as if it has a
6692     // specific calling convention, and only for x86_64.
6693     // FIXME: Support other platforms later.
6694     const auto &Triple = DAG.getTarget().getTargetTriple();
6695     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6696       return;
6697 
6698     SDLoc DL = getCurSDLoc();
6699     SmallVector<SDValue, 8> Ops;
6700 
6701     // We want to say that we always want the arguments in registers.
6702     // It's unclear to me how manipulating the selection DAG here forces callers
6703     // to provide arguments in registers instead of on the stack.
6704     SDValue LogTypeId = getValue(I.getArgOperand(0));
6705     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6706     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6707     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6708     SDValue Chain = getRoot();
6709     Ops.push_back(LogTypeId);
6710     Ops.push_back(LogEntryVal);
6711     Ops.push_back(StrSizeVal);
6712     Ops.push_back(Chain);
6713 
6714     // We need to enforce the calling convention for the callsite, so that
6715     // argument ordering is enforced correctly, and that register allocation can
6716     // see that some registers may be assumed clobbered and have to preserve
6717     // them across calls to the intrinsic.
6718     MachineSDNode *MN = DAG.getMachineNode(
6719         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6720     SDValue patchableNode = SDValue(MN, 0);
6721     DAG.setRoot(patchableNode);
6722     setValue(&I, patchableNode);
6723     return;
6724   }
6725   case Intrinsic::experimental_deoptimize:
6726     LowerDeoptimizeCall(&I);
6727     return;
6728 
6729   case Intrinsic::experimental_vector_reduce_v2_fadd:
6730   case Intrinsic::experimental_vector_reduce_v2_fmul:
6731   case Intrinsic::experimental_vector_reduce_add:
6732   case Intrinsic::experimental_vector_reduce_mul:
6733   case Intrinsic::experimental_vector_reduce_and:
6734   case Intrinsic::experimental_vector_reduce_or:
6735   case Intrinsic::experimental_vector_reduce_xor:
6736   case Intrinsic::experimental_vector_reduce_smax:
6737   case Intrinsic::experimental_vector_reduce_smin:
6738   case Intrinsic::experimental_vector_reduce_umax:
6739   case Intrinsic::experimental_vector_reduce_umin:
6740   case Intrinsic::experimental_vector_reduce_fmax:
6741   case Intrinsic::experimental_vector_reduce_fmin:
6742     visitVectorReduce(I, Intrinsic);
6743     return;
6744 
6745   case Intrinsic::icall_branch_funnel: {
6746     SmallVector<SDValue, 16> Ops;
6747     Ops.push_back(DAG.getRoot());
6748     Ops.push_back(getValue(I.getArgOperand(0)));
6749 
6750     int64_t Offset;
6751     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6752         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6753     if (!Base)
6754       report_fatal_error(
6755           "llvm.icall.branch.funnel operand must be a GlobalValue");
6756     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6757 
6758     struct BranchFunnelTarget {
6759       int64_t Offset;
6760       SDValue Target;
6761     };
6762     SmallVector<BranchFunnelTarget, 8> Targets;
6763 
6764     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6765       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6766           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6767       if (ElemBase != Base)
6768         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6769                            "to the same GlobalValue");
6770 
6771       SDValue Val = getValue(I.getArgOperand(Op + 1));
6772       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6773       if (!GA)
6774         report_fatal_error(
6775             "llvm.icall.branch.funnel operand must be a GlobalValue");
6776       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6777                                      GA->getGlobal(), getCurSDLoc(),
6778                                      Val.getValueType(), GA->getOffset())});
6779     }
6780     llvm::sort(Targets,
6781                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6782                  return T1.Offset < T2.Offset;
6783                });
6784 
6785     for (auto &T : Targets) {
6786       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6787       Ops.push_back(T.Target);
6788     }
6789 
6790     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6791                                  getCurSDLoc(), MVT::Other, Ops),
6792               0);
6793     DAG.setRoot(N);
6794     setValue(&I, N);
6795     HasTailCall = true;
6796     return;
6797   }
6798 
6799   case Intrinsic::wasm_landingpad_index:
6800     // Information this intrinsic contained has been transferred to
6801     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6802     // delete it now.
6803     return;
6804   }
6805 }
6806 
6807 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6808     const ConstrainedFPIntrinsic &FPI) {
6809   SDLoc sdl = getCurSDLoc();
6810   unsigned Opcode;
6811   switch (FPI.getIntrinsicID()) {
6812   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6813   case Intrinsic::experimental_constrained_fadd:
6814     Opcode = ISD::STRICT_FADD;
6815     break;
6816   case Intrinsic::experimental_constrained_fsub:
6817     Opcode = ISD::STRICT_FSUB;
6818     break;
6819   case Intrinsic::experimental_constrained_fmul:
6820     Opcode = ISD::STRICT_FMUL;
6821     break;
6822   case Intrinsic::experimental_constrained_fdiv:
6823     Opcode = ISD::STRICT_FDIV;
6824     break;
6825   case Intrinsic::experimental_constrained_frem:
6826     Opcode = ISD::STRICT_FREM;
6827     break;
6828   case Intrinsic::experimental_constrained_fma:
6829     Opcode = ISD::STRICT_FMA;
6830     break;
6831   case Intrinsic::experimental_constrained_fptrunc:
6832     Opcode = ISD::STRICT_FP_ROUND;
6833     break;
6834   case Intrinsic::experimental_constrained_fpext:
6835     Opcode = ISD::STRICT_FP_EXTEND;
6836     break;
6837   case Intrinsic::experimental_constrained_sqrt:
6838     Opcode = ISD::STRICT_FSQRT;
6839     break;
6840   case Intrinsic::experimental_constrained_pow:
6841     Opcode = ISD::STRICT_FPOW;
6842     break;
6843   case Intrinsic::experimental_constrained_powi:
6844     Opcode = ISD::STRICT_FPOWI;
6845     break;
6846   case Intrinsic::experimental_constrained_sin:
6847     Opcode = ISD::STRICT_FSIN;
6848     break;
6849   case Intrinsic::experimental_constrained_cos:
6850     Opcode = ISD::STRICT_FCOS;
6851     break;
6852   case Intrinsic::experimental_constrained_exp:
6853     Opcode = ISD::STRICT_FEXP;
6854     break;
6855   case Intrinsic::experimental_constrained_exp2:
6856     Opcode = ISD::STRICT_FEXP2;
6857     break;
6858   case Intrinsic::experimental_constrained_log:
6859     Opcode = ISD::STRICT_FLOG;
6860     break;
6861   case Intrinsic::experimental_constrained_log10:
6862     Opcode = ISD::STRICT_FLOG10;
6863     break;
6864   case Intrinsic::experimental_constrained_log2:
6865     Opcode = ISD::STRICT_FLOG2;
6866     break;
6867   case Intrinsic::experimental_constrained_rint:
6868     Opcode = ISD::STRICT_FRINT;
6869     break;
6870   case Intrinsic::experimental_constrained_nearbyint:
6871     Opcode = ISD::STRICT_FNEARBYINT;
6872     break;
6873   case Intrinsic::experimental_constrained_maxnum:
6874     Opcode = ISD::STRICT_FMAXNUM;
6875     break;
6876   case Intrinsic::experimental_constrained_minnum:
6877     Opcode = ISD::STRICT_FMINNUM;
6878     break;
6879   case Intrinsic::experimental_constrained_ceil:
6880     Opcode = ISD::STRICT_FCEIL;
6881     break;
6882   case Intrinsic::experimental_constrained_floor:
6883     Opcode = ISD::STRICT_FFLOOR;
6884     break;
6885   case Intrinsic::experimental_constrained_round:
6886     Opcode = ISD::STRICT_FROUND;
6887     break;
6888   case Intrinsic::experimental_constrained_trunc:
6889     Opcode = ISD::STRICT_FTRUNC;
6890     break;
6891   }
6892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6893   SDValue Chain = getRoot();
6894   SmallVector<EVT, 4> ValueVTs;
6895   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6896   ValueVTs.push_back(MVT::Other); // Out chain
6897 
6898   SDVTList VTs = DAG.getVTList(ValueVTs);
6899   SDValue Result;
6900   if (Opcode == ISD::STRICT_FP_ROUND)
6901     Result = DAG.getNode(Opcode, sdl, VTs,
6902                           { Chain, getValue(FPI.getArgOperand(0)),
6903                                DAG.getTargetConstant(0, sdl,
6904                                TLI.getPointerTy(DAG.getDataLayout())) });
6905   else if (FPI.isUnaryOp())
6906     Result = DAG.getNode(Opcode, sdl, VTs,
6907                          { Chain, getValue(FPI.getArgOperand(0)) });
6908   else if (FPI.isTernaryOp())
6909     Result = DAG.getNode(Opcode, sdl, VTs,
6910                          { Chain, getValue(FPI.getArgOperand(0)),
6911                                   getValue(FPI.getArgOperand(1)),
6912                                   getValue(FPI.getArgOperand(2)) });
6913   else
6914     Result = DAG.getNode(Opcode, sdl, VTs,
6915                          { Chain, getValue(FPI.getArgOperand(0)),
6916                            getValue(FPI.getArgOperand(1))  });
6917 
6918   if (FPI.getExceptionBehavior() !=
6919       ConstrainedFPIntrinsic::ExceptionBehavior::ebIgnore) {
6920     SDNodeFlags Flags;
6921     Flags.setFPExcept(true);
6922     Result->setFlags(Flags);
6923   }
6924 
6925   assert(Result.getNode()->getNumValues() == 2);
6926   SDValue OutChain = Result.getValue(1);
6927   DAG.setRoot(OutChain);
6928   SDValue FPResult = Result.getValue(0);
6929   setValue(&FPI, FPResult);
6930 }
6931 
6932 std::pair<SDValue, SDValue>
6933 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6934                                     const BasicBlock *EHPadBB) {
6935   MachineFunction &MF = DAG.getMachineFunction();
6936   MachineModuleInfo &MMI = MF.getMMI();
6937   MCSymbol *BeginLabel = nullptr;
6938 
6939   if (EHPadBB) {
6940     // Insert a label before the invoke call to mark the try range.  This can be
6941     // used to detect deletion of the invoke via the MachineModuleInfo.
6942     BeginLabel = MMI.getContext().createTempSymbol();
6943 
6944     // For SjLj, keep track of which landing pads go with which invokes
6945     // so as to maintain the ordering of pads in the LSDA.
6946     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6947     if (CallSiteIndex) {
6948       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6949       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6950 
6951       // Now that the call site is handled, stop tracking it.
6952       MMI.setCurrentCallSite(0);
6953     }
6954 
6955     // Both PendingLoads and PendingExports must be flushed here;
6956     // this call might not return.
6957     (void)getRoot();
6958     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6959 
6960     CLI.setChain(getRoot());
6961   }
6962   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6963   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6964 
6965   assert((CLI.IsTailCall || Result.second.getNode()) &&
6966          "Non-null chain expected with non-tail call!");
6967   assert((Result.second.getNode() || !Result.first.getNode()) &&
6968          "Null value expected with tail call!");
6969 
6970   if (!Result.second.getNode()) {
6971     // As a special case, a null chain means that a tail call has been emitted
6972     // and the DAG root is already updated.
6973     HasTailCall = true;
6974 
6975     // Since there's no actual continuation from this block, nothing can be
6976     // relying on us setting vregs for them.
6977     PendingExports.clear();
6978   } else {
6979     DAG.setRoot(Result.second);
6980   }
6981 
6982   if (EHPadBB) {
6983     // Insert a label at the end of the invoke call to mark the try range.  This
6984     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6985     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6986     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6987 
6988     // Inform MachineModuleInfo of range.
6989     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6990     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6991     // actually use outlined funclets and their LSDA info style.
6992     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6993       assert(CLI.CS);
6994       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6995       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6996                                 BeginLabel, EndLabel);
6997     } else if (!isScopedEHPersonality(Pers)) {
6998       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6999     }
7000   }
7001 
7002   return Result;
7003 }
7004 
7005 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7006                                       bool isTailCall,
7007                                       const BasicBlock *EHPadBB) {
7008   auto &DL = DAG.getDataLayout();
7009   FunctionType *FTy = CS.getFunctionType();
7010   Type *RetTy = CS.getType();
7011 
7012   TargetLowering::ArgListTy Args;
7013   Args.reserve(CS.arg_size());
7014 
7015   const Value *SwiftErrorVal = nullptr;
7016   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7017 
7018   // We can't tail call inside a function with a swifterror argument. Lowering
7019   // does not support this yet. It would have to move into the swifterror
7020   // register before the call.
7021   auto *Caller = CS.getInstruction()->getParent()->getParent();
7022   if (TLI.supportSwiftError() &&
7023       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7024     isTailCall = false;
7025 
7026   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7027        i != e; ++i) {
7028     TargetLowering::ArgListEntry Entry;
7029     const Value *V = *i;
7030 
7031     // Skip empty types
7032     if (V->getType()->isEmptyTy())
7033       continue;
7034 
7035     SDValue ArgNode = getValue(V);
7036     Entry.Node = ArgNode; Entry.Ty = V->getType();
7037 
7038     Entry.setAttributes(&CS, i - CS.arg_begin());
7039 
7040     // Use swifterror virtual register as input to the call.
7041     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7042       SwiftErrorVal = V;
7043       // We find the virtual register for the actual swifterror argument.
7044       // Instead of using the Value, we use the virtual register instead.
7045       Entry.Node = DAG.getRegister(
7046           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7047           EVT(TLI.getPointerTy(DL)));
7048     }
7049 
7050     Args.push_back(Entry);
7051 
7052     // If we have an explicit sret argument that is an Instruction, (i.e., it
7053     // might point to function-local memory), we can't meaningfully tail-call.
7054     if (Entry.IsSRet && isa<Instruction>(V))
7055       isTailCall = false;
7056   }
7057 
7058   // Check if target-independent constraints permit a tail call here.
7059   // Target-dependent constraints are checked within TLI->LowerCallTo.
7060   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7061     isTailCall = false;
7062 
7063   // Disable tail calls if there is an swifterror argument. Targets have not
7064   // been updated to support tail calls.
7065   if (TLI.supportSwiftError() && SwiftErrorVal)
7066     isTailCall = false;
7067 
7068   TargetLowering::CallLoweringInfo CLI(DAG);
7069   CLI.setDebugLoc(getCurSDLoc())
7070       .setChain(getRoot())
7071       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7072       .setTailCall(isTailCall)
7073       .setConvergent(CS.isConvergent());
7074   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7075 
7076   if (Result.first.getNode()) {
7077     const Instruction *Inst = CS.getInstruction();
7078     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7079     setValue(Inst, Result.first);
7080   }
7081 
7082   // The last element of CLI.InVals has the SDValue for swifterror return.
7083   // Here we copy it to a virtual register and update SwiftErrorMap for
7084   // book-keeping.
7085   if (SwiftErrorVal && TLI.supportSwiftError()) {
7086     // Get the last element of InVals.
7087     SDValue Src = CLI.InVals.back();
7088     unsigned VReg = SwiftError.getOrCreateVRegDefAt(
7089         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7090     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7091     DAG.setRoot(CopyNode);
7092   }
7093 }
7094 
7095 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7096                              SelectionDAGBuilder &Builder) {
7097   // Check to see if this load can be trivially constant folded, e.g. if the
7098   // input is from a string literal.
7099   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7100     // Cast pointer to the type we really want to load.
7101     Type *LoadTy =
7102         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7103     if (LoadVT.isVector())
7104       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7105 
7106     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7107                                          PointerType::getUnqual(LoadTy));
7108 
7109     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7110             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7111       return Builder.getValue(LoadCst);
7112   }
7113 
7114   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7115   // still constant memory, the input chain can be the entry node.
7116   SDValue Root;
7117   bool ConstantMemory = false;
7118 
7119   // Do not serialize (non-volatile) loads of constant memory with anything.
7120   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7121     Root = Builder.DAG.getEntryNode();
7122     ConstantMemory = true;
7123   } else {
7124     // Do not serialize non-volatile loads against each other.
7125     Root = Builder.DAG.getRoot();
7126   }
7127 
7128   SDValue Ptr = Builder.getValue(PtrVal);
7129   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7130                                         Ptr, MachinePointerInfo(PtrVal),
7131                                         /* Alignment = */ 1);
7132 
7133   if (!ConstantMemory)
7134     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7135   return LoadVal;
7136 }
7137 
7138 /// Record the value for an instruction that produces an integer result,
7139 /// converting the type where necessary.
7140 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7141                                                   SDValue Value,
7142                                                   bool IsSigned) {
7143   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7144                                                     I.getType(), true);
7145   if (IsSigned)
7146     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7147   else
7148     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7149   setValue(&I, Value);
7150 }
7151 
7152 /// See if we can lower a memcmp call into an optimized form. If so, return
7153 /// true and lower it. Otherwise return false, and it will be lowered like a
7154 /// normal call.
7155 /// The caller already checked that \p I calls the appropriate LibFunc with a
7156 /// correct prototype.
7157 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7158   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7159   const Value *Size = I.getArgOperand(2);
7160   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7161   if (CSize && CSize->getZExtValue() == 0) {
7162     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7163                                                           I.getType(), true);
7164     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7165     return true;
7166   }
7167 
7168   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7169   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7170       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7171       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7172   if (Res.first.getNode()) {
7173     processIntegerCallValue(I, Res.first, true);
7174     PendingLoads.push_back(Res.second);
7175     return true;
7176   }
7177 
7178   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7179   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7180   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7181     return false;
7182 
7183   // If the target has a fast compare for the given size, it will return a
7184   // preferred load type for that size. Require that the load VT is legal and
7185   // that the target supports unaligned loads of that type. Otherwise, return
7186   // INVALID.
7187   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7188     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7189     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7190     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7191       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7192       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7193       // TODO: Check alignment of src and dest ptrs.
7194       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7195       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7196       if (!TLI.isTypeLegal(LVT) ||
7197           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7198           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7199         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7200     }
7201 
7202     return LVT;
7203   };
7204 
7205   // This turns into unaligned loads. We only do this if the target natively
7206   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7207   // we'll only produce a small number of byte loads.
7208   MVT LoadVT;
7209   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7210   switch (NumBitsToCompare) {
7211   default:
7212     return false;
7213   case 16:
7214     LoadVT = MVT::i16;
7215     break;
7216   case 32:
7217     LoadVT = MVT::i32;
7218     break;
7219   case 64:
7220   case 128:
7221   case 256:
7222     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7223     break;
7224   }
7225 
7226   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7227     return false;
7228 
7229   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7230   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7231 
7232   // Bitcast to a wide integer type if the loads are vectors.
7233   if (LoadVT.isVector()) {
7234     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7235     LoadL = DAG.getBitcast(CmpVT, LoadL);
7236     LoadR = DAG.getBitcast(CmpVT, LoadR);
7237   }
7238 
7239   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7240   processIntegerCallValue(I, Cmp, false);
7241   return true;
7242 }
7243 
7244 /// See if we can lower a memchr call into an optimized form. If so, return
7245 /// true and lower it. Otherwise return false, and it will be lowered like a
7246 /// normal call.
7247 /// The caller already checked that \p I calls the appropriate LibFunc with a
7248 /// correct prototype.
7249 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7250   const Value *Src = I.getArgOperand(0);
7251   const Value *Char = I.getArgOperand(1);
7252   const Value *Length = I.getArgOperand(2);
7253 
7254   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7255   std::pair<SDValue, SDValue> Res =
7256     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7257                                 getValue(Src), getValue(Char), getValue(Length),
7258                                 MachinePointerInfo(Src));
7259   if (Res.first.getNode()) {
7260     setValue(&I, Res.first);
7261     PendingLoads.push_back(Res.second);
7262     return true;
7263   }
7264 
7265   return false;
7266 }
7267 
7268 /// See if we can lower a mempcpy call into an optimized form. If so, return
7269 /// true and lower it. Otherwise return false, and it will be lowered like a
7270 /// normal call.
7271 /// The caller already checked that \p I calls the appropriate LibFunc with a
7272 /// correct prototype.
7273 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7274   SDValue Dst = getValue(I.getArgOperand(0));
7275   SDValue Src = getValue(I.getArgOperand(1));
7276   SDValue Size = getValue(I.getArgOperand(2));
7277 
7278   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7279   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7280   unsigned Align = std::min(DstAlign, SrcAlign);
7281   if (Align == 0) // Alignment of one or both could not be inferred.
7282     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7283 
7284   bool isVol = false;
7285   SDLoc sdl = getCurSDLoc();
7286 
7287   // In the mempcpy context we need to pass in a false value for isTailCall
7288   // because the return pointer needs to be adjusted by the size of
7289   // the copied memory.
7290   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7291                              false, /*isTailCall=*/false,
7292                              MachinePointerInfo(I.getArgOperand(0)),
7293                              MachinePointerInfo(I.getArgOperand(1)));
7294   assert(MC.getNode() != nullptr &&
7295          "** memcpy should not be lowered as TailCall in mempcpy context **");
7296   DAG.setRoot(MC);
7297 
7298   // Check if Size needs to be truncated or extended.
7299   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7300 
7301   // Adjust return pointer to point just past the last dst byte.
7302   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7303                                     Dst, Size);
7304   setValue(&I, DstPlusSize);
7305   return true;
7306 }
7307 
7308 /// See if we can lower a strcpy call into an optimized form.  If so, return
7309 /// true and lower it, otherwise return false and it will be lowered like a
7310 /// normal call.
7311 /// The caller already checked that \p I calls the appropriate LibFunc with a
7312 /// correct prototype.
7313 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7314   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7315 
7316   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7317   std::pair<SDValue, SDValue> Res =
7318     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7319                                 getValue(Arg0), getValue(Arg1),
7320                                 MachinePointerInfo(Arg0),
7321                                 MachinePointerInfo(Arg1), isStpcpy);
7322   if (Res.first.getNode()) {
7323     setValue(&I, Res.first);
7324     DAG.setRoot(Res.second);
7325     return true;
7326   }
7327 
7328   return false;
7329 }
7330 
7331 /// See if we can lower a strcmp call into an optimized form.  If so, return
7332 /// true and lower it, otherwise return false and it will be lowered like a
7333 /// normal call.
7334 /// The caller already checked that \p I calls the appropriate LibFunc with a
7335 /// correct prototype.
7336 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7337   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7338 
7339   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7340   std::pair<SDValue, SDValue> Res =
7341     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7342                                 getValue(Arg0), getValue(Arg1),
7343                                 MachinePointerInfo(Arg0),
7344                                 MachinePointerInfo(Arg1));
7345   if (Res.first.getNode()) {
7346     processIntegerCallValue(I, Res.first, true);
7347     PendingLoads.push_back(Res.second);
7348     return true;
7349   }
7350 
7351   return false;
7352 }
7353 
7354 /// See if we can lower a strlen call into an optimized form.  If so, return
7355 /// true and lower it, otherwise return false and it will be lowered like a
7356 /// normal call.
7357 /// The caller already checked that \p I calls the appropriate LibFunc with a
7358 /// correct prototype.
7359 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7360   const Value *Arg0 = I.getArgOperand(0);
7361 
7362   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7363   std::pair<SDValue, SDValue> Res =
7364     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7365                                 getValue(Arg0), MachinePointerInfo(Arg0));
7366   if (Res.first.getNode()) {
7367     processIntegerCallValue(I, Res.first, false);
7368     PendingLoads.push_back(Res.second);
7369     return true;
7370   }
7371 
7372   return false;
7373 }
7374 
7375 /// See if we can lower a strnlen call into an optimized form.  If so, return
7376 /// true and lower it, otherwise return false and it will be lowered like a
7377 /// normal call.
7378 /// The caller already checked that \p I calls the appropriate LibFunc with a
7379 /// correct prototype.
7380 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7381   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7382 
7383   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7384   std::pair<SDValue, SDValue> Res =
7385     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7386                                  getValue(Arg0), getValue(Arg1),
7387                                  MachinePointerInfo(Arg0));
7388   if (Res.first.getNode()) {
7389     processIntegerCallValue(I, Res.first, false);
7390     PendingLoads.push_back(Res.second);
7391     return true;
7392   }
7393 
7394   return false;
7395 }
7396 
7397 /// See if we can lower a unary floating-point operation into an SDNode with
7398 /// the specified Opcode.  If so, return true and lower it, otherwise return
7399 /// false and it will be lowered like a normal call.
7400 /// The caller already checked that \p I calls the appropriate LibFunc with a
7401 /// correct prototype.
7402 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7403                                               unsigned Opcode) {
7404   // We already checked this call's prototype; verify it doesn't modify errno.
7405   if (!I.onlyReadsMemory())
7406     return false;
7407 
7408   SDValue Tmp = getValue(I.getArgOperand(0));
7409   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7410   return true;
7411 }
7412 
7413 /// See if we can lower a binary floating-point operation into an SDNode with
7414 /// the specified Opcode. If so, return true and lower it. Otherwise return
7415 /// false, and it will be lowered like a normal call.
7416 /// The caller already checked that \p I calls the appropriate LibFunc with a
7417 /// correct prototype.
7418 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7419                                                unsigned Opcode) {
7420   // We already checked this call's prototype; verify it doesn't modify errno.
7421   if (!I.onlyReadsMemory())
7422     return false;
7423 
7424   SDValue Tmp0 = getValue(I.getArgOperand(0));
7425   SDValue Tmp1 = getValue(I.getArgOperand(1));
7426   EVT VT = Tmp0.getValueType();
7427   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7428   return true;
7429 }
7430 
7431 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7432   // Handle inline assembly differently.
7433   if (isa<InlineAsm>(I.getCalledValue())) {
7434     visitInlineAsm(&I);
7435     return;
7436   }
7437 
7438   if (Function *F = I.getCalledFunction()) {
7439     if (F->isDeclaration()) {
7440       // Is this an LLVM intrinsic or a target-specific intrinsic?
7441       unsigned IID = F->getIntrinsicID();
7442       if (!IID)
7443         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7444           IID = II->getIntrinsicID(F);
7445 
7446       if (IID) {
7447         visitIntrinsicCall(I, IID);
7448         return;
7449       }
7450     }
7451 
7452     // Check for well-known libc/libm calls.  If the function is internal, it
7453     // can't be a library call.  Don't do the check if marked as nobuiltin for
7454     // some reason or the call site requires strict floating point semantics.
7455     LibFunc Func;
7456     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7457         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7458         LibInfo->hasOptimizedCodeGen(Func)) {
7459       switch (Func) {
7460       default: break;
7461       case LibFunc_copysign:
7462       case LibFunc_copysignf:
7463       case LibFunc_copysignl:
7464         // We already checked this call's prototype; verify it doesn't modify
7465         // errno.
7466         if (I.onlyReadsMemory()) {
7467           SDValue LHS = getValue(I.getArgOperand(0));
7468           SDValue RHS = getValue(I.getArgOperand(1));
7469           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7470                                    LHS.getValueType(), LHS, RHS));
7471           return;
7472         }
7473         break;
7474       case LibFunc_fabs:
7475       case LibFunc_fabsf:
7476       case LibFunc_fabsl:
7477         if (visitUnaryFloatCall(I, ISD::FABS))
7478           return;
7479         break;
7480       case LibFunc_fmin:
7481       case LibFunc_fminf:
7482       case LibFunc_fminl:
7483         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7484           return;
7485         break;
7486       case LibFunc_fmax:
7487       case LibFunc_fmaxf:
7488       case LibFunc_fmaxl:
7489         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7490           return;
7491         break;
7492       case LibFunc_sin:
7493       case LibFunc_sinf:
7494       case LibFunc_sinl:
7495         if (visitUnaryFloatCall(I, ISD::FSIN))
7496           return;
7497         break;
7498       case LibFunc_cos:
7499       case LibFunc_cosf:
7500       case LibFunc_cosl:
7501         if (visitUnaryFloatCall(I, ISD::FCOS))
7502           return;
7503         break;
7504       case LibFunc_sqrt:
7505       case LibFunc_sqrtf:
7506       case LibFunc_sqrtl:
7507       case LibFunc_sqrt_finite:
7508       case LibFunc_sqrtf_finite:
7509       case LibFunc_sqrtl_finite:
7510         if (visitUnaryFloatCall(I, ISD::FSQRT))
7511           return;
7512         break;
7513       case LibFunc_floor:
7514       case LibFunc_floorf:
7515       case LibFunc_floorl:
7516         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7517           return;
7518         break;
7519       case LibFunc_nearbyint:
7520       case LibFunc_nearbyintf:
7521       case LibFunc_nearbyintl:
7522         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7523           return;
7524         break;
7525       case LibFunc_ceil:
7526       case LibFunc_ceilf:
7527       case LibFunc_ceill:
7528         if (visitUnaryFloatCall(I, ISD::FCEIL))
7529           return;
7530         break;
7531       case LibFunc_rint:
7532       case LibFunc_rintf:
7533       case LibFunc_rintl:
7534         if (visitUnaryFloatCall(I, ISD::FRINT))
7535           return;
7536         break;
7537       case LibFunc_round:
7538       case LibFunc_roundf:
7539       case LibFunc_roundl:
7540         if (visitUnaryFloatCall(I, ISD::FROUND))
7541           return;
7542         break;
7543       case LibFunc_trunc:
7544       case LibFunc_truncf:
7545       case LibFunc_truncl:
7546         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7547           return;
7548         break;
7549       case LibFunc_log2:
7550       case LibFunc_log2f:
7551       case LibFunc_log2l:
7552         if (visitUnaryFloatCall(I, ISD::FLOG2))
7553           return;
7554         break;
7555       case LibFunc_exp2:
7556       case LibFunc_exp2f:
7557       case LibFunc_exp2l:
7558         if (visitUnaryFloatCall(I, ISD::FEXP2))
7559           return;
7560         break;
7561       case LibFunc_memcmp:
7562         if (visitMemCmpCall(I))
7563           return;
7564         break;
7565       case LibFunc_mempcpy:
7566         if (visitMemPCpyCall(I))
7567           return;
7568         break;
7569       case LibFunc_memchr:
7570         if (visitMemChrCall(I))
7571           return;
7572         break;
7573       case LibFunc_strcpy:
7574         if (visitStrCpyCall(I, false))
7575           return;
7576         break;
7577       case LibFunc_stpcpy:
7578         if (visitStrCpyCall(I, true))
7579           return;
7580         break;
7581       case LibFunc_strcmp:
7582         if (visitStrCmpCall(I))
7583           return;
7584         break;
7585       case LibFunc_strlen:
7586         if (visitStrLenCall(I))
7587           return;
7588         break;
7589       case LibFunc_strnlen:
7590         if (visitStrNLenCall(I))
7591           return;
7592         break;
7593       }
7594     }
7595   }
7596 
7597   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7598   // have to do anything here to lower funclet bundles.
7599   assert(!I.hasOperandBundlesOtherThan(
7600              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7601          "Cannot lower calls with arbitrary operand bundles!");
7602 
7603   SDValue Callee = getValue(I.getCalledValue());
7604 
7605   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7606     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7607   else
7608     // Check if we can potentially perform a tail call. More detailed checking
7609     // is be done within LowerCallTo, after more information about the call is
7610     // known.
7611     LowerCallTo(&I, Callee, I.isTailCall());
7612 }
7613 
7614 namespace {
7615 
7616 /// AsmOperandInfo - This contains information for each constraint that we are
7617 /// lowering.
7618 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7619 public:
7620   /// CallOperand - If this is the result output operand or a clobber
7621   /// this is null, otherwise it is the incoming operand to the CallInst.
7622   /// This gets modified as the asm is processed.
7623   SDValue CallOperand;
7624 
7625   /// AssignedRegs - If this is a register or register class operand, this
7626   /// contains the set of register corresponding to the operand.
7627   RegsForValue AssignedRegs;
7628 
7629   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7630     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7631   }
7632 
7633   /// Whether or not this operand accesses memory
7634   bool hasMemory(const TargetLowering &TLI) const {
7635     // Indirect operand accesses access memory.
7636     if (isIndirect)
7637       return true;
7638 
7639     for (const auto &Code : Codes)
7640       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7641         return true;
7642 
7643     return false;
7644   }
7645 
7646   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7647   /// corresponds to.  If there is no Value* for this operand, it returns
7648   /// MVT::Other.
7649   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7650                            const DataLayout &DL) const {
7651     if (!CallOperandVal) return MVT::Other;
7652 
7653     if (isa<BasicBlock>(CallOperandVal))
7654       return TLI.getPointerTy(DL);
7655 
7656     llvm::Type *OpTy = CallOperandVal->getType();
7657 
7658     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7659     // If this is an indirect operand, the operand is a pointer to the
7660     // accessed type.
7661     if (isIndirect) {
7662       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7663       if (!PtrTy)
7664         report_fatal_error("Indirect operand for inline asm not a pointer!");
7665       OpTy = PtrTy->getElementType();
7666     }
7667 
7668     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7669     if (StructType *STy = dyn_cast<StructType>(OpTy))
7670       if (STy->getNumElements() == 1)
7671         OpTy = STy->getElementType(0);
7672 
7673     // If OpTy is not a single value, it may be a struct/union that we
7674     // can tile with integers.
7675     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7676       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7677       switch (BitSize) {
7678       default: break;
7679       case 1:
7680       case 8:
7681       case 16:
7682       case 32:
7683       case 64:
7684       case 128:
7685         OpTy = IntegerType::get(Context, BitSize);
7686         break;
7687       }
7688     }
7689 
7690     return TLI.getValueType(DL, OpTy, true);
7691   }
7692 };
7693 
7694 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7695 
7696 } // end anonymous namespace
7697 
7698 /// Make sure that the output operand \p OpInfo and its corresponding input
7699 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7700 /// out).
7701 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7702                                SDISelAsmOperandInfo &MatchingOpInfo,
7703                                SelectionDAG &DAG) {
7704   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7705     return;
7706 
7707   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7708   const auto &TLI = DAG.getTargetLoweringInfo();
7709 
7710   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7711       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7712                                        OpInfo.ConstraintVT);
7713   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7714       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7715                                        MatchingOpInfo.ConstraintVT);
7716   if ((OpInfo.ConstraintVT.isInteger() !=
7717        MatchingOpInfo.ConstraintVT.isInteger()) ||
7718       (MatchRC.second != InputRC.second)) {
7719     // FIXME: error out in a more elegant fashion
7720     report_fatal_error("Unsupported asm: input constraint"
7721                        " with a matching output constraint of"
7722                        " incompatible type!");
7723   }
7724   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7725 }
7726 
7727 /// Get a direct memory input to behave well as an indirect operand.
7728 /// This may introduce stores, hence the need for a \p Chain.
7729 /// \return The (possibly updated) chain.
7730 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7731                                         SDISelAsmOperandInfo &OpInfo,
7732                                         SelectionDAG &DAG) {
7733   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7734 
7735   // If we don't have an indirect input, put it in the constpool if we can,
7736   // otherwise spill it to a stack slot.
7737   // TODO: This isn't quite right. We need to handle these according to
7738   // the addressing mode that the constraint wants. Also, this may take
7739   // an additional register for the computation and we don't want that
7740   // either.
7741 
7742   // If the operand is a float, integer, or vector constant, spill to a
7743   // constant pool entry to get its address.
7744   const Value *OpVal = OpInfo.CallOperandVal;
7745   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7746       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7747     OpInfo.CallOperand = DAG.getConstantPool(
7748         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7749     return Chain;
7750   }
7751 
7752   // Otherwise, create a stack slot and emit a store to it before the asm.
7753   Type *Ty = OpVal->getType();
7754   auto &DL = DAG.getDataLayout();
7755   uint64_t TySize = DL.getTypeAllocSize(Ty);
7756   unsigned Align = DL.getPrefTypeAlignment(Ty);
7757   MachineFunction &MF = DAG.getMachineFunction();
7758   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7759   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7760   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7761                             MachinePointerInfo::getFixedStack(MF, SSFI),
7762                             TLI.getMemValueType(DL, Ty));
7763   OpInfo.CallOperand = StackSlot;
7764 
7765   return Chain;
7766 }
7767 
7768 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7769 /// specified operand.  We prefer to assign virtual registers, to allow the
7770 /// register allocator to handle the assignment process.  However, if the asm
7771 /// uses features that we can't model on machineinstrs, we have SDISel do the
7772 /// allocation.  This produces generally horrible, but correct, code.
7773 ///
7774 ///   OpInfo describes the operand
7775 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7776 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7777                                  SDISelAsmOperandInfo &OpInfo,
7778                                  SDISelAsmOperandInfo &RefOpInfo) {
7779   LLVMContext &Context = *DAG.getContext();
7780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7781 
7782   MachineFunction &MF = DAG.getMachineFunction();
7783   SmallVector<unsigned, 4> Regs;
7784   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7785 
7786   // No work to do for memory operations.
7787   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7788     return;
7789 
7790   // If this is a constraint for a single physreg, or a constraint for a
7791   // register class, find it.
7792   unsigned AssignedReg;
7793   const TargetRegisterClass *RC;
7794   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7795       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7796   // RC is unset only on failure. Return immediately.
7797   if (!RC)
7798     return;
7799 
7800   // Get the actual register value type.  This is important, because the user
7801   // may have asked for (e.g.) the AX register in i32 type.  We need to
7802   // remember that AX is actually i16 to get the right extension.
7803   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7804 
7805   if (OpInfo.ConstraintVT != MVT::Other) {
7806     // If this is an FP operand in an integer register (or visa versa), or more
7807     // generally if the operand value disagrees with the register class we plan
7808     // to stick it in, fix the operand type.
7809     //
7810     // If this is an input value, the bitcast to the new type is done now.
7811     // Bitcast for output value is done at the end of visitInlineAsm().
7812     if ((OpInfo.Type == InlineAsm::isOutput ||
7813          OpInfo.Type == InlineAsm::isInput) &&
7814         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7815       // Try to convert to the first EVT that the reg class contains.  If the
7816       // types are identical size, use a bitcast to convert (e.g. two differing
7817       // vector types).  Note: output bitcast is done at the end of
7818       // visitInlineAsm().
7819       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7820         // Exclude indirect inputs while they are unsupported because the code
7821         // to perform the load is missing and thus OpInfo.CallOperand still
7822         // refers to the input address rather than the pointed-to value.
7823         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7824           OpInfo.CallOperand =
7825               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7826         OpInfo.ConstraintVT = RegVT;
7827         // If the operand is an FP value and we want it in integer registers,
7828         // use the corresponding integer type. This turns an f64 value into
7829         // i64, which can be passed with two i32 values on a 32-bit machine.
7830       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7831         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7832         if (OpInfo.Type == InlineAsm::isInput)
7833           OpInfo.CallOperand =
7834               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7835         OpInfo.ConstraintVT = VT;
7836       }
7837     }
7838   }
7839 
7840   // No need to allocate a matching input constraint since the constraint it's
7841   // matching to has already been allocated.
7842   if (OpInfo.isMatchingInputConstraint())
7843     return;
7844 
7845   EVT ValueVT = OpInfo.ConstraintVT;
7846   if (OpInfo.ConstraintVT == MVT::Other)
7847     ValueVT = RegVT;
7848 
7849   // Initialize NumRegs.
7850   unsigned NumRegs = 1;
7851   if (OpInfo.ConstraintVT != MVT::Other)
7852     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7853 
7854   // If this is a constraint for a specific physical register, like {r17},
7855   // assign it now.
7856 
7857   // If this associated to a specific register, initialize iterator to correct
7858   // place. If virtual, make sure we have enough registers
7859 
7860   // Initialize iterator if necessary
7861   TargetRegisterClass::iterator I = RC->begin();
7862   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7863 
7864   // Do not check for single registers.
7865   if (AssignedReg) {
7866       for (; *I != AssignedReg; ++I)
7867         assert(I != RC->end() && "AssignedReg should be member of RC");
7868   }
7869 
7870   for (; NumRegs; --NumRegs, ++I) {
7871     assert(I != RC->end() && "Ran out of registers to allocate!");
7872     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7873     Regs.push_back(R);
7874   }
7875 
7876   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7877 }
7878 
7879 static unsigned
7880 findMatchingInlineAsmOperand(unsigned OperandNo,
7881                              const std::vector<SDValue> &AsmNodeOperands) {
7882   // Scan until we find the definition we already emitted of this operand.
7883   unsigned CurOp = InlineAsm::Op_FirstOperand;
7884   for (; OperandNo; --OperandNo) {
7885     // Advance to the next operand.
7886     unsigned OpFlag =
7887         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7888     assert((InlineAsm::isRegDefKind(OpFlag) ||
7889             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7890             InlineAsm::isMemKind(OpFlag)) &&
7891            "Skipped past definitions?");
7892     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7893   }
7894   return CurOp;
7895 }
7896 
7897 namespace {
7898 
7899 class ExtraFlags {
7900   unsigned Flags = 0;
7901 
7902 public:
7903   explicit ExtraFlags(ImmutableCallSite CS) {
7904     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7905     if (IA->hasSideEffects())
7906       Flags |= InlineAsm::Extra_HasSideEffects;
7907     if (IA->isAlignStack())
7908       Flags |= InlineAsm::Extra_IsAlignStack;
7909     if (CS.isConvergent())
7910       Flags |= InlineAsm::Extra_IsConvergent;
7911     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7912   }
7913 
7914   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7915     // Ideally, we would only check against memory constraints.  However, the
7916     // meaning of an Other constraint can be target-specific and we can't easily
7917     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7918     // for Other constraints as well.
7919     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7920         OpInfo.ConstraintType == TargetLowering::C_Other) {
7921       if (OpInfo.Type == InlineAsm::isInput)
7922         Flags |= InlineAsm::Extra_MayLoad;
7923       else if (OpInfo.Type == InlineAsm::isOutput)
7924         Flags |= InlineAsm::Extra_MayStore;
7925       else if (OpInfo.Type == InlineAsm::isClobber)
7926         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7927     }
7928   }
7929 
7930   unsigned get() const { return Flags; }
7931 };
7932 
7933 } // end anonymous namespace
7934 
7935 /// visitInlineAsm - Handle a call to an InlineAsm object.
7936 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7937   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7938 
7939   /// ConstraintOperands - Information about all of the constraints.
7940   SDISelAsmOperandInfoVector ConstraintOperands;
7941 
7942   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7943   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7944       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7945 
7946   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7947   // AsmDialect, MayLoad, MayStore).
7948   bool HasSideEffect = IA->hasSideEffects();
7949   ExtraFlags ExtraInfo(CS);
7950 
7951   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7952   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7953   for (auto &T : TargetConstraints) {
7954     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7955     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7956 
7957     // Compute the value type for each operand.
7958     if (OpInfo.Type == InlineAsm::isInput ||
7959         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7960       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7961 
7962       // Process the call argument. BasicBlocks are labels, currently appearing
7963       // only in asm's.
7964       const Instruction *I = CS.getInstruction();
7965       if (isa<CallBrInst>(I) &&
7966           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
7967                           cast<CallBrInst>(I)->getNumIndirectDests())) {
7968         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
7969         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
7970         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
7971       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7972         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7973       } else {
7974         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7975       }
7976 
7977       OpInfo.ConstraintVT =
7978           OpInfo
7979               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7980               .getSimpleVT();
7981     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7982       // The return value of the call is this value.  As such, there is no
7983       // corresponding argument.
7984       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7985       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7986         OpInfo.ConstraintVT = TLI.getSimpleValueType(
7987             DAG.getDataLayout(), STy->getElementType(ResNo));
7988       } else {
7989         assert(ResNo == 0 && "Asm only has one result!");
7990         OpInfo.ConstraintVT =
7991             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7992       }
7993       ++ResNo;
7994     } else {
7995       OpInfo.ConstraintVT = MVT::Other;
7996     }
7997 
7998     if (!HasSideEffect)
7999       HasSideEffect = OpInfo.hasMemory(TLI);
8000 
8001     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8002     // FIXME: Could we compute this on OpInfo rather than T?
8003 
8004     // Compute the constraint code and ConstraintType to use.
8005     TLI.ComputeConstraintToUse(T, SDValue());
8006 
8007     ExtraInfo.update(T);
8008   }
8009 
8010 
8011   // We won't need to flush pending loads if this asm doesn't touch
8012   // memory and is nonvolatile.
8013   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8014 
8015   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8016   if (IsCallBr) {
8017     // If this is a callbr we need to flush pending exports since inlineasm_br
8018     // is a terminator. We need to do this before nodes are glued to
8019     // the inlineasm_br node.
8020     Chain = getControlRoot();
8021   }
8022 
8023   // Second pass over the constraints: compute which constraint option to use.
8024   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8025     // If this is an output operand with a matching input operand, look up the
8026     // matching input. If their types mismatch, e.g. one is an integer, the
8027     // other is floating point, or their sizes are different, flag it as an
8028     // error.
8029     if (OpInfo.hasMatchingInput()) {
8030       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8031       patchMatchingInput(OpInfo, Input, DAG);
8032     }
8033 
8034     // Compute the constraint code and ConstraintType to use.
8035     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8036 
8037     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8038         OpInfo.Type == InlineAsm::isClobber)
8039       continue;
8040 
8041     // If this is a memory input, and if the operand is not indirect, do what we
8042     // need to provide an address for the memory input.
8043     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8044         !OpInfo.isIndirect) {
8045       assert((OpInfo.isMultipleAlternative ||
8046               (OpInfo.Type == InlineAsm::isInput)) &&
8047              "Can only indirectify direct input operands!");
8048 
8049       // Memory operands really want the address of the value.
8050       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8051 
8052       // There is no longer a Value* corresponding to this operand.
8053       OpInfo.CallOperandVal = nullptr;
8054 
8055       // It is now an indirect operand.
8056       OpInfo.isIndirect = true;
8057     }
8058 
8059   }
8060 
8061   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8062   std::vector<SDValue> AsmNodeOperands;
8063   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8064   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8065       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8066 
8067   // If we have a !srcloc metadata node associated with it, we want to attach
8068   // this to the ultimately generated inline asm machineinstr.  To do this, we
8069   // pass in the third operand as this (potentially null) inline asm MDNode.
8070   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8071   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8072 
8073   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8074   // bits as operand 3.
8075   AsmNodeOperands.push_back(DAG.getTargetConstant(
8076       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8077 
8078   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8079   // this, assign virtual and physical registers for inputs and otput.
8080   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8081     // Assign Registers.
8082     SDISelAsmOperandInfo &RefOpInfo =
8083         OpInfo.isMatchingInputConstraint()
8084             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8085             : OpInfo;
8086     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8087 
8088     switch (OpInfo.Type) {
8089     case InlineAsm::isOutput:
8090       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8091           (OpInfo.ConstraintType == TargetLowering::C_Other &&
8092            OpInfo.isIndirect)) {
8093         unsigned ConstraintID =
8094             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8095         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8096                "Failed to convert memory constraint code to constraint id.");
8097 
8098         // Add information to the INLINEASM node to know about this output.
8099         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8100         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8101         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8102                                                         MVT::i32));
8103         AsmNodeOperands.push_back(OpInfo.CallOperand);
8104         break;
8105       } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
8106                   !OpInfo.isIndirect) ||
8107                  OpInfo.ConstraintType == TargetLowering::C_Register ||
8108                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
8109         // Otherwise, this outputs to a register (directly for C_Register /
8110         // C_RegisterClass, and a target-defined fashion for C_Other). Find a
8111         // register that we can use.
8112         if (OpInfo.AssignedRegs.Regs.empty()) {
8113           emitInlineAsmError(
8114               CS, "couldn't allocate output register for constraint '" +
8115                       Twine(OpInfo.ConstraintCode) + "'");
8116           return;
8117         }
8118 
8119         // Add information to the INLINEASM node to know that this register is
8120         // set.
8121         OpInfo.AssignedRegs.AddInlineAsmOperands(
8122             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8123                                   : InlineAsm::Kind_RegDef,
8124             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8125       }
8126       break;
8127 
8128     case InlineAsm::isInput: {
8129       SDValue InOperandVal = OpInfo.CallOperand;
8130 
8131       if (OpInfo.isMatchingInputConstraint()) {
8132         // If this is required to match an output register we have already set,
8133         // just use its register.
8134         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8135                                                   AsmNodeOperands);
8136         unsigned OpFlag =
8137           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8138         if (InlineAsm::isRegDefKind(OpFlag) ||
8139             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8140           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8141           if (OpInfo.isIndirect) {
8142             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8143             emitInlineAsmError(CS, "inline asm not supported yet:"
8144                                    " don't know how to handle tied "
8145                                    "indirect register inputs");
8146             return;
8147           }
8148 
8149           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8150           SmallVector<unsigned, 4> Regs;
8151 
8152           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8153             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8154             MachineRegisterInfo &RegInfo =
8155                 DAG.getMachineFunction().getRegInfo();
8156             for (unsigned i = 0; i != NumRegs; ++i)
8157               Regs.push_back(RegInfo.createVirtualRegister(RC));
8158           } else {
8159             emitInlineAsmError(CS, "inline asm error: This value type register "
8160                                    "class is not natively supported!");
8161             return;
8162           }
8163 
8164           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8165 
8166           SDLoc dl = getCurSDLoc();
8167           // Use the produced MatchedRegs object to
8168           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8169                                     CS.getInstruction());
8170           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8171                                            true, OpInfo.getMatchedOperand(), dl,
8172                                            DAG, AsmNodeOperands);
8173           break;
8174         }
8175 
8176         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8177         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8178                "Unexpected number of operands");
8179         // Add information to the INLINEASM node to know about this input.
8180         // See InlineAsm.h isUseOperandTiedToDef.
8181         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8182         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8183                                                     OpInfo.getMatchedOperand());
8184         AsmNodeOperands.push_back(DAG.getTargetConstant(
8185             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8186         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8187         break;
8188       }
8189 
8190       // Treat indirect 'X' constraint as memory.
8191       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8192           OpInfo.isIndirect)
8193         OpInfo.ConstraintType = TargetLowering::C_Memory;
8194 
8195       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
8196         std::vector<SDValue> Ops;
8197         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8198                                           Ops, DAG);
8199         if (Ops.empty()) {
8200           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8201                                      Twine(OpInfo.ConstraintCode) + "'");
8202           return;
8203         }
8204 
8205         // Add information to the INLINEASM node to know about this input.
8206         unsigned ResOpType =
8207           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8208         AsmNodeOperands.push_back(DAG.getTargetConstant(
8209             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8210         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8211         break;
8212       }
8213 
8214       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8215         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8216         assert(InOperandVal.getValueType() ==
8217                    TLI.getPointerTy(DAG.getDataLayout()) &&
8218                "Memory operands expect pointer values");
8219 
8220         unsigned ConstraintID =
8221             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8222         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8223                "Failed to convert memory constraint code to constraint id.");
8224 
8225         // Add information to the INLINEASM node to know about this input.
8226         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8227         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8228         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8229                                                         getCurSDLoc(),
8230                                                         MVT::i32));
8231         AsmNodeOperands.push_back(InOperandVal);
8232         break;
8233       }
8234 
8235       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8236               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8237              "Unknown constraint type!");
8238 
8239       // TODO: Support this.
8240       if (OpInfo.isIndirect) {
8241         emitInlineAsmError(
8242             CS, "Don't know how to handle indirect register inputs yet "
8243                 "for constraint '" +
8244                     Twine(OpInfo.ConstraintCode) + "'");
8245         return;
8246       }
8247 
8248       // Copy the input into the appropriate registers.
8249       if (OpInfo.AssignedRegs.Regs.empty()) {
8250         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8251                                    Twine(OpInfo.ConstraintCode) + "'");
8252         return;
8253       }
8254 
8255       SDLoc dl = getCurSDLoc();
8256 
8257       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8258                                         Chain, &Flag, CS.getInstruction());
8259 
8260       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8261                                                dl, DAG, AsmNodeOperands);
8262       break;
8263     }
8264     case InlineAsm::isClobber:
8265       // Add the clobbered value to the operand list, so that the register
8266       // allocator is aware that the physreg got clobbered.
8267       if (!OpInfo.AssignedRegs.Regs.empty())
8268         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8269                                                  false, 0, getCurSDLoc(), DAG,
8270                                                  AsmNodeOperands);
8271       break;
8272     }
8273   }
8274 
8275   // Finish up input operands.  Set the input chain and add the flag last.
8276   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8277   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8278 
8279   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8280   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8281                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8282   Flag = Chain.getValue(1);
8283 
8284   // Do additional work to generate outputs.
8285 
8286   SmallVector<EVT, 1> ResultVTs;
8287   SmallVector<SDValue, 1> ResultValues;
8288   SmallVector<SDValue, 8> OutChains;
8289 
8290   llvm::Type *CSResultType = CS.getType();
8291   ArrayRef<Type *> ResultTypes;
8292   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8293     ResultTypes = StructResult->elements();
8294   else if (!CSResultType->isVoidTy())
8295     ResultTypes = makeArrayRef(CSResultType);
8296 
8297   auto CurResultType = ResultTypes.begin();
8298   auto handleRegAssign = [&](SDValue V) {
8299     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8300     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8301     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8302     ++CurResultType;
8303     // If the type of the inline asm call site return value is different but has
8304     // same size as the type of the asm output bitcast it.  One example of this
8305     // is for vectors with different width / number of elements.  This can
8306     // happen for register classes that can contain multiple different value
8307     // types.  The preg or vreg allocated may not have the same VT as was
8308     // expected.
8309     //
8310     // This can also happen for a return value that disagrees with the register
8311     // class it is put in, eg. a double in a general-purpose register on a
8312     // 32-bit machine.
8313     if (ResultVT != V.getValueType() &&
8314         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8315       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8316     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8317              V.getValueType().isInteger()) {
8318       // If a result value was tied to an input value, the computed result
8319       // may have a wider width than the expected result.  Extract the
8320       // relevant portion.
8321       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8322     }
8323     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8324     ResultVTs.push_back(ResultVT);
8325     ResultValues.push_back(V);
8326   };
8327 
8328   // Deal with output operands.
8329   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8330     if (OpInfo.Type == InlineAsm::isOutput) {
8331       SDValue Val;
8332       // Skip trivial output operands.
8333       if (OpInfo.AssignedRegs.Regs.empty())
8334         continue;
8335 
8336       switch (OpInfo.ConstraintType) {
8337       case TargetLowering::C_Register:
8338       case TargetLowering::C_RegisterClass:
8339         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8340             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8341         break;
8342       case TargetLowering::C_Other:
8343         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8344                                               OpInfo, DAG);
8345         break;
8346       case TargetLowering::C_Memory:
8347         break; // Already handled.
8348       case TargetLowering::C_Unknown:
8349         assert(false && "Unexpected unknown constraint");
8350       }
8351 
8352       // Indirect output manifest as stores. Record output chains.
8353       if (OpInfo.isIndirect) {
8354         const Value *Ptr = OpInfo.CallOperandVal;
8355         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8356         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8357                                      MachinePointerInfo(Ptr));
8358         OutChains.push_back(Store);
8359       } else {
8360         // generate CopyFromRegs to associated registers.
8361         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8362         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8363           for (const SDValue &V : Val->op_values())
8364             handleRegAssign(V);
8365         } else
8366           handleRegAssign(Val);
8367       }
8368     }
8369   }
8370 
8371   // Set results.
8372   if (!ResultValues.empty()) {
8373     assert(CurResultType == ResultTypes.end() &&
8374            "Mismatch in number of ResultTypes");
8375     assert(ResultValues.size() == ResultTypes.size() &&
8376            "Mismatch in number of output operands in asm result");
8377 
8378     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8379                             DAG.getVTList(ResultVTs), ResultValues);
8380     setValue(CS.getInstruction(), V);
8381   }
8382 
8383   // Collect store chains.
8384   if (!OutChains.empty())
8385     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8386 
8387   // Only Update Root if inline assembly has a memory effect.
8388   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8389     DAG.setRoot(Chain);
8390 }
8391 
8392 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8393                                              const Twine &Message) {
8394   LLVMContext &Ctx = *DAG.getContext();
8395   Ctx.emitError(CS.getInstruction(), Message);
8396 
8397   // Make sure we leave the DAG in a valid state
8398   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8399   SmallVector<EVT, 1> ValueVTs;
8400   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8401 
8402   if (ValueVTs.empty())
8403     return;
8404 
8405   SmallVector<SDValue, 1> Ops;
8406   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8407     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8408 
8409   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8410 }
8411 
8412 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8413   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8414                           MVT::Other, getRoot(),
8415                           getValue(I.getArgOperand(0)),
8416                           DAG.getSrcValue(I.getArgOperand(0))));
8417 }
8418 
8419 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8420   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8421   const DataLayout &DL = DAG.getDataLayout();
8422   SDValue V = DAG.getVAArg(
8423       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8424       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8425       DL.getABITypeAlignment(I.getType()));
8426   DAG.setRoot(V.getValue(1));
8427 
8428   if (I.getType()->isPointerTy())
8429     V = DAG.getPtrExtOrTrunc(
8430         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8431   setValue(&I, V);
8432 }
8433 
8434 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8435   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8436                           MVT::Other, getRoot(),
8437                           getValue(I.getArgOperand(0)),
8438                           DAG.getSrcValue(I.getArgOperand(0))));
8439 }
8440 
8441 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8442   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8443                           MVT::Other, getRoot(),
8444                           getValue(I.getArgOperand(0)),
8445                           getValue(I.getArgOperand(1)),
8446                           DAG.getSrcValue(I.getArgOperand(0)),
8447                           DAG.getSrcValue(I.getArgOperand(1))));
8448 }
8449 
8450 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8451                                                     const Instruction &I,
8452                                                     SDValue Op) {
8453   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8454   if (!Range)
8455     return Op;
8456 
8457   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8458   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8459     return Op;
8460 
8461   APInt Lo = CR.getUnsignedMin();
8462   if (!Lo.isMinValue())
8463     return Op;
8464 
8465   APInt Hi = CR.getUnsignedMax();
8466   unsigned Bits = std::max(Hi.getActiveBits(),
8467                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8468 
8469   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8470 
8471   SDLoc SL = getCurSDLoc();
8472 
8473   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8474                              DAG.getValueType(SmallVT));
8475   unsigned NumVals = Op.getNode()->getNumValues();
8476   if (NumVals == 1)
8477     return ZExt;
8478 
8479   SmallVector<SDValue, 4> Ops;
8480 
8481   Ops.push_back(ZExt);
8482   for (unsigned I = 1; I != NumVals; ++I)
8483     Ops.push_back(Op.getValue(I));
8484 
8485   return DAG.getMergeValues(Ops, SL);
8486 }
8487 
8488 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8489 /// the call being lowered.
8490 ///
8491 /// This is a helper for lowering intrinsics that follow a target calling
8492 /// convention or require stack pointer adjustment. Only a subset of the
8493 /// intrinsic's operands need to participate in the calling convention.
8494 void SelectionDAGBuilder::populateCallLoweringInfo(
8495     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8496     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8497     bool IsPatchPoint) {
8498   TargetLowering::ArgListTy Args;
8499   Args.reserve(NumArgs);
8500 
8501   // Populate the argument list.
8502   // Attributes for args start at offset 1, after the return attribute.
8503   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8504        ArgI != ArgE; ++ArgI) {
8505     const Value *V = Call->getOperand(ArgI);
8506 
8507     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8508 
8509     TargetLowering::ArgListEntry Entry;
8510     Entry.Node = getValue(V);
8511     Entry.Ty = V->getType();
8512     Entry.setAttributes(Call, ArgI);
8513     Args.push_back(Entry);
8514   }
8515 
8516   CLI.setDebugLoc(getCurSDLoc())
8517       .setChain(getRoot())
8518       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8519       .setDiscardResult(Call->use_empty())
8520       .setIsPatchPoint(IsPatchPoint);
8521 }
8522 
8523 /// Add a stack map intrinsic call's live variable operands to a stackmap
8524 /// or patchpoint target node's operand list.
8525 ///
8526 /// Constants are converted to TargetConstants purely as an optimization to
8527 /// avoid constant materialization and register allocation.
8528 ///
8529 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8530 /// generate addess computation nodes, and so FinalizeISel can convert the
8531 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8532 /// address materialization and register allocation, but may also be required
8533 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8534 /// alloca in the entry block, then the runtime may assume that the alloca's
8535 /// StackMap location can be read immediately after compilation and that the
8536 /// location is valid at any point during execution (this is similar to the
8537 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8538 /// only available in a register, then the runtime would need to trap when
8539 /// execution reaches the StackMap in order to read the alloca's location.
8540 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8541                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8542                                 SelectionDAGBuilder &Builder) {
8543   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8544     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8545     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8546       Ops.push_back(
8547         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8548       Ops.push_back(
8549         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8550     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8551       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8552       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8553           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8554     } else
8555       Ops.push_back(OpVal);
8556   }
8557 }
8558 
8559 /// Lower llvm.experimental.stackmap directly to its target opcode.
8560 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8561   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8562   //                                  [live variables...])
8563 
8564   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8565 
8566   SDValue Chain, InFlag, Callee, NullPtr;
8567   SmallVector<SDValue, 32> Ops;
8568 
8569   SDLoc DL = getCurSDLoc();
8570   Callee = getValue(CI.getCalledValue());
8571   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8572 
8573   // The stackmap intrinsic only records the live variables (the arguemnts
8574   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8575   // intrinsic, this won't be lowered to a function call. This means we don't
8576   // have to worry about calling conventions and target specific lowering code.
8577   // Instead we perform the call lowering right here.
8578   //
8579   // chain, flag = CALLSEQ_START(chain, 0, 0)
8580   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8581   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8582   //
8583   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8584   InFlag = Chain.getValue(1);
8585 
8586   // Add the <id> and <numBytes> constants.
8587   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8588   Ops.push_back(DAG.getTargetConstant(
8589                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8590   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8591   Ops.push_back(DAG.getTargetConstant(
8592                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8593                   MVT::i32));
8594 
8595   // Push live variables for the stack map.
8596   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8597 
8598   // We are not pushing any register mask info here on the operands list,
8599   // because the stackmap doesn't clobber anything.
8600 
8601   // Push the chain and the glue flag.
8602   Ops.push_back(Chain);
8603   Ops.push_back(InFlag);
8604 
8605   // Create the STACKMAP node.
8606   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8607   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8608   Chain = SDValue(SM, 0);
8609   InFlag = Chain.getValue(1);
8610 
8611   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8612 
8613   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8614 
8615   // Set the root to the target-lowered call chain.
8616   DAG.setRoot(Chain);
8617 
8618   // Inform the Frame Information that we have a stackmap in this function.
8619   FuncInfo.MF->getFrameInfo().setHasStackMap();
8620 }
8621 
8622 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8623 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8624                                           const BasicBlock *EHPadBB) {
8625   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8626   //                                                 i32 <numBytes>,
8627   //                                                 i8* <target>,
8628   //                                                 i32 <numArgs>,
8629   //                                                 [Args...],
8630   //                                                 [live variables...])
8631 
8632   CallingConv::ID CC = CS.getCallingConv();
8633   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8634   bool HasDef = !CS->getType()->isVoidTy();
8635   SDLoc dl = getCurSDLoc();
8636   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8637 
8638   // Handle immediate and symbolic callees.
8639   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8640     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8641                                    /*isTarget=*/true);
8642   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8643     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8644                                          SDLoc(SymbolicCallee),
8645                                          SymbolicCallee->getValueType(0));
8646 
8647   // Get the real number of arguments participating in the call <numArgs>
8648   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8649   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8650 
8651   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8652   // Intrinsics include all meta-operands up to but not including CC.
8653   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8654   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8655          "Not enough arguments provided to the patchpoint intrinsic");
8656 
8657   // For AnyRegCC the arguments are lowered later on manually.
8658   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8659   Type *ReturnTy =
8660     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8661 
8662   TargetLowering::CallLoweringInfo CLI(DAG);
8663   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8664                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8665   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8666 
8667   SDNode *CallEnd = Result.second.getNode();
8668   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8669     CallEnd = CallEnd->getOperand(0).getNode();
8670 
8671   /// Get a call instruction from the call sequence chain.
8672   /// Tail calls are not allowed.
8673   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8674          "Expected a callseq node.");
8675   SDNode *Call = CallEnd->getOperand(0).getNode();
8676   bool HasGlue = Call->getGluedNode();
8677 
8678   // Replace the target specific call node with the patchable intrinsic.
8679   SmallVector<SDValue, 8> Ops;
8680 
8681   // Add the <id> and <numBytes> constants.
8682   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8683   Ops.push_back(DAG.getTargetConstant(
8684                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8685   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8686   Ops.push_back(DAG.getTargetConstant(
8687                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8688                   MVT::i32));
8689 
8690   // Add the callee.
8691   Ops.push_back(Callee);
8692 
8693   // Adjust <numArgs> to account for any arguments that have been passed on the
8694   // stack instead.
8695   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8696   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8697   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8698   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8699 
8700   // Add the calling convention
8701   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8702 
8703   // Add the arguments we omitted previously. The register allocator should
8704   // place these in any free register.
8705   if (IsAnyRegCC)
8706     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8707       Ops.push_back(getValue(CS.getArgument(i)));
8708 
8709   // Push the arguments from the call instruction up to the register mask.
8710   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8711   Ops.append(Call->op_begin() + 2, e);
8712 
8713   // Push live variables for the stack map.
8714   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8715 
8716   // Push the register mask info.
8717   if (HasGlue)
8718     Ops.push_back(*(Call->op_end()-2));
8719   else
8720     Ops.push_back(*(Call->op_end()-1));
8721 
8722   // Push the chain (this is originally the first operand of the call, but
8723   // becomes now the last or second to last operand).
8724   Ops.push_back(*(Call->op_begin()));
8725 
8726   // Push the glue flag (last operand).
8727   if (HasGlue)
8728     Ops.push_back(*(Call->op_end()-1));
8729 
8730   SDVTList NodeTys;
8731   if (IsAnyRegCC && HasDef) {
8732     // Create the return types based on the intrinsic definition
8733     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8734     SmallVector<EVT, 3> ValueVTs;
8735     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8736     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8737 
8738     // There is always a chain and a glue type at the end
8739     ValueVTs.push_back(MVT::Other);
8740     ValueVTs.push_back(MVT::Glue);
8741     NodeTys = DAG.getVTList(ValueVTs);
8742   } else
8743     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8744 
8745   // Replace the target specific call node with a PATCHPOINT node.
8746   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8747                                          dl, NodeTys, Ops);
8748 
8749   // Update the NodeMap.
8750   if (HasDef) {
8751     if (IsAnyRegCC)
8752       setValue(CS.getInstruction(), SDValue(MN, 0));
8753     else
8754       setValue(CS.getInstruction(), Result.first);
8755   }
8756 
8757   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8758   // call sequence. Furthermore the location of the chain and glue can change
8759   // when the AnyReg calling convention is used and the intrinsic returns a
8760   // value.
8761   if (IsAnyRegCC && HasDef) {
8762     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8763     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8764     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8765   } else
8766     DAG.ReplaceAllUsesWith(Call, MN);
8767   DAG.DeleteNode(Call);
8768 
8769   // Inform the Frame Information that we have a patchpoint in this function.
8770   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8771 }
8772 
8773 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8774                                             unsigned Intrinsic) {
8775   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8776   SDValue Op1 = getValue(I.getArgOperand(0));
8777   SDValue Op2;
8778   if (I.getNumArgOperands() > 1)
8779     Op2 = getValue(I.getArgOperand(1));
8780   SDLoc dl = getCurSDLoc();
8781   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8782   SDValue Res;
8783   FastMathFlags FMF;
8784   if (isa<FPMathOperator>(I))
8785     FMF = I.getFastMathFlags();
8786 
8787   switch (Intrinsic) {
8788   case Intrinsic::experimental_vector_reduce_v2_fadd:
8789     if (FMF.allowReassoc())
8790       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8791                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8792     else
8793       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8794     break;
8795   case Intrinsic::experimental_vector_reduce_v2_fmul:
8796     if (FMF.allowReassoc())
8797       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8798                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8799     else
8800       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8801     break;
8802   case Intrinsic::experimental_vector_reduce_add:
8803     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8804     break;
8805   case Intrinsic::experimental_vector_reduce_mul:
8806     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8807     break;
8808   case Intrinsic::experimental_vector_reduce_and:
8809     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8810     break;
8811   case Intrinsic::experimental_vector_reduce_or:
8812     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8813     break;
8814   case Intrinsic::experimental_vector_reduce_xor:
8815     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8816     break;
8817   case Intrinsic::experimental_vector_reduce_smax:
8818     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8819     break;
8820   case Intrinsic::experimental_vector_reduce_smin:
8821     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8822     break;
8823   case Intrinsic::experimental_vector_reduce_umax:
8824     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8825     break;
8826   case Intrinsic::experimental_vector_reduce_umin:
8827     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8828     break;
8829   case Intrinsic::experimental_vector_reduce_fmax:
8830     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8831     break;
8832   case Intrinsic::experimental_vector_reduce_fmin:
8833     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8834     break;
8835   default:
8836     llvm_unreachable("Unhandled vector reduce intrinsic");
8837   }
8838   setValue(&I, Res);
8839 }
8840 
8841 /// Returns an AttributeList representing the attributes applied to the return
8842 /// value of the given call.
8843 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8844   SmallVector<Attribute::AttrKind, 2> Attrs;
8845   if (CLI.RetSExt)
8846     Attrs.push_back(Attribute::SExt);
8847   if (CLI.RetZExt)
8848     Attrs.push_back(Attribute::ZExt);
8849   if (CLI.IsInReg)
8850     Attrs.push_back(Attribute::InReg);
8851 
8852   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8853                             Attrs);
8854 }
8855 
8856 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8857 /// implementation, which just calls LowerCall.
8858 /// FIXME: When all targets are
8859 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8860 std::pair<SDValue, SDValue>
8861 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8862   // Handle the incoming return values from the call.
8863   CLI.Ins.clear();
8864   Type *OrigRetTy = CLI.RetTy;
8865   SmallVector<EVT, 4> RetTys;
8866   SmallVector<uint64_t, 4> Offsets;
8867   auto &DL = CLI.DAG.getDataLayout();
8868   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8869 
8870   if (CLI.IsPostTypeLegalization) {
8871     // If we are lowering a libcall after legalization, split the return type.
8872     SmallVector<EVT, 4> OldRetTys;
8873     SmallVector<uint64_t, 4> OldOffsets;
8874     RetTys.swap(OldRetTys);
8875     Offsets.swap(OldOffsets);
8876 
8877     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8878       EVT RetVT = OldRetTys[i];
8879       uint64_t Offset = OldOffsets[i];
8880       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8881       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8882       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8883       RetTys.append(NumRegs, RegisterVT);
8884       for (unsigned j = 0; j != NumRegs; ++j)
8885         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8886     }
8887   }
8888 
8889   SmallVector<ISD::OutputArg, 4> Outs;
8890   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8891 
8892   bool CanLowerReturn =
8893       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8894                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8895 
8896   SDValue DemoteStackSlot;
8897   int DemoteStackIdx = -100;
8898   if (!CanLowerReturn) {
8899     // FIXME: equivalent assert?
8900     // assert(!CS.hasInAllocaArgument() &&
8901     //        "sret demotion is incompatible with inalloca");
8902     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8903     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8904     MachineFunction &MF = CLI.DAG.getMachineFunction();
8905     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8906     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8907                                               DL.getAllocaAddrSpace());
8908 
8909     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8910     ArgListEntry Entry;
8911     Entry.Node = DemoteStackSlot;
8912     Entry.Ty = StackSlotPtrType;
8913     Entry.IsSExt = false;
8914     Entry.IsZExt = false;
8915     Entry.IsInReg = false;
8916     Entry.IsSRet = true;
8917     Entry.IsNest = false;
8918     Entry.IsByVal = false;
8919     Entry.IsReturned = false;
8920     Entry.IsSwiftSelf = false;
8921     Entry.IsSwiftError = false;
8922     Entry.Alignment = Align;
8923     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8924     CLI.NumFixedArgs += 1;
8925     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8926 
8927     // sret demotion isn't compatible with tail-calls, since the sret argument
8928     // points into the callers stack frame.
8929     CLI.IsTailCall = false;
8930   } else {
8931     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8932         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
8933     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8934       ISD::ArgFlagsTy Flags;
8935       if (NeedsRegBlock) {
8936         Flags.setInConsecutiveRegs();
8937         if (I == RetTys.size() - 1)
8938           Flags.setInConsecutiveRegsLast();
8939       }
8940       EVT VT = RetTys[I];
8941       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8942                                                      CLI.CallConv, VT);
8943       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8944                                                        CLI.CallConv, VT);
8945       for (unsigned i = 0; i != NumRegs; ++i) {
8946         ISD::InputArg MyFlags;
8947         MyFlags.Flags = Flags;
8948         MyFlags.VT = RegisterVT;
8949         MyFlags.ArgVT = VT;
8950         MyFlags.Used = CLI.IsReturnValueUsed;
8951         if (CLI.RetTy->isPointerTy()) {
8952           MyFlags.Flags.setPointer();
8953           MyFlags.Flags.setPointerAddrSpace(
8954               cast<PointerType>(CLI.RetTy)->getAddressSpace());
8955         }
8956         if (CLI.RetSExt)
8957           MyFlags.Flags.setSExt();
8958         if (CLI.RetZExt)
8959           MyFlags.Flags.setZExt();
8960         if (CLI.IsInReg)
8961           MyFlags.Flags.setInReg();
8962         CLI.Ins.push_back(MyFlags);
8963       }
8964     }
8965   }
8966 
8967   // We push in swifterror return as the last element of CLI.Ins.
8968   ArgListTy &Args = CLI.getArgs();
8969   if (supportSwiftError()) {
8970     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8971       if (Args[i].IsSwiftError) {
8972         ISD::InputArg MyFlags;
8973         MyFlags.VT = getPointerTy(DL);
8974         MyFlags.ArgVT = EVT(getPointerTy(DL));
8975         MyFlags.Flags.setSwiftError();
8976         CLI.Ins.push_back(MyFlags);
8977       }
8978     }
8979   }
8980 
8981   // Handle all of the outgoing arguments.
8982   CLI.Outs.clear();
8983   CLI.OutVals.clear();
8984   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8985     SmallVector<EVT, 4> ValueVTs;
8986     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8987     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8988     Type *FinalType = Args[i].Ty;
8989     if (Args[i].IsByVal)
8990       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8991     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8992         FinalType, CLI.CallConv, CLI.IsVarArg);
8993     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8994          ++Value) {
8995       EVT VT = ValueVTs[Value];
8996       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8997       SDValue Op = SDValue(Args[i].Node.getNode(),
8998                            Args[i].Node.getResNo() + Value);
8999       ISD::ArgFlagsTy Flags;
9000 
9001       // Certain targets (such as MIPS), may have a different ABI alignment
9002       // for a type depending on the context. Give the target a chance to
9003       // specify the alignment it wants.
9004       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
9005 
9006       if (Args[i].Ty->isPointerTy()) {
9007         Flags.setPointer();
9008         Flags.setPointerAddrSpace(
9009             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9010       }
9011       if (Args[i].IsZExt)
9012         Flags.setZExt();
9013       if (Args[i].IsSExt)
9014         Flags.setSExt();
9015       if (Args[i].IsInReg) {
9016         // If we are using vectorcall calling convention, a structure that is
9017         // passed InReg - is surely an HVA
9018         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9019             isa<StructType>(FinalType)) {
9020           // The first value of a structure is marked
9021           if (0 == Value)
9022             Flags.setHvaStart();
9023           Flags.setHva();
9024         }
9025         // Set InReg Flag
9026         Flags.setInReg();
9027       }
9028       if (Args[i].IsSRet)
9029         Flags.setSRet();
9030       if (Args[i].IsSwiftSelf)
9031         Flags.setSwiftSelf();
9032       if (Args[i].IsSwiftError)
9033         Flags.setSwiftError();
9034       if (Args[i].IsByVal)
9035         Flags.setByVal();
9036       if (Args[i].IsInAlloca) {
9037         Flags.setInAlloca();
9038         // Set the byval flag for CCAssignFn callbacks that don't know about
9039         // inalloca.  This way we can know how many bytes we should've allocated
9040         // and how many bytes a callee cleanup function will pop.  If we port
9041         // inalloca to more targets, we'll have to add custom inalloca handling
9042         // in the various CC lowering callbacks.
9043         Flags.setByVal();
9044       }
9045       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9046         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9047         Type *ElementTy = Ty->getElementType();
9048 
9049         unsigned FrameSize = DL.getTypeAllocSize(
9050             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9051         Flags.setByValSize(FrameSize);
9052 
9053         // info is not there but there are cases it cannot get right.
9054         unsigned FrameAlign;
9055         if (Args[i].Alignment)
9056           FrameAlign = Args[i].Alignment;
9057         else
9058           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9059         Flags.setByValAlign(FrameAlign);
9060       }
9061       if (Args[i].IsNest)
9062         Flags.setNest();
9063       if (NeedsRegBlock)
9064         Flags.setInConsecutiveRegs();
9065       Flags.setOrigAlign(OriginalAlignment);
9066 
9067       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9068                                                  CLI.CallConv, VT);
9069       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9070                                                         CLI.CallConv, VT);
9071       SmallVector<SDValue, 4> Parts(NumParts);
9072       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9073 
9074       if (Args[i].IsSExt)
9075         ExtendKind = ISD::SIGN_EXTEND;
9076       else if (Args[i].IsZExt)
9077         ExtendKind = ISD::ZERO_EXTEND;
9078 
9079       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9080       // for now.
9081       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9082           CanLowerReturn) {
9083         assert((CLI.RetTy == Args[i].Ty ||
9084                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9085                  CLI.RetTy->getPointerAddressSpace() ==
9086                      Args[i].Ty->getPointerAddressSpace())) &&
9087                RetTys.size() == NumValues && "unexpected use of 'returned'");
9088         // Before passing 'returned' to the target lowering code, ensure that
9089         // either the register MVT and the actual EVT are the same size or that
9090         // the return value and argument are extended in the same way; in these
9091         // cases it's safe to pass the argument register value unchanged as the
9092         // return register value (although it's at the target's option whether
9093         // to do so)
9094         // TODO: allow code generation to take advantage of partially preserved
9095         // registers rather than clobbering the entire register when the
9096         // parameter extension method is not compatible with the return
9097         // extension method
9098         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9099             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9100              CLI.RetZExt == Args[i].IsZExt))
9101           Flags.setReturned();
9102       }
9103 
9104       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9105                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9106 
9107       for (unsigned j = 0; j != NumParts; ++j) {
9108         // if it isn't first piece, alignment must be 1
9109         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9110                                i < CLI.NumFixedArgs,
9111                                i, j*Parts[j].getValueType().getStoreSize());
9112         if (NumParts > 1 && j == 0)
9113           MyFlags.Flags.setSplit();
9114         else if (j != 0) {
9115           MyFlags.Flags.setOrigAlign(1);
9116           if (j == NumParts - 1)
9117             MyFlags.Flags.setSplitEnd();
9118         }
9119 
9120         CLI.Outs.push_back(MyFlags);
9121         CLI.OutVals.push_back(Parts[j]);
9122       }
9123 
9124       if (NeedsRegBlock && Value == NumValues - 1)
9125         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9126     }
9127   }
9128 
9129   SmallVector<SDValue, 4> InVals;
9130   CLI.Chain = LowerCall(CLI, InVals);
9131 
9132   // Update CLI.InVals to use outside of this function.
9133   CLI.InVals = InVals;
9134 
9135   // Verify that the target's LowerCall behaved as expected.
9136   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9137          "LowerCall didn't return a valid chain!");
9138   assert((!CLI.IsTailCall || InVals.empty()) &&
9139          "LowerCall emitted a return value for a tail call!");
9140   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9141          "LowerCall didn't emit the correct number of values!");
9142 
9143   // For a tail call, the return value is merely live-out and there aren't
9144   // any nodes in the DAG representing it. Return a special value to
9145   // indicate that a tail call has been emitted and no more Instructions
9146   // should be processed in the current block.
9147   if (CLI.IsTailCall) {
9148     CLI.DAG.setRoot(CLI.Chain);
9149     return std::make_pair(SDValue(), SDValue());
9150   }
9151 
9152 #ifndef NDEBUG
9153   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9154     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9155     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9156            "LowerCall emitted a value with the wrong type!");
9157   }
9158 #endif
9159 
9160   SmallVector<SDValue, 4> ReturnValues;
9161   if (!CanLowerReturn) {
9162     // The instruction result is the result of loading from the
9163     // hidden sret parameter.
9164     SmallVector<EVT, 1> PVTs;
9165     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9166 
9167     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9168     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9169     EVT PtrVT = PVTs[0];
9170 
9171     unsigned NumValues = RetTys.size();
9172     ReturnValues.resize(NumValues);
9173     SmallVector<SDValue, 4> Chains(NumValues);
9174 
9175     // An aggregate return value cannot wrap around the address space, so
9176     // offsets to its parts don't wrap either.
9177     SDNodeFlags Flags;
9178     Flags.setNoUnsignedWrap(true);
9179 
9180     for (unsigned i = 0; i < NumValues; ++i) {
9181       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9182                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9183                                                         PtrVT), Flags);
9184       SDValue L = CLI.DAG.getLoad(
9185           RetTys[i], CLI.DL, CLI.Chain, Add,
9186           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9187                                             DemoteStackIdx, Offsets[i]),
9188           /* Alignment = */ 1);
9189       ReturnValues[i] = L;
9190       Chains[i] = L.getValue(1);
9191     }
9192 
9193     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9194   } else {
9195     // Collect the legal value parts into potentially illegal values
9196     // that correspond to the original function's return values.
9197     Optional<ISD::NodeType> AssertOp;
9198     if (CLI.RetSExt)
9199       AssertOp = ISD::AssertSext;
9200     else if (CLI.RetZExt)
9201       AssertOp = ISD::AssertZext;
9202     unsigned CurReg = 0;
9203     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9204       EVT VT = RetTys[I];
9205       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9206                                                      CLI.CallConv, VT);
9207       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9208                                                        CLI.CallConv, VT);
9209 
9210       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9211                                               NumRegs, RegisterVT, VT, nullptr,
9212                                               CLI.CallConv, AssertOp));
9213       CurReg += NumRegs;
9214     }
9215 
9216     // For a function returning void, there is no return value. We can't create
9217     // such a node, so we just return a null return value in that case. In
9218     // that case, nothing will actually look at the value.
9219     if (ReturnValues.empty())
9220       return std::make_pair(SDValue(), CLI.Chain);
9221   }
9222 
9223   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9224                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9225   return std::make_pair(Res, CLI.Chain);
9226 }
9227 
9228 void TargetLowering::LowerOperationWrapper(SDNode *N,
9229                                            SmallVectorImpl<SDValue> &Results,
9230                                            SelectionDAG &DAG) const {
9231   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9232     Results.push_back(Res);
9233 }
9234 
9235 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9236   llvm_unreachable("LowerOperation not implemented for this target!");
9237 }
9238 
9239 void
9240 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9241   SDValue Op = getNonRegisterValue(V);
9242   assert((Op.getOpcode() != ISD::CopyFromReg ||
9243           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9244          "Copy from a reg to the same reg!");
9245   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
9246 
9247   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9248   // If this is an InlineAsm we have to match the registers required, not the
9249   // notional registers required by the type.
9250 
9251   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9252                    None); // This is not an ABI copy.
9253   SDValue Chain = DAG.getEntryNode();
9254 
9255   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9256                               FuncInfo.PreferredExtendType.end())
9257                                  ? ISD::ANY_EXTEND
9258                                  : FuncInfo.PreferredExtendType[V];
9259   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9260   PendingExports.push_back(Chain);
9261 }
9262 
9263 #include "llvm/CodeGen/SelectionDAGISel.h"
9264 
9265 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9266 /// entry block, return true.  This includes arguments used by switches, since
9267 /// the switch may expand into multiple basic blocks.
9268 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9269   // With FastISel active, we may be splitting blocks, so force creation
9270   // of virtual registers for all non-dead arguments.
9271   if (FastISel)
9272     return A->use_empty();
9273 
9274   const BasicBlock &Entry = A->getParent()->front();
9275   for (const User *U : A->users())
9276     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9277       return false;  // Use not in entry block.
9278 
9279   return true;
9280 }
9281 
9282 using ArgCopyElisionMapTy =
9283     DenseMap<const Argument *,
9284              std::pair<const AllocaInst *, const StoreInst *>>;
9285 
9286 /// Scan the entry block of the function in FuncInfo for arguments that look
9287 /// like copies into a local alloca. Record any copied arguments in
9288 /// ArgCopyElisionCandidates.
9289 static void
9290 findArgumentCopyElisionCandidates(const DataLayout &DL,
9291                                   FunctionLoweringInfo *FuncInfo,
9292                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9293   // Record the state of every static alloca used in the entry block. Argument
9294   // allocas are all used in the entry block, so we need approximately as many
9295   // entries as we have arguments.
9296   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9297   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9298   unsigned NumArgs = FuncInfo->Fn->arg_size();
9299   StaticAllocas.reserve(NumArgs * 2);
9300 
9301   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9302     if (!V)
9303       return nullptr;
9304     V = V->stripPointerCasts();
9305     const auto *AI = dyn_cast<AllocaInst>(V);
9306     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9307       return nullptr;
9308     auto Iter = StaticAllocas.insert({AI, Unknown});
9309     return &Iter.first->second;
9310   };
9311 
9312   // Look for stores of arguments to static allocas. Look through bitcasts and
9313   // GEPs to handle type coercions, as long as the alloca is fully initialized
9314   // by the store. Any non-store use of an alloca escapes it and any subsequent
9315   // unanalyzed store might write it.
9316   // FIXME: Handle structs initialized with multiple stores.
9317   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9318     // Look for stores, and handle non-store uses conservatively.
9319     const auto *SI = dyn_cast<StoreInst>(&I);
9320     if (!SI) {
9321       // We will look through cast uses, so ignore them completely.
9322       if (I.isCast())
9323         continue;
9324       // Ignore debug info intrinsics, they don't escape or store to allocas.
9325       if (isa<DbgInfoIntrinsic>(I))
9326         continue;
9327       // This is an unknown instruction. Assume it escapes or writes to all
9328       // static alloca operands.
9329       for (const Use &U : I.operands()) {
9330         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9331           *Info = StaticAllocaInfo::Clobbered;
9332       }
9333       continue;
9334     }
9335 
9336     // If the stored value is a static alloca, mark it as escaped.
9337     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9338       *Info = StaticAllocaInfo::Clobbered;
9339 
9340     // Check if the destination is a static alloca.
9341     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9342     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9343     if (!Info)
9344       continue;
9345     const AllocaInst *AI = cast<AllocaInst>(Dst);
9346 
9347     // Skip allocas that have been initialized or clobbered.
9348     if (*Info != StaticAllocaInfo::Unknown)
9349       continue;
9350 
9351     // Check if the stored value is an argument, and that this store fully
9352     // initializes the alloca. Don't elide copies from the same argument twice.
9353     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9354     const auto *Arg = dyn_cast<Argument>(Val);
9355     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9356         Arg->getType()->isEmptyTy() ||
9357         DL.getTypeStoreSize(Arg->getType()) !=
9358             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9359         ArgCopyElisionCandidates.count(Arg)) {
9360       *Info = StaticAllocaInfo::Clobbered;
9361       continue;
9362     }
9363 
9364     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9365                       << '\n');
9366 
9367     // Mark this alloca and store for argument copy elision.
9368     *Info = StaticAllocaInfo::Elidable;
9369     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9370 
9371     // Stop scanning if we've seen all arguments. This will happen early in -O0
9372     // builds, which is useful, because -O0 builds have large entry blocks and
9373     // many allocas.
9374     if (ArgCopyElisionCandidates.size() == NumArgs)
9375       break;
9376   }
9377 }
9378 
9379 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9380 /// ArgVal is a load from a suitable fixed stack object.
9381 static void tryToElideArgumentCopy(
9382     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9383     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9384     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9385     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9386     SDValue ArgVal, bool &ArgHasUses) {
9387   // Check if this is a load from a fixed stack object.
9388   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9389   if (!LNode)
9390     return;
9391   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9392   if (!FINode)
9393     return;
9394 
9395   // Check that the fixed stack object is the right size and alignment.
9396   // Look at the alignment that the user wrote on the alloca instead of looking
9397   // at the stack object.
9398   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9399   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9400   const AllocaInst *AI = ArgCopyIter->second.first;
9401   int FixedIndex = FINode->getIndex();
9402   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9403   int OldIndex = AllocaIndex;
9404   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9405   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9406     LLVM_DEBUG(
9407         dbgs() << "  argument copy elision failed due to bad fixed stack "
9408                   "object size\n");
9409     return;
9410   }
9411   unsigned RequiredAlignment = AI->getAlignment();
9412   if (!RequiredAlignment) {
9413     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9414         AI->getAllocatedType());
9415   }
9416   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9417     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9418                          "greater than stack argument alignment ("
9419                       << RequiredAlignment << " vs "
9420                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9421     return;
9422   }
9423 
9424   // Perform the elision. Delete the old stack object and replace its only use
9425   // in the variable info map. Mark the stack object as mutable.
9426   LLVM_DEBUG({
9427     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9428            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9429            << '\n';
9430   });
9431   MFI.RemoveStackObject(OldIndex);
9432   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9433   AllocaIndex = FixedIndex;
9434   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9435   Chains.push_back(ArgVal.getValue(1));
9436 
9437   // Avoid emitting code for the store implementing the copy.
9438   const StoreInst *SI = ArgCopyIter->second.second;
9439   ElidedArgCopyInstrs.insert(SI);
9440 
9441   // Check for uses of the argument again so that we can avoid exporting ArgVal
9442   // if it is't used by anything other than the store.
9443   for (const Value *U : Arg.users()) {
9444     if (U != SI) {
9445       ArgHasUses = true;
9446       break;
9447     }
9448   }
9449 }
9450 
9451 void SelectionDAGISel::LowerArguments(const Function &F) {
9452   SelectionDAG &DAG = SDB->DAG;
9453   SDLoc dl = SDB->getCurSDLoc();
9454   const DataLayout &DL = DAG.getDataLayout();
9455   SmallVector<ISD::InputArg, 16> Ins;
9456 
9457   if (!FuncInfo->CanLowerReturn) {
9458     // Put in an sret pointer parameter before all the other parameters.
9459     SmallVector<EVT, 1> ValueVTs;
9460     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9461                     F.getReturnType()->getPointerTo(
9462                         DAG.getDataLayout().getAllocaAddrSpace()),
9463                     ValueVTs);
9464 
9465     // NOTE: Assuming that a pointer will never break down to more than one VT
9466     // or one register.
9467     ISD::ArgFlagsTy Flags;
9468     Flags.setSRet();
9469     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9470     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9471                          ISD::InputArg::NoArgIndex, 0);
9472     Ins.push_back(RetArg);
9473   }
9474 
9475   // Look for stores of arguments to static allocas. Mark such arguments with a
9476   // flag to ask the target to give us the memory location of that argument if
9477   // available.
9478   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9479   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9480 
9481   // Set up the incoming argument description vector.
9482   for (const Argument &Arg : F.args()) {
9483     unsigned ArgNo = Arg.getArgNo();
9484     SmallVector<EVT, 4> ValueVTs;
9485     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9486     bool isArgValueUsed = !Arg.use_empty();
9487     unsigned PartBase = 0;
9488     Type *FinalType = Arg.getType();
9489     if (Arg.hasAttribute(Attribute::ByVal))
9490       FinalType = cast<PointerType>(FinalType)->getElementType();
9491     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9492         FinalType, F.getCallingConv(), F.isVarArg());
9493     for (unsigned Value = 0, NumValues = ValueVTs.size();
9494          Value != NumValues; ++Value) {
9495       EVT VT = ValueVTs[Value];
9496       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9497       ISD::ArgFlagsTy Flags;
9498 
9499       // Certain targets (such as MIPS), may have a different ABI alignment
9500       // for a type depending on the context. Give the target a chance to
9501       // specify the alignment it wants.
9502       unsigned OriginalAlignment =
9503           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9504 
9505       if (Arg.getType()->isPointerTy()) {
9506         Flags.setPointer();
9507         Flags.setPointerAddrSpace(
9508             cast<PointerType>(Arg.getType())->getAddressSpace());
9509       }
9510       if (Arg.hasAttribute(Attribute::ZExt))
9511         Flags.setZExt();
9512       if (Arg.hasAttribute(Attribute::SExt))
9513         Flags.setSExt();
9514       if (Arg.hasAttribute(Attribute::InReg)) {
9515         // If we are using vectorcall calling convention, a structure that is
9516         // passed InReg - is surely an HVA
9517         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9518             isa<StructType>(Arg.getType())) {
9519           // The first value of a structure is marked
9520           if (0 == Value)
9521             Flags.setHvaStart();
9522           Flags.setHva();
9523         }
9524         // Set InReg Flag
9525         Flags.setInReg();
9526       }
9527       if (Arg.hasAttribute(Attribute::StructRet))
9528         Flags.setSRet();
9529       if (Arg.hasAttribute(Attribute::SwiftSelf))
9530         Flags.setSwiftSelf();
9531       if (Arg.hasAttribute(Attribute::SwiftError))
9532         Flags.setSwiftError();
9533       if (Arg.hasAttribute(Attribute::ByVal))
9534         Flags.setByVal();
9535       if (Arg.hasAttribute(Attribute::InAlloca)) {
9536         Flags.setInAlloca();
9537         // Set the byval flag for CCAssignFn callbacks that don't know about
9538         // inalloca.  This way we can know how many bytes we should've allocated
9539         // and how many bytes a callee cleanup function will pop.  If we port
9540         // inalloca to more targets, we'll have to add custom inalloca handling
9541         // in the various CC lowering callbacks.
9542         Flags.setByVal();
9543       }
9544       if (F.getCallingConv() == CallingConv::X86_INTR) {
9545         // IA Interrupt passes frame (1st parameter) by value in the stack.
9546         if (ArgNo == 0)
9547           Flags.setByVal();
9548       }
9549       if (Flags.isByVal() || Flags.isInAlloca()) {
9550         PointerType *Ty = cast<PointerType>(Arg.getType());
9551         Type *ElementTy = Ty->getElementType();
9552 
9553         // For ByVal, size and alignment should be passed from FE.  BE will
9554         // guess if this info is not there but there are cases it cannot get
9555         // right.
9556         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9557         Flags.setByValSize(FrameSize);
9558 
9559         unsigned FrameAlign;
9560         if (Arg.getParamAlignment())
9561           FrameAlign = Arg.getParamAlignment();
9562         else
9563           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9564         Flags.setByValAlign(FrameAlign);
9565       }
9566       if (Arg.hasAttribute(Attribute::Nest))
9567         Flags.setNest();
9568       if (NeedsRegBlock)
9569         Flags.setInConsecutiveRegs();
9570       Flags.setOrigAlign(OriginalAlignment);
9571       if (ArgCopyElisionCandidates.count(&Arg))
9572         Flags.setCopyElisionCandidate();
9573 
9574       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9575           *CurDAG->getContext(), F.getCallingConv(), VT);
9576       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9577           *CurDAG->getContext(), F.getCallingConv(), VT);
9578       for (unsigned i = 0; i != NumRegs; ++i) {
9579         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9580                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9581         if (NumRegs > 1 && i == 0)
9582           MyFlags.Flags.setSplit();
9583         // if it isn't first piece, alignment must be 1
9584         else if (i > 0) {
9585           MyFlags.Flags.setOrigAlign(1);
9586           if (i == NumRegs - 1)
9587             MyFlags.Flags.setSplitEnd();
9588         }
9589         Ins.push_back(MyFlags);
9590       }
9591       if (NeedsRegBlock && Value == NumValues - 1)
9592         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9593       PartBase += VT.getStoreSize();
9594     }
9595   }
9596 
9597   // Call the target to set up the argument values.
9598   SmallVector<SDValue, 8> InVals;
9599   SDValue NewRoot = TLI->LowerFormalArguments(
9600       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9601 
9602   // Verify that the target's LowerFormalArguments behaved as expected.
9603   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9604          "LowerFormalArguments didn't return a valid chain!");
9605   assert(InVals.size() == Ins.size() &&
9606          "LowerFormalArguments didn't emit the correct number of values!");
9607   LLVM_DEBUG({
9608     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9609       assert(InVals[i].getNode() &&
9610              "LowerFormalArguments emitted a null value!");
9611       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9612              "LowerFormalArguments emitted a value with the wrong type!");
9613     }
9614   });
9615 
9616   // Update the DAG with the new chain value resulting from argument lowering.
9617   DAG.setRoot(NewRoot);
9618 
9619   // Set up the argument values.
9620   unsigned i = 0;
9621   if (!FuncInfo->CanLowerReturn) {
9622     // Create a virtual register for the sret pointer, and put in a copy
9623     // from the sret argument into it.
9624     SmallVector<EVT, 1> ValueVTs;
9625     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9626                     F.getReturnType()->getPointerTo(
9627                         DAG.getDataLayout().getAllocaAddrSpace()),
9628                     ValueVTs);
9629     MVT VT = ValueVTs[0].getSimpleVT();
9630     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9631     Optional<ISD::NodeType> AssertOp = None;
9632     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9633                                         nullptr, F.getCallingConv(), AssertOp);
9634 
9635     MachineFunction& MF = SDB->DAG.getMachineFunction();
9636     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9637     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9638     FuncInfo->DemoteRegister = SRetReg;
9639     NewRoot =
9640         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9641     DAG.setRoot(NewRoot);
9642 
9643     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9644     ++i;
9645   }
9646 
9647   SmallVector<SDValue, 4> Chains;
9648   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9649   for (const Argument &Arg : F.args()) {
9650     SmallVector<SDValue, 4> ArgValues;
9651     SmallVector<EVT, 4> ValueVTs;
9652     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9653     unsigned NumValues = ValueVTs.size();
9654     if (NumValues == 0)
9655       continue;
9656 
9657     bool ArgHasUses = !Arg.use_empty();
9658 
9659     // Elide the copying store if the target loaded this argument from a
9660     // suitable fixed stack object.
9661     if (Ins[i].Flags.isCopyElisionCandidate()) {
9662       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9663                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9664                              InVals[i], ArgHasUses);
9665     }
9666 
9667     // If this argument is unused then remember its value. It is used to generate
9668     // debugging information.
9669     bool isSwiftErrorArg =
9670         TLI->supportSwiftError() &&
9671         Arg.hasAttribute(Attribute::SwiftError);
9672     if (!ArgHasUses && !isSwiftErrorArg) {
9673       SDB->setUnusedArgValue(&Arg, InVals[i]);
9674 
9675       // Also remember any frame index for use in FastISel.
9676       if (FrameIndexSDNode *FI =
9677           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9678         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9679     }
9680 
9681     for (unsigned Val = 0; Val != NumValues; ++Val) {
9682       EVT VT = ValueVTs[Val];
9683       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9684                                                       F.getCallingConv(), VT);
9685       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9686           *CurDAG->getContext(), F.getCallingConv(), VT);
9687 
9688       // Even an apparant 'unused' swifterror argument needs to be returned. So
9689       // we do generate a copy for it that can be used on return from the
9690       // function.
9691       if (ArgHasUses || isSwiftErrorArg) {
9692         Optional<ISD::NodeType> AssertOp;
9693         if (Arg.hasAttribute(Attribute::SExt))
9694           AssertOp = ISD::AssertSext;
9695         else if (Arg.hasAttribute(Attribute::ZExt))
9696           AssertOp = ISD::AssertZext;
9697 
9698         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9699                                              PartVT, VT, nullptr,
9700                                              F.getCallingConv(), AssertOp));
9701       }
9702 
9703       i += NumParts;
9704     }
9705 
9706     // We don't need to do anything else for unused arguments.
9707     if (ArgValues.empty())
9708       continue;
9709 
9710     // Note down frame index.
9711     if (FrameIndexSDNode *FI =
9712         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9713       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9714 
9715     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9716                                      SDB->getCurSDLoc());
9717 
9718     SDB->setValue(&Arg, Res);
9719     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9720       // We want to associate the argument with the frame index, among
9721       // involved operands, that correspond to the lowest address. The
9722       // getCopyFromParts function, called earlier, is swapping the order of
9723       // the operands to BUILD_PAIR depending on endianness. The result of
9724       // that swapping is that the least significant bits of the argument will
9725       // be in the first operand of the BUILD_PAIR node, and the most
9726       // significant bits will be in the second operand.
9727       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9728       if (LoadSDNode *LNode =
9729           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9730         if (FrameIndexSDNode *FI =
9731             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9732           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9733     }
9734 
9735     // Update the SwiftErrorVRegDefMap.
9736     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9737       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9738       if (TargetRegisterInfo::isVirtualRegister(Reg))
9739         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9740                                    Reg);
9741     }
9742 
9743     // If this argument is live outside of the entry block, insert a copy from
9744     // wherever we got it to the vreg that other BB's will reference it as.
9745     if (Res.getOpcode() == ISD::CopyFromReg) {
9746       // If we can, though, try to skip creating an unnecessary vreg.
9747       // FIXME: This isn't very clean... it would be nice to make this more
9748       // general.
9749       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9750       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9751         FuncInfo->ValueMap[&Arg] = Reg;
9752         continue;
9753       }
9754     }
9755     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9756       FuncInfo->InitializeRegForValue(&Arg);
9757       SDB->CopyToExportRegsIfNeeded(&Arg);
9758     }
9759   }
9760 
9761   if (!Chains.empty()) {
9762     Chains.push_back(NewRoot);
9763     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9764   }
9765 
9766   DAG.setRoot(NewRoot);
9767 
9768   assert(i == InVals.size() && "Argument register count mismatch!");
9769 
9770   // If any argument copy elisions occurred and we have debug info, update the
9771   // stale frame indices used in the dbg.declare variable info table.
9772   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9773   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9774     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9775       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9776       if (I != ArgCopyElisionFrameIndexMap.end())
9777         VI.Slot = I->second;
9778     }
9779   }
9780 
9781   // Finally, if the target has anything special to do, allow it to do so.
9782   EmitFunctionEntryCode();
9783 }
9784 
9785 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9786 /// ensure constants are generated when needed.  Remember the virtual registers
9787 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9788 /// directly add them, because expansion might result in multiple MBB's for one
9789 /// BB.  As such, the start of the BB might correspond to a different MBB than
9790 /// the end.
9791 void
9792 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9793   const Instruction *TI = LLVMBB->getTerminator();
9794 
9795   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9796 
9797   // Check PHI nodes in successors that expect a value to be available from this
9798   // block.
9799   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9800     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9801     if (!isa<PHINode>(SuccBB->begin())) continue;
9802     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9803 
9804     // If this terminator has multiple identical successors (common for
9805     // switches), only handle each succ once.
9806     if (!SuccsHandled.insert(SuccMBB).second)
9807       continue;
9808 
9809     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9810 
9811     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9812     // nodes and Machine PHI nodes, but the incoming operands have not been
9813     // emitted yet.
9814     for (const PHINode &PN : SuccBB->phis()) {
9815       // Ignore dead phi's.
9816       if (PN.use_empty())
9817         continue;
9818 
9819       // Skip empty types
9820       if (PN.getType()->isEmptyTy())
9821         continue;
9822 
9823       unsigned Reg;
9824       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9825 
9826       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9827         unsigned &RegOut = ConstantsOut[C];
9828         if (RegOut == 0) {
9829           RegOut = FuncInfo.CreateRegs(C);
9830           CopyValueToVirtualRegister(C, RegOut);
9831         }
9832         Reg = RegOut;
9833       } else {
9834         DenseMap<const Value *, unsigned>::iterator I =
9835           FuncInfo.ValueMap.find(PHIOp);
9836         if (I != FuncInfo.ValueMap.end())
9837           Reg = I->second;
9838         else {
9839           assert(isa<AllocaInst>(PHIOp) &&
9840                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9841                  "Didn't codegen value into a register!??");
9842           Reg = FuncInfo.CreateRegs(PHIOp);
9843           CopyValueToVirtualRegister(PHIOp, Reg);
9844         }
9845       }
9846 
9847       // Remember that this register needs to added to the machine PHI node as
9848       // the input for this MBB.
9849       SmallVector<EVT, 4> ValueVTs;
9850       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9851       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9852       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9853         EVT VT = ValueVTs[vti];
9854         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9855         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9856           FuncInfo.PHINodesToUpdate.push_back(
9857               std::make_pair(&*MBBI++, Reg + i));
9858         Reg += NumRegisters;
9859       }
9860     }
9861   }
9862 
9863   ConstantsOut.clear();
9864 }
9865 
9866 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9867 /// is 0.
9868 MachineBasicBlock *
9869 SelectionDAGBuilder::StackProtectorDescriptor::
9870 AddSuccessorMBB(const BasicBlock *BB,
9871                 MachineBasicBlock *ParentMBB,
9872                 bool IsLikely,
9873                 MachineBasicBlock *SuccMBB) {
9874   // If SuccBB has not been created yet, create it.
9875   if (!SuccMBB) {
9876     MachineFunction *MF = ParentMBB->getParent();
9877     MachineFunction::iterator BBI(ParentMBB);
9878     SuccMBB = MF->CreateMachineBasicBlock(BB);
9879     MF->insert(++BBI, SuccMBB);
9880   }
9881   // Add it as a successor of ParentMBB.
9882   ParentMBB->addSuccessor(
9883       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9884   return SuccMBB;
9885 }
9886 
9887 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9888   MachineFunction::iterator I(MBB);
9889   if (++I == FuncInfo.MF->end())
9890     return nullptr;
9891   return &*I;
9892 }
9893 
9894 /// During lowering new call nodes can be created (such as memset, etc.).
9895 /// Those will become new roots of the current DAG, but complications arise
9896 /// when they are tail calls. In such cases, the call lowering will update
9897 /// the root, but the builder still needs to know that a tail call has been
9898 /// lowered in order to avoid generating an additional return.
9899 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9900   // If the node is null, we do have a tail call.
9901   if (MaybeTC.getNode() != nullptr)
9902     DAG.setRoot(MaybeTC);
9903   else
9904     HasTailCall = true;
9905 }
9906 
9907 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9908                                         MachineBasicBlock *SwitchMBB,
9909                                         MachineBasicBlock *DefaultMBB) {
9910   MachineFunction *CurMF = FuncInfo.MF;
9911   MachineBasicBlock *NextMBB = nullptr;
9912   MachineFunction::iterator BBI(W.MBB);
9913   if (++BBI != FuncInfo.MF->end())
9914     NextMBB = &*BBI;
9915 
9916   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9917 
9918   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9919 
9920   if (Size == 2 && W.MBB == SwitchMBB) {
9921     // If any two of the cases has the same destination, and if one value
9922     // is the same as the other, but has one bit unset that the other has set,
9923     // use bit manipulation to do two compares at once.  For example:
9924     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9925     // TODO: This could be extended to merge any 2 cases in switches with 3
9926     // cases.
9927     // TODO: Handle cases where W.CaseBB != SwitchBB.
9928     CaseCluster &Small = *W.FirstCluster;
9929     CaseCluster &Big = *W.LastCluster;
9930 
9931     if (Small.Low == Small.High && Big.Low == Big.High &&
9932         Small.MBB == Big.MBB) {
9933       const APInt &SmallValue = Small.Low->getValue();
9934       const APInt &BigValue = Big.Low->getValue();
9935 
9936       // Check that there is only one bit different.
9937       APInt CommonBit = BigValue ^ SmallValue;
9938       if (CommonBit.isPowerOf2()) {
9939         SDValue CondLHS = getValue(Cond);
9940         EVT VT = CondLHS.getValueType();
9941         SDLoc DL = getCurSDLoc();
9942 
9943         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9944                                  DAG.getConstant(CommonBit, DL, VT));
9945         SDValue Cond = DAG.getSetCC(
9946             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9947             ISD::SETEQ);
9948 
9949         // Update successor info.
9950         // Both Small and Big will jump to Small.BB, so we sum up the
9951         // probabilities.
9952         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9953         if (BPI)
9954           addSuccessorWithProb(
9955               SwitchMBB, DefaultMBB,
9956               // The default destination is the first successor in IR.
9957               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9958         else
9959           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9960 
9961         // Insert the true branch.
9962         SDValue BrCond =
9963             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9964                         DAG.getBasicBlock(Small.MBB));
9965         // Insert the false branch.
9966         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9967                              DAG.getBasicBlock(DefaultMBB));
9968 
9969         DAG.setRoot(BrCond);
9970         return;
9971       }
9972     }
9973   }
9974 
9975   if (TM.getOptLevel() != CodeGenOpt::None) {
9976     // Here, we order cases by probability so the most likely case will be
9977     // checked first. However, two clusters can have the same probability in
9978     // which case their relative ordering is non-deterministic. So we use Low
9979     // as a tie-breaker as clusters are guaranteed to never overlap.
9980     llvm::sort(W.FirstCluster, W.LastCluster + 1,
9981                [](const CaseCluster &a, const CaseCluster &b) {
9982       return a.Prob != b.Prob ?
9983              a.Prob > b.Prob :
9984              a.Low->getValue().slt(b.Low->getValue());
9985     });
9986 
9987     // Rearrange the case blocks so that the last one falls through if possible
9988     // without changing the order of probabilities.
9989     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9990       --I;
9991       if (I->Prob > W.LastCluster->Prob)
9992         break;
9993       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9994         std::swap(*I, *W.LastCluster);
9995         break;
9996       }
9997     }
9998   }
9999 
10000   // Compute total probability.
10001   BranchProbability DefaultProb = W.DefaultProb;
10002   BranchProbability UnhandledProbs = DefaultProb;
10003   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10004     UnhandledProbs += I->Prob;
10005 
10006   MachineBasicBlock *CurMBB = W.MBB;
10007   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10008     bool FallthroughUnreachable = false;
10009     MachineBasicBlock *Fallthrough;
10010     if (I == W.LastCluster) {
10011       // For the last cluster, fall through to the default destination.
10012       Fallthrough = DefaultMBB;
10013       FallthroughUnreachable = isa<UnreachableInst>(
10014           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10015     } else {
10016       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10017       CurMF->insert(BBI, Fallthrough);
10018       // Put Cond in a virtual register to make it available from the new blocks.
10019       ExportFromCurrentBlock(Cond);
10020     }
10021     UnhandledProbs -= I->Prob;
10022 
10023     switch (I->Kind) {
10024       case CC_JumpTable: {
10025         // FIXME: Optimize away range check based on pivot comparisons.
10026         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10027         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10028 
10029         // The jump block hasn't been inserted yet; insert it here.
10030         MachineBasicBlock *JumpMBB = JT->MBB;
10031         CurMF->insert(BBI, JumpMBB);
10032 
10033         auto JumpProb = I->Prob;
10034         auto FallthroughProb = UnhandledProbs;
10035 
10036         // If the default statement is a target of the jump table, we evenly
10037         // distribute the default probability to successors of CurMBB. Also
10038         // update the probability on the edge from JumpMBB to Fallthrough.
10039         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10040                                               SE = JumpMBB->succ_end();
10041              SI != SE; ++SI) {
10042           if (*SI == DefaultMBB) {
10043             JumpProb += DefaultProb / 2;
10044             FallthroughProb -= DefaultProb / 2;
10045             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10046             JumpMBB->normalizeSuccProbs();
10047             break;
10048           }
10049         }
10050 
10051         if (FallthroughUnreachable) {
10052           // Skip the range check if the fallthrough block is unreachable.
10053           JTH->OmitRangeCheck = true;
10054         }
10055 
10056         if (!JTH->OmitRangeCheck)
10057           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10058         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10059         CurMBB->normalizeSuccProbs();
10060 
10061         // The jump table header will be inserted in our current block, do the
10062         // range check, and fall through to our fallthrough block.
10063         JTH->HeaderBB = CurMBB;
10064         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10065 
10066         // If we're in the right place, emit the jump table header right now.
10067         if (CurMBB == SwitchMBB) {
10068           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10069           JTH->Emitted = true;
10070         }
10071         break;
10072       }
10073       case CC_BitTests: {
10074         // FIXME: If Fallthrough is unreachable, skip the range check.
10075 
10076         // FIXME: Optimize away range check based on pivot comparisons.
10077         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10078 
10079         // The bit test blocks haven't been inserted yet; insert them here.
10080         for (BitTestCase &BTC : BTB->Cases)
10081           CurMF->insert(BBI, BTC.ThisBB);
10082 
10083         // Fill in fields of the BitTestBlock.
10084         BTB->Parent = CurMBB;
10085         BTB->Default = Fallthrough;
10086 
10087         BTB->DefaultProb = UnhandledProbs;
10088         // If the cases in bit test don't form a contiguous range, we evenly
10089         // distribute the probability on the edge to Fallthrough to two
10090         // successors of CurMBB.
10091         if (!BTB->ContiguousRange) {
10092           BTB->Prob += DefaultProb / 2;
10093           BTB->DefaultProb -= DefaultProb / 2;
10094         }
10095 
10096         // If we're in the right place, emit the bit test header right now.
10097         if (CurMBB == SwitchMBB) {
10098           visitBitTestHeader(*BTB, SwitchMBB);
10099           BTB->Emitted = true;
10100         }
10101         break;
10102       }
10103       case CC_Range: {
10104         const Value *RHS, *LHS, *MHS;
10105         ISD::CondCode CC;
10106         if (I->Low == I->High) {
10107           // Check Cond == I->Low.
10108           CC = ISD::SETEQ;
10109           LHS = Cond;
10110           RHS=I->Low;
10111           MHS = nullptr;
10112         } else {
10113           // Check I->Low <= Cond <= I->High.
10114           CC = ISD::SETLE;
10115           LHS = I->Low;
10116           MHS = Cond;
10117           RHS = I->High;
10118         }
10119 
10120         // If Fallthrough is unreachable, fold away the comparison.
10121         if (FallthroughUnreachable)
10122           CC = ISD::SETTRUE;
10123 
10124         // The false probability is the sum of all unhandled cases.
10125         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10126                      getCurSDLoc(), I->Prob, UnhandledProbs);
10127 
10128         if (CurMBB == SwitchMBB)
10129           visitSwitchCase(CB, SwitchMBB);
10130         else
10131           SL->SwitchCases.push_back(CB);
10132 
10133         break;
10134       }
10135     }
10136     CurMBB = Fallthrough;
10137   }
10138 }
10139 
10140 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10141                                               CaseClusterIt First,
10142                                               CaseClusterIt Last) {
10143   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10144     if (X.Prob != CC.Prob)
10145       return X.Prob > CC.Prob;
10146 
10147     // Ties are broken by comparing the case value.
10148     return X.Low->getValue().slt(CC.Low->getValue());
10149   });
10150 }
10151 
10152 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10153                                         const SwitchWorkListItem &W,
10154                                         Value *Cond,
10155                                         MachineBasicBlock *SwitchMBB) {
10156   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10157          "Clusters not sorted?");
10158 
10159   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10160 
10161   // Balance the tree based on branch probabilities to create a near-optimal (in
10162   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10163   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10164   CaseClusterIt LastLeft = W.FirstCluster;
10165   CaseClusterIt FirstRight = W.LastCluster;
10166   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10167   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10168 
10169   // Move LastLeft and FirstRight towards each other from opposite directions to
10170   // find a partitioning of the clusters which balances the probability on both
10171   // sides. If LeftProb and RightProb are equal, alternate which side is
10172   // taken to ensure 0-probability nodes are distributed evenly.
10173   unsigned I = 0;
10174   while (LastLeft + 1 < FirstRight) {
10175     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10176       LeftProb += (++LastLeft)->Prob;
10177     else
10178       RightProb += (--FirstRight)->Prob;
10179     I++;
10180   }
10181 
10182   while (true) {
10183     // Our binary search tree differs from a typical BST in that ours can have up
10184     // to three values in each leaf. The pivot selection above doesn't take that
10185     // into account, which means the tree might require more nodes and be less
10186     // efficient. We compensate for this here.
10187 
10188     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10189     unsigned NumRight = W.LastCluster - FirstRight + 1;
10190 
10191     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10192       // If one side has less than 3 clusters, and the other has more than 3,
10193       // consider taking a cluster from the other side.
10194 
10195       if (NumLeft < NumRight) {
10196         // Consider moving the first cluster on the right to the left side.
10197         CaseCluster &CC = *FirstRight;
10198         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10199         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10200         if (LeftSideRank <= RightSideRank) {
10201           // Moving the cluster to the left does not demote it.
10202           ++LastLeft;
10203           ++FirstRight;
10204           continue;
10205         }
10206       } else {
10207         assert(NumRight < NumLeft);
10208         // Consider moving the last element on the left to the right side.
10209         CaseCluster &CC = *LastLeft;
10210         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10211         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10212         if (RightSideRank <= LeftSideRank) {
10213           // Moving the cluster to the right does not demot it.
10214           --LastLeft;
10215           --FirstRight;
10216           continue;
10217         }
10218       }
10219     }
10220     break;
10221   }
10222 
10223   assert(LastLeft + 1 == FirstRight);
10224   assert(LastLeft >= W.FirstCluster);
10225   assert(FirstRight <= W.LastCluster);
10226 
10227   // Use the first element on the right as pivot since we will make less-than
10228   // comparisons against it.
10229   CaseClusterIt PivotCluster = FirstRight;
10230   assert(PivotCluster > W.FirstCluster);
10231   assert(PivotCluster <= W.LastCluster);
10232 
10233   CaseClusterIt FirstLeft = W.FirstCluster;
10234   CaseClusterIt LastRight = W.LastCluster;
10235 
10236   const ConstantInt *Pivot = PivotCluster->Low;
10237 
10238   // New blocks will be inserted immediately after the current one.
10239   MachineFunction::iterator BBI(W.MBB);
10240   ++BBI;
10241 
10242   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10243   // we can branch to its destination directly if it's squeezed exactly in
10244   // between the known lower bound and Pivot - 1.
10245   MachineBasicBlock *LeftMBB;
10246   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10247       FirstLeft->Low == W.GE &&
10248       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10249     LeftMBB = FirstLeft->MBB;
10250   } else {
10251     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10252     FuncInfo.MF->insert(BBI, LeftMBB);
10253     WorkList.push_back(
10254         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10255     // Put Cond in a virtual register to make it available from the new blocks.
10256     ExportFromCurrentBlock(Cond);
10257   }
10258 
10259   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10260   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10261   // directly if RHS.High equals the current upper bound.
10262   MachineBasicBlock *RightMBB;
10263   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10264       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10265     RightMBB = FirstRight->MBB;
10266   } else {
10267     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10268     FuncInfo.MF->insert(BBI, RightMBB);
10269     WorkList.push_back(
10270         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10271     // Put Cond in a virtual register to make it available from the new blocks.
10272     ExportFromCurrentBlock(Cond);
10273   }
10274 
10275   // Create the CaseBlock record that will be used to lower the branch.
10276   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10277                getCurSDLoc(), LeftProb, RightProb);
10278 
10279   if (W.MBB == SwitchMBB)
10280     visitSwitchCase(CB, SwitchMBB);
10281   else
10282     SL->SwitchCases.push_back(CB);
10283 }
10284 
10285 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10286 // from the swith statement.
10287 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10288                                             BranchProbability PeeledCaseProb) {
10289   if (PeeledCaseProb == BranchProbability::getOne())
10290     return BranchProbability::getZero();
10291   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10292 
10293   uint32_t Numerator = CaseProb.getNumerator();
10294   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10295   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10296 }
10297 
10298 // Try to peel the top probability case if it exceeds the threshold.
10299 // Return current MachineBasicBlock for the switch statement if the peeling
10300 // does not occur.
10301 // If the peeling is performed, return the newly created MachineBasicBlock
10302 // for the peeled switch statement. Also update Clusters to remove the peeled
10303 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10304 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10305     const SwitchInst &SI, CaseClusterVector &Clusters,
10306     BranchProbability &PeeledCaseProb) {
10307   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10308   // Don't perform if there is only one cluster or optimizing for size.
10309   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10310       TM.getOptLevel() == CodeGenOpt::None ||
10311       SwitchMBB->getParent()->getFunction().hasMinSize())
10312     return SwitchMBB;
10313 
10314   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10315   unsigned PeeledCaseIndex = 0;
10316   bool SwitchPeeled = false;
10317   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10318     CaseCluster &CC = Clusters[Index];
10319     if (CC.Prob < TopCaseProb)
10320       continue;
10321     TopCaseProb = CC.Prob;
10322     PeeledCaseIndex = Index;
10323     SwitchPeeled = true;
10324   }
10325   if (!SwitchPeeled)
10326     return SwitchMBB;
10327 
10328   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10329                     << TopCaseProb << "\n");
10330 
10331   // Record the MBB for the peeled switch statement.
10332   MachineFunction::iterator BBI(SwitchMBB);
10333   ++BBI;
10334   MachineBasicBlock *PeeledSwitchMBB =
10335       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10336   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10337 
10338   ExportFromCurrentBlock(SI.getCondition());
10339   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10340   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10341                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10342   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10343 
10344   Clusters.erase(PeeledCaseIt);
10345   for (CaseCluster &CC : Clusters) {
10346     LLVM_DEBUG(
10347         dbgs() << "Scale the probablity for one cluster, before scaling: "
10348                << CC.Prob << "\n");
10349     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10350     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10351   }
10352   PeeledCaseProb = TopCaseProb;
10353   return PeeledSwitchMBB;
10354 }
10355 
10356 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10357   // Extract cases from the switch.
10358   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10359   CaseClusterVector Clusters;
10360   Clusters.reserve(SI.getNumCases());
10361   for (auto I : SI.cases()) {
10362     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10363     const ConstantInt *CaseVal = I.getCaseValue();
10364     BranchProbability Prob =
10365         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10366             : BranchProbability(1, SI.getNumCases() + 1);
10367     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10368   }
10369 
10370   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10371 
10372   // Cluster adjacent cases with the same destination. We do this at all
10373   // optimization levels because it's cheap to do and will make codegen faster
10374   // if there are many clusters.
10375   sortAndRangeify(Clusters);
10376 
10377   // The branch probablity of the peeled case.
10378   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10379   MachineBasicBlock *PeeledSwitchMBB =
10380       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10381 
10382   // If there is only the default destination, jump there directly.
10383   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10384   if (Clusters.empty()) {
10385     assert(PeeledSwitchMBB == SwitchMBB);
10386     SwitchMBB->addSuccessor(DefaultMBB);
10387     if (DefaultMBB != NextBlock(SwitchMBB)) {
10388       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10389                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10390     }
10391     return;
10392   }
10393 
10394   SL->findJumpTables(Clusters, &SI, DefaultMBB);
10395   SL->findBitTestClusters(Clusters, &SI);
10396 
10397   LLVM_DEBUG({
10398     dbgs() << "Case clusters: ";
10399     for (const CaseCluster &C : Clusters) {
10400       if (C.Kind == CC_JumpTable)
10401         dbgs() << "JT:";
10402       if (C.Kind == CC_BitTests)
10403         dbgs() << "BT:";
10404 
10405       C.Low->getValue().print(dbgs(), true);
10406       if (C.Low != C.High) {
10407         dbgs() << '-';
10408         C.High->getValue().print(dbgs(), true);
10409       }
10410       dbgs() << ' ';
10411     }
10412     dbgs() << '\n';
10413   });
10414 
10415   assert(!Clusters.empty());
10416   SwitchWorkList WorkList;
10417   CaseClusterIt First = Clusters.begin();
10418   CaseClusterIt Last = Clusters.end() - 1;
10419   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10420   // Scale the branchprobability for DefaultMBB if the peel occurs and
10421   // DefaultMBB is not replaced.
10422   if (PeeledCaseProb != BranchProbability::getZero() &&
10423       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10424     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10425   WorkList.push_back(
10426       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10427 
10428   while (!WorkList.empty()) {
10429     SwitchWorkListItem W = WorkList.back();
10430     WorkList.pop_back();
10431     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10432 
10433     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10434         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10435       // For optimized builds, lower large range as a balanced binary tree.
10436       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10437       continue;
10438     }
10439 
10440     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10441   }
10442 }
10443