xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 291713a596fb165d0029d05a835c437371cad67f)
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/TargetFrameLowering.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/CodeGen/WinEHFuncInfo.h"
65 #include "llvm/IR/Argument.h"
66 #include "llvm/IR/Attributes.h"
67 #include "llvm/IR/BasicBlock.h"
68 #include "llvm/IR/CFG.h"
69 #include "llvm/IR/CallSite.h"
70 #include "llvm/IR/CallingConv.h"
71 #include "llvm/IR/Constant.h"
72 #include "llvm/IR/ConstantRange.h"
73 #include "llvm/IR/Constants.h"
74 #include "llvm/IR/DataLayout.h"
75 #include "llvm/IR/DebugInfoMetadata.h"
76 #include "llvm/IR/DebugLoc.h"
77 #include "llvm/IR/DerivedTypes.h"
78 #include "llvm/IR/Function.h"
79 #include "llvm/IR/GetElementPtrTypeIterator.h"
80 #include "llvm/IR/InlineAsm.h"
81 #include "llvm/IR/InstrTypes.h"
82 #include "llvm/IR/Instruction.h"
83 #include "llvm/IR/Instructions.h"
84 #include "llvm/IR/IntrinsicInst.h"
85 #include "llvm/IR/Intrinsics.h"
86 #include "llvm/IR/LLVMContext.h"
87 #include "llvm/IR/Metadata.h"
88 #include "llvm/IR/Module.h"
89 #include "llvm/IR/Operator.h"
90 #include "llvm/IR/PatternMatch.h"
91 #include "llvm/IR/Statepoint.h"
92 #include "llvm/IR/Type.h"
93 #include "llvm/IR/User.h"
94 #include "llvm/IR/Value.h"
95 #include "llvm/MC/MCContext.h"
96 #include "llvm/MC/MCSymbol.h"
97 #include "llvm/Support/AtomicOrdering.h"
98 #include "llvm/Support/BranchProbability.h"
99 #include "llvm/Support/Casting.h"
100 #include "llvm/Support/CodeGen.h"
101 #include "llvm/Support/CommandLine.h"
102 #include "llvm/Support/Compiler.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Support/ErrorHandling.h"
105 #include "llvm/Support/MachineValueType.h"
106 #include "llvm/Support/MathExtras.h"
107 #include "llvm/Support/raw_ostream.h"
108 #include "llvm/Target/TargetIntrinsicInfo.h"
109 #include "llvm/Target/TargetMachine.h"
110 #include "llvm/Target/TargetOptions.h"
111 #include "llvm/Transforms/Utils/Local.h"
112 #include <algorithm>
113 #include <cassert>
114 #include <cstddef>
115 #include <cstdint>
116 #include <cstring>
117 #include <iterator>
118 #include <limits>
119 #include <numeric>
120 #include <tuple>
121 #include <utility>
122 #include <vector>
123 
124 using namespace llvm;
125 using namespace PatternMatch;
126 
127 #define DEBUG_TYPE "isel"
128 
129 /// LimitFloatPrecision - Generate low-precision inline sequences for
130 /// some float libcalls (6, 8 or 12 bits).
131 static unsigned LimitFloatPrecision;
132 
133 static cl::opt<unsigned, true>
134     LimitFPPrecision("limit-float-precision",
135                      cl::desc("Generate low-precision inline sequences "
136                               "for some float libcalls"),
137                      cl::location(LimitFloatPrecision), cl::Hidden,
138                      cl::init(0));
139 
140 static cl::opt<unsigned> SwitchPeelThreshold(
141     "switch-peel-threshold", cl::Hidden, cl::init(66),
142     cl::desc("Set the case probability threshold for peeling the case from a "
143              "switch statement. A value greater than 100 will void this "
144              "optimization"));
145 
146 // Limit the width of DAG chains. This is important in general to prevent
147 // DAG-based analysis from blowing up. For example, alias analysis and
148 // load clustering may not complete in reasonable time. It is difficult to
149 // recognize and avoid this situation within each individual analysis, and
150 // future analyses are likely to have the same behavior. Limiting DAG width is
151 // the safe approach and will be especially important with global DAGs.
152 //
153 // MaxParallelChains default is arbitrarily high to avoid affecting
154 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
155 // sequence over this should have been converted to llvm.memcpy by the
156 // frontend. It is easy to induce this behavior with .ll code such as:
157 // %buffer = alloca [4096 x i8]
158 // %data = load [4096 x i8]* %argPtr
159 // store [4096 x i8] %data, [4096 x i8]* %buffer
160 static const unsigned MaxParallelChains = 64;
161 
162 // Return the calling convention if the Value passed requires ABI mangling as it
163 // is a parameter to a function or a return value from a function which is not
164 // an intrinsic.
165 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
166   if (auto *R = dyn_cast<ReturnInst>(V))
167     return R->getParent()->getParent()->getCallingConv();
168 
169   if (auto *CI = dyn_cast<CallInst>(V)) {
170     const bool IsInlineAsm = CI->isInlineAsm();
171     const bool IsIndirectFunctionCall =
172         !IsInlineAsm && !CI->getCalledFunction();
173 
174     // It is possible that the call instruction is an inline asm statement or an
175     // indirect function call in which case the return value of
176     // getCalledFunction() would be nullptr.
177     const bool IsInstrinsicCall =
178         !IsInlineAsm && !IsIndirectFunctionCall &&
179         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
180 
181     if (!IsInlineAsm && !IsInstrinsicCall)
182       return CI->getCallingConv();
183   }
184 
185   return None;
186 }
187 
188 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
189                                       const SDValue *Parts, unsigned NumParts,
190                                       MVT PartVT, EVT ValueVT, const Value *V,
191                                       Optional<CallingConv::ID> CC);
192 
193 /// getCopyFromParts - Create a value that contains the specified legal parts
194 /// combined into the value they represent.  If the parts combine to a type
195 /// larger than ValueVT then AssertOp can be used to specify whether the extra
196 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
197 /// (ISD::AssertSext).
198 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
199                                 const SDValue *Parts, unsigned NumParts,
200                                 MVT PartVT, EVT ValueVT, const Value *V,
201                                 Optional<CallingConv::ID> CC = None,
202                                 Optional<ISD::NodeType> AssertOp = None) {
203   if (ValueVT.isVector())
204     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
205                                   CC);
206 
207   assert(NumParts > 0 && "No parts to assemble!");
208   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
209   SDValue Val = Parts[0];
210 
211   if (NumParts > 1) {
212     // Assemble the value from multiple parts.
213     if (ValueVT.isInteger()) {
214       unsigned PartBits = PartVT.getSizeInBits();
215       unsigned ValueBits = ValueVT.getSizeInBits();
216 
217       // Assemble the power of 2 part.
218       unsigned RoundParts = NumParts & (NumParts - 1) ?
219         1 << Log2_32(NumParts) : NumParts;
220       unsigned RoundBits = PartBits * RoundParts;
221       EVT RoundVT = RoundBits == ValueBits ?
222         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
223       SDValue Lo, Hi;
224 
225       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
226 
227       if (RoundParts > 2) {
228         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
229                               PartVT, HalfVT, V);
230         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
231                               RoundParts / 2, PartVT, HalfVT, V);
232       } else {
233         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
234         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
235       }
236 
237       if (DAG.getDataLayout().isBigEndian())
238         std::swap(Lo, Hi);
239 
240       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
241 
242       if (RoundParts < NumParts) {
243         // Assemble the trailing non-power-of-2 part.
244         unsigned OddParts = NumParts - RoundParts;
245         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
246         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
247                               OddVT, V, CC);
248 
249         // Combine the round and odd parts.
250         Lo = Val;
251         if (DAG.getDataLayout().isBigEndian())
252           std::swap(Lo, Hi);
253         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
254         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
255         Hi =
256             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
257                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
258                                         TLI.getPointerTy(DAG.getDataLayout())));
259         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
260         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
261       }
262     } else if (PartVT.isFloatingPoint()) {
263       // FP split into multiple FP parts (for ppcf128)
264       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
265              "Unexpected split");
266       SDValue Lo, Hi;
267       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
268       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
269       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
270         std::swap(Lo, Hi);
271       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
272     } else {
273       // FP split into integer parts (soft fp)
274       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
275              !PartVT.isVector() && "Unexpected split");
276       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
277       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
278     }
279   }
280 
281   // There is now one part, held in Val.  Correct it to match ValueVT.
282   // PartEVT is the type of the register class that holds the value.
283   // ValueVT is the type of the inline asm operation.
284   EVT PartEVT = Val.getValueType();
285 
286   if (PartEVT == ValueVT)
287     return Val;
288 
289   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
290       ValueVT.bitsLT(PartEVT)) {
291     // For an FP value in an integer part, we need to truncate to the right
292     // width first.
293     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
294     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
295   }
296 
297   // Handle types that have the same size.
298   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
299     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
300 
301   // Handle types with different sizes.
302   if (PartEVT.isInteger() && ValueVT.isInteger()) {
303     if (ValueVT.bitsLT(PartEVT)) {
304       // For a truncate, see if we have any information to
305       // indicate whether the truncated bits will always be
306       // zero or sign-extension.
307       if (AssertOp.hasValue())
308         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
309                           DAG.getValueType(ValueVT));
310       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
311     }
312     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
313   }
314 
315   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
316     // FP_ROUND's are always exact here.
317     if (ValueVT.bitsLT(Val.getValueType()))
318       return DAG.getNode(
319           ISD::FP_ROUND, DL, ValueVT, Val,
320           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
321 
322     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
323   }
324 
325   llvm_unreachable("Unknown mismatch!");
326 }
327 
328 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
329                                               const Twine &ErrMsg) {
330   const Instruction *I = dyn_cast_or_null<Instruction>(V);
331   if (!V)
332     return Ctx.emitError(ErrMsg);
333 
334   const char *AsmError = ", possible invalid constraint for vector type";
335   if (const CallInst *CI = dyn_cast<CallInst>(I))
336     if (isa<InlineAsm>(CI->getCalledValue()))
337       return Ctx.emitError(I, ErrMsg + AsmError);
338 
339   return Ctx.emitError(I, ErrMsg);
340 }
341 
342 /// getCopyFromPartsVector - Create a value that contains the specified legal
343 /// parts combined into the value they represent.  If the parts combine to a
344 /// type larger than ValueVT then AssertOp can be used to specify whether the
345 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
346 /// ValueVT (ISD::AssertSext).
347 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
348                                       const SDValue *Parts, unsigned NumParts,
349                                       MVT PartVT, EVT ValueVT, const Value *V,
350                                       Optional<CallingConv::ID> CallConv) {
351   assert(ValueVT.isVector() && "Not a vector value");
352   assert(NumParts > 0 && "No parts to assemble!");
353   const bool IsABIRegCopy = CallConv.hasValue();
354 
355   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
356   SDValue Val = Parts[0];
357 
358   // Handle a multi-element vector.
359   if (NumParts > 1) {
360     EVT IntermediateVT;
361     MVT RegisterVT;
362     unsigned NumIntermediates;
363     unsigned NumRegs;
364 
365     if (IsABIRegCopy) {
366       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
367           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
368           NumIntermediates, RegisterVT);
369     } else {
370       NumRegs =
371           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
372                                      NumIntermediates, RegisterVT);
373     }
374 
375     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
376     NumParts = NumRegs; // Silence a compiler warning.
377     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
378     assert(RegisterVT.getSizeInBits() ==
379            Parts[0].getSimpleValueType().getSizeInBits() &&
380            "Part type sizes don't match!");
381 
382     // Assemble the parts into intermediate operands.
383     SmallVector<SDValue, 8> Ops(NumIntermediates);
384     if (NumIntermediates == NumParts) {
385       // If the register was not expanded, truncate or copy the value,
386       // as appropriate.
387       for (unsigned i = 0; i != NumParts; ++i)
388         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
389                                   PartVT, IntermediateVT, V);
390     } else if (NumParts > 0) {
391       // If the intermediate type was expanded, build the intermediate
392       // operands from the parts.
393       assert(NumParts % NumIntermediates == 0 &&
394              "Must expand into a divisible number of parts!");
395       unsigned Factor = NumParts / NumIntermediates;
396       for (unsigned i = 0; i != NumIntermediates; ++i)
397         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
398                                   PartVT, IntermediateVT, V);
399     }
400 
401     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
402     // intermediate operands.
403     EVT BuiltVectorTy =
404         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
405                          (IntermediateVT.isVector()
406                               ? IntermediateVT.getVectorNumElements() * NumParts
407                               : NumIntermediates));
408     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
409                                                 : ISD::BUILD_VECTOR,
410                       DL, BuiltVectorTy, Ops);
411   }
412 
413   // There is now one part, held in Val.  Correct it to match ValueVT.
414   EVT PartEVT = Val.getValueType();
415 
416   if (PartEVT == ValueVT)
417     return Val;
418 
419   if (PartEVT.isVector()) {
420     // If the element type of the source/dest vectors are the same, but the
421     // parts vector has more elements than the value vector, then we have a
422     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
423     // elements we want.
424     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
425       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
426              "Cannot narrow, it would be a lossy transformation");
427       return DAG.getNode(
428           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
429           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
430     }
431 
432     // Vector/Vector bitcast.
433     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
434       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
435 
436     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
437       "Cannot handle this kind of promotion");
438     // Promoted vector extract
439     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
440 
441   }
442 
443   // Trivial bitcast if the types are the same size and the destination
444   // vector type is legal.
445   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
446       TLI.isTypeLegal(ValueVT))
447     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
448 
449   if (ValueVT.getVectorNumElements() != 1) {
450      // Certain ABIs require that vectors are passed as integers. For vectors
451      // are the same size, this is an obvious bitcast.
452      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
453        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
454      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
455        // Bitcast Val back the original type and extract the corresponding
456        // vector we want.
457        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
458        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
459                                            ValueVT.getVectorElementType(), Elts);
460        Val = DAG.getBitcast(WiderVecType, Val);
461        return DAG.getNode(
462            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
463            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
464      }
465 
466      diagnosePossiblyInvalidConstraint(
467          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
468      return DAG.getUNDEF(ValueVT);
469   }
470 
471   // Handle cases such as i8 -> <1 x i1>
472   EVT ValueSVT = ValueVT.getVectorElementType();
473   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
474     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
475                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
476 
477   return DAG.getBuildVector(ValueVT, DL, Val);
478 }
479 
480 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
481                                  SDValue Val, SDValue *Parts, unsigned NumParts,
482                                  MVT PartVT, const Value *V,
483                                  Optional<CallingConv::ID> CallConv);
484 
485 /// getCopyToParts - Create a series of nodes that contain the specified value
486 /// split into legal parts.  If the parts contain more bits than Val, then, for
487 /// integers, ExtendKind can be used to specify how to generate the extra bits.
488 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
489                            SDValue *Parts, unsigned NumParts, MVT PartVT,
490                            const Value *V,
491                            Optional<CallingConv::ID> CallConv = None,
492                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
493   EVT ValueVT = Val.getValueType();
494 
495   // Handle the vector case separately.
496   if (ValueVT.isVector())
497     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
498                                 CallConv);
499 
500   unsigned PartBits = PartVT.getSizeInBits();
501   unsigned OrigNumParts = NumParts;
502   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
503          "Copying to an illegal type!");
504 
505   if (NumParts == 0)
506     return;
507 
508   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
509   EVT PartEVT = PartVT;
510   if (PartEVT == ValueVT) {
511     assert(NumParts == 1 && "No-op copy with multiple parts!");
512     Parts[0] = Val;
513     return;
514   }
515 
516   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
517     // If the parts cover more bits than the value has, promote the value.
518     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
519       assert(NumParts == 1 && "Do not know what to promote to!");
520       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
521     } else {
522       if (ValueVT.isFloatingPoint()) {
523         // FP values need to be bitcast, then extended if they are being put
524         // into a larger container.
525         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
526         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
527       }
528       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
529              ValueVT.isInteger() &&
530              "Unknown mismatch!");
531       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
532       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
533       if (PartVT == MVT::x86mmx)
534         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
535     }
536   } else if (PartBits == ValueVT.getSizeInBits()) {
537     // Different types of the same size.
538     assert(NumParts == 1 && PartEVT != ValueVT);
539     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
540   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
541     // If the parts cover less bits than value has, truncate the value.
542     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
543            ValueVT.isInteger() &&
544            "Unknown mismatch!");
545     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
546     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
547     if (PartVT == MVT::x86mmx)
548       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
549   }
550 
551   // The value may have changed - recompute ValueVT.
552   ValueVT = Val.getValueType();
553   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
554          "Failed to tile the value with PartVT!");
555 
556   if (NumParts == 1) {
557     if (PartEVT != ValueVT) {
558       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
559                                         "scalar-to-vector conversion failed");
560       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
561     }
562 
563     Parts[0] = Val;
564     return;
565   }
566 
567   // Expand the value into multiple parts.
568   if (NumParts & (NumParts - 1)) {
569     // The number of parts is not a power of 2.  Split off and copy the tail.
570     assert(PartVT.isInteger() && ValueVT.isInteger() &&
571            "Do not know what to expand to!");
572     unsigned RoundParts = 1 << Log2_32(NumParts);
573     unsigned RoundBits = RoundParts * PartBits;
574     unsigned OddParts = NumParts - RoundParts;
575     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
576                                  DAG.getIntPtrConstant(RoundBits, DL));
577     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
578                    CallConv);
579 
580     if (DAG.getDataLayout().isBigEndian())
581       // The odd parts were reversed by getCopyToParts - unreverse them.
582       std::reverse(Parts + RoundParts, Parts + NumParts);
583 
584     NumParts = RoundParts;
585     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
586     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
587   }
588 
589   // The number of parts is a power of 2.  Repeatedly bisect the value using
590   // EXTRACT_ELEMENT.
591   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
592                          EVT::getIntegerVT(*DAG.getContext(),
593                                            ValueVT.getSizeInBits()),
594                          Val);
595 
596   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
597     for (unsigned i = 0; i < NumParts; i += StepSize) {
598       unsigned ThisBits = StepSize * PartBits / 2;
599       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
600       SDValue &Part0 = Parts[i];
601       SDValue &Part1 = Parts[i+StepSize/2];
602 
603       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
604                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
605       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
606                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
607 
608       if (ThisBits == PartBits && ThisVT != PartVT) {
609         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
610         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
611       }
612     }
613   }
614 
615   if (DAG.getDataLayout().isBigEndian())
616     std::reverse(Parts, Parts + OrigNumParts);
617 }
618 
619 static SDValue widenVectorToPartType(SelectionDAG &DAG,
620                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
621   if (!PartVT.isVector())
622     return SDValue();
623 
624   EVT ValueVT = Val.getValueType();
625   unsigned PartNumElts = PartVT.getVectorNumElements();
626   unsigned ValueNumElts = ValueVT.getVectorNumElements();
627   if (PartNumElts > ValueNumElts &&
628       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
629     EVT ElementVT = PartVT.getVectorElementType();
630     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
631     // undef elements.
632     SmallVector<SDValue, 16> Ops;
633     DAG.ExtractVectorElements(Val, Ops);
634     SDValue EltUndef = DAG.getUNDEF(ElementVT);
635     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
636       Ops.push_back(EltUndef);
637 
638     // FIXME: Use CONCAT for 2x -> 4x.
639     return DAG.getBuildVector(PartVT, DL, Ops);
640   }
641 
642   return SDValue();
643 }
644 
645 /// getCopyToPartsVector - Create a series of nodes that contain the specified
646 /// value split into legal parts.
647 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
648                                  SDValue Val, SDValue *Parts, unsigned NumParts,
649                                  MVT PartVT, const Value *V,
650                                  Optional<CallingConv::ID> CallConv) {
651   EVT ValueVT = Val.getValueType();
652   assert(ValueVT.isVector() && "Not a vector");
653   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
654   const bool IsABIRegCopy = CallConv.hasValue();
655 
656   if (NumParts == 1) {
657     EVT PartEVT = PartVT;
658     if (PartEVT == ValueVT) {
659       // Nothing to do.
660     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
661       // Bitconvert vector->vector case.
662       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
663     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
664       Val = Widened;
665     } else if (PartVT.isVector() &&
666                PartEVT.getVectorElementType().bitsGE(
667                  ValueVT.getVectorElementType()) &&
668                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
669 
670       // Promoted vector extract
671       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
672     } else {
673       if (ValueVT.getVectorNumElements() == 1) {
674         Val = DAG.getNode(
675             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
676             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
677       } else {
678         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
679                "lossy conversion of vector to scalar type");
680         EVT IntermediateType =
681             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
682         Val = DAG.getBitcast(IntermediateType, Val);
683         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
684       }
685     }
686 
687     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
688     Parts[0] = Val;
689     return;
690   }
691 
692   // Handle a multi-element vector.
693   EVT IntermediateVT;
694   MVT RegisterVT;
695   unsigned NumIntermediates;
696   unsigned NumRegs;
697   if (IsABIRegCopy) {
698     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
699         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
700         NumIntermediates, RegisterVT);
701   } else {
702     NumRegs =
703         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
704                                    NumIntermediates, RegisterVT);
705   }
706 
707   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
708   NumParts = NumRegs; // Silence a compiler warning.
709   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
710 
711   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
712     IntermediateVT.getVectorNumElements() : 1;
713 
714   // Convert the vector to the appropiate type if necessary.
715   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
716 
717   EVT BuiltVectorTy = EVT::getVectorVT(
718       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
719   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
720   if (ValueVT != BuiltVectorTy) {
721     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
722       Val = Widened;
723 
724     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
725   }
726 
727   // Split the vector into intermediate operands.
728   SmallVector<SDValue, 8> Ops(NumIntermediates);
729   for (unsigned i = 0; i != NumIntermediates; ++i) {
730     if (IntermediateVT.isVector()) {
731       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
732                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
733     } else {
734       Ops[i] = DAG.getNode(
735           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
736           DAG.getConstant(i, DL, IdxVT));
737     }
738   }
739 
740   // Split the intermediate operands into legal parts.
741   if (NumParts == NumIntermediates) {
742     // If the register was not expanded, promote or copy the value,
743     // as appropriate.
744     for (unsigned i = 0; i != NumParts; ++i)
745       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
746   } else if (NumParts > 0) {
747     // If the intermediate type was expanded, split each the value into
748     // legal parts.
749     assert(NumIntermediates != 0 && "division by zero");
750     assert(NumParts % NumIntermediates == 0 &&
751            "Must expand into a divisible number of parts!");
752     unsigned Factor = NumParts / NumIntermediates;
753     for (unsigned i = 0; i != NumIntermediates; ++i)
754       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
755                      CallConv);
756   }
757 }
758 
759 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
760                            EVT valuevt, Optional<CallingConv::ID> CC)
761     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
762       RegCount(1, regs.size()), CallConv(CC) {}
763 
764 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
765                            const DataLayout &DL, unsigned Reg, Type *Ty,
766                            Optional<CallingConv::ID> CC) {
767   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
768 
769   CallConv = CC;
770 
771   for (EVT ValueVT : ValueVTs) {
772     unsigned NumRegs =
773         isABIMangled()
774             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
775             : TLI.getNumRegisters(Context, ValueVT);
776     MVT RegisterVT =
777         isABIMangled()
778             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
779             : TLI.getRegisterType(Context, ValueVT);
780     for (unsigned i = 0; i != NumRegs; ++i)
781       Regs.push_back(Reg + i);
782     RegVTs.push_back(RegisterVT);
783     RegCount.push_back(NumRegs);
784     Reg += NumRegs;
785   }
786 }
787 
788 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
789                                       FunctionLoweringInfo &FuncInfo,
790                                       const SDLoc &dl, SDValue &Chain,
791                                       SDValue *Flag, const Value *V) const {
792   // A Value with type {} or [0 x %t] needs no registers.
793   if (ValueVTs.empty())
794     return SDValue();
795 
796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
797 
798   // Assemble the legal parts into the final values.
799   SmallVector<SDValue, 4> Values(ValueVTs.size());
800   SmallVector<SDValue, 8> Parts;
801   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
802     // Copy the legal parts from the registers.
803     EVT ValueVT = ValueVTs[Value];
804     unsigned NumRegs = RegCount[Value];
805     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
806                                           *DAG.getContext(),
807                                           CallConv.getValue(), RegVTs[Value])
808                                     : RegVTs[Value];
809 
810     Parts.resize(NumRegs);
811     for (unsigned i = 0; i != NumRegs; ++i) {
812       SDValue P;
813       if (!Flag) {
814         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
815       } else {
816         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
817         *Flag = P.getValue(2);
818       }
819 
820       Chain = P.getValue(1);
821       Parts[i] = P;
822 
823       // If the source register was virtual and if we know something about it,
824       // add an assert node.
825       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
826           !RegisterVT.isInteger())
827         continue;
828 
829       const FunctionLoweringInfo::LiveOutInfo *LOI =
830         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
831       if (!LOI)
832         continue;
833 
834       unsigned RegSize = RegisterVT.getScalarSizeInBits();
835       unsigned NumSignBits = LOI->NumSignBits;
836       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
837 
838       if (NumZeroBits == RegSize) {
839         // The current value is a zero.
840         // Explicitly express that as it would be easier for
841         // optimizations to kick in.
842         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
843         continue;
844       }
845 
846       // FIXME: We capture more information than the dag can represent.  For
847       // now, just use the tightest assertzext/assertsext possible.
848       bool isSExt;
849       EVT FromVT(MVT::Other);
850       if (NumZeroBits) {
851         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
852         isSExt = false;
853       } else if (NumSignBits > 1) {
854         FromVT =
855             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
856         isSExt = true;
857       } else {
858         continue;
859       }
860       // Add an assertion node.
861       assert(FromVT != MVT::Other);
862       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
863                              RegisterVT, P, DAG.getValueType(FromVT));
864     }
865 
866     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
867                                      RegisterVT, ValueVT, V, CallConv);
868     Part += NumRegs;
869     Parts.clear();
870   }
871 
872   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
873 }
874 
875 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
876                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
877                                  const Value *V,
878                                  ISD::NodeType PreferredExtendType) const {
879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
880   ISD::NodeType ExtendKind = PreferredExtendType;
881 
882   // Get the list of the values's legal parts.
883   unsigned NumRegs = Regs.size();
884   SmallVector<SDValue, 8> Parts(NumRegs);
885   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
886     unsigned NumParts = RegCount[Value];
887 
888     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
889                                           *DAG.getContext(),
890                                           CallConv.getValue(), RegVTs[Value])
891                                     : RegVTs[Value];
892 
893     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
894       ExtendKind = ISD::ZERO_EXTEND;
895 
896     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
897                    NumParts, RegisterVT, V, CallConv, ExtendKind);
898     Part += NumParts;
899   }
900 
901   // Copy the parts into the registers.
902   SmallVector<SDValue, 8> Chains(NumRegs);
903   for (unsigned i = 0; i != NumRegs; ++i) {
904     SDValue Part;
905     if (!Flag) {
906       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
907     } else {
908       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
909       *Flag = Part.getValue(1);
910     }
911 
912     Chains[i] = Part.getValue(0);
913   }
914 
915   if (NumRegs == 1 || Flag)
916     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
917     // flagged to it. That is the CopyToReg nodes and the user are considered
918     // a single scheduling unit. If we create a TokenFactor and return it as
919     // chain, then the TokenFactor is both a predecessor (operand) of the
920     // user as well as a successor (the TF operands are flagged to the user).
921     // c1, f1 = CopyToReg
922     // c2, f2 = CopyToReg
923     // c3     = TokenFactor c1, c2
924     // ...
925     //        = op c3, ..., f2
926     Chain = Chains[NumRegs-1];
927   else
928     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
929 }
930 
931 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
932                                         unsigned MatchingIdx, const SDLoc &dl,
933                                         SelectionDAG &DAG,
934                                         std::vector<SDValue> &Ops) const {
935   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
936 
937   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
938   if (HasMatching)
939     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
940   else if (!Regs.empty() &&
941            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
942     // Put the register class of the virtual registers in the flag word.  That
943     // way, later passes can recompute register class constraints for inline
944     // assembly as well as normal instructions.
945     // Don't do this for tied operands that can use the regclass information
946     // from the def.
947     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
948     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
949     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
950   }
951 
952   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
953   Ops.push_back(Res);
954 
955   if (Code == InlineAsm::Kind_Clobber) {
956     // Clobbers should always have a 1:1 mapping with registers, and may
957     // reference registers that have illegal (e.g. vector) types. Hence, we
958     // shouldn't try to apply any sort of splitting logic to them.
959     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
960            "No 1:1 mapping from clobbers to regs?");
961     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
962     (void)SP;
963     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
964       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
965       assert(
966           (Regs[I] != SP ||
967            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
968           "If we clobbered the stack pointer, MFI should know about it.");
969     }
970     return;
971   }
972 
973   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
974     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
975     MVT RegisterVT = RegVTs[Value];
976     for (unsigned i = 0; i != NumRegs; ++i) {
977       assert(Reg < Regs.size() && "Mismatch in # registers expected");
978       unsigned TheReg = Regs[Reg++];
979       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
980     }
981   }
982 }
983 
984 SmallVector<std::pair<unsigned, unsigned>, 4>
985 RegsForValue::getRegsAndSizes() const {
986   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
987   unsigned I = 0;
988   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
989     unsigned RegCount = std::get<0>(CountAndVT);
990     MVT RegisterVT = std::get<1>(CountAndVT);
991     unsigned RegisterSize = RegisterVT.getSizeInBits();
992     for (unsigned E = I + RegCount; I != E; ++I)
993       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
994   }
995   return OutVec;
996 }
997 
998 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
999                                const TargetLibraryInfo *li) {
1000   AA = aa;
1001   GFI = gfi;
1002   LibInfo = li;
1003   DL = &DAG.getDataLayout();
1004   Context = DAG.getContext();
1005   LPadToCallSiteMap.clear();
1006 }
1007 
1008 void SelectionDAGBuilder::clear() {
1009   NodeMap.clear();
1010   UnusedArgNodeMap.clear();
1011   PendingLoads.clear();
1012   PendingExports.clear();
1013   CurInst = nullptr;
1014   HasTailCall = false;
1015   SDNodeOrder = LowestSDNodeOrder;
1016   StatepointLowering.clear();
1017 }
1018 
1019 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1020   DanglingDebugInfoMap.clear();
1021 }
1022 
1023 SDValue SelectionDAGBuilder::getRoot() {
1024   if (PendingLoads.empty())
1025     return DAG.getRoot();
1026 
1027   if (PendingLoads.size() == 1) {
1028     SDValue Root = PendingLoads[0];
1029     DAG.setRoot(Root);
1030     PendingLoads.clear();
1031     return Root;
1032   }
1033 
1034   // Otherwise, we have to make a token factor node.
1035   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1036   PendingLoads.clear();
1037   DAG.setRoot(Root);
1038   return Root;
1039 }
1040 
1041 SDValue SelectionDAGBuilder::getControlRoot() {
1042   SDValue Root = DAG.getRoot();
1043 
1044   if (PendingExports.empty())
1045     return Root;
1046 
1047   // Turn all of the CopyToReg chains into one factored node.
1048   if (Root.getOpcode() != ISD::EntryToken) {
1049     unsigned i = 0, e = PendingExports.size();
1050     for (; i != e; ++i) {
1051       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1052       if (PendingExports[i].getNode()->getOperand(0) == Root)
1053         break;  // Don't add the root if we already indirectly depend on it.
1054     }
1055 
1056     if (i == e)
1057       PendingExports.push_back(Root);
1058   }
1059 
1060   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1061                      PendingExports);
1062   PendingExports.clear();
1063   DAG.setRoot(Root);
1064   return Root;
1065 }
1066 
1067 void SelectionDAGBuilder::visit(const Instruction &I) {
1068   // Set up outgoing PHI node register values before emitting the terminator.
1069   if (I.isTerminator()) {
1070     HandlePHINodesInSuccessorBlocks(I.getParent());
1071   }
1072 
1073   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1074   if (!isa<DbgInfoIntrinsic>(I))
1075     ++SDNodeOrder;
1076 
1077   CurInst = &I;
1078 
1079   visit(I.getOpcode(), I);
1080 
1081   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1082     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1083     // maps to this instruction.
1084     // TODO: We could handle all flags (nsw, etc) here.
1085     // TODO: If an IR instruction maps to >1 node, only the final node will have
1086     //       flags set.
1087     if (SDNode *Node = getNodeForIRValue(&I)) {
1088       SDNodeFlags IncomingFlags;
1089       IncomingFlags.copyFMF(*FPMO);
1090       if (!Node->getFlags().isDefined())
1091         Node->setFlags(IncomingFlags);
1092       else
1093         Node->intersectFlagsWith(IncomingFlags);
1094     }
1095   }
1096 
1097   if (!I.isTerminator() && !HasTailCall &&
1098       !isStatepoint(&I)) // statepoints handle their exports internally
1099     CopyToExportRegsIfNeeded(&I);
1100 
1101   CurInst = nullptr;
1102 }
1103 
1104 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1105   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1106 }
1107 
1108 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1109   // Note: this doesn't use InstVisitor, because it has to work with
1110   // ConstantExpr's in addition to instructions.
1111   switch (Opcode) {
1112   default: llvm_unreachable("Unknown instruction type encountered!");
1113     // Build the switch statement using the Instruction.def file.
1114 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1115     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1116 #include "llvm/IR/Instruction.def"
1117   }
1118 }
1119 
1120 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1121                                                 const DIExpression *Expr) {
1122   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1123     const DbgValueInst *DI = DDI.getDI();
1124     DIVariable *DanglingVariable = DI->getVariable();
1125     DIExpression *DanglingExpr = DI->getExpression();
1126     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1127       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1128       return true;
1129     }
1130     return false;
1131   };
1132 
1133   for (auto &DDIMI : DanglingDebugInfoMap) {
1134     DanglingDebugInfoVector &DDIV = DDIMI.second;
1135 
1136     // If debug info is to be dropped, run it through final checks to see
1137     // whether it can be salvaged.
1138     for (auto &DDI : DDIV)
1139       if (isMatchingDbgValue(DDI))
1140         salvageUnresolvedDbgValue(DDI);
1141 
1142     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1143   }
1144 }
1145 
1146 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1147 // generate the debug data structures now that we've seen its definition.
1148 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1149                                                    SDValue Val) {
1150   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1151   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1152     return;
1153 
1154   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1155   for (auto &DDI : DDIV) {
1156     const DbgValueInst *DI = DDI.getDI();
1157     assert(DI && "Ill-formed DanglingDebugInfo");
1158     DebugLoc dl = DDI.getdl();
1159     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1160     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1161     DILocalVariable *Variable = DI->getVariable();
1162     DIExpression *Expr = DI->getExpression();
1163     assert(Variable->isValidLocationForIntrinsic(dl) &&
1164            "Expected inlined-at fields to agree");
1165     SDDbgValue *SDV;
1166     if (Val.getNode()) {
1167       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1168       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1169       // we couldn't resolve it directly when examining the DbgValue intrinsic
1170       // in the first place we should not be more successful here). Unless we
1171       // have some test case that prove this to be correct we should avoid
1172       // calling EmitFuncArgumentDbgValue here.
1173       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1174         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1175                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1176         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1177         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1178         // inserted after the definition of Val when emitting the instructions
1179         // after ISel. An alternative could be to teach
1180         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1181         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1182                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1183                    << ValSDNodeOrder << "\n");
1184         SDV = getDbgValue(Val, Variable, Expr, dl,
1185                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1186         DAG.AddDbgValue(SDV, Val.getNode(), false);
1187       } else
1188         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1189                           << "in EmitFuncArgumentDbgValue\n");
1190     } else {
1191       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1192       auto Undef =
1193           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1194       auto SDV =
1195           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1196       DAG.AddDbgValue(SDV, nullptr, false);
1197     }
1198   }
1199   DDIV.clear();
1200 }
1201 
1202 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1203   Value *V = DDI.getDI()->getValue();
1204   DILocalVariable *Var = DDI.getDI()->getVariable();
1205   DIExpression *Expr = DDI.getDI()->getExpression();
1206   DebugLoc DL = DDI.getdl();
1207   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1208   unsigned SDOrder = DDI.getSDNodeOrder();
1209 
1210   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1211   // that DW_OP_stack_value is desired.
1212   assert(isa<DbgValueInst>(DDI.getDI()));
1213   bool StackValue = true;
1214 
1215   // Can this Value can be encoded without any further work?
1216   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1217     return;
1218 
1219   // Attempt to salvage back through as many instructions as possible. Bail if
1220   // a non-instruction is seen, such as a constant expression or global
1221   // variable. FIXME: Further work could recover those too.
1222   while (isa<Instruction>(V)) {
1223     Instruction &VAsInst = *cast<Instruction>(V);
1224     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1225 
1226     // If we cannot salvage any further, and haven't yet found a suitable debug
1227     // expression, bail out.
1228     if (!NewExpr)
1229       break;
1230 
1231     // New value and expr now represent this debuginfo.
1232     V = VAsInst.getOperand(0);
1233     Expr = NewExpr;
1234 
1235     // Some kind of simplification occurred: check whether the operand of the
1236     // salvaged debug expression can be encoded in this DAG.
1237     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1238       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1239                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1240       return;
1241     }
1242   }
1243 
1244   // This was the final opportunity to salvage this debug information, and it
1245   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1246   // any earlier variable location.
1247   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1248   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1249   DAG.AddDbgValue(SDV, nullptr, false);
1250 
1251   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1252                     << "\n");
1253   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1254                     << "\n");
1255 }
1256 
1257 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1258                                            DIExpression *Expr, DebugLoc dl,
1259                                            DebugLoc InstDL, unsigned Order) {
1260   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1261   SDDbgValue *SDV;
1262   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1263       isa<ConstantPointerNull>(V)) {
1264     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1265     DAG.AddDbgValue(SDV, nullptr, false);
1266     return true;
1267   }
1268 
1269   // If the Value is a frame index, we can create a FrameIndex debug value
1270   // without relying on the DAG at all.
1271   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1272     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1273     if (SI != FuncInfo.StaticAllocaMap.end()) {
1274       auto SDV =
1275           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1276                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1277       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1278       // is still available even if the SDNode gets optimized out.
1279       DAG.AddDbgValue(SDV, nullptr, false);
1280       return true;
1281     }
1282   }
1283 
1284   // Do not use getValue() in here; we don't want to generate code at
1285   // this point if it hasn't been done yet.
1286   SDValue N = NodeMap[V];
1287   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1288     N = UnusedArgNodeMap[V];
1289   if (N.getNode()) {
1290     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1291       return true;
1292     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1293     DAG.AddDbgValue(SDV, N.getNode(), false);
1294     return true;
1295   }
1296 
1297   // Special rules apply for the first dbg.values of parameter variables in a
1298   // function. Identify them by the fact they reference Argument Values, that
1299   // they're parameters, and they are parameters of the current function. We
1300   // need to let them dangle until they get an SDNode.
1301   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1302                        !InstDL.getInlinedAt();
1303   if (!IsParamOfFunc) {
1304     // The value is not used in this block yet (or it would have an SDNode).
1305     // We still want the value to appear for the user if possible -- if it has
1306     // an associated VReg, we can refer to that instead.
1307     auto VMI = FuncInfo.ValueMap.find(V);
1308     if (VMI != FuncInfo.ValueMap.end()) {
1309       unsigned Reg = VMI->second;
1310       // If this is a PHI node, it may be split up into several MI PHI nodes
1311       // (in FunctionLoweringInfo::set).
1312       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1313                        V->getType(), None);
1314       if (RFV.occupiesMultipleRegs()) {
1315         unsigned Offset = 0;
1316         unsigned BitsToDescribe = 0;
1317         if (auto VarSize = Var->getSizeInBits())
1318           BitsToDescribe = *VarSize;
1319         if (auto Fragment = Expr->getFragmentInfo())
1320           BitsToDescribe = Fragment->SizeInBits;
1321         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1322           unsigned RegisterSize = RegAndSize.second;
1323           // Bail out if all bits are described already.
1324           if (Offset >= BitsToDescribe)
1325             break;
1326           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1327               ? BitsToDescribe - Offset
1328               : RegisterSize;
1329           auto FragmentExpr = DIExpression::createFragmentExpression(
1330               Expr, Offset, FragmentSize);
1331           if (!FragmentExpr)
1332               continue;
1333           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1334                                     false, dl, SDNodeOrder);
1335           DAG.AddDbgValue(SDV, nullptr, false);
1336           Offset += RegisterSize;
1337         }
1338       } else {
1339         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1340         DAG.AddDbgValue(SDV, nullptr, false);
1341       }
1342       return true;
1343     }
1344   }
1345 
1346   return false;
1347 }
1348 
1349 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1350   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1351   for (auto &Pair : DanglingDebugInfoMap)
1352     for (auto &DDI : Pair.getSecond())
1353       salvageUnresolvedDbgValue(DDI);
1354   clearDanglingDebugInfo();
1355 }
1356 
1357 /// getCopyFromRegs - If there was virtual register allocated for the value V
1358 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1359 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1360   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1361   SDValue Result;
1362 
1363   if (It != FuncInfo.ValueMap.end()) {
1364     unsigned InReg = It->second;
1365 
1366     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1367                      DAG.getDataLayout(), InReg, Ty,
1368                      None); // This is not an ABI copy.
1369     SDValue Chain = DAG.getEntryNode();
1370     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1371                                  V);
1372     resolveDanglingDebugInfo(V, Result);
1373   }
1374 
1375   return Result;
1376 }
1377 
1378 /// getValue - Return an SDValue for the given Value.
1379 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1380   // If we already have an SDValue for this value, use it. It's important
1381   // to do this first, so that we don't create a CopyFromReg if we already
1382   // have a regular SDValue.
1383   SDValue &N = NodeMap[V];
1384   if (N.getNode()) return N;
1385 
1386   // If there's a virtual register allocated and initialized for this
1387   // value, use it.
1388   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1389     return copyFromReg;
1390 
1391   // Otherwise create a new SDValue and remember it.
1392   SDValue Val = getValueImpl(V);
1393   NodeMap[V] = Val;
1394   resolveDanglingDebugInfo(V, Val);
1395   return Val;
1396 }
1397 
1398 // Return true if SDValue exists for the given Value
1399 bool SelectionDAGBuilder::findValue(const Value *V) const {
1400   return (NodeMap.find(V) != NodeMap.end()) ||
1401     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1402 }
1403 
1404 /// getNonRegisterValue - Return an SDValue for the given Value, but
1405 /// don't look in FuncInfo.ValueMap for a virtual register.
1406 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1407   // If we already have an SDValue for this value, use it.
1408   SDValue &N = NodeMap[V];
1409   if (N.getNode()) {
1410     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1411       // Remove the debug location from the node as the node is about to be used
1412       // in a location which may differ from the original debug location.  This
1413       // is relevant to Constant and ConstantFP nodes because they can appear
1414       // as constant expressions inside PHI nodes.
1415       N->setDebugLoc(DebugLoc());
1416     }
1417     return N;
1418   }
1419 
1420   // Otherwise create a new SDValue and remember it.
1421   SDValue Val = getValueImpl(V);
1422   NodeMap[V] = Val;
1423   resolveDanglingDebugInfo(V, Val);
1424   return Val;
1425 }
1426 
1427 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1428 /// Create an SDValue for the given value.
1429 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1430   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1431 
1432   if (const Constant *C = dyn_cast<Constant>(V)) {
1433     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1434 
1435     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1436       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1437 
1438     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1439       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1440 
1441     if (isa<ConstantPointerNull>(C)) {
1442       unsigned AS = V->getType()->getPointerAddressSpace();
1443       return DAG.getConstant(0, getCurSDLoc(),
1444                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1445     }
1446 
1447     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1448       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1449 
1450     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1451       return DAG.getUNDEF(VT);
1452 
1453     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1454       visit(CE->getOpcode(), *CE);
1455       SDValue N1 = NodeMap[V];
1456       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1457       return N1;
1458     }
1459 
1460     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1461       SmallVector<SDValue, 4> Constants;
1462       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1463            OI != OE; ++OI) {
1464         SDNode *Val = getValue(*OI).getNode();
1465         // If the operand is an empty aggregate, there are no values.
1466         if (!Val) continue;
1467         // Add each leaf value from the operand to the Constants list
1468         // to form a flattened list of all the values.
1469         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1470           Constants.push_back(SDValue(Val, i));
1471       }
1472 
1473       return DAG.getMergeValues(Constants, getCurSDLoc());
1474     }
1475 
1476     if (const ConstantDataSequential *CDS =
1477           dyn_cast<ConstantDataSequential>(C)) {
1478       SmallVector<SDValue, 4> Ops;
1479       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1480         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1481         // Add each leaf value from the operand to the Constants list
1482         // to form a flattened list of all the values.
1483         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1484           Ops.push_back(SDValue(Val, i));
1485       }
1486 
1487       if (isa<ArrayType>(CDS->getType()))
1488         return DAG.getMergeValues(Ops, getCurSDLoc());
1489       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1490     }
1491 
1492     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1493       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1494              "Unknown struct or array constant!");
1495 
1496       SmallVector<EVT, 4> ValueVTs;
1497       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1498       unsigned NumElts = ValueVTs.size();
1499       if (NumElts == 0)
1500         return SDValue(); // empty struct
1501       SmallVector<SDValue, 4> Constants(NumElts);
1502       for (unsigned i = 0; i != NumElts; ++i) {
1503         EVT EltVT = ValueVTs[i];
1504         if (isa<UndefValue>(C))
1505           Constants[i] = DAG.getUNDEF(EltVT);
1506         else if (EltVT.isFloatingPoint())
1507           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1508         else
1509           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1510       }
1511 
1512       return DAG.getMergeValues(Constants, getCurSDLoc());
1513     }
1514 
1515     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1516       return DAG.getBlockAddress(BA, VT);
1517 
1518     VectorType *VecTy = cast<VectorType>(V->getType());
1519     unsigned NumElements = VecTy->getNumElements();
1520 
1521     // Now that we know the number and type of the elements, get that number of
1522     // elements into the Ops array based on what kind of constant it is.
1523     SmallVector<SDValue, 16> Ops;
1524     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1525       for (unsigned i = 0; i != NumElements; ++i)
1526         Ops.push_back(getValue(CV->getOperand(i)));
1527     } else {
1528       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1529       EVT EltVT =
1530           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1531 
1532       SDValue Op;
1533       if (EltVT.isFloatingPoint())
1534         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1535       else
1536         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1537       Ops.assign(NumElements, Op);
1538     }
1539 
1540     // Create a BUILD_VECTOR node.
1541     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1542   }
1543 
1544   // If this is a static alloca, generate it as the frameindex instead of
1545   // computation.
1546   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1547     DenseMap<const AllocaInst*, int>::iterator SI =
1548       FuncInfo.StaticAllocaMap.find(AI);
1549     if (SI != FuncInfo.StaticAllocaMap.end())
1550       return DAG.getFrameIndex(SI->second,
1551                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1552   }
1553 
1554   // If this is an instruction which fast-isel has deferred, select it now.
1555   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1556     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1557 
1558     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1559                      Inst->getType(), getABIRegCopyCC(V));
1560     SDValue Chain = DAG.getEntryNode();
1561     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1562   }
1563 
1564   llvm_unreachable("Can't get register for value!");
1565 }
1566 
1567 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1568   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1569   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1570   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1571   bool IsSEH = isAsynchronousEHPersonality(Pers);
1572   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1573   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1574   if (!IsSEH)
1575     CatchPadMBB->setIsEHScopeEntry();
1576   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1577   if (IsMSVCCXX || IsCoreCLR)
1578     CatchPadMBB->setIsEHFuncletEntry();
1579   // Wasm does not need catchpads anymore
1580   if (!IsWasmCXX)
1581     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1582                             getControlRoot()));
1583 }
1584 
1585 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1586   // Update machine-CFG edge.
1587   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1588   FuncInfo.MBB->addSuccessor(TargetMBB);
1589 
1590   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1591   bool IsSEH = isAsynchronousEHPersonality(Pers);
1592   if (IsSEH) {
1593     // If this is not a fall-through branch or optimizations are switched off,
1594     // emit the branch.
1595     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1596         TM.getOptLevel() == CodeGenOpt::None)
1597       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1598                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1599     return;
1600   }
1601 
1602   // Figure out the funclet membership for the catchret's successor.
1603   // This will be used by the FuncletLayout pass to determine how to order the
1604   // BB's.
1605   // A 'catchret' returns to the outer scope's color.
1606   Value *ParentPad = I.getCatchSwitchParentPad();
1607   const BasicBlock *SuccessorColor;
1608   if (isa<ConstantTokenNone>(ParentPad))
1609     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1610   else
1611     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1612   assert(SuccessorColor && "No parent funclet for catchret!");
1613   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1614   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1615 
1616   // Create the terminator node.
1617   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1618                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1619                             DAG.getBasicBlock(SuccessorColorMBB));
1620   DAG.setRoot(Ret);
1621 }
1622 
1623 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1624   // Don't emit any special code for the cleanuppad instruction. It just marks
1625   // the start of an EH scope/funclet.
1626   FuncInfo.MBB->setIsEHScopeEntry();
1627   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1628   if (Pers != EHPersonality::Wasm_CXX) {
1629     FuncInfo.MBB->setIsEHFuncletEntry();
1630     FuncInfo.MBB->setIsCleanupFuncletEntry();
1631   }
1632 }
1633 
1634 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1635 // the control flow always stops at the single catch pad, as it does for a
1636 // cleanup pad. In case the exception caught is not of the types the catch pad
1637 // catches, it will be rethrown by a rethrow.
1638 static void findWasmUnwindDestinations(
1639     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1640     BranchProbability Prob,
1641     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1642         &UnwindDests) {
1643   while (EHPadBB) {
1644     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1645     if (isa<CleanupPadInst>(Pad)) {
1646       // Stop on cleanup pads.
1647       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1648       UnwindDests.back().first->setIsEHScopeEntry();
1649       break;
1650     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1651       // Add the catchpad handlers to the possible destinations. We don't
1652       // continue to the unwind destination of the catchswitch for wasm.
1653       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1654         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1655         UnwindDests.back().first->setIsEHScopeEntry();
1656       }
1657       break;
1658     } else {
1659       continue;
1660     }
1661   }
1662 }
1663 
1664 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1665 /// many places it could ultimately go. In the IR, we have a single unwind
1666 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1667 /// This function skips over imaginary basic blocks that hold catchswitch
1668 /// instructions, and finds all the "real" machine
1669 /// basic block destinations. As those destinations may not be successors of
1670 /// EHPadBB, here we also calculate the edge probability to those destinations.
1671 /// The passed-in Prob is the edge probability to EHPadBB.
1672 static void findUnwindDestinations(
1673     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1674     BranchProbability Prob,
1675     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1676         &UnwindDests) {
1677   EHPersonality Personality =
1678     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1679   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1680   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1681   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1682   bool IsSEH = isAsynchronousEHPersonality(Personality);
1683 
1684   if (IsWasmCXX) {
1685     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1686     return;
1687   }
1688 
1689   while (EHPadBB) {
1690     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1691     BasicBlock *NewEHPadBB = nullptr;
1692     if (isa<LandingPadInst>(Pad)) {
1693       // Stop on landingpads. They are not funclets.
1694       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1695       break;
1696     } else if (isa<CleanupPadInst>(Pad)) {
1697       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1698       // personalities.
1699       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1700       UnwindDests.back().first->setIsEHScopeEntry();
1701       UnwindDests.back().first->setIsEHFuncletEntry();
1702       break;
1703     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1704       // Add the catchpad handlers to the possible destinations.
1705       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1706         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1707         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1708         if (IsMSVCCXX || IsCoreCLR)
1709           UnwindDests.back().first->setIsEHFuncletEntry();
1710         if (!IsSEH)
1711           UnwindDests.back().first->setIsEHScopeEntry();
1712       }
1713       NewEHPadBB = CatchSwitch->getUnwindDest();
1714     } else {
1715       continue;
1716     }
1717 
1718     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1719     if (BPI && NewEHPadBB)
1720       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1721     EHPadBB = NewEHPadBB;
1722   }
1723 }
1724 
1725 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1726   // Update successor info.
1727   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1728   auto UnwindDest = I.getUnwindDest();
1729   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1730   BranchProbability UnwindDestProb =
1731       (BPI && UnwindDest)
1732           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1733           : BranchProbability::getZero();
1734   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1735   for (auto &UnwindDest : UnwindDests) {
1736     UnwindDest.first->setIsEHPad();
1737     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1738   }
1739   FuncInfo.MBB->normalizeSuccProbs();
1740 
1741   // Create the terminator node.
1742   SDValue Ret =
1743       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1744   DAG.setRoot(Ret);
1745 }
1746 
1747 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1748   report_fatal_error("visitCatchSwitch not yet implemented!");
1749 }
1750 
1751 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1752   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1753   auto &DL = DAG.getDataLayout();
1754   SDValue Chain = getControlRoot();
1755   SmallVector<ISD::OutputArg, 8> Outs;
1756   SmallVector<SDValue, 8> OutVals;
1757 
1758   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1759   // lower
1760   //
1761   //   %val = call <ty> @llvm.experimental.deoptimize()
1762   //   ret <ty> %val
1763   //
1764   // differently.
1765   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1766     LowerDeoptimizingReturn();
1767     return;
1768   }
1769 
1770   if (!FuncInfo.CanLowerReturn) {
1771     unsigned DemoteReg = FuncInfo.DemoteRegister;
1772     const Function *F = I.getParent()->getParent();
1773 
1774     // Emit a store of the return value through the virtual register.
1775     // Leave Outs empty so that LowerReturn won't try to load return
1776     // registers the usual way.
1777     SmallVector<EVT, 1> PtrValueVTs;
1778     ComputeValueVTs(TLI, DL,
1779                     F->getReturnType()->getPointerTo(
1780                         DAG.getDataLayout().getAllocaAddrSpace()),
1781                     PtrValueVTs);
1782 
1783     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1784                                         DemoteReg, PtrValueVTs[0]);
1785     SDValue RetOp = getValue(I.getOperand(0));
1786 
1787     SmallVector<EVT, 4> ValueVTs;
1788     SmallVector<uint64_t, 4> Offsets;
1789     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1790     unsigned NumValues = ValueVTs.size();
1791 
1792     SmallVector<SDValue, 4> Chains(NumValues);
1793     for (unsigned i = 0; i != NumValues; ++i) {
1794       // An aggregate return value cannot wrap around the address space, so
1795       // offsets to its parts don't wrap either.
1796       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1797       Chains[i] = DAG.getStore(
1798           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1799           // FIXME: better loc info would be nice.
1800           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1801     }
1802 
1803     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1804                         MVT::Other, Chains);
1805   } else if (I.getNumOperands() != 0) {
1806     SmallVector<EVT, 4> ValueVTs;
1807     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1808     unsigned NumValues = ValueVTs.size();
1809     if (NumValues) {
1810       SDValue RetOp = getValue(I.getOperand(0));
1811 
1812       const Function *F = I.getParent()->getParent();
1813 
1814       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1815       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1816                                           Attribute::SExt))
1817         ExtendKind = ISD::SIGN_EXTEND;
1818       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1819                                                Attribute::ZExt))
1820         ExtendKind = ISD::ZERO_EXTEND;
1821 
1822       LLVMContext &Context = F->getContext();
1823       bool RetInReg = F->getAttributes().hasAttribute(
1824           AttributeList::ReturnIndex, Attribute::InReg);
1825 
1826       for (unsigned j = 0; j != NumValues; ++j) {
1827         EVT VT = ValueVTs[j];
1828 
1829         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1830           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1831 
1832         CallingConv::ID CC = F->getCallingConv();
1833 
1834         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1835         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1836         SmallVector<SDValue, 4> Parts(NumParts);
1837         getCopyToParts(DAG, getCurSDLoc(),
1838                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1839                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1840 
1841         // 'inreg' on function refers to return value
1842         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1843         if (RetInReg)
1844           Flags.setInReg();
1845 
1846         // Propagate extension type if any
1847         if (ExtendKind == ISD::SIGN_EXTEND)
1848           Flags.setSExt();
1849         else if (ExtendKind == ISD::ZERO_EXTEND)
1850           Flags.setZExt();
1851 
1852         for (unsigned i = 0; i < NumParts; ++i) {
1853           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1854                                         VT, /*isfixed=*/true, 0, 0));
1855           OutVals.push_back(Parts[i]);
1856         }
1857       }
1858     }
1859   }
1860 
1861   // Push in swifterror virtual register as the last element of Outs. This makes
1862   // sure swifterror virtual register will be returned in the swifterror
1863   // physical register.
1864   const Function *F = I.getParent()->getParent();
1865   if (TLI.supportSwiftError() &&
1866       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1867     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1868     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1869     Flags.setSwiftError();
1870     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1871                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1872                                   true /*isfixed*/, 1 /*origidx*/,
1873                                   0 /*partOffs*/));
1874     // Create SDNode for the swifterror virtual register.
1875     OutVals.push_back(
1876         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1877                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1878                         EVT(TLI.getPointerTy(DL))));
1879   }
1880 
1881   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1882   CallingConv::ID CallConv =
1883     DAG.getMachineFunction().getFunction().getCallingConv();
1884   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1885       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1886 
1887   // Verify that the target's LowerReturn behaved as expected.
1888   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1889          "LowerReturn didn't return a valid chain!");
1890 
1891   // Update the DAG with the new chain value resulting from return lowering.
1892   DAG.setRoot(Chain);
1893 }
1894 
1895 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1896 /// created for it, emit nodes to copy the value into the virtual
1897 /// registers.
1898 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1899   // Skip empty types
1900   if (V->getType()->isEmptyTy())
1901     return;
1902 
1903   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1904   if (VMI != FuncInfo.ValueMap.end()) {
1905     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1906     CopyValueToVirtualRegister(V, VMI->second);
1907   }
1908 }
1909 
1910 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1911 /// the current basic block, add it to ValueMap now so that we'll get a
1912 /// CopyTo/FromReg.
1913 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1914   // No need to export constants.
1915   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1916 
1917   // Already exported?
1918   if (FuncInfo.isExportedInst(V)) return;
1919 
1920   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1921   CopyValueToVirtualRegister(V, Reg);
1922 }
1923 
1924 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1925                                                      const BasicBlock *FromBB) {
1926   // The operands of the setcc have to be in this block.  We don't know
1927   // how to export them from some other block.
1928   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1929     // Can export from current BB.
1930     if (VI->getParent() == FromBB)
1931       return true;
1932 
1933     // Is already exported, noop.
1934     return FuncInfo.isExportedInst(V);
1935   }
1936 
1937   // If this is an argument, we can export it if the BB is the entry block or
1938   // if it is already exported.
1939   if (isa<Argument>(V)) {
1940     if (FromBB == &FromBB->getParent()->getEntryBlock())
1941       return true;
1942 
1943     // Otherwise, can only export this if it is already exported.
1944     return FuncInfo.isExportedInst(V);
1945   }
1946 
1947   // Otherwise, constants can always be exported.
1948   return true;
1949 }
1950 
1951 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1952 BranchProbability
1953 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1954                                         const MachineBasicBlock *Dst) const {
1955   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1956   const BasicBlock *SrcBB = Src->getBasicBlock();
1957   const BasicBlock *DstBB = Dst->getBasicBlock();
1958   if (!BPI) {
1959     // If BPI is not available, set the default probability as 1 / N, where N is
1960     // the number of successors.
1961     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1962     return BranchProbability(1, SuccSize);
1963   }
1964   return BPI->getEdgeProbability(SrcBB, DstBB);
1965 }
1966 
1967 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1968                                                MachineBasicBlock *Dst,
1969                                                BranchProbability Prob) {
1970   if (!FuncInfo.BPI)
1971     Src->addSuccessorWithoutProb(Dst);
1972   else {
1973     if (Prob.isUnknown())
1974       Prob = getEdgeProbability(Src, Dst);
1975     Src->addSuccessor(Dst, Prob);
1976   }
1977 }
1978 
1979 static bool InBlock(const Value *V, const BasicBlock *BB) {
1980   if (const Instruction *I = dyn_cast<Instruction>(V))
1981     return I->getParent() == BB;
1982   return true;
1983 }
1984 
1985 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1986 /// This function emits a branch and is used at the leaves of an OR or an
1987 /// AND operator tree.
1988 void
1989 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1990                                                   MachineBasicBlock *TBB,
1991                                                   MachineBasicBlock *FBB,
1992                                                   MachineBasicBlock *CurBB,
1993                                                   MachineBasicBlock *SwitchBB,
1994                                                   BranchProbability TProb,
1995                                                   BranchProbability FProb,
1996                                                   bool InvertCond) {
1997   const BasicBlock *BB = CurBB->getBasicBlock();
1998 
1999   // If the leaf of the tree is a comparison, merge the condition into
2000   // the caseblock.
2001   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2002     // The operands of the cmp have to be in this block.  We don't know
2003     // how to export them from some other block.  If this is the first block
2004     // of the sequence, no exporting is needed.
2005     if (CurBB == SwitchBB ||
2006         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2007          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2008       ISD::CondCode Condition;
2009       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2010         ICmpInst::Predicate Pred =
2011             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2012         Condition = getICmpCondCode(Pred);
2013       } else {
2014         const FCmpInst *FC = cast<FCmpInst>(Cond);
2015         FCmpInst::Predicate Pred =
2016             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2017         Condition = getFCmpCondCode(Pred);
2018         if (TM.Options.NoNaNsFPMath)
2019           Condition = getFCmpCodeWithoutNaN(Condition);
2020       }
2021 
2022       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2023                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2024       SwitchCases.push_back(CB);
2025       return;
2026     }
2027   }
2028 
2029   // Create a CaseBlock record representing this branch.
2030   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2031   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2032                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2033   SwitchCases.push_back(CB);
2034 }
2035 
2036 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2037                                                MachineBasicBlock *TBB,
2038                                                MachineBasicBlock *FBB,
2039                                                MachineBasicBlock *CurBB,
2040                                                MachineBasicBlock *SwitchBB,
2041                                                Instruction::BinaryOps Opc,
2042                                                BranchProbability TProb,
2043                                                BranchProbability FProb,
2044                                                bool InvertCond) {
2045   // Skip over not part of the tree and remember to invert op and operands at
2046   // next level.
2047   Value *NotCond;
2048   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2049       InBlock(NotCond, CurBB->getBasicBlock())) {
2050     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2051                          !InvertCond);
2052     return;
2053   }
2054 
2055   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2056   // Compute the effective opcode for Cond, taking into account whether it needs
2057   // to be inverted, e.g.
2058   //   and (not (or A, B)), C
2059   // gets lowered as
2060   //   and (and (not A, not B), C)
2061   unsigned BOpc = 0;
2062   if (BOp) {
2063     BOpc = BOp->getOpcode();
2064     if (InvertCond) {
2065       if (BOpc == Instruction::And)
2066         BOpc = Instruction::Or;
2067       else if (BOpc == Instruction::Or)
2068         BOpc = Instruction::And;
2069     }
2070   }
2071 
2072   // If this node is not part of the or/and tree, emit it as a branch.
2073   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2074       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2075       BOp->getParent() != CurBB->getBasicBlock() ||
2076       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2077       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2078     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2079                                  TProb, FProb, InvertCond);
2080     return;
2081   }
2082 
2083   //  Create TmpBB after CurBB.
2084   MachineFunction::iterator BBI(CurBB);
2085   MachineFunction &MF = DAG.getMachineFunction();
2086   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2087   CurBB->getParent()->insert(++BBI, TmpBB);
2088 
2089   if (Opc == Instruction::Or) {
2090     // Codegen X | Y as:
2091     // BB1:
2092     //   jmp_if_X TBB
2093     //   jmp TmpBB
2094     // TmpBB:
2095     //   jmp_if_Y TBB
2096     //   jmp FBB
2097     //
2098 
2099     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2100     // The requirement is that
2101     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2102     //     = TrueProb for original BB.
2103     // Assuming the original probabilities are A and B, one choice is to set
2104     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2105     // A/(1+B) and 2B/(1+B). This choice assumes that
2106     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2107     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2108     // TmpBB, but the math is more complicated.
2109 
2110     auto NewTrueProb = TProb / 2;
2111     auto NewFalseProb = TProb / 2 + FProb;
2112     // Emit the LHS condition.
2113     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2114                          NewTrueProb, NewFalseProb, InvertCond);
2115 
2116     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2117     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2118     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2119     // Emit the RHS condition into TmpBB.
2120     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2121                          Probs[0], Probs[1], InvertCond);
2122   } else {
2123     assert(Opc == Instruction::And && "Unknown merge op!");
2124     // Codegen X & Y as:
2125     // BB1:
2126     //   jmp_if_X TmpBB
2127     //   jmp FBB
2128     // TmpBB:
2129     //   jmp_if_Y TBB
2130     //   jmp FBB
2131     //
2132     //  This requires creation of TmpBB after CurBB.
2133 
2134     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2135     // The requirement is that
2136     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2137     //     = FalseProb for original BB.
2138     // Assuming the original probabilities are A and B, one choice is to set
2139     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2140     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2141     // TrueProb for BB1 * FalseProb for TmpBB.
2142 
2143     auto NewTrueProb = TProb + FProb / 2;
2144     auto NewFalseProb = FProb / 2;
2145     // Emit the LHS condition.
2146     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2147                          NewTrueProb, NewFalseProb, InvertCond);
2148 
2149     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2150     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2151     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2152     // Emit the RHS condition into TmpBB.
2153     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2154                          Probs[0], Probs[1], InvertCond);
2155   }
2156 }
2157 
2158 /// If the set of cases should be emitted as a series of branches, return true.
2159 /// If we should emit this as a bunch of and/or'd together conditions, return
2160 /// false.
2161 bool
2162 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2163   if (Cases.size() != 2) return true;
2164 
2165   // If this is two comparisons of the same values or'd or and'd together, they
2166   // will get folded into a single comparison, so don't emit two blocks.
2167   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2168        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2169       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2170        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2171     return false;
2172   }
2173 
2174   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2175   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2176   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2177       Cases[0].CC == Cases[1].CC &&
2178       isa<Constant>(Cases[0].CmpRHS) &&
2179       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2180     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2181       return false;
2182     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2183       return false;
2184   }
2185 
2186   return true;
2187 }
2188 
2189 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2190   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2191 
2192   // Update machine-CFG edges.
2193   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2194 
2195   if (I.isUnconditional()) {
2196     // Update machine-CFG edges.
2197     BrMBB->addSuccessor(Succ0MBB);
2198 
2199     // If this is not a fall-through branch or optimizations are switched off,
2200     // emit the branch.
2201     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2202       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2203                               MVT::Other, getControlRoot(),
2204                               DAG.getBasicBlock(Succ0MBB)));
2205 
2206     return;
2207   }
2208 
2209   // If this condition is one of the special cases we handle, do special stuff
2210   // now.
2211   const Value *CondVal = I.getCondition();
2212   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2213 
2214   // If this is a series of conditions that are or'd or and'd together, emit
2215   // this as a sequence of branches instead of setcc's with and/or operations.
2216   // As long as jumps are not expensive, this should improve performance.
2217   // For example, instead of something like:
2218   //     cmp A, B
2219   //     C = seteq
2220   //     cmp D, E
2221   //     F = setle
2222   //     or C, F
2223   //     jnz foo
2224   // Emit:
2225   //     cmp A, B
2226   //     je foo
2227   //     cmp D, E
2228   //     jle foo
2229   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2230     Instruction::BinaryOps Opcode = BOp->getOpcode();
2231     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2232         !I.getMetadata(LLVMContext::MD_unpredictable) &&
2233         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2234       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2235                            Opcode,
2236                            getEdgeProbability(BrMBB, Succ0MBB),
2237                            getEdgeProbability(BrMBB, Succ1MBB),
2238                            /*InvertCond=*/false);
2239       // If the compares in later blocks need to use values not currently
2240       // exported from this block, export them now.  This block should always
2241       // be the first entry.
2242       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2243 
2244       // Allow some cases to be rejected.
2245       if (ShouldEmitAsBranches(SwitchCases)) {
2246         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
2247           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
2248           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
2249         }
2250 
2251         // Emit the branch for this block.
2252         visitSwitchCase(SwitchCases[0], BrMBB);
2253         SwitchCases.erase(SwitchCases.begin());
2254         return;
2255       }
2256 
2257       // Okay, we decided not to do this, remove any inserted MBB's and clear
2258       // SwitchCases.
2259       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2260         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2261 
2262       SwitchCases.clear();
2263     }
2264   }
2265 
2266   // Create a CaseBlock record representing this branch.
2267   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2268                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2269 
2270   // Use visitSwitchCase to actually insert the fast branch sequence for this
2271   // cond branch.
2272   visitSwitchCase(CB, BrMBB);
2273 }
2274 
2275 /// visitSwitchCase - Emits the necessary code to represent a single node in
2276 /// the binary search tree resulting from lowering a switch instruction.
2277 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2278                                           MachineBasicBlock *SwitchBB) {
2279   SDValue Cond;
2280   SDValue CondLHS = getValue(CB.CmpLHS);
2281   SDLoc dl = CB.DL;
2282 
2283   // Build the setcc now.
2284   if (!CB.CmpMHS) {
2285     // Fold "(X == true)" to X and "(X == false)" to !X to
2286     // handle common cases produced by branch lowering.
2287     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2288         CB.CC == ISD::SETEQ)
2289       Cond = CondLHS;
2290     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2291              CB.CC == ISD::SETEQ) {
2292       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2293       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2294     } else
2295       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2296   } else {
2297     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2298 
2299     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2300     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2301 
2302     SDValue CmpOp = getValue(CB.CmpMHS);
2303     EVT VT = CmpOp.getValueType();
2304 
2305     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2306       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2307                           ISD::SETLE);
2308     } else {
2309       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2310                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2311       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2312                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2313     }
2314   }
2315 
2316   // Update successor info
2317   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2318   // TrueBB and FalseBB are always different unless the incoming IR is
2319   // degenerate. This only happens when running llc on weird IR.
2320   if (CB.TrueBB != CB.FalseBB)
2321     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2322   SwitchBB->normalizeSuccProbs();
2323 
2324   // If the lhs block is the next block, invert the condition so that we can
2325   // fall through to the lhs instead of the rhs block.
2326   if (CB.TrueBB == NextBlock(SwitchBB)) {
2327     std::swap(CB.TrueBB, CB.FalseBB);
2328     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2329     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2330   }
2331 
2332   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2333                                MVT::Other, getControlRoot(), Cond,
2334                                DAG.getBasicBlock(CB.TrueBB));
2335 
2336   // Insert the false branch. Do this even if it's a fall through branch,
2337   // this makes it easier to do DAG optimizations which require inverting
2338   // the branch condition.
2339   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2340                        DAG.getBasicBlock(CB.FalseBB));
2341 
2342   DAG.setRoot(BrCond);
2343 }
2344 
2345 /// visitJumpTable - Emit JumpTable node in the current MBB
2346 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2347   // Emit the code for the jump table
2348   assert(JT.Reg != -1U && "Should lower JT Header first!");
2349   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2350   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2351                                      JT.Reg, PTy);
2352   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2353   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2354                                     MVT::Other, Index.getValue(1),
2355                                     Table, Index);
2356   DAG.setRoot(BrJumpTable);
2357 }
2358 
2359 /// visitJumpTableHeader - This function emits necessary code to produce index
2360 /// in the JumpTable from switch case.
2361 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2362                                                JumpTableHeader &JTH,
2363                                                MachineBasicBlock *SwitchBB) {
2364   SDLoc dl = getCurSDLoc();
2365 
2366   // Subtract the lowest switch case value from the value being switched on and
2367   // conditional branch to default mbb if the result is greater than the
2368   // difference between smallest and largest cases.
2369   SDValue SwitchOp = getValue(JTH.SValue);
2370   EVT VT = SwitchOp.getValueType();
2371   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2372                             DAG.getConstant(JTH.First, dl, VT));
2373 
2374   // The SDNode we just created, which holds the value being switched on minus
2375   // the smallest case value, needs to be copied to a virtual register so it
2376   // can be used as an index into the jump table in a subsequent basic block.
2377   // This value may be smaller or larger than the target's pointer type, and
2378   // therefore require extension or truncating.
2379   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2380   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2381 
2382   unsigned JumpTableReg =
2383       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2384   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2385                                     JumpTableReg, SwitchOp);
2386   JT.Reg = JumpTableReg;
2387 
2388   // Emit the range check for the jump table, and branch to the default block
2389   // for the switch statement if the value being switched on exceeds the largest
2390   // case in the switch.
2391   SDValue CMP = DAG.getSetCC(
2392       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2393                                  Sub.getValueType()),
2394       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2395 
2396   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2397                                MVT::Other, CopyTo, CMP,
2398                                DAG.getBasicBlock(JT.Default));
2399 
2400   // Avoid emitting unnecessary branches to the next block.
2401   if (JT.MBB != NextBlock(SwitchBB))
2402     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2403                          DAG.getBasicBlock(JT.MBB));
2404 
2405   DAG.setRoot(BrCond);
2406 }
2407 
2408 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2409 /// variable if there exists one.
2410 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2411                                  SDValue &Chain) {
2412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2413   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2414   MachineFunction &MF = DAG.getMachineFunction();
2415   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2416   MachineSDNode *Node =
2417       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2418   if (Global) {
2419     MachinePointerInfo MPInfo(Global);
2420     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2421                  MachineMemOperand::MODereferenceable;
2422     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2423         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2424     DAG.setNodeMemRefs(Node, {MemRef});
2425   }
2426   return SDValue(Node, 0);
2427 }
2428 
2429 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2430 /// tail spliced into a stack protector check success bb.
2431 ///
2432 /// For a high level explanation of how this fits into the stack protector
2433 /// generation see the comment on the declaration of class
2434 /// StackProtectorDescriptor.
2435 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2436                                                   MachineBasicBlock *ParentBB) {
2437 
2438   // First create the loads to the guard/stack slot for the comparison.
2439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2440   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2441 
2442   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2443   int FI = MFI.getStackProtectorIndex();
2444 
2445   SDValue Guard;
2446   SDLoc dl = getCurSDLoc();
2447   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2448   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2449   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2450 
2451   // Generate code to load the content of the guard slot.
2452   SDValue GuardVal = DAG.getLoad(
2453       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2454       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2455       MachineMemOperand::MOVolatile);
2456 
2457   if (TLI.useStackGuardXorFP())
2458     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2459 
2460   // Retrieve guard check function, nullptr if instrumentation is inlined.
2461   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2462     // The target provides a guard check function to validate the guard value.
2463     // Generate a call to that function with the content of the guard slot as
2464     // argument.
2465     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2466     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2467 
2468     TargetLowering::ArgListTy Args;
2469     TargetLowering::ArgListEntry Entry;
2470     Entry.Node = GuardVal;
2471     Entry.Ty = FnTy->getParamType(0);
2472     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2473       Entry.IsInReg = true;
2474     Args.push_back(Entry);
2475 
2476     TargetLowering::CallLoweringInfo CLI(DAG);
2477     CLI.setDebugLoc(getCurSDLoc())
2478         .setChain(DAG.getEntryNode())
2479         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2480                    getValue(GuardCheckFn), std::move(Args));
2481 
2482     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2483     DAG.setRoot(Result.second);
2484     return;
2485   }
2486 
2487   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2488   // Otherwise, emit a volatile load to retrieve the stack guard value.
2489   SDValue Chain = DAG.getEntryNode();
2490   if (TLI.useLoadStackGuardNode()) {
2491     Guard = getLoadStackGuard(DAG, dl, Chain);
2492   } else {
2493     const Value *IRGuard = TLI.getSDagStackGuard(M);
2494     SDValue GuardPtr = getValue(IRGuard);
2495 
2496     Guard =
2497         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2498                     Align, MachineMemOperand::MOVolatile);
2499   }
2500 
2501   // Perform the comparison via a subtract/getsetcc.
2502   EVT VT = Guard.getValueType();
2503   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2504 
2505   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2506                                                         *DAG.getContext(),
2507                                                         Sub.getValueType()),
2508                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2509 
2510   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2511   // branch to failure MBB.
2512   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2513                                MVT::Other, GuardVal.getOperand(0),
2514                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2515   // Otherwise branch to success MBB.
2516   SDValue Br = DAG.getNode(ISD::BR, dl,
2517                            MVT::Other, BrCond,
2518                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2519 
2520   DAG.setRoot(Br);
2521 }
2522 
2523 /// Codegen the failure basic block for a stack protector check.
2524 ///
2525 /// A failure stack protector machine basic block consists simply of a call to
2526 /// __stack_chk_fail().
2527 ///
2528 /// For a high level explanation of how this fits into the stack protector
2529 /// generation see the comment on the declaration of class
2530 /// StackProtectorDescriptor.
2531 void
2532 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2533   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2534   SDValue Chain =
2535       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2536                       None, false, getCurSDLoc(), false, false).second;
2537   DAG.setRoot(Chain);
2538 }
2539 
2540 /// visitBitTestHeader - This function emits necessary code to produce value
2541 /// suitable for "bit tests"
2542 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2543                                              MachineBasicBlock *SwitchBB) {
2544   SDLoc dl = getCurSDLoc();
2545 
2546   // Subtract the minimum value
2547   SDValue SwitchOp = getValue(B.SValue);
2548   EVT VT = SwitchOp.getValueType();
2549   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2550                             DAG.getConstant(B.First, dl, VT));
2551 
2552   // Check range
2553   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2554   SDValue RangeCmp = DAG.getSetCC(
2555       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2556                                  Sub.getValueType()),
2557       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2558 
2559   // Determine the type of the test operands.
2560   bool UsePtrType = false;
2561   if (!TLI.isTypeLegal(VT))
2562     UsePtrType = true;
2563   else {
2564     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2565       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2566         // Switch table case range are encoded into series of masks.
2567         // Just use pointer type, it's guaranteed to fit.
2568         UsePtrType = true;
2569         break;
2570       }
2571   }
2572   if (UsePtrType) {
2573     VT = TLI.getPointerTy(DAG.getDataLayout());
2574     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2575   }
2576 
2577   B.RegVT = VT.getSimpleVT();
2578   B.Reg = FuncInfo.CreateReg(B.RegVT);
2579   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2580 
2581   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2582 
2583   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2584   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2585   SwitchBB->normalizeSuccProbs();
2586 
2587   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2588                                 MVT::Other, CopyTo, RangeCmp,
2589                                 DAG.getBasicBlock(B.Default));
2590 
2591   // Avoid emitting unnecessary branches to the next block.
2592   if (MBB != NextBlock(SwitchBB))
2593     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2594                           DAG.getBasicBlock(MBB));
2595 
2596   DAG.setRoot(BrRange);
2597 }
2598 
2599 /// visitBitTestCase - this function produces one "bit test"
2600 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2601                                            MachineBasicBlock* NextMBB,
2602                                            BranchProbability BranchProbToNext,
2603                                            unsigned Reg,
2604                                            BitTestCase &B,
2605                                            MachineBasicBlock *SwitchBB) {
2606   SDLoc dl = getCurSDLoc();
2607   MVT VT = BB.RegVT;
2608   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2609   SDValue Cmp;
2610   unsigned PopCount = countPopulation(B.Mask);
2611   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2612   if (PopCount == 1) {
2613     // Testing for a single bit; just compare the shift count with what it
2614     // would need to be to shift a 1 bit in that position.
2615     Cmp = DAG.getSetCC(
2616         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2617         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2618         ISD::SETEQ);
2619   } else if (PopCount == BB.Range) {
2620     // There is only one zero bit in the range, test for it directly.
2621     Cmp = DAG.getSetCC(
2622         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2623         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2624         ISD::SETNE);
2625   } else {
2626     // Make desired shift
2627     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2628                                     DAG.getConstant(1, dl, VT), ShiftOp);
2629 
2630     // Emit bit tests and jumps
2631     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2632                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2633     Cmp = DAG.getSetCC(
2634         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2635         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2636   }
2637 
2638   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2639   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2640   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2641   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2642   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2643   // one as they are relative probabilities (and thus work more like weights),
2644   // and hence we need to normalize them to let the sum of them become one.
2645   SwitchBB->normalizeSuccProbs();
2646 
2647   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2648                               MVT::Other, getControlRoot(),
2649                               Cmp, DAG.getBasicBlock(B.TargetBB));
2650 
2651   // Avoid emitting unnecessary branches to the next block.
2652   if (NextMBB != NextBlock(SwitchBB))
2653     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2654                         DAG.getBasicBlock(NextMBB));
2655 
2656   DAG.setRoot(BrAnd);
2657 }
2658 
2659 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2660   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2661 
2662   // Retrieve successors. Look through artificial IR level blocks like
2663   // catchswitch for successors.
2664   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2665   const BasicBlock *EHPadBB = I.getSuccessor(1);
2666 
2667   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2668   // have to do anything here to lower funclet bundles.
2669   assert(!I.hasOperandBundlesOtherThan(
2670              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2671          "Cannot lower invokes with arbitrary operand bundles yet!");
2672 
2673   const Value *Callee(I.getCalledValue());
2674   const Function *Fn = dyn_cast<Function>(Callee);
2675   if (isa<InlineAsm>(Callee))
2676     visitInlineAsm(&I);
2677   else if (Fn && Fn->isIntrinsic()) {
2678     switch (Fn->getIntrinsicID()) {
2679     default:
2680       llvm_unreachable("Cannot invoke this intrinsic");
2681     case Intrinsic::donothing:
2682       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2683       break;
2684     case Intrinsic::experimental_patchpoint_void:
2685     case Intrinsic::experimental_patchpoint_i64:
2686       visitPatchpoint(&I, EHPadBB);
2687       break;
2688     case Intrinsic::experimental_gc_statepoint:
2689       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2690       break;
2691     }
2692   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2693     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2694     // Eventually we will support lowering the @llvm.experimental.deoptimize
2695     // intrinsic, and right now there are no plans to support other intrinsics
2696     // with deopt state.
2697     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2698   } else {
2699     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2700   }
2701 
2702   // If the value of the invoke is used outside of its defining block, make it
2703   // available as a virtual register.
2704   // We already took care of the exported value for the statepoint instruction
2705   // during call to the LowerStatepoint.
2706   if (!isStatepoint(I)) {
2707     CopyToExportRegsIfNeeded(&I);
2708   }
2709 
2710   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2711   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2712   BranchProbability EHPadBBProb =
2713       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2714           : BranchProbability::getZero();
2715   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2716 
2717   // Update successor info.
2718   addSuccessorWithProb(InvokeMBB, Return);
2719   for (auto &UnwindDest : UnwindDests) {
2720     UnwindDest.first->setIsEHPad();
2721     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2722   }
2723   InvokeMBB->normalizeSuccProbs();
2724 
2725   // Drop into normal successor.
2726   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2727                           DAG.getBasicBlock(Return)));
2728 }
2729 
2730 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2731   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2732 
2733   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2734   // have to do anything here to lower funclet bundles.
2735   assert(!I.hasOperandBundlesOtherThan(
2736              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2737          "Cannot lower callbrs with arbitrary operand bundles yet!");
2738 
2739   assert(isa<InlineAsm>(I.getCalledValue()) &&
2740          "Only know how to handle inlineasm callbr");
2741   visitInlineAsm(&I);
2742 
2743   // Retrieve successors.
2744   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2745 
2746   // Update successor info.
2747   addSuccessorWithProb(CallBrMBB, Return);
2748   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2749     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2750     addSuccessorWithProb(CallBrMBB, Target);
2751   }
2752   CallBrMBB->normalizeSuccProbs();
2753 
2754   // Drop into default successor.
2755   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2756                           MVT::Other, getControlRoot(),
2757                           DAG.getBasicBlock(Return)));
2758 }
2759 
2760 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2761   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2762 }
2763 
2764 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2765   assert(FuncInfo.MBB->isEHPad() &&
2766          "Call to landingpad not in landing pad!");
2767 
2768   // If there aren't registers to copy the values into (e.g., during SjLj
2769   // exceptions), then don't bother to create these DAG nodes.
2770   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2771   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2772   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2773       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2774     return;
2775 
2776   // If landingpad's return type is token type, we don't create DAG nodes
2777   // for its exception pointer and selector value. The extraction of exception
2778   // pointer or selector value from token type landingpads is not currently
2779   // supported.
2780   if (LP.getType()->isTokenTy())
2781     return;
2782 
2783   SmallVector<EVT, 2> ValueVTs;
2784   SDLoc dl = getCurSDLoc();
2785   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2786   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2787 
2788   // Get the two live-in registers as SDValues. The physregs have already been
2789   // copied into virtual registers.
2790   SDValue Ops[2];
2791   if (FuncInfo.ExceptionPointerVirtReg) {
2792     Ops[0] = DAG.getZExtOrTrunc(
2793         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2794                            FuncInfo.ExceptionPointerVirtReg,
2795                            TLI.getPointerTy(DAG.getDataLayout())),
2796         dl, ValueVTs[0]);
2797   } else {
2798     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2799   }
2800   Ops[1] = DAG.getZExtOrTrunc(
2801       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2802                          FuncInfo.ExceptionSelectorVirtReg,
2803                          TLI.getPointerTy(DAG.getDataLayout())),
2804       dl, ValueVTs[1]);
2805 
2806   // Merge into one.
2807   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2808                             DAG.getVTList(ValueVTs), Ops);
2809   setValue(&LP, Res);
2810 }
2811 
2812 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2813 #ifndef NDEBUG
2814   for (const CaseCluster &CC : Clusters)
2815     assert(CC.Low == CC.High && "Input clusters must be single-case");
2816 #endif
2817 
2818   llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
2819     return a.Low->getValue().slt(b.Low->getValue());
2820   });
2821 
2822   // Merge adjacent clusters with the same destination.
2823   const unsigned N = Clusters.size();
2824   unsigned DstIndex = 0;
2825   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2826     CaseCluster &CC = Clusters[SrcIndex];
2827     const ConstantInt *CaseVal = CC.Low;
2828     MachineBasicBlock *Succ = CC.MBB;
2829 
2830     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2831         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2832       // If this case has the same successor and is a neighbour, merge it into
2833       // the previous cluster.
2834       Clusters[DstIndex - 1].High = CaseVal;
2835       Clusters[DstIndex - 1].Prob += CC.Prob;
2836     } else {
2837       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2838                    sizeof(Clusters[SrcIndex]));
2839     }
2840   }
2841   Clusters.resize(DstIndex);
2842 }
2843 
2844 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2845                                            MachineBasicBlock *Last) {
2846   // Update JTCases.
2847   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2848     if (JTCases[i].first.HeaderBB == First)
2849       JTCases[i].first.HeaderBB = Last;
2850 
2851   // Update BitTestCases.
2852   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2853     if (BitTestCases[i].Parent == First)
2854       BitTestCases[i].Parent = Last;
2855 }
2856 
2857 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2858   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2859 
2860   // Update machine-CFG edges with unique successors.
2861   SmallSet<BasicBlock*, 32> Done;
2862   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2863     BasicBlock *BB = I.getSuccessor(i);
2864     bool Inserted = Done.insert(BB).second;
2865     if (!Inserted)
2866         continue;
2867 
2868     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2869     addSuccessorWithProb(IndirectBrMBB, Succ);
2870   }
2871   IndirectBrMBB->normalizeSuccProbs();
2872 
2873   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2874                           MVT::Other, getControlRoot(),
2875                           getValue(I.getAddress())));
2876 }
2877 
2878 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2879   if (!DAG.getTarget().Options.TrapUnreachable)
2880     return;
2881 
2882   // We may be able to ignore unreachable behind a noreturn call.
2883   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2884     const BasicBlock &BB = *I.getParent();
2885     if (&I != &BB.front()) {
2886       BasicBlock::const_iterator PredI =
2887         std::prev(BasicBlock::const_iterator(&I));
2888       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2889         if (Call->doesNotReturn())
2890           return;
2891       }
2892     }
2893   }
2894 
2895   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2896 }
2897 
2898 void SelectionDAGBuilder::visitFSub(const User &I) {
2899   // -0.0 - X --> fneg
2900   Type *Ty = I.getType();
2901   if (isa<Constant>(I.getOperand(0)) &&
2902       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2903     SDValue Op2 = getValue(I.getOperand(1));
2904     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2905                              Op2.getValueType(), Op2));
2906     return;
2907   }
2908 
2909   visitBinary(I, ISD::FSUB);
2910 }
2911 
2912 /// Checks if the given instruction performs a vector reduction, in which case
2913 /// we have the freedom to alter the elements in the result as long as the
2914 /// reduction of them stays unchanged.
2915 static bool isVectorReductionOp(const User *I) {
2916   const Instruction *Inst = dyn_cast<Instruction>(I);
2917   if (!Inst || !Inst->getType()->isVectorTy())
2918     return false;
2919 
2920   auto OpCode = Inst->getOpcode();
2921   switch (OpCode) {
2922   case Instruction::Add:
2923   case Instruction::Mul:
2924   case Instruction::And:
2925   case Instruction::Or:
2926   case Instruction::Xor:
2927     break;
2928   case Instruction::FAdd:
2929   case Instruction::FMul:
2930     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2931       if (FPOp->getFastMathFlags().isFast())
2932         break;
2933     LLVM_FALLTHROUGH;
2934   default:
2935     return false;
2936   }
2937 
2938   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2939   // Ensure the reduction size is a power of 2.
2940   if (!isPowerOf2_32(ElemNum))
2941     return false;
2942 
2943   unsigned ElemNumToReduce = ElemNum;
2944 
2945   // Do DFS search on the def-use chain from the given instruction. We only
2946   // allow four kinds of operations during the search until we reach the
2947   // instruction that extracts the first element from the vector:
2948   //
2949   //   1. The reduction operation of the same opcode as the given instruction.
2950   //
2951   //   2. PHI node.
2952   //
2953   //   3. ShuffleVector instruction together with a reduction operation that
2954   //      does a partial reduction.
2955   //
2956   //   4. ExtractElement that extracts the first element from the vector, and we
2957   //      stop searching the def-use chain here.
2958   //
2959   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2960   // from 1-3 to the stack to continue the DFS. The given instruction is not
2961   // a reduction operation if we meet any other instructions other than those
2962   // listed above.
2963 
2964   SmallVector<const User *, 16> UsersToVisit{Inst};
2965   SmallPtrSet<const User *, 16> Visited;
2966   bool ReduxExtracted = false;
2967 
2968   while (!UsersToVisit.empty()) {
2969     auto User = UsersToVisit.back();
2970     UsersToVisit.pop_back();
2971     if (!Visited.insert(User).second)
2972       continue;
2973 
2974     for (const auto &U : User->users()) {
2975       auto Inst = dyn_cast<Instruction>(U);
2976       if (!Inst)
2977         return false;
2978 
2979       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2980         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2981           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2982             return false;
2983         UsersToVisit.push_back(U);
2984       } else if (const ShuffleVectorInst *ShufInst =
2985                      dyn_cast<ShuffleVectorInst>(U)) {
2986         // Detect the following pattern: A ShuffleVector instruction together
2987         // with a reduction that do partial reduction on the first and second
2988         // ElemNumToReduce / 2 elements, and store the result in
2989         // ElemNumToReduce / 2 elements in another vector.
2990 
2991         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2992         if (ResultElements < ElemNum)
2993           return false;
2994 
2995         if (ElemNumToReduce == 1)
2996           return false;
2997         if (!isa<UndefValue>(U->getOperand(1)))
2998           return false;
2999         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3000           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3001             return false;
3002         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3003           if (ShufInst->getMaskValue(i) != -1)
3004             return false;
3005 
3006         // There is only one user of this ShuffleVector instruction, which
3007         // must be a reduction operation.
3008         if (!U->hasOneUse())
3009           return false;
3010 
3011         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3012         if (!U2 || U2->getOpcode() != OpCode)
3013           return false;
3014 
3015         // Check operands of the reduction operation.
3016         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3017             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3018           UsersToVisit.push_back(U2);
3019           ElemNumToReduce /= 2;
3020         } else
3021           return false;
3022       } else if (isa<ExtractElementInst>(U)) {
3023         // At this moment we should have reduced all elements in the vector.
3024         if (ElemNumToReduce != 1)
3025           return false;
3026 
3027         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3028         if (!Val || !Val->isZero())
3029           return false;
3030 
3031         ReduxExtracted = true;
3032       } else
3033         return false;
3034     }
3035   }
3036   return ReduxExtracted;
3037 }
3038 
3039 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3040   SDNodeFlags Flags;
3041 
3042   SDValue Op = getValue(I.getOperand(0));
3043   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3044                                     Op, Flags);
3045   setValue(&I, UnNodeValue);
3046 }
3047 
3048 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3049   SDNodeFlags Flags;
3050   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3051     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3052     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3053   }
3054   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3055     Flags.setExact(ExactOp->isExact());
3056   }
3057   if (isVectorReductionOp(&I)) {
3058     Flags.setVectorReduction(true);
3059     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3060   }
3061 
3062   SDValue Op1 = getValue(I.getOperand(0));
3063   SDValue Op2 = getValue(I.getOperand(1));
3064   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3065                                      Op1, Op2, Flags);
3066   setValue(&I, BinNodeValue);
3067 }
3068 
3069 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3070   SDValue Op1 = getValue(I.getOperand(0));
3071   SDValue Op2 = getValue(I.getOperand(1));
3072 
3073   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3074       Op1.getValueType(), DAG.getDataLayout());
3075 
3076   // Coerce the shift amount to the right type if we can.
3077   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3078     unsigned ShiftSize = ShiftTy.getSizeInBits();
3079     unsigned Op2Size = Op2.getValueSizeInBits();
3080     SDLoc DL = getCurSDLoc();
3081 
3082     // If the operand is smaller than the shift count type, promote it.
3083     if (ShiftSize > Op2Size)
3084       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3085 
3086     // If the operand is larger than the shift count type but the shift
3087     // count type has enough bits to represent any shift value, truncate
3088     // it now. This is a common case and it exposes the truncate to
3089     // optimization early.
3090     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3091       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3092     // Otherwise we'll need to temporarily settle for some other convenient
3093     // type.  Type legalization will make adjustments once the shiftee is split.
3094     else
3095       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3096   }
3097 
3098   bool nuw = false;
3099   bool nsw = false;
3100   bool exact = false;
3101 
3102   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3103 
3104     if (const OverflowingBinaryOperator *OFBinOp =
3105             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3106       nuw = OFBinOp->hasNoUnsignedWrap();
3107       nsw = OFBinOp->hasNoSignedWrap();
3108     }
3109     if (const PossiblyExactOperator *ExactOp =
3110             dyn_cast<const PossiblyExactOperator>(&I))
3111       exact = ExactOp->isExact();
3112   }
3113   SDNodeFlags Flags;
3114   Flags.setExact(exact);
3115   Flags.setNoSignedWrap(nsw);
3116   Flags.setNoUnsignedWrap(nuw);
3117   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3118                             Flags);
3119   setValue(&I, Res);
3120 }
3121 
3122 void SelectionDAGBuilder::visitSDiv(const User &I) {
3123   SDValue Op1 = getValue(I.getOperand(0));
3124   SDValue Op2 = getValue(I.getOperand(1));
3125 
3126   SDNodeFlags Flags;
3127   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3128                  cast<PossiblyExactOperator>(&I)->isExact());
3129   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3130                            Op2, Flags));
3131 }
3132 
3133 void SelectionDAGBuilder::visitICmp(const User &I) {
3134   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3135   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3136     predicate = IC->getPredicate();
3137   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3138     predicate = ICmpInst::Predicate(IC->getPredicate());
3139   SDValue Op1 = getValue(I.getOperand(0));
3140   SDValue Op2 = getValue(I.getOperand(1));
3141   ISD::CondCode Opcode = getICmpCondCode(predicate);
3142 
3143   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3144                                                         I.getType());
3145   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3146 }
3147 
3148 void SelectionDAGBuilder::visitFCmp(const User &I) {
3149   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3150   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3151     predicate = FC->getPredicate();
3152   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3153     predicate = FCmpInst::Predicate(FC->getPredicate());
3154   SDValue Op1 = getValue(I.getOperand(0));
3155   SDValue Op2 = getValue(I.getOperand(1));
3156 
3157   ISD::CondCode Condition = getFCmpCondCode(predicate);
3158   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3159   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3160     Condition = getFCmpCodeWithoutNaN(Condition);
3161 
3162   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3163                                                         I.getType());
3164   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3165 }
3166 
3167 // Check if the condition of the select has one use or two users that are both
3168 // selects with the same condition.
3169 static bool hasOnlySelectUsers(const Value *Cond) {
3170   return llvm::all_of(Cond->users(), [](const Value *V) {
3171     return isa<SelectInst>(V);
3172   });
3173 }
3174 
3175 void SelectionDAGBuilder::visitSelect(const User &I) {
3176   SmallVector<EVT, 4> ValueVTs;
3177   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3178                   ValueVTs);
3179   unsigned NumValues = ValueVTs.size();
3180   if (NumValues == 0) return;
3181 
3182   SmallVector<SDValue, 4> Values(NumValues);
3183   SDValue Cond     = getValue(I.getOperand(0));
3184   SDValue LHSVal   = getValue(I.getOperand(1));
3185   SDValue RHSVal   = getValue(I.getOperand(2));
3186   auto BaseOps = {Cond};
3187   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3188     ISD::VSELECT : ISD::SELECT;
3189 
3190   // Min/max matching is only viable if all output VTs are the same.
3191   if (is_splat(ValueVTs)) {
3192     EVT VT = ValueVTs[0];
3193     LLVMContext &Ctx = *DAG.getContext();
3194     auto &TLI = DAG.getTargetLoweringInfo();
3195 
3196     // We care about the legality of the operation after it has been type
3197     // legalized.
3198     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
3199            VT != TLI.getTypeToTransformTo(Ctx, VT))
3200       VT = TLI.getTypeToTransformTo(Ctx, VT);
3201 
3202     // If the vselect is legal, assume we want to leave this as a vector setcc +
3203     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3204     // min/max is legal on the scalar type.
3205     bool UseScalarMinMax = VT.isVector() &&
3206       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3207 
3208     Value *LHS, *RHS;
3209     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3210     ISD::NodeType Opc = ISD::DELETED_NODE;
3211     switch (SPR.Flavor) {
3212     case SPF_UMAX:    Opc = ISD::UMAX; break;
3213     case SPF_UMIN:    Opc = ISD::UMIN; break;
3214     case SPF_SMAX:    Opc = ISD::SMAX; break;
3215     case SPF_SMIN:    Opc = ISD::SMIN; break;
3216     case SPF_FMINNUM:
3217       switch (SPR.NaNBehavior) {
3218       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3219       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3220       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3221       case SPNB_RETURNS_ANY: {
3222         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3223           Opc = ISD::FMINNUM;
3224         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3225           Opc = ISD::FMINIMUM;
3226         else if (UseScalarMinMax)
3227           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3228             ISD::FMINNUM : ISD::FMINIMUM;
3229         break;
3230       }
3231       }
3232       break;
3233     case SPF_FMAXNUM:
3234       switch (SPR.NaNBehavior) {
3235       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3236       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3237       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3238       case SPNB_RETURNS_ANY:
3239 
3240         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3241           Opc = ISD::FMAXNUM;
3242         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3243           Opc = ISD::FMAXIMUM;
3244         else if (UseScalarMinMax)
3245           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3246             ISD::FMAXNUM : ISD::FMAXIMUM;
3247         break;
3248       }
3249       break;
3250     default: break;
3251     }
3252 
3253     if (Opc != ISD::DELETED_NODE &&
3254         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3255          (UseScalarMinMax &&
3256           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3257         // If the underlying comparison instruction is used by any other
3258         // instruction, the consumed instructions won't be destroyed, so it is
3259         // not profitable to convert to a min/max.
3260         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3261       OpCode = Opc;
3262       LHSVal = getValue(LHS);
3263       RHSVal = getValue(RHS);
3264       BaseOps = {};
3265     }
3266   }
3267 
3268   for (unsigned i = 0; i != NumValues; ++i) {
3269     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3270     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3271     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3272     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
3273                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
3274                             Ops);
3275   }
3276 
3277   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3278                            DAG.getVTList(ValueVTs), Values));
3279 }
3280 
3281 void SelectionDAGBuilder::visitTrunc(const User &I) {
3282   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3283   SDValue N = getValue(I.getOperand(0));
3284   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3285                                                         I.getType());
3286   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3287 }
3288 
3289 void SelectionDAGBuilder::visitZExt(const User &I) {
3290   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3291   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3292   SDValue N = getValue(I.getOperand(0));
3293   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3294                                                         I.getType());
3295   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3296 }
3297 
3298 void SelectionDAGBuilder::visitSExt(const User &I) {
3299   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3300   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3301   SDValue N = getValue(I.getOperand(0));
3302   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3303                                                         I.getType());
3304   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3305 }
3306 
3307 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3308   // FPTrunc is never a no-op cast, no need to check
3309   SDValue N = getValue(I.getOperand(0));
3310   SDLoc dl = getCurSDLoc();
3311   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3312   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3313   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3314                            DAG.getTargetConstant(
3315                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3316 }
3317 
3318 void SelectionDAGBuilder::visitFPExt(const User &I) {
3319   // FPExt is never a no-op cast, no need to check
3320   SDValue N = getValue(I.getOperand(0));
3321   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3322                                                         I.getType());
3323   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3324 }
3325 
3326 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3327   // FPToUI is never a no-op cast, no need to check
3328   SDValue N = getValue(I.getOperand(0));
3329   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3330                                                         I.getType());
3331   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3332 }
3333 
3334 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3335   // FPToSI is never a no-op cast, no need to check
3336   SDValue N = getValue(I.getOperand(0));
3337   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3338                                                         I.getType());
3339   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3340 }
3341 
3342 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3343   // UIToFP is never a no-op cast, no need to check
3344   SDValue N = getValue(I.getOperand(0));
3345   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3346                                                         I.getType());
3347   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3348 }
3349 
3350 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3351   // SIToFP is never a no-op cast, no need to check
3352   SDValue N = getValue(I.getOperand(0));
3353   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3354                                                         I.getType());
3355   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3356 }
3357 
3358 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3359   // What to do depends on the size of the integer and the size of the pointer.
3360   // We can either truncate, zero extend, or no-op, accordingly.
3361   SDValue N = getValue(I.getOperand(0));
3362   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3363                                                         I.getType());
3364   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3365 }
3366 
3367 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3368   // What to do depends on the size of the integer and the size of the pointer.
3369   // We can either truncate, zero extend, or no-op, accordingly.
3370   SDValue N = getValue(I.getOperand(0));
3371   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3372                                                         I.getType());
3373   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3374 }
3375 
3376 void SelectionDAGBuilder::visitBitCast(const User &I) {
3377   SDValue N = getValue(I.getOperand(0));
3378   SDLoc dl = getCurSDLoc();
3379   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3380                                                         I.getType());
3381 
3382   // BitCast assures us that source and destination are the same size so this is
3383   // either a BITCAST or a no-op.
3384   if (DestVT != N.getValueType())
3385     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3386                              DestVT, N)); // convert types.
3387   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3388   // might fold any kind of constant expression to an integer constant and that
3389   // is not what we are looking for. Only recognize a bitcast of a genuine
3390   // constant integer as an opaque constant.
3391   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3392     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3393                                  /*isOpaque*/true));
3394   else
3395     setValue(&I, N);            // noop cast.
3396 }
3397 
3398 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3399   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3400   const Value *SV = I.getOperand(0);
3401   SDValue N = getValue(SV);
3402   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3403 
3404   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3405   unsigned DestAS = I.getType()->getPointerAddressSpace();
3406 
3407   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3408     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3409 
3410   setValue(&I, N);
3411 }
3412 
3413 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3414   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3415   SDValue InVec = getValue(I.getOperand(0));
3416   SDValue InVal = getValue(I.getOperand(1));
3417   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3418                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3419   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3420                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3421                            InVec, InVal, InIdx));
3422 }
3423 
3424 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3425   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3426   SDValue InVec = getValue(I.getOperand(0));
3427   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3428                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3429   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3430                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3431                            InVec, InIdx));
3432 }
3433 
3434 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3435   SDValue Src1 = getValue(I.getOperand(0));
3436   SDValue Src2 = getValue(I.getOperand(1));
3437   SDLoc DL = getCurSDLoc();
3438 
3439   SmallVector<int, 8> Mask;
3440   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3441   unsigned MaskNumElts = Mask.size();
3442 
3443   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3444   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3445   EVT SrcVT = Src1.getValueType();
3446   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3447 
3448   if (SrcNumElts == MaskNumElts) {
3449     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3450     return;
3451   }
3452 
3453   // Normalize the shuffle vector since mask and vector length don't match.
3454   if (SrcNumElts < MaskNumElts) {
3455     // Mask is longer than the source vectors. We can use concatenate vector to
3456     // make the mask and vectors lengths match.
3457 
3458     if (MaskNumElts % SrcNumElts == 0) {
3459       // Mask length is a multiple of the source vector length.
3460       // Check if the shuffle is some kind of concatenation of the input
3461       // vectors.
3462       unsigned NumConcat = MaskNumElts / SrcNumElts;
3463       bool IsConcat = true;
3464       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3465       for (unsigned i = 0; i != MaskNumElts; ++i) {
3466         int Idx = Mask[i];
3467         if (Idx < 0)
3468           continue;
3469         // Ensure the indices in each SrcVT sized piece are sequential and that
3470         // the same source is used for the whole piece.
3471         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3472             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3473              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3474           IsConcat = false;
3475           break;
3476         }
3477         // Remember which source this index came from.
3478         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3479       }
3480 
3481       // The shuffle is concatenating multiple vectors together. Just emit
3482       // a CONCAT_VECTORS operation.
3483       if (IsConcat) {
3484         SmallVector<SDValue, 8> ConcatOps;
3485         for (auto Src : ConcatSrcs) {
3486           if (Src < 0)
3487             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3488           else if (Src == 0)
3489             ConcatOps.push_back(Src1);
3490           else
3491             ConcatOps.push_back(Src2);
3492         }
3493         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3494         return;
3495       }
3496     }
3497 
3498     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3499     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3500     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3501                                     PaddedMaskNumElts);
3502 
3503     // Pad both vectors with undefs to make them the same length as the mask.
3504     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3505 
3506     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3507     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3508     MOps1[0] = Src1;
3509     MOps2[0] = Src2;
3510 
3511     Src1 = Src1.isUndef()
3512                ? DAG.getUNDEF(PaddedVT)
3513                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3514     Src2 = Src2.isUndef()
3515                ? DAG.getUNDEF(PaddedVT)
3516                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3517 
3518     // Readjust mask for new input vector length.
3519     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3520     for (unsigned i = 0; i != MaskNumElts; ++i) {
3521       int Idx = Mask[i];
3522       if (Idx >= (int)SrcNumElts)
3523         Idx -= SrcNumElts - PaddedMaskNumElts;
3524       MappedOps[i] = Idx;
3525     }
3526 
3527     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3528 
3529     // If the concatenated vector was padded, extract a subvector with the
3530     // correct number of elements.
3531     if (MaskNumElts != PaddedMaskNumElts)
3532       Result = DAG.getNode(
3533           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3534           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3535 
3536     setValue(&I, Result);
3537     return;
3538   }
3539 
3540   if (SrcNumElts > MaskNumElts) {
3541     // Analyze the access pattern of the vector to see if we can extract
3542     // two subvectors and do the shuffle.
3543     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3544     bool CanExtract = true;
3545     for (int Idx : Mask) {
3546       unsigned Input = 0;
3547       if (Idx < 0)
3548         continue;
3549 
3550       if (Idx >= (int)SrcNumElts) {
3551         Input = 1;
3552         Idx -= SrcNumElts;
3553       }
3554 
3555       // If all the indices come from the same MaskNumElts sized portion of
3556       // the sources we can use extract. Also make sure the extract wouldn't
3557       // extract past the end of the source.
3558       int NewStartIdx = alignDown(Idx, MaskNumElts);
3559       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3560           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3561         CanExtract = false;
3562       // Make sure we always update StartIdx as we use it to track if all
3563       // elements are undef.
3564       StartIdx[Input] = NewStartIdx;
3565     }
3566 
3567     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3568       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3569       return;
3570     }
3571     if (CanExtract) {
3572       // Extract appropriate subvector and generate a vector shuffle
3573       for (unsigned Input = 0; Input < 2; ++Input) {
3574         SDValue &Src = Input == 0 ? Src1 : Src2;
3575         if (StartIdx[Input] < 0)
3576           Src = DAG.getUNDEF(VT);
3577         else {
3578           Src = DAG.getNode(
3579               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3580               DAG.getConstant(StartIdx[Input], DL,
3581                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3582         }
3583       }
3584 
3585       // Calculate new mask.
3586       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3587       for (int &Idx : MappedOps) {
3588         if (Idx >= (int)SrcNumElts)
3589           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3590         else if (Idx >= 0)
3591           Idx -= StartIdx[0];
3592       }
3593 
3594       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3595       return;
3596     }
3597   }
3598 
3599   // We can't use either concat vectors or extract subvectors so fall back to
3600   // replacing the shuffle with extract and build vector.
3601   // to insert and build vector.
3602   EVT EltVT = VT.getVectorElementType();
3603   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3604   SmallVector<SDValue,8> Ops;
3605   for (int Idx : Mask) {
3606     SDValue Res;
3607 
3608     if (Idx < 0) {
3609       Res = DAG.getUNDEF(EltVT);
3610     } else {
3611       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3612       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3613 
3614       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3615                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3616     }
3617 
3618     Ops.push_back(Res);
3619   }
3620 
3621   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3622 }
3623 
3624 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3625   ArrayRef<unsigned> Indices;
3626   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3627     Indices = IV->getIndices();
3628   else
3629     Indices = cast<ConstantExpr>(&I)->getIndices();
3630 
3631   const Value *Op0 = I.getOperand(0);
3632   const Value *Op1 = I.getOperand(1);
3633   Type *AggTy = I.getType();
3634   Type *ValTy = Op1->getType();
3635   bool IntoUndef = isa<UndefValue>(Op0);
3636   bool FromUndef = isa<UndefValue>(Op1);
3637 
3638   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3639 
3640   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3641   SmallVector<EVT, 4> AggValueVTs;
3642   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3643   SmallVector<EVT, 4> ValValueVTs;
3644   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3645 
3646   unsigned NumAggValues = AggValueVTs.size();
3647   unsigned NumValValues = ValValueVTs.size();
3648   SmallVector<SDValue, 4> Values(NumAggValues);
3649 
3650   // Ignore an insertvalue that produces an empty object
3651   if (!NumAggValues) {
3652     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3653     return;
3654   }
3655 
3656   SDValue Agg = getValue(Op0);
3657   unsigned i = 0;
3658   // Copy the beginning value(s) from the original aggregate.
3659   for (; i != LinearIndex; ++i)
3660     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3661                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3662   // Copy values from the inserted value(s).
3663   if (NumValValues) {
3664     SDValue Val = getValue(Op1);
3665     for (; i != LinearIndex + NumValValues; ++i)
3666       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3667                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3668   }
3669   // Copy remaining value(s) from the original aggregate.
3670   for (; i != NumAggValues; ++i)
3671     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3672                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3673 
3674   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3675                            DAG.getVTList(AggValueVTs), Values));
3676 }
3677 
3678 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3679   ArrayRef<unsigned> Indices;
3680   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3681     Indices = EV->getIndices();
3682   else
3683     Indices = cast<ConstantExpr>(&I)->getIndices();
3684 
3685   const Value *Op0 = I.getOperand(0);
3686   Type *AggTy = Op0->getType();
3687   Type *ValTy = I.getType();
3688   bool OutOfUndef = isa<UndefValue>(Op0);
3689 
3690   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3691 
3692   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3693   SmallVector<EVT, 4> ValValueVTs;
3694   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3695 
3696   unsigned NumValValues = ValValueVTs.size();
3697 
3698   // Ignore a extractvalue that produces an empty object
3699   if (!NumValValues) {
3700     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3701     return;
3702   }
3703 
3704   SmallVector<SDValue, 4> Values(NumValValues);
3705 
3706   SDValue Agg = getValue(Op0);
3707   // Copy out the selected value(s).
3708   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3709     Values[i - LinearIndex] =
3710       OutOfUndef ?
3711         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3712         SDValue(Agg.getNode(), Agg.getResNo() + i);
3713 
3714   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3715                            DAG.getVTList(ValValueVTs), Values));
3716 }
3717 
3718 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3719   Value *Op0 = I.getOperand(0);
3720   // Note that the pointer operand may be a vector of pointers. Take the scalar
3721   // element which holds a pointer.
3722   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3723   SDValue N = getValue(Op0);
3724   SDLoc dl = getCurSDLoc();
3725 
3726   // Normalize Vector GEP - all scalar operands should be converted to the
3727   // splat vector.
3728   unsigned VectorWidth = I.getType()->isVectorTy() ?
3729     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3730 
3731   if (VectorWidth && !N.getValueType().isVector()) {
3732     LLVMContext &Context = *DAG.getContext();
3733     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3734     N = DAG.getSplatBuildVector(VT, dl, N);
3735   }
3736 
3737   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3738        GTI != E; ++GTI) {
3739     const Value *Idx = GTI.getOperand();
3740     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3741       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3742       if (Field) {
3743         // N = N + Offset
3744         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3745 
3746         // In an inbounds GEP with an offset that is nonnegative even when
3747         // interpreted as signed, assume there is no unsigned overflow.
3748         SDNodeFlags Flags;
3749         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3750           Flags.setNoUnsignedWrap(true);
3751 
3752         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3753                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3754       }
3755     } else {
3756       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3757       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3758       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3759 
3760       // If this is a scalar constant or a splat vector of constants,
3761       // handle it quickly.
3762       const auto *CI = dyn_cast<ConstantInt>(Idx);
3763       if (!CI && isa<ConstantDataVector>(Idx) &&
3764           cast<ConstantDataVector>(Idx)->getSplatValue())
3765         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3766 
3767       if (CI) {
3768         if (CI->isZero())
3769           continue;
3770         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3771         LLVMContext &Context = *DAG.getContext();
3772         SDValue OffsVal = VectorWidth ?
3773           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3774           DAG.getConstant(Offs, dl, IdxTy);
3775 
3776         // In an inbouds GEP with an offset that is nonnegative even when
3777         // interpreted as signed, assume there is no unsigned overflow.
3778         SDNodeFlags Flags;
3779         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3780           Flags.setNoUnsignedWrap(true);
3781 
3782         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3783         continue;
3784       }
3785 
3786       // N = N + Idx * ElementSize;
3787       SDValue IdxN = getValue(Idx);
3788 
3789       if (!IdxN.getValueType().isVector() && VectorWidth) {
3790         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3791         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3792       }
3793 
3794       // If the index is smaller or larger than intptr_t, truncate or extend
3795       // it.
3796       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3797 
3798       // If this is a multiply by a power of two, turn it into a shl
3799       // immediately.  This is a very common case.
3800       if (ElementSize != 1) {
3801         if (ElementSize.isPowerOf2()) {
3802           unsigned Amt = ElementSize.logBase2();
3803           IdxN = DAG.getNode(ISD::SHL, dl,
3804                              N.getValueType(), IdxN,
3805                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3806         } else {
3807           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3808           IdxN = DAG.getNode(ISD::MUL, dl,
3809                              N.getValueType(), IdxN, Scale);
3810         }
3811       }
3812 
3813       N = DAG.getNode(ISD::ADD, dl,
3814                       N.getValueType(), N, IdxN);
3815     }
3816   }
3817 
3818   setValue(&I, N);
3819 }
3820 
3821 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3822   // If this is a fixed sized alloca in the entry block of the function,
3823   // allocate it statically on the stack.
3824   if (FuncInfo.StaticAllocaMap.count(&I))
3825     return;   // getValue will auto-populate this.
3826 
3827   SDLoc dl = getCurSDLoc();
3828   Type *Ty = I.getAllocatedType();
3829   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3830   auto &DL = DAG.getDataLayout();
3831   uint64_t TySize = DL.getTypeAllocSize(Ty);
3832   unsigned Align =
3833       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3834 
3835   SDValue AllocSize = getValue(I.getArraySize());
3836 
3837   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3838   if (AllocSize.getValueType() != IntPtr)
3839     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3840 
3841   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3842                           AllocSize,
3843                           DAG.getConstant(TySize, dl, IntPtr));
3844 
3845   // Handle alignment.  If the requested alignment is less than or equal to
3846   // the stack alignment, ignore it.  If the size is greater than or equal to
3847   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3848   unsigned StackAlign =
3849       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3850   if (Align <= StackAlign)
3851     Align = 0;
3852 
3853   // Round the size of the allocation up to the stack alignment size
3854   // by add SA-1 to the size. This doesn't overflow because we're computing
3855   // an address inside an alloca.
3856   SDNodeFlags Flags;
3857   Flags.setNoUnsignedWrap(true);
3858   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3859                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3860 
3861   // Mask out the low bits for alignment purposes.
3862   AllocSize =
3863       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3864                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3865 
3866   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3867   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3868   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3869   setValue(&I, DSA);
3870   DAG.setRoot(DSA.getValue(1));
3871 
3872   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3873 }
3874 
3875 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3876   if (I.isAtomic())
3877     return visitAtomicLoad(I);
3878 
3879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3880   const Value *SV = I.getOperand(0);
3881   if (TLI.supportSwiftError()) {
3882     // Swifterror values can come from either a function parameter with
3883     // swifterror attribute or an alloca with swifterror attribute.
3884     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3885       if (Arg->hasSwiftErrorAttr())
3886         return visitLoadFromSwiftError(I);
3887     }
3888 
3889     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3890       if (Alloca->isSwiftError())
3891         return visitLoadFromSwiftError(I);
3892     }
3893   }
3894 
3895   SDValue Ptr = getValue(SV);
3896 
3897   Type *Ty = I.getType();
3898 
3899   bool isVolatile = I.isVolatile();
3900   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3901   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3902   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3903   unsigned Alignment = I.getAlignment();
3904 
3905   AAMDNodes AAInfo;
3906   I.getAAMetadata(AAInfo);
3907   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3908 
3909   SmallVector<EVT, 4> ValueVTs;
3910   SmallVector<uint64_t, 4> Offsets;
3911   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3912   unsigned NumValues = ValueVTs.size();
3913   if (NumValues == 0)
3914     return;
3915 
3916   SDValue Root;
3917   bool ConstantMemory = false;
3918   if (isVolatile || NumValues > MaxParallelChains)
3919     // Serialize volatile loads with other side effects.
3920     Root = getRoot();
3921   else if (AA &&
3922            AA->pointsToConstantMemory(MemoryLocation(
3923                SV,
3924                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3925                AAInfo))) {
3926     // Do not serialize (non-volatile) loads of constant memory with anything.
3927     Root = DAG.getEntryNode();
3928     ConstantMemory = true;
3929   } else {
3930     // Do not serialize non-volatile loads against each other.
3931     Root = DAG.getRoot();
3932   }
3933 
3934   SDLoc dl = getCurSDLoc();
3935 
3936   if (isVolatile)
3937     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3938 
3939   // An aggregate load cannot wrap around the address space, so offsets to its
3940   // parts don't wrap either.
3941   SDNodeFlags Flags;
3942   Flags.setNoUnsignedWrap(true);
3943 
3944   SmallVector<SDValue, 4> Values(NumValues);
3945   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3946   EVT PtrVT = Ptr.getValueType();
3947   unsigned ChainI = 0;
3948   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3949     // Serializing loads here may result in excessive register pressure, and
3950     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3951     // could recover a bit by hoisting nodes upward in the chain by recognizing
3952     // they are side-effect free or do not alias. The optimizer should really
3953     // avoid this case by converting large object/array copies to llvm.memcpy
3954     // (MaxParallelChains should always remain as failsafe).
3955     if (ChainI == MaxParallelChains) {
3956       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3957       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3958                                   makeArrayRef(Chains.data(), ChainI));
3959       Root = Chain;
3960       ChainI = 0;
3961     }
3962     SDValue A = DAG.getNode(ISD::ADD, dl,
3963                             PtrVT, Ptr,
3964                             DAG.getConstant(Offsets[i], dl, PtrVT),
3965                             Flags);
3966     auto MMOFlags = MachineMemOperand::MONone;
3967     if (isVolatile)
3968       MMOFlags |= MachineMemOperand::MOVolatile;
3969     if (isNonTemporal)
3970       MMOFlags |= MachineMemOperand::MONonTemporal;
3971     if (isInvariant)
3972       MMOFlags |= MachineMemOperand::MOInvariant;
3973     if (isDereferenceable)
3974       MMOFlags |= MachineMemOperand::MODereferenceable;
3975     MMOFlags |= TLI.getMMOFlags(I);
3976 
3977     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3978                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3979                             MMOFlags, AAInfo, Ranges);
3980 
3981     Values[i] = L;
3982     Chains[ChainI] = L.getValue(1);
3983   }
3984 
3985   if (!ConstantMemory) {
3986     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3987                                 makeArrayRef(Chains.data(), ChainI));
3988     if (isVolatile)
3989       DAG.setRoot(Chain);
3990     else
3991       PendingLoads.push_back(Chain);
3992   }
3993 
3994   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3995                            DAG.getVTList(ValueVTs), Values));
3996 }
3997 
3998 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3999   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4000          "call visitStoreToSwiftError when backend supports swifterror");
4001 
4002   SmallVector<EVT, 4> ValueVTs;
4003   SmallVector<uint64_t, 4> Offsets;
4004   const Value *SrcV = I.getOperand(0);
4005   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4006                   SrcV->getType(), ValueVTs, &Offsets);
4007   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4008          "expect a single EVT for swifterror");
4009 
4010   SDValue Src = getValue(SrcV);
4011   // Create a virtual register, then update the virtual register.
4012   unsigned VReg; bool CreatedVReg;
4013   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
4014   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4015   // Chain can be getRoot or getControlRoot.
4016   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4017                                       SDValue(Src.getNode(), Src.getResNo()));
4018   DAG.setRoot(CopyNode);
4019   if (CreatedVReg)
4020     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
4021 }
4022 
4023 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4024   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4025          "call visitLoadFromSwiftError when backend supports swifterror");
4026 
4027   assert(!I.isVolatile() &&
4028          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
4029          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
4030          "Support volatile, non temporal, invariant for load_from_swift_error");
4031 
4032   const Value *SV = I.getOperand(0);
4033   Type *Ty = I.getType();
4034   AAMDNodes AAInfo;
4035   I.getAAMetadata(AAInfo);
4036   assert(
4037       (!AA ||
4038        !AA->pointsToConstantMemory(MemoryLocation(
4039            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4040            AAInfo))) &&
4041       "load_from_swift_error should not be constant memory");
4042 
4043   SmallVector<EVT, 4> ValueVTs;
4044   SmallVector<uint64_t, 4> Offsets;
4045   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4046                   ValueVTs, &Offsets);
4047   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4048          "expect a single EVT for swifterror");
4049 
4050   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4051   SDValue L = DAG.getCopyFromReg(
4052       getRoot(), getCurSDLoc(),
4053       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
4054       ValueVTs[0]);
4055 
4056   setValue(&I, L);
4057 }
4058 
4059 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4060   if (I.isAtomic())
4061     return visitAtomicStore(I);
4062 
4063   const Value *SrcV = I.getOperand(0);
4064   const Value *PtrV = I.getOperand(1);
4065 
4066   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4067   if (TLI.supportSwiftError()) {
4068     // Swifterror values can come from either a function parameter with
4069     // swifterror attribute or an alloca with swifterror attribute.
4070     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4071       if (Arg->hasSwiftErrorAttr())
4072         return visitStoreToSwiftError(I);
4073     }
4074 
4075     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4076       if (Alloca->isSwiftError())
4077         return visitStoreToSwiftError(I);
4078     }
4079   }
4080 
4081   SmallVector<EVT, 4> ValueVTs;
4082   SmallVector<uint64_t, 4> Offsets;
4083   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4084                   SrcV->getType(), ValueVTs, &Offsets);
4085   unsigned NumValues = ValueVTs.size();
4086   if (NumValues == 0)
4087     return;
4088 
4089   // Get the lowered operands. Note that we do this after
4090   // checking if NumResults is zero, because with zero results
4091   // the operands won't have values in the map.
4092   SDValue Src = getValue(SrcV);
4093   SDValue Ptr = getValue(PtrV);
4094 
4095   SDValue Root = getRoot();
4096   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4097   SDLoc dl = getCurSDLoc();
4098   EVT PtrVT = Ptr.getValueType();
4099   unsigned Alignment = I.getAlignment();
4100   AAMDNodes AAInfo;
4101   I.getAAMetadata(AAInfo);
4102 
4103   auto MMOFlags = MachineMemOperand::MONone;
4104   if (I.isVolatile())
4105     MMOFlags |= MachineMemOperand::MOVolatile;
4106   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
4107     MMOFlags |= MachineMemOperand::MONonTemporal;
4108   MMOFlags |= TLI.getMMOFlags(I);
4109 
4110   // An aggregate load cannot wrap around the address space, so offsets to its
4111   // parts don't wrap either.
4112   SDNodeFlags Flags;
4113   Flags.setNoUnsignedWrap(true);
4114 
4115   unsigned ChainI = 0;
4116   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4117     // See visitLoad comments.
4118     if (ChainI == MaxParallelChains) {
4119       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4120                                   makeArrayRef(Chains.data(), ChainI));
4121       Root = Chain;
4122       ChainI = 0;
4123     }
4124     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
4125                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
4126     SDValue St = DAG.getStore(
4127         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
4128         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
4129     Chains[ChainI] = St;
4130   }
4131 
4132   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4133                                   makeArrayRef(Chains.data(), ChainI));
4134   DAG.setRoot(StoreNode);
4135 }
4136 
4137 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4138                                            bool IsCompressing) {
4139   SDLoc sdl = getCurSDLoc();
4140 
4141   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4142                            unsigned& Alignment) {
4143     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4144     Src0 = I.getArgOperand(0);
4145     Ptr = I.getArgOperand(1);
4146     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4147     Mask = I.getArgOperand(3);
4148   };
4149   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4150                            unsigned& Alignment) {
4151     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4152     Src0 = I.getArgOperand(0);
4153     Ptr = I.getArgOperand(1);
4154     Mask = I.getArgOperand(2);
4155     Alignment = 0;
4156   };
4157 
4158   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4159   unsigned Alignment;
4160   if (IsCompressing)
4161     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4162   else
4163     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4164 
4165   SDValue Ptr = getValue(PtrOperand);
4166   SDValue Src0 = getValue(Src0Operand);
4167   SDValue Mask = getValue(MaskOperand);
4168 
4169   EVT VT = Src0.getValueType();
4170   if (!Alignment)
4171     Alignment = DAG.getEVTAlignment(VT);
4172 
4173   AAMDNodes AAInfo;
4174   I.getAAMetadata(AAInfo);
4175 
4176   MachineMemOperand *MMO =
4177     DAG.getMachineFunction().
4178     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4179                           MachineMemOperand::MOStore,  VT.getStoreSize(),
4180                           Alignment, AAInfo);
4181   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
4182                                          MMO, false /* Truncating */,
4183                                          IsCompressing);
4184   DAG.setRoot(StoreNode);
4185   setValue(&I, StoreNode);
4186 }
4187 
4188 // Get a uniform base for the Gather/Scatter intrinsic.
4189 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4190 // We try to represent it as a base pointer + vector of indices.
4191 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4192 // The first operand of the GEP may be a single pointer or a vector of pointers
4193 // Example:
4194 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4195 //  or
4196 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4197 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4198 //
4199 // When the first GEP operand is a single pointer - it is the uniform base we
4200 // are looking for. If first operand of the GEP is a splat vector - we
4201 // extract the splat value and use it as a uniform base.
4202 // In all other cases the function returns 'false'.
4203 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
4204                            SDValue &Scale, SelectionDAGBuilder* SDB) {
4205   SelectionDAG& DAG = SDB->DAG;
4206   LLVMContext &Context = *DAG.getContext();
4207 
4208   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4209   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4210   if (!GEP)
4211     return false;
4212 
4213   const Value *GEPPtr = GEP->getPointerOperand();
4214   if (!GEPPtr->getType()->isVectorTy())
4215     Ptr = GEPPtr;
4216   else if (!(Ptr = getSplatValue(GEPPtr)))
4217     return false;
4218 
4219   unsigned FinalIndex = GEP->getNumOperands() - 1;
4220   Value *IndexVal = GEP->getOperand(FinalIndex);
4221 
4222   // Ensure all the other indices are 0.
4223   for (unsigned i = 1; i < FinalIndex; ++i) {
4224     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
4225     if (!C || !C->isZero())
4226       return false;
4227   }
4228 
4229   // The operands of the GEP may be defined in another basic block.
4230   // In this case we'll not find nodes for the operands.
4231   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
4232     return false;
4233 
4234   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4235   const DataLayout &DL = DAG.getDataLayout();
4236   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4237                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4238   Base = SDB->getValue(Ptr);
4239   Index = SDB->getValue(IndexVal);
4240 
4241   if (!Index.getValueType().isVector()) {
4242     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4243     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4244     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4245   }
4246   return true;
4247 }
4248 
4249 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4250   SDLoc sdl = getCurSDLoc();
4251 
4252   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4253   const Value *Ptr = I.getArgOperand(1);
4254   SDValue Src0 = getValue(I.getArgOperand(0));
4255   SDValue Mask = getValue(I.getArgOperand(3));
4256   EVT VT = Src0.getValueType();
4257   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4258   if (!Alignment)
4259     Alignment = DAG.getEVTAlignment(VT);
4260   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4261 
4262   AAMDNodes AAInfo;
4263   I.getAAMetadata(AAInfo);
4264 
4265   SDValue Base;
4266   SDValue Index;
4267   SDValue Scale;
4268   const Value *BasePtr = Ptr;
4269   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4270 
4271   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4272   MachineMemOperand *MMO = DAG.getMachineFunction().
4273     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4274                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4275                          Alignment, AAInfo);
4276   if (!UniformBase) {
4277     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4278     Index = getValue(Ptr);
4279     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4280   }
4281   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4282   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4283                                          Ops, MMO);
4284   DAG.setRoot(Scatter);
4285   setValue(&I, Scatter);
4286 }
4287 
4288 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4289   SDLoc sdl = getCurSDLoc();
4290 
4291   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4292                            unsigned& Alignment) {
4293     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4294     Ptr = I.getArgOperand(0);
4295     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4296     Mask = I.getArgOperand(2);
4297     Src0 = I.getArgOperand(3);
4298   };
4299   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4300                            unsigned& Alignment) {
4301     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4302     Ptr = I.getArgOperand(0);
4303     Alignment = 0;
4304     Mask = I.getArgOperand(1);
4305     Src0 = I.getArgOperand(2);
4306   };
4307 
4308   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4309   unsigned Alignment;
4310   if (IsExpanding)
4311     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4312   else
4313     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4314 
4315   SDValue Ptr = getValue(PtrOperand);
4316   SDValue Src0 = getValue(Src0Operand);
4317   SDValue Mask = getValue(MaskOperand);
4318 
4319   EVT VT = Src0.getValueType();
4320   if (!Alignment)
4321     Alignment = DAG.getEVTAlignment(VT);
4322 
4323   AAMDNodes AAInfo;
4324   I.getAAMetadata(AAInfo);
4325   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4326 
4327   // Do not serialize masked loads of constant memory with anything.
4328   bool AddToChain =
4329       !AA || !AA->pointsToConstantMemory(MemoryLocation(
4330                  PtrOperand,
4331                  LocationSize::precise(
4332                      DAG.getDataLayout().getTypeStoreSize(I.getType())),
4333                  AAInfo));
4334   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4335 
4336   MachineMemOperand *MMO =
4337     DAG.getMachineFunction().
4338     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4339                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4340                           Alignment, AAInfo, Ranges);
4341 
4342   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4343                                    ISD::NON_EXTLOAD, IsExpanding);
4344   if (AddToChain)
4345     PendingLoads.push_back(Load.getValue(1));
4346   setValue(&I, Load);
4347 }
4348 
4349 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4350   SDLoc sdl = getCurSDLoc();
4351 
4352   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4353   const Value *Ptr = I.getArgOperand(0);
4354   SDValue Src0 = getValue(I.getArgOperand(3));
4355   SDValue Mask = getValue(I.getArgOperand(2));
4356 
4357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4358   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4359   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4360   if (!Alignment)
4361     Alignment = DAG.getEVTAlignment(VT);
4362 
4363   AAMDNodes AAInfo;
4364   I.getAAMetadata(AAInfo);
4365   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4366 
4367   SDValue Root = DAG.getRoot();
4368   SDValue Base;
4369   SDValue Index;
4370   SDValue Scale;
4371   const Value *BasePtr = Ptr;
4372   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4373   bool ConstantMemory = false;
4374   if (UniformBase && AA &&
4375       AA->pointsToConstantMemory(
4376           MemoryLocation(BasePtr,
4377                          LocationSize::precise(
4378                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4379                          AAInfo))) {
4380     // Do not serialize (non-volatile) loads of constant memory with anything.
4381     Root = DAG.getEntryNode();
4382     ConstantMemory = true;
4383   }
4384 
4385   MachineMemOperand *MMO =
4386     DAG.getMachineFunction().
4387     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4388                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4389                          Alignment, AAInfo, Ranges);
4390 
4391   if (!UniformBase) {
4392     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4393     Index = getValue(Ptr);
4394     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4395   }
4396   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4397   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4398                                        Ops, MMO);
4399 
4400   SDValue OutChain = Gather.getValue(1);
4401   if (!ConstantMemory)
4402     PendingLoads.push_back(OutChain);
4403   setValue(&I, Gather);
4404 }
4405 
4406 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4407   SDLoc dl = getCurSDLoc();
4408   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4409   AtomicOrdering FailureOrder = I.getFailureOrdering();
4410   SyncScope::ID SSID = I.getSyncScopeID();
4411 
4412   SDValue InChain = getRoot();
4413 
4414   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4415   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4416   SDValue L = DAG.getAtomicCmpSwap(
4417       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4418       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4419       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4420       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4421 
4422   SDValue OutChain = L.getValue(2);
4423 
4424   setValue(&I, L);
4425   DAG.setRoot(OutChain);
4426 }
4427 
4428 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4429   SDLoc dl = getCurSDLoc();
4430   ISD::NodeType NT;
4431   switch (I.getOperation()) {
4432   default: llvm_unreachable("Unknown atomicrmw operation");
4433   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4434   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4435   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4436   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4437   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4438   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4439   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4440   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4441   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4442   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4443   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4444   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4445   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4446   }
4447   AtomicOrdering Order = I.getOrdering();
4448   SyncScope::ID SSID = I.getSyncScopeID();
4449 
4450   SDValue InChain = getRoot();
4451 
4452   SDValue L =
4453     DAG.getAtomic(NT, dl,
4454                   getValue(I.getValOperand()).getSimpleValueType(),
4455                   InChain,
4456                   getValue(I.getPointerOperand()),
4457                   getValue(I.getValOperand()),
4458                   I.getPointerOperand(),
4459                   /* Alignment=*/ 0, Order, SSID);
4460 
4461   SDValue OutChain = L.getValue(1);
4462 
4463   setValue(&I, L);
4464   DAG.setRoot(OutChain);
4465 }
4466 
4467 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4468   SDLoc dl = getCurSDLoc();
4469   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4470   SDValue Ops[3];
4471   Ops[0] = getRoot();
4472   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4473                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4474   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4475                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4476   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4477 }
4478 
4479 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4480   SDLoc dl = getCurSDLoc();
4481   AtomicOrdering Order = I.getOrdering();
4482   SyncScope::ID SSID = I.getSyncScopeID();
4483 
4484   SDValue InChain = getRoot();
4485 
4486   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4487   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4488 
4489   if (!TLI.supportsUnalignedAtomics() &&
4490       I.getAlignment() < VT.getStoreSize())
4491     report_fatal_error("Cannot generate unaligned atomic load");
4492 
4493   MachineMemOperand *MMO =
4494       DAG.getMachineFunction().
4495       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4496                            MachineMemOperand::MOVolatile |
4497                            MachineMemOperand::MOLoad,
4498                            VT.getStoreSize(),
4499                            I.getAlignment() ? I.getAlignment() :
4500                                               DAG.getEVTAlignment(VT),
4501                            AAMDNodes(), nullptr, SSID, Order);
4502 
4503   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4504   SDValue L =
4505       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4506                     getValue(I.getPointerOperand()), MMO);
4507 
4508   SDValue OutChain = L.getValue(1);
4509 
4510   setValue(&I, L);
4511   DAG.setRoot(OutChain);
4512 }
4513 
4514 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4515   SDLoc dl = getCurSDLoc();
4516 
4517   AtomicOrdering Order = I.getOrdering();
4518   SyncScope::ID SSID = I.getSyncScopeID();
4519 
4520   SDValue InChain = getRoot();
4521 
4522   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4523   EVT VT =
4524       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4525 
4526   if (I.getAlignment() < VT.getStoreSize())
4527     report_fatal_error("Cannot generate unaligned atomic store");
4528 
4529   SDValue OutChain =
4530     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4531                   InChain,
4532                   getValue(I.getPointerOperand()),
4533                   getValue(I.getValueOperand()),
4534                   I.getPointerOperand(), I.getAlignment(),
4535                   Order, SSID);
4536 
4537   DAG.setRoot(OutChain);
4538 }
4539 
4540 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4541 /// node.
4542 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4543                                                unsigned Intrinsic) {
4544   // Ignore the callsite's attributes. A specific call site may be marked with
4545   // readnone, but the lowering code will expect the chain based on the
4546   // definition.
4547   const Function *F = I.getCalledFunction();
4548   bool HasChain = !F->doesNotAccessMemory();
4549   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4550 
4551   // Build the operand list.
4552   SmallVector<SDValue, 8> Ops;
4553   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4554     if (OnlyLoad) {
4555       // We don't need to serialize loads against other loads.
4556       Ops.push_back(DAG.getRoot());
4557     } else {
4558       Ops.push_back(getRoot());
4559     }
4560   }
4561 
4562   // Info is set by getTgtMemInstrinsic
4563   TargetLowering::IntrinsicInfo Info;
4564   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4565   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4566                                                DAG.getMachineFunction(),
4567                                                Intrinsic);
4568 
4569   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4570   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4571       Info.opc == ISD::INTRINSIC_W_CHAIN)
4572     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4573                                         TLI.getPointerTy(DAG.getDataLayout())));
4574 
4575   // Add all operands of the call to the operand list.
4576   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4577     SDValue Op = getValue(I.getArgOperand(i));
4578     Ops.push_back(Op);
4579   }
4580 
4581   SmallVector<EVT, 4> ValueVTs;
4582   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4583 
4584   if (HasChain)
4585     ValueVTs.push_back(MVT::Other);
4586 
4587   SDVTList VTs = DAG.getVTList(ValueVTs);
4588 
4589   // Create the node.
4590   SDValue Result;
4591   if (IsTgtIntrinsic) {
4592     // This is target intrinsic that touches memory
4593     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4594       Ops, Info.memVT,
4595       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4596       Info.flags, Info.size);
4597   } else if (!HasChain) {
4598     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4599   } else if (!I.getType()->isVoidTy()) {
4600     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4601   } else {
4602     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4603   }
4604 
4605   if (HasChain) {
4606     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4607     if (OnlyLoad)
4608       PendingLoads.push_back(Chain);
4609     else
4610       DAG.setRoot(Chain);
4611   }
4612 
4613   if (!I.getType()->isVoidTy()) {
4614     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4615       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4616       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4617     } else
4618       Result = lowerRangeToAssertZExt(DAG, I, Result);
4619 
4620     setValue(&I, Result);
4621   }
4622 }
4623 
4624 /// GetSignificand - Get the significand and build it into a floating-point
4625 /// number with exponent of 1:
4626 ///
4627 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4628 ///
4629 /// where Op is the hexadecimal representation of floating point value.
4630 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4631   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4632                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4633   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4634                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4635   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4636 }
4637 
4638 /// GetExponent - Get the exponent:
4639 ///
4640 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4641 ///
4642 /// where Op is the hexadecimal representation of floating point value.
4643 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4644                            const TargetLowering &TLI, const SDLoc &dl) {
4645   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4646                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4647   SDValue t1 = DAG.getNode(
4648       ISD::SRL, dl, MVT::i32, t0,
4649       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4650   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4651                            DAG.getConstant(127, dl, MVT::i32));
4652   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4653 }
4654 
4655 /// getF32Constant - Get 32-bit floating point constant.
4656 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4657                               const SDLoc &dl) {
4658   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4659                            MVT::f32);
4660 }
4661 
4662 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4663                                        SelectionDAG &DAG) {
4664   // TODO: What fast-math-flags should be set on the floating-point nodes?
4665 
4666   //   IntegerPartOfX = ((int32_t)(t0);
4667   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4668 
4669   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4670   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4671   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4672 
4673   //   IntegerPartOfX <<= 23;
4674   IntegerPartOfX = DAG.getNode(
4675       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4676       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4677                                   DAG.getDataLayout())));
4678 
4679   SDValue TwoToFractionalPartOfX;
4680   if (LimitFloatPrecision <= 6) {
4681     // For floating-point precision of 6:
4682     //
4683     //   TwoToFractionalPartOfX =
4684     //     0.997535578f +
4685     //       (0.735607626f + 0.252464424f * x) * x;
4686     //
4687     // error 0.0144103317, which is 6 bits
4688     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4689                              getF32Constant(DAG, 0x3e814304, dl));
4690     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4691                              getF32Constant(DAG, 0x3f3c50c8, dl));
4692     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4693     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4694                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4695   } else if (LimitFloatPrecision <= 12) {
4696     // For floating-point precision of 12:
4697     //
4698     //   TwoToFractionalPartOfX =
4699     //     0.999892986f +
4700     //       (0.696457318f +
4701     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4702     //
4703     // error 0.000107046256, which is 13 to 14 bits
4704     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4705                              getF32Constant(DAG, 0x3da235e3, dl));
4706     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4707                              getF32Constant(DAG, 0x3e65b8f3, dl));
4708     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4709     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4710                              getF32Constant(DAG, 0x3f324b07, dl));
4711     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4712     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4713                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4714   } else { // LimitFloatPrecision <= 18
4715     // For floating-point precision of 18:
4716     //
4717     //   TwoToFractionalPartOfX =
4718     //     0.999999982f +
4719     //       (0.693148872f +
4720     //         (0.240227044f +
4721     //           (0.554906021e-1f +
4722     //             (0.961591928e-2f +
4723     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4724     // error 2.47208000*10^(-7), which is better than 18 bits
4725     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4726                              getF32Constant(DAG, 0x3924b03e, dl));
4727     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4728                              getF32Constant(DAG, 0x3ab24b87, dl));
4729     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4730     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4731                              getF32Constant(DAG, 0x3c1d8c17, dl));
4732     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4733     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4734                              getF32Constant(DAG, 0x3d634a1d, dl));
4735     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4736     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4737                              getF32Constant(DAG, 0x3e75fe14, dl));
4738     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4739     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4740                               getF32Constant(DAG, 0x3f317234, dl));
4741     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4742     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4743                                          getF32Constant(DAG, 0x3f800000, dl));
4744   }
4745 
4746   // Add the exponent into the result in integer domain.
4747   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4748   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4749                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4750 }
4751 
4752 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4753 /// limited-precision mode.
4754 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4755                          const TargetLowering &TLI) {
4756   if (Op.getValueType() == MVT::f32 &&
4757       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4758 
4759     // Put the exponent in the right bit position for later addition to the
4760     // final result:
4761     //
4762     //   #define LOG2OFe 1.4426950f
4763     //   t0 = Op * LOG2OFe
4764 
4765     // TODO: What fast-math-flags should be set here?
4766     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4767                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4768     return getLimitedPrecisionExp2(t0, dl, DAG);
4769   }
4770 
4771   // No special expansion.
4772   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4773 }
4774 
4775 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4776 /// limited-precision mode.
4777 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4778                          const TargetLowering &TLI) {
4779   // TODO: What fast-math-flags should be set on the floating-point nodes?
4780 
4781   if (Op.getValueType() == MVT::f32 &&
4782       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4783     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4784 
4785     // Scale the exponent by log(2) [0.69314718f].
4786     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4787     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4788                                         getF32Constant(DAG, 0x3f317218, dl));
4789 
4790     // Get the significand and build it into a floating-point number with
4791     // exponent of 1.
4792     SDValue X = GetSignificand(DAG, Op1, dl);
4793 
4794     SDValue LogOfMantissa;
4795     if (LimitFloatPrecision <= 6) {
4796       // For floating-point precision of 6:
4797       //
4798       //   LogofMantissa =
4799       //     -1.1609546f +
4800       //       (1.4034025f - 0.23903021f * x) * x;
4801       //
4802       // error 0.0034276066, which is better than 8 bits
4803       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4804                                getF32Constant(DAG, 0xbe74c456, dl));
4805       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4806                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4807       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4808       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4809                                   getF32Constant(DAG, 0x3f949a29, dl));
4810     } else if (LimitFloatPrecision <= 12) {
4811       // For floating-point precision of 12:
4812       //
4813       //   LogOfMantissa =
4814       //     -1.7417939f +
4815       //       (2.8212026f +
4816       //         (-1.4699568f +
4817       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4818       //
4819       // error 0.000061011436, which is 14 bits
4820       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4821                                getF32Constant(DAG, 0xbd67b6d6, dl));
4822       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4823                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4824       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4825       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4826                                getF32Constant(DAG, 0x3fbc278b, dl));
4827       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4828       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4829                                getF32Constant(DAG, 0x40348e95, dl));
4830       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4831       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4832                                   getF32Constant(DAG, 0x3fdef31a, dl));
4833     } else { // LimitFloatPrecision <= 18
4834       // For floating-point precision of 18:
4835       //
4836       //   LogOfMantissa =
4837       //     -2.1072184f +
4838       //       (4.2372794f +
4839       //         (-3.7029485f +
4840       //           (2.2781945f +
4841       //             (-0.87823314f +
4842       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4843       //
4844       // error 0.0000023660568, which is better than 18 bits
4845       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4846                                getF32Constant(DAG, 0xbc91e5ac, dl));
4847       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4848                                getF32Constant(DAG, 0x3e4350aa, dl));
4849       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4850       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4851                                getF32Constant(DAG, 0x3f60d3e3, dl));
4852       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4853       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4854                                getF32Constant(DAG, 0x4011cdf0, dl));
4855       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4856       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4857                                getF32Constant(DAG, 0x406cfd1c, dl));
4858       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4859       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4860                                getF32Constant(DAG, 0x408797cb, dl));
4861       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4862       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4863                                   getF32Constant(DAG, 0x4006dcab, dl));
4864     }
4865 
4866     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4867   }
4868 
4869   // No special expansion.
4870   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4871 }
4872 
4873 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4874 /// limited-precision mode.
4875 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4876                           const TargetLowering &TLI) {
4877   // TODO: What fast-math-flags should be set on the floating-point nodes?
4878 
4879   if (Op.getValueType() == MVT::f32 &&
4880       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4881     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4882 
4883     // Get the exponent.
4884     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4885 
4886     // Get the significand and build it into a floating-point number with
4887     // exponent of 1.
4888     SDValue X = GetSignificand(DAG, Op1, dl);
4889 
4890     // Different possible minimax approximations of significand in
4891     // floating-point for various degrees of accuracy over [1,2].
4892     SDValue Log2ofMantissa;
4893     if (LimitFloatPrecision <= 6) {
4894       // For floating-point precision of 6:
4895       //
4896       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4897       //
4898       // error 0.0049451742, which is more than 7 bits
4899       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4900                                getF32Constant(DAG, 0xbeb08fe0, dl));
4901       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4902                                getF32Constant(DAG, 0x40019463, dl));
4903       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4904       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4905                                    getF32Constant(DAG, 0x3fd6633d, dl));
4906     } else if (LimitFloatPrecision <= 12) {
4907       // For floating-point precision of 12:
4908       //
4909       //   Log2ofMantissa =
4910       //     -2.51285454f +
4911       //       (4.07009056f +
4912       //         (-2.12067489f +
4913       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4914       //
4915       // error 0.0000876136000, which is better than 13 bits
4916       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4917                                getF32Constant(DAG, 0xbda7262e, dl));
4918       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4919                                getF32Constant(DAG, 0x3f25280b, dl));
4920       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4921       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4922                                getF32Constant(DAG, 0x4007b923, dl));
4923       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4924       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4925                                getF32Constant(DAG, 0x40823e2f, dl));
4926       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4927       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4928                                    getF32Constant(DAG, 0x4020d29c, dl));
4929     } else { // LimitFloatPrecision <= 18
4930       // For floating-point precision of 18:
4931       //
4932       //   Log2ofMantissa =
4933       //     -3.0400495f +
4934       //       (6.1129976f +
4935       //         (-5.3420409f +
4936       //           (3.2865683f +
4937       //             (-1.2669343f +
4938       //               (0.27515199f -
4939       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4940       //
4941       // error 0.0000018516, which is better than 18 bits
4942       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4943                                getF32Constant(DAG, 0xbcd2769e, dl));
4944       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4945                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4946       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4947       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4948                                getF32Constant(DAG, 0x3fa22ae7, dl));
4949       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4950       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4951                                getF32Constant(DAG, 0x40525723, dl));
4952       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4953       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4954                                getF32Constant(DAG, 0x40aaf200, dl));
4955       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4956       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4957                                getF32Constant(DAG, 0x40c39dad, dl));
4958       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4959       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4960                                    getF32Constant(DAG, 0x4042902c, dl));
4961     }
4962 
4963     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4964   }
4965 
4966   // No special expansion.
4967   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4968 }
4969 
4970 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4971 /// limited-precision mode.
4972 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4973                            const TargetLowering &TLI) {
4974   // TODO: What fast-math-flags should be set on the floating-point nodes?
4975 
4976   if (Op.getValueType() == MVT::f32 &&
4977       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4978     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4979 
4980     // Scale the exponent by log10(2) [0.30102999f].
4981     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4982     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4983                                         getF32Constant(DAG, 0x3e9a209a, dl));
4984 
4985     // Get the significand and build it into a floating-point number with
4986     // exponent of 1.
4987     SDValue X = GetSignificand(DAG, Op1, dl);
4988 
4989     SDValue Log10ofMantissa;
4990     if (LimitFloatPrecision <= 6) {
4991       // For floating-point precision of 6:
4992       //
4993       //   Log10ofMantissa =
4994       //     -0.50419619f +
4995       //       (0.60948995f - 0.10380950f * x) * x;
4996       //
4997       // error 0.0014886165, which is 6 bits
4998       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4999                                getF32Constant(DAG, 0xbdd49a13, dl));
5000       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5001                                getF32Constant(DAG, 0x3f1c0789, dl));
5002       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5003       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5004                                     getF32Constant(DAG, 0x3f011300, dl));
5005     } else if (LimitFloatPrecision <= 12) {
5006       // For floating-point precision of 12:
5007       //
5008       //   Log10ofMantissa =
5009       //     -0.64831180f +
5010       //       (0.91751397f +
5011       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5012       //
5013       // error 0.00019228036, which is better than 12 bits
5014       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5015                                getF32Constant(DAG, 0x3d431f31, dl));
5016       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5017                                getF32Constant(DAG, 0x3ea21fb2, dl));
5018       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5019       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5020                                getF32Constant(DAG, 0x3f6ae232, dl));
5021       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5022       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5023                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5024     } else { // LimitFloatPrecision <= 18
5025       // For floating-point precision of 18:
5026       //
5027       //   Log10ofMantissa =
5028       //     -0.84299375f +
5029       //       (1.5327582f +
5030       //         (-1.0688956f +
5031       //           (0.49102474f +
5032       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5033       //
5034       // error 0.0000037995730, which is better than 18 bits
5035       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5036                                getF32Constant(DAG, 0x3c5d51ce, dl));
5037       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5038                                getF32Constant(DAG, 0x3e00685a, dl));
5039       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5040       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5041                                getF32Constant(DAG, 0x3efb6798, dl));
5042       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5043       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5044                                getF32Constant(DAG, 0x3f88d192, dl));
5045       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5046       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5047                                getF32Constant(DAG, 0x3fc4316c, dl));
5048       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5049       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5050                                     getF32Constant(DAG, 0x3f57ce70, dl));
5051     }
5052 
5053     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5054   }
5055 
5056   // No special expansion.
5057   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5058 }
5059 
5060 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5061 /// limited-precision mode.
5062 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5063                           const TargetLowering &TLI) {
5064   if (Op.getValueType() == MVT::f32 &&
5065       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5066     return getLimitedPrecisionExp2(Op, dl, DAG);
5067 
5068   // No special expansion.
5069   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5070 }
5071 
5072 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5073 /// limited-precision mode with x == 10.0f.
5074 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5075                          SelectionDAG &DAG, const TargetLowering &TLI) {
5076   bool IsExp10 = false;
5077   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5078       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5079     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5080       APFloat Ten(10.0f);
5081       IsExp10 = LHSC->isExactlyValue(Ten);
5082     }
5083   }
5084 
5085   // TODO: What fast-math-flags should be set on the FMUL node?
5086   if (IsExp10) {
5087     // Put the exponent in the right bit position for later addition to the
5088     // final result:
5089     //
5090     //   #define LOG2OF10 3.3219281f
5091     //   t0 = Op * LOG2OF10;
5092     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5093                              getF32Constant(DAG, 0x40549a78, dl));
5094     return getLimitedPrecisionExp2(t0, dl, DAG);
5095   }
5096 
5097   // No special expansion.
5098   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5099 }
5100 
5101 /// ExpandPowI - Expand a llvm.powi intrinsic.
5102 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5103                           SelectionDAG &DAG) {
5104   // If RHS is a constant, we can expand this out to a multiplication tree,
5105   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5106   // optimizing for size, we only want to do this if the expansion would produce
5107   // a small number of multiplies, otherwise we do the full expansion.
5108   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5109     // Get the exponent as a positive value.
5110     unsigned Val = RHSC->getSExtValue();
5111     if ((int)Val < 0) Val = -Val;
5112 
5113     // powi(x, 0) -> 1.0
5114     if (Val == 0)
5115       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5116 
5117     const Function &F = DAG.getMachineFunction().getFunction();
5118     if (!F.optForSize() ||
5119         // If optimizing for size, don't insert too many multiplies.
5120         // This inserts up to 5 multiplies.
5121         countPopulation(Val) + Log2_32(Val) < 7) {
5122       // We use the simple binary decomposition method to generate the multiply
5123       // sequence.  There are more optimal ways to do this (for example,
5124       // powi(x,15) generates one more multiply than it should), but this has
5125       // the benefit of being both really simple and much better than a libcall.
5126       SDValue Res;  // Logically starts equal to 1.0
5127       SDValue CurSquare = LHS;
5128       // TODO: Intrinsics should have fast-math-flags that propagate to these
5129       // nodes.
5130       while (Val) {
5131         if (Val & 1) {
5132           if (Res.getNode())
5133             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5134           else
5135             Res = CurSquare;  // 1.0*CurSquare.
5136         }
5137 
5138         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5139                                 CurSquare, CurSquare);
5140         Val >>= 1;
5141       }
5142 
5143       // If the original was negative, invert the result, producing 1/(x*x*x).
5144       if (RHSC->getSExtValue() < 0)
5145         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5146                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5147       return Res;
5148     }
5149   }
5150 
5151   // Otherwise, expand to a libcall.
5152   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5153 }
5154 
5155 // getUnderlyingArgReg - Find underlying register used for a truncated or
5156 // bitcasted argument.
5157 static unsigned getUnderlyingArgReg(const SDValue &N) {
5158   switch (N.getOpcode()) {
5159   case ISD::CopyFromReg:
5160     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
5161   case ISD::BITCAST:
5162   case ISD::AssertZext:
5163   case ISD::AssertSext:
5164   case ISD::TRUNCATE:
5165     return getUnderlyingArgReg(N.getOperand(0));
5166   default:
5167     return 0;
5168   }
5169 }
5170 
5171 /// If the DbgValueInst is a dbg_value of a function argument, create the
5172 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5173 /// instruction selection, they will be inserted to the entry BB.
5174 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5175     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5176     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5177   const Argument *Arg = dyn_cast<Argument>(V);
5178   if (!Arg)
5179     return false;
5180 
5181   if (!IsDbgDeclare) {
5182     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5183     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5184     // the entry block.
5185     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5186     if (!IsInEntryBlock)
5187       return false;
5188 
5189     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5190     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5191     // variable that also is a param.
5192     //
5193     // Although, if we are at the top of the entry block already, we can still
5194     // emit using ArgDbgValue. This might catch some situations when the
5195     // dbg.value refers to an argument that isn't used in the entry block, so
5196     // any CopyToReg node would be optimized out and the only way to express
5197     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5198     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5199     // we should only emit as ArgDbgValue if the Variable is an argument to the
5200     // current function, and the dbg.value intrinsic is found in the entry
5201     // block.
5202     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5203         !DL->getInlinedAt();
5204     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5205     if (!IsInPrologue && !VariableIsFunctionInputArg)
5206       return false;
5207 
5208     // Here we assume that a function argument on IR level only can be used to
5209     // describe one input parameter on source level. If we for example have
5210     // source code like this
5211     //
5212     //    struct A { long x, y; };
5213     //    void foo(struct A a, long b) {
5214     //      ...
5215     //      b = a.x;
5216     //      ...
5217     //    }
5218     //
5219     // and IR like this
5220     //
5221     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5222     //  entry:
5223     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5224     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5225     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5226     //    ...
5227     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5228     //    ...
5229     //
5230     // then the last dbg.value is describing a parameter "b" using a value that
5231     // is an argument. But since we already has used %a1 to describe a parameter
5232     // we should not handle that last dbg.value here (that would result in an
5233     // incorrect hoisting of the DBG_VALUE to the function entry).
5234     // Notice that we allow one dbg.value per IR level argument, to accomodate
5235     // for the situation with fragments above.
5236     if (VariableIsFunctionInputArg) {
5237       unsigned ArgNo = Arg->getArgNo();
5238       if (ArgNo >= FuncInfo.DescribedArgs.size())
5239         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5240       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5241         return false;
5242       FuncInfo.DescribedArgs.set(ArgNo);
5243     }
5244   }
5245 
5246   MachineFunction &MF = DAG.getMachineFunction();
5247   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5248 
5249   bool IsIndirect = false;
5250   Optional<MachineOperand> Op;
5251   // Some arguments' frame index is recorded during argument lowering.
5252   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5253   if (FI != std::numeric_limits<int>::max())
5254     Op = MachineOperand::CreateFI(FI);
5255 
5256   if (!Op && N.getNode()) {
5257     unsigned Reg = getUnderlyingArgReg(N);
5258     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
5259       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5260       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
5261       if (PR)
5262         Reg = PR;
5263     }
5264     if (Reg) {
5265       Op = MachineOperand::CreateReg(Reg, false);
5266       IsIndirect = IsDbgDeclare;
5267     }
5268   }
5269 
5270   if (!Op && N.getNode())
5271     // Check if frame index is available.
5272     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
5273       if (FrameIndexSDNode *FINode =
5274           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5275         Op = MachineOperand::CreateFI(FINode->getIndex());
5276 
5277   if (!Op) {
5278     // Check if ValueMap has reg number.
5279     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
5280     if (VMI != FuncInfo.ValueMap.end()) {
5281       const auto &TLI = DAG.getTargetLoweringInfo();
5282       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5283                        V->getType(), getABIRegCopyCC(V));
5284       if (RFV.occupiesMultipleRegs()) {
5285         unsigned Offset = 0;
5286         for (auto RegAndSize : RFV.getRegsAndSizes()) {
5287           Op = MachineOperand::CreateReg(RegAndSize.first, false);
5288           auto FragmentExpr = DIExpression::createFragmentExpression(
5289               Expr, Offset, RegAndSize.second);
5290           if (!FragmentExpr)
5291             continue;
5292           FuncInfo.ArgDbgValues.push_back(
5293               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5294                       Op->getReg(), Variable, *FragmentExpr));
5295           Offset += RegAndSize.second;
5296         }
5297         return true;
5298       }
5299       Op = MachineOperand::CreateReg(VMI->second, false);
5300       IsIndirect = IsDbgDeclare;
5301     }
5302   }
5303 
5304   if (!Op)
5305     return false;
5306 
5307   assert(Variable->isValidLocationForIntrinsic(DL) &&
5308          "Expected inlined-at fields to agree");
5309   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5310   FuncInfo.ArgDbgValues.push_back(
5311       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5312               *Op, Variable, Expr));
5313 
5314   return true;
5315 }
5316 
5317 /// Return the appropriate SDDbgValue based on N.
5318 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5319                                              DILocalVariable *Variable,
5320                                              DIExpression *Expr,
5321                                              const DebugLoc &dl,
5322                                              unsigned DbgSDNodeOrder) {
5323   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5324     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5325     // stack slot locations.
5326     //
5327     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5328     // debug values here after optimization:
5329     //
5330     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5331     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5332     //
5333     // Both describe the direct values of their associated variables.
5334     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5335                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5336   }
5337   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5338                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5339 }
5340 
5341 // VisualStudio defines setjmp as _setjmp
5342 #if defined(_MSC_VER) && defined(setjmp) && \
5343                          !defined(setjmp_undefined_for_msvc)
5344 #  pragma push_macro("setjmp")
5345 #  undef setjmp
5346 #  define setjmp_undefined_for_msvc
5347 #endif
5348 
5349 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5350   switch (Intrinsic) {
5351   case Intrinsic::smul_fix:
5352     return ISD::SMULFIX;
5353   case Intrinsic::umul_fix:
5354     return ISD::UMULFIX;
5355   default:
5356     llvm_unreachable("Unhandled fixed point intrinsic");
5357   }
5358 }
5359 
5360 /// Lower the call to the specified intrinsic function. If we want to emit this
5361 /// as a call to a named external function, return the name. Otherwise, lower it
5362 /// and return null.
5363 const char *
5364 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
5365   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5366   SDLoc sdl = getCurSDLoc();
5367   DebugLoc dl = getCurDebugLoc();
5368   SDValue Res;
5369 
5370   switch (Intrinsic) {
5371   default:
5372     // By default, turn this into a target intrinsic node.
5373     visitTargetIntrinsic(I, Intrinsic);
5374     return nullptr;
5375   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5376   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5377   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5378   case Intrinsic::returnaddress:
5379     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5380                              TLI.getPointerTy(DAG.getDataLayout()),
5381                              getValue(I.getArgOperand(0))));
5382     return nullptr;
5383   case Intrinsic::addressofreturnaddress:
5384     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5385                              TLI.getPointerTy(DAG.getDataLayout())));
5386     return nullptr;
5387   case Intrinsic::sponentry:
5388     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5389                              TLI.getPointerTy(DAG.getDataLayout())));
5390     return nullptr;
5391   case Intrinsic::frameaddress:
5392     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5393                              TLI.getPointerTy(DAG.getDataLayout()),
5394                              getValue(I.getArgOperand(0))));
5395     return nullptr;
5396   case Intrinsic::read_register: {
5397     Value *Reg = I.getArgOperand(0);
5398     SDValue Chain = getRoot();
5399     SDValue RegName =
5400         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5401     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5402     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5403       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5404     setValue(&I, Res);
5405     DAG.setRoot(Res.getValue(1));
5406     return nullptr;
5407   }
5408   case Intrinsic::write_register: {
5409     Value *Reg = I.getArgOperand(0);
5410     Value *RegValue = I.getArgOperand(1);
5411     SDValue Chain = getRoot();
5412     SDValue RegName =
5413         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5414     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5415                             RegName, getValue(RegValue)));
5416     return nullptr;
5417   }
5418   case Intrinsic::setjmp:
5419     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5420   case Intrinsic::longjmp:
5421     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5422   case Intrinsic::memcpy: {
5423     const auto &MCI = cast<MemCpyInst>(I);
5424     SDValue Op1 = getValue(I.getArgOperand(0));
5425     SDValue Op2 = getValue(I.getArgOperand(1));
5426     SDValue Op3 = getValue(I.getArgOperand(2));
5427     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5428     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5429     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5430     unsigned Align = MinAlign(DstAlign, SrcAlign);
5431     bool isVol = MCI.isVolatile();
5432     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5433     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5434     // node.
5435     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5436                                false, isTC,
5437                                MachinePointerInfo(I.getArgOperand(0)),
5438                                MachinePointerInfo(I.getArgOperand(1)));
5439     updateDAGForMaybeTailCall(MC);
5440     return nullptr;
5441   }
5442   case Intrinsic::memset: {
5443     const auto &MSI = cast<MemSetInst>(I);
5444     SDValue Op1 = getValue(I.getArgOperand(0));
5445     SDValue Op2 = getValue(I.getArgOperand(1));
5446     SDValue Op3 = getValue(I.getArgOperand(2));
5447     // @llvm.memset defines 0 and 1 to both mean no alignment.
5448     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5449     bool isVol = MSI.isVolatile();
5450     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5451     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5452                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5453     updateDAGForMaybeTailCall(MS);
5454     return nullptr;
5455   }
5456   case Intrinsic::memmove: {
5457     const auto &MMI = cast<MemMoveInst>(I);
5458     SDValue Op1 = getValue(I.getArgOperand(0));
5459     SDValue Op2 = getValue(I.getArgOperand(1));
5460     SDValue Op3 = getValue(I.getArgOperand(2));
5461     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5462     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5463     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5464     unsigned Align = MinAlign(DstAlign, SrcAlign);
5465     bool isVol = MMI.isVolatile();
5466     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5467     // FIXME: Support passing different dest/src alignments to the memmove DAG
5468     // node.
5469     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5470                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5471                                 MachinePointerInfo(I.getArgOperand(1)));
5472     updateDAGForMaybeTailCall(MM);
5473     return nullptr;
5474   }
5475   case Intrinsic::memcpy_element_unordered_atomic: {
5476     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5477     SDValue Dst = getValue(MI.getRawDest());
5478     SDValue Src = getValue(MI.getRawSource());
5479     SDValue Length = getValue(MI.getLength());
5480 
5481     unsigned DstAlign = MI.getDestAlignment();
5482     unsigned SrcAlign = MI.getSourceAlignment();
5483     Type *LengthTy = MI.getLength()->getType();
5484     unsigned ElemSz = MI.getElementSizeInBytes();
5485     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5486     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5487                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5488                                      MachinePointerInfo(MI.getRawDest()),
5489                                      MachinePointerInfo(MI.getRawSource()));
5490     updateDAGForMaybeTailCall(MC);
5491     return nullptr;
5492   }
5493   case Intrinsic::memmove_element_unordered_atomic: {
5494     auto &MI = cast<AtomicMemMoveInst>(I);
5495     SDValue Dst = getValue(MI.getRawDest());
5496     SDValue Src = getValue(MI.getRawSource());
5497     SDValue Length = getValue(MI.getLength());
5498 
5499     unsigned DstAlign = MI.getDestAlignment();
5500     unsigned SrcAlign = MI.getSourceAlignment();
5501     Type *LengthTy = MI.getLength()->getType();
5502     unsigned ElemSz = MI.getElementSizeInBytes();
5503     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5504     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5505                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5506                                       MachinePointerInfo(MI.getRawDest()),
5507                                       MachinePointerInfo(MI.getRawSource()));
5508     updateDAGForMaybeTailCall(MC);
5509     return nullptr;
5510   }
5511   case Intrinsic::memset_element_unordered_atomic: {
5512     auto &MI = cast<AtomicMemSetInst>(I);
5513     SDValue Dst = getValue(MI.getRawDest());
5514     SDValue Val = getValue(MI.getValue());
5515     SDValue Length = getValue(MI.getLength());
5516 
5517     unsigned DstAlign = MI.getDestAlignment();
5518     Type *LengthTy = MI.getLength()->getType();
5519     unsigned ElemSz = MI.getElementSizeInBytes();
5520     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5521     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5522                                      LengthTy, ElemSz, isTC,
5523                                      MachinePointerInfo(MI.getRawDest()));
5524     updateDAGForMaybeTailCall(MC);
5525     return nullptr;
5526   }
5527   case Intrinsic::dbg_addr:
5528   case Intrinsic::dbg_declare: {
5529     const auto &DI = cast<DbgVariableIntrinsic>(I);
5530     DILocalVariable *Variable = DI.getVariable();
5531     DIExpression *Expression = DI.getExpression();
5532     dropDanglingDebugInfo(Variable, Expression);
5533     assert(Variable && "Missing variable");
5534 
5535     // Check if address has undef value.
5536     const Value *Address = DI.getVariableLocation();
5537     if (!Address || isa<UndefValue>(Address) ||
5538         (Address->use_empty() && !isa<Argument>(Address))) {
5539       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5540       return nullptr;
5541     }
5542 
5543     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5544 
5545     // Check if this variable can be described by a frame index, typically
5546     // either as a static alloca or a byval parameter.
5547     int FI = std::numeric_limits<int>::max();
5548     if (const auto *AI =
5549             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5550       if (AI->isStaticAlloca()) {
5551         auto I = FuncInfo.StaticAllocaMap.find(AI);
5552         if (I != FuncInfo.StaticAllocaMap.end())
5553           FI = I->second;
5554       }
5555     } else if (const auto *Arg = dyn_cast<Argument>(
5556                    Address->stripInBoundsConstantOffsets())) {
5557       FI = FuncInfo.getArgumentFrameIndex(Arg);
5558     }
5559 
5560     // llvm.dbg.addr is control dependent and always generates indirect
5561     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5562     // the MachineFunction variable table.
5563     if (FI != std::numeric_limits<int>::max()) {
5564       if (Intrinsic == Intrinsic::dbg_addr) {
5565         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5566             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5567         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5568       }
5569       return nullptr;
5570     }
5571 
5572     SDValue &N = NodeMap[Address];
5573     if (!N.getNode() && isa<Argument>(Address))
5574       // Check unused arguments map.
5575       N = UnusedArgNodeMap[Address];
5576     SDDbgValue *SDV;
5577     if (N.getNode()) {
5578       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5579         Address = BCI->getOperand(0);
5580       // Parameters are handled specially.
5581       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5582       if (isParameter && FINode) {
5583         // Byval parameter. We have a frame index at this point.
5584         SDV =
5585             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5586                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5587       } else if (isa<Argument>(Address)) {
5588         // Address is an argument, so try to emit its dbg value using
5589         // virtual register info from the FuncInfo.ValueMap.
5590         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5591         return nullptr;
5592       } else {
5593         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5594                               true, dl, SDNodeOrder);
5595       }
5596       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5597     } else {
5598       // If Address is an argument then try to emit its dbg value using
5599       // virtual register info from the FuncInfo.ValueMap.
5600       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5601                                     N)) {
5602         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5603       }
5604     }
5605     return nullptr;
5606   }
5607   case Intrinsic::dbg_label: {
5608     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5609     DILabel *Label = DI.getLabel();
5610     assert(Label && "Missing label");
5611 
5612     SDDbgLabel *SDV;
5613     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5614     DAG.AddDbgLabel(SDV);
5615     return nullptr;
5616   }
5617   case Intrinsic::dbg_value: {
5618     const DbgValueInst &DI = cast<DbgValueInst>(I);
5619     assert(DI.getVariable() && "Missing variable");
5620 
5621     DILocalVariable *Variable = DI.getVariable();
5622     DIExpression *Expression = DI.getExpression();
5623     dropDanglingDebugInfo(Variable, Expression);
5624     const Value *V = DI.getValue();
5625     if (!V)
5626       return nullptr;
5627 
5628     if (handleDebugValue(V, Variable, Expression, DI.getDebugLoc(), dl,
5629         SDNodeOrder))
5630       return nullptr;
5631 
5632     // TODO: Dangling debug info will eventually either be resolved or produce
5633     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5634     // between the original dbg.value location and its resolved DBG_VALUE, which
5635     // we should ideally fill with an extra Undef DBG_VALUE.
5636 
5637     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5638     return nullptr;
5639   }
5640 
5641   case Intrinsic::eh_typeid_for: {
5642     // Find the type id for the given typeinfo.
5643     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5644     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5645     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5646     setValue(&I, Res);
5647     return nullptr;
5648   }
5649 
5650   case Intrinsic::eh_return_i32:
5651   case Intrinsic::eh_return_i64:
5652     DAG.getMachineFunction().setCallsEHReturn(true);
5653     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5654                             MVT::Other,
5655                             getControlRoot(),
5656                             getValue(I.getArgOperand(0)),
5657                             getValue(I.getArgOperand(1))));
5658     return nullptr;
5659   case Intrinsic::eh_unwind_init:
5660     DAG.getMachineFunction().setCallsUnwindInit(true);
5661     return nullptr;
5662   case Intrinsic::eh_dwarf_cfa:
5663     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5664                              TLI.getPointerTy(DAG.getDataLayout()),
5665                              getValue(I.getArgOperand(0))));
5666     return nullptr;
5667   case Intrinsic::eh_sjlj_callsite: {
5668     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5669     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5670     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5671     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5672 
5673     MMI.setCurrentCallSite(CI->getZExtValue());
5674     return nullptr;
5675   }
5676   case Intrinsic::eh_sjlj_functioncontext: {
5677     // Get and store the index of the function context.
5678     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5679     AllocaInst *FnCtx =
5680       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5681     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5682     MFI.setFunctionContextIndex(FI);
5683     return nullptr;
5684   }
5685   case Intrinsic::eh_sjlj_setjmp: {
5686     SDValue Ops[2];
5687     Ops[0] = getRoot();
5688     Ops[1] = getValue(I.getArgOperand(0));
5689     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5690                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5691     setValue(&I, Op.getValue(0));
5692     DAG.setRoot(Op.getValue(1));
5693     return nullptr;
5694   }
5695   case Intrinsic::eh_sjlj_longjmp:
5696     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5697                             getRoot(), getValue(I.getArgOperand(0))));
5698     return nullptr;
5699   case Intrinsic::eh_sjlj_setup_dispatch:
5700     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5701                             getRoot()));
5702     return nullptr;
5703   case Intrinsic::masked_gather:
5704     visitMaskedGather(I);
5705     return nullptr;
5706   case Intrinsic::masked_load:
5707     visitMaskedLoad(I);
5708     return nullptr;
5709   case Intrinsic::masked_scatter:
5710     visitMaskedScatter(I);
5711     return nullptr;
5712   case Intrinsic::masked_store:
5713     visitMaskedStore(I);
5714     return nullptr;
5715   case Intrinsic::masked_expandload:
5716     visitMaskedLoad(I, true /* IsExpanding */);
5717     return nullptr;
5718   case Intrinsic::masked_compressstore:
5719     visitMaskedStore(I, true /* IsCompressing */);
5720     return nullptr;
5721   case Intrinsic::x86_mmx_pslli_w:
5722   case Intrinsic::x86_mmx_pslli_d:
5723   case Intrinsic::x86_mmx_pslli_q:
5724   case Intrinsic::x86_mmx_psrli_w:
5725   case Intrinsic::x86_mmx_psrli_d:
5726   case Intrinsic::x86_mmx_psrli_q:
5727   case Intrinsic::x86_mmx_psrai_w:
5728   case Intrinsic::x86_mmx_psrai_d: {
5729     SDValue ShAmt = getValue(I.getArgOperand(1));
5730     if (isa<ConstantSDNode>(ShAmt)) {
5731       visitTargetIntrinsic(I, Intrinsic);
5732       return nullptr;
5733     }
5734     unsigned NewIntrinsic = 0;
5735     EVT ShAmtVT = MVT::v2i32;
5736     switch (Intrinsic) {
5737     case Intrinsic::x86_mmx_pslli_w:
5738       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5739       break;
5740     case Intrinsic::x86_mmx_pslli_d:
5741       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5742       break;
5743     case Intrinsic::x86_mmx_pslli_q:
5744       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5745       break;
5746     case Intrinsic::x86_mmx_psrli_w:
5747       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5748       break;
5749     case Intrinsic::x86_mmx_psrli_d:
5750       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5751       break;
5752     case Intrinsic::x86_mmx_psrli_q:
5753       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5754       break;
5755     case Intrinsic::x86_mmx_psrai_w:
5756       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5757       break;
5758     case Intrinsic::x86_mmx_psrai_d:
5759       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5760       break;
5761     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5762     }
5763 
5764     // The vector shift intrinsics with scalars uses 32b shift amounts but
5765     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5766     // to be zero.
5767     // We must do this early because v2i32 is not a legal type.
5768     SDValue ShOps[2];
5769     ShOps[0] = ShAmt;
5770     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5771     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5772     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5773     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5774     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5775                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5776                        getValue(I.getArgOperand(0)), ShAmt);
5777     setValue(&I, Res);
5778     return nullptr;
5779   }
5780   case Intrinsic::powi:
5781     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5782                             getValue(I.getArgOperand(1)), DAG));
5783     return nullptr;
5784   case Intrinsic::log:
5785     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5786     return nullptr;
5787   case Intrinsic::log2:
5788     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5789     return nullptr;
5790   case Intrinsic::log10:
5791     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5792     return nullptr;
5793   case Intrinsic::exp:
5794     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5795     return nullptr;
5796   case Intrinsic::exp2:
5797     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5798     return nullptr;
5799   case Intrinsic::pow:
5800     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5801                            getValue(I.getArgOperand(1)), DAG, TLI));
5802     return nullptr;
5803   case Intrinsic::sqrt:
5804   case Intrinsic::fabs:
5805   case Intrinsic::sin:
5806   case Intrinsic::cos:
5807   case Intrinsic::floor:
5808   case Intrinsic::ceil:
5809   case Intrinsic::trunc:
5810   case Intrinsic::rint:
5811   case Intrinsic::nearbyint:
5812   case Intrinsic::round:
5813   case Intrinsic::canonicalize: {
5814     unsigned Opcode;
5815     switch (Intrinsic) {
5816     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5817     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5818     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5819     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5820     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5821     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5822     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5823     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5824     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5825     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5826     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5827     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5828     }
5829 
5830     setValue(&I, DAG.getNode(Opcode, sdl,
5831                              getValue(I.getArgOperand(0)).getValueType(),
5832                              getValue(I.getArgOperand(0))));
5833     return nullptr;
5834   }
5835   case Intrinsic::minnum: {
5836     auto VT = getValue(I.getArgOperand(0)).getValueType();
5837     unsigned Opc =
5838         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
5839             ? ISD::FMINIMUM
5840             : ISD::FMINNUM;
5841     setValue(&I, DAG.getNode(Opc, sdl, VT,
5842                              getValue(I.getArgOperand(0)),
5843                              getValue(I.getArgOperand(1))));
5844     return nullptr;
5845   }
5846   case Intrinsic::maxnum: {
5847     auto VT = getValue(I.getArgOperand(0)).getValueType();
5848     unsigned Opc =
5849         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
5850             ? ISD::FMAXIMUM
5851             : ISD::FMAXNUM;
5852     setValue(&I, DAG.getNode(Opc, sdl, VT,
5853                              getValue(I.getArgOperand(0)),
5854                              getValue(I.getArgOperand(1))));
5855     return nullptr;
5856   }
5857   case Intrinsic::minimum:
5858     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
5859                              getValue(I.getArgOperand(0)).getValueType(),
5860                              getValue(I.getArgOperand(0)),
5861                              getValue(I.getArgOperand(1))));
5862     return nullptr;
5863   case Intrinsic::maximum:
5864     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
5865                              getValue(I.getArgOperand(0)).getValueType(),
5866                              getValue(I.getArgOperand(0)),
5867                              getValue(I.getArgOperand(1))));
5868     return nullptr;
5869   case Intrinsic::copysign:
5870     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5871                              getValue(I.getArgOperand(0)).getValueType(),
5872                              getValue(I.getArgOperand(0)),
5873                              getValue(I.getArgOperand(1))));
5874     return nullptr;
5875   case Intrinsic::fma:
5876     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5877                              getValue(I.getArgOperand(0)).getValueType(),
5878                              getValue(I.getArgOperand(0)),
5879                              getValue(I.getArgOperand(1)),
5880                              getValue(I.getArgOperand(2))));
5881     return nullptr;
5882   case Intrinsic::experimental_constrained_fadd:
5883   case Intrinsic::experimental_constrained_fsub:
5884   case Intrinsic::experimental_constrained_fmul:
5885   case Intrinsic::experimental_constrained_fdiv:
5886   case Intrinsic::experimental_constrained_frem:
5887   case Intrinsic::experimental_constrained_fma:
5888   case Intrinsic::experimental_constrained_sqrt:
5889   case Intrinsic::experimental_constrained_pow:
5890   case Intrinsic::experimental_constrained_powi:
5891   case Intrinsic::experimental_constrained_sin:
5892   case Intrinsic::experimental_constrained_cos:
5893   case Intrinsic::experimental_constrained_exp:
5894   case Intrinsic::experimental_constrained_exp2:
5895   case Intrinsic::experimental_constrained_log:
5896   case Intrinsic::experimental_constrained_log10:
5897   case Intrinsic::experimental_constrained_log2:
5898   case Intrinsic::experimental_constrained_rint:
5899   case Intrinsic::experimental_constrained_nearbyint:
5900   case Intrinsic::experimental_constrained_maxnum:
5901   case Intrinsic::experimental_constrained_minnum:
5902   case Intrinsic::experimental_constrained_ceil:
5903   case Intrinsic::experimental_constrained_floor:
5904   case Intrinsic::experimental_constrained_round:
5905   case Intrinsic::experimental_constrained_trunc:
5906     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5907     return nullptr;
5908   case Intrinsic::fmuladd: {
5909     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5910     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5911         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5912       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5913                                getValue(I.getArgOperand(0)).getValueType(),
5914                                getValue(I.getArgOperand(0)),
5915                                getValue(I.getArgOperand(1)),
5916                                getValue(I.getArgOperand(2))));
5917     } else {
5918       // TODO: Intrinsic calls should have fast-math-flags.
5919       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5920                                 getValue(I.getArgOperand(0)).getValueType(),
5921                                 getValue(I.getArgOperand(0)),
5922                                 getValue(I.getArgOperand(1)));
5923       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5924                                 getValue(I.getArgOperand(0)).getValueType(),
5925                                 Mul,
5926                                 getValue(I.getArgOperand(2)));
5927       setValue(&I, Add);
5928     }
5929     return nullptr;
5930   }
5931   case Intrinsic::convert_to_fp16:
5932     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5933                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5934                                          getValue(I.getArgOperand(0)),
5935                                          DAG.getTargetConstant(0, sdl,
5936                                                                MVT::i32))));
5937     return nullptr;
5938   case Intrinsic::convert_from_fp16:
5939     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5940                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5941                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5942                                          getValue(I.getArgOperand(0)))));
5943     return nullptr;
5944   case Intrinsic::pcmarker: {
5945     SDValue Tmp = getValue(I.getArgOperand(0));
5946     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5947     return nullptr;
5948   }
5949   case Intrinsic::readcyclecounter: {
5950     SDValue Op = getRoot();
5951     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5952                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5953     setValue(&I, Res);
5954     DAG.setRoot(Res.getValue(1));
5955     return nullptr;
5956   }
5957   case Intrinsic::bitreverse:
5958     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5959                              getValue(I.getArgOperand(0)).getValueType(),
5960                              getValue(I.getArgOperand(0))));
5961     return nullptr;
5962   case Intrinsic::bswap:
5963     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5964                              getValue(I.getArgOperand(0)).getValueType(),
5965                              getValue(I.getArgOperand(0))));
5966     return nullptr;
5967   case Intrinsic::cttz: {
5968     SDValue Arg = getValue(I.getArgOperand(0));
5969     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5970     EVT Ty = Arg.getValueType();
5971     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5972                              sdl, Ty, Arg));
5973     return nullptr;
5974   }
5975   case Intrinsic::ctlz: {
5976     SDValue Arg = getValue(I.getArgOperand(0));
5977     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5978     EVT Ty = Arg.getValueType();
5979     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5980                              sdl, Ty, Arg));
5981     return nullptr;
5982   }
5983   case Intrinsic::ctpop: {
5984     SDValue Arg = getValue(I.getArgOperand(0));
5985     EVT Ty = Arg.getValueType();
5986     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5987     return nullptr;
5988   }
5989   case Intrinsic::fshl:
5990   case Intrinsic::fshr: {
5991     bool IsFSHL = Intrinsic == Intrinsic::fshl;
5992     SDValue X = getValue(I.getArgOperand(0));
5993     SDValue Y = getValue(I.getArgOperand(1));
5994     SDValue Z = getValue(I.getArgOperand(2));
5995     EVT VT = X.getValueType();
5996     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
5997     SDValue Zero = DAG.getConstant(0, sdl, VT);
5998     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
5999 
6000     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6001     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6002       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6003       return nullptr;
6004     }
6005 
6006     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6007     // avoid the select that is necessary in the general case to filter out
6008     // the 0-shift possibility that leads to UB.
6009     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6010       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6011       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6012         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6013         return nullptr;
6014       }
6015 
6016       // Some targets only rotate one way. Try the opposite direction.
6017       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6018       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6019         // Negate the shift amount because it is safe to ignore the high bits.
6020         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6021         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6022         return nullptr;
6023       }
6024 
6025       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6026       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6027       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6028       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6029       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6030       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6031       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6032       return nullptr;
6033     }
6034 
6035     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6036     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6037     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6038     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6039     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6040     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6041 
6042     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6043     // and that is undefined. We must compare and select to avoid UB.
6044     EVT CCVT = MVT::i1;
6045     if (VT.isVector())
6046       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6047 
6048     // For fshl, 0-shift returns the 1st arg (X).
6049     // For fshr, 0-shift returns the 2nd arg (Y).
6050     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6051     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6052     return nullptr;
6053   }
6054   case Intrinsic::sadd_sat: {
6055     SDValue Op1 = getValue(I.getArgOperand(0));
6056     SDValue Op2 = getValue(I.getArgOperand(1));
6057     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6058     return nullptr;
6059   }
6060   case Intrinsic::uadd_sat: {
6061     SDValue Op1 = getValue(I.getArgOperand(0));
6062     SDValue Op2 = getValue(I.getArgOperand(1));
6063     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6064     return nullptr;
6065   }
6066   case Intrinsic::ssub_sat: {
6067     SDValue Op1 = getValue(I.getArgOperand(0));
6068     SDValue Op2 = getValue(I.getArgOperand(1));
6069     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6070     return nullptr;
6071   }
6072   case Intrinsic::usub_sat: {
6073     SDValue Op1 = getValue(I.getArgOperand(0));
6074     SDValue Op2 = getValue(I.getArgOperand(1));
6075     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6076     return nullptr;
6077   }
6078   case Intrinsic::smul_fix:
6079   case Intrinsic::umul_fix: {
6080     SDValue Op1 = getValue(I.getArgOperand(0));
6081     SDValue Op2 = getValue(I.getArgOperand(1));
6082     SDValue Op3 = getValue(I.getArgOperand(2));
6083     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6084                              Op1.getValueType(), Op1, Op2, Op3));
6085     return nullptr;
6086   }
6087   case Intrinsic::stacksave: {
6088     SDValue Op = getRoot();
6089     Res = DAG.getNode(
6090         ISD::STACKSAVE, sdl,
6091         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6092     setValue(&I, Res);
6093     DAG.setRoot(Res.getValue(1));
6094     return nullptr;
6095   }
6096   case Intrinsic::stackrestore:
6097     Res = getValue(I.getArgOperand(0));
6098     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6099     return nullptr;
6100   case Intrinsic::get_dynamic_area_offset: {
6101     SDValue Op = getRoot();
6102     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6103     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6104     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6105     // target.
6106     if (PtrTy != ResTy)
6107       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6108                          " intrinsic!");
6109     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6110                       Op);
6111     DAG.setRoot(Op);
6112     setValue(&I, Res);
6113     return nullptr;
6114   }
6115   case Intrinsic::stackguard: {
6116     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6117     MachineFunction &MF = DAG.getMachineFunction();
6118     const Module &M = *MF.getFunction().getParent();
6119     SDValue Chain = getRoot();
6120     if (TLI.useLoadStackGuardNode()) {
6121       Res = getLoadStackGuard(DAG, sdl, Chain);
6122     } else {
6123       const Value *Global = TLI.getSDagStackGuard(M);
6124       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6125       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6126                         MachinePointerInfo(Global, 0), Align,
6127                         MachineMemOperand::MOVolatile);
6128     }
6129     if (TLI.useStackGuardXorFP())
6130       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6131     DAG.setRoot(Chain);
6132     setValue(&I, Res);
6133     return nullptr;
6134   }
6135   case Intrinsic::stackprotector: {
6136     // Emit code into the DAG to store the stack guard onto the stack.
6137     MachineFunction &MF = DAG.getMachineFunction();
6138     MachineFrameInfo &MFI = MF.getFrameInfo();
6139     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6140     SDValue Src, Chain = getRoot();
6141 
6142     if (TLI.useLoadStackGuardNode())
6143       Src = getLoadStackGuard(DAG, sdl, Chain);
6144     else
6145       Src = getValue(I.getArgOperand(0));   // The guard's value.
6146 
6147     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6148 
6149     int FI = FuncInfo.StaticAllocaMap[Slot];
6150     MFI.setStackProtectorIndex(FI);
6151 
6152     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6153 
6154     // Store the stack protector onto the stack.
6155     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6156                                                  DAG.getMachineFunction(), FI),
6157                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6158     setValue(&I, Res);
6159     DAG.setRoot(Res);
6160     return nullptr;
6161   }
6162   case Intrinsic::objectsize: {
6163     // If we don't know by now, we're never going to know.
6164     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
6165 
6166     assert(CI && "Non-constant type in __builtin_object_size?");
6167 
6168     SDValue Arg = getValue(I.getCalledValue());
6169     EVT Ty = Arg.getValueType();
6170 
6171     if (CI->isZero())
6172       Res = DAG.getConstant(-1ULL, sdl, Ty);
6173     else
6174       Res = DAG.getConstant(0, sdl, Ty);
6175 
6176     setValue(&I, Res);
6177     return nullptr;
6178   }
6179 
6180   case Intrinsic::is_constant:
6181     // If this wasn't constant-folded away by now, then it's not a
6182     // constant.
6183     setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
6184     return nullptr;
6185 
6186   case Intrinsic::annotation:
6187   case Intrinsic::ptr_annotation:
6188   case Intrinsic::launder_invariant_group:
6189   case Intrinsic::strip_invariant_group:
6190     // Drop the intrinsic, but forward the value
6191     setValue(&I, getValue(I.getOperand(0)));
6192     return nullptr;
6193   case Intrinsic::assume:
6194   case Intrinsic::var_annotation:
6195   case Intrinsic::sideeffect:
6196     // Discard annotate attributes, assumptions, and artificial side-effects.
6197     return nullptr;
6198 
6199   case Intrinsic::codeview_annotation: {
6200     // Emit a label associated with this metadata.
6201     MachineFunction &MF = DAG.getMachineFunction();
6202     MCSymbol *Label =
6203         MF.getMMI().getContext().createTempSymbol("annotation", true);
6204     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6205     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6206     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6207     DAG.setRoot(Res);
6208     return nullptr;
6209   }
6210 
6211   case Intrinsic::init_trampoline: {
6212     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6213 
6214     SDValue Ops[6];
6215     Ops[0] = getRoot();
6216     Ops[1] = getValue(I.getArgOperand(0));
6217     Ops[2] = getValue(I.getArgOperand(1));
6218     Ops[3] = getValue(I.getArgOperand(2));
6219     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6220     Ops[5] = DAG.getSrcValue(F);
6221 
6222     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6223 
6224     DAG.setRoot(Res);
6225     return nullptr;
6226   }
6227   case Intrinsic::adjust_trampoline:
6228     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6229                              TLI.getPointerTy(DAG.getDataLayout()),
6230                              getValue(I.getArgOperand(0))));
6231     return nullptr;
6232   case Intrinsic::gcroot: {
6233     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6234            "only valid in functions with gc specified, enforced by Verifier");
6235     assert(GFI && "implied by previous");
6236     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6237     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6238 
6239     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6240     GFI->addStackRoot(FI->getIndex(), TypeMap);
6241     return nullptr;
6242   }
6243   case Intrinsic::gcread:
6244   case Intrinsic::gcwrite:
6245     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6246   case Intrinsic::flt_rounds:
6247     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6248     return nullptr;
6249 
6250   case Intrinsic::expect:
6251     // Just replace __builtin_expect(exp, c) with EXP.
6252     setValue(&I, getValue(I.getArgOperand(0)));
6253     return nullptr;
6254 
6255   case Intrinsic::debugtrap:
6256   case Intrinsic::trap: {
6257     StringRef TrapFuncName =
6258         I.getAttributes()
6259             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6260             .getValueAsString();
6261     if (TrapFuncName.empty()) {
6262       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6263         ISD::TRAP : ISD::DEBUGTRAP;
6264       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6265       return nullptr;
6266     }
6267     TargetLowering::ArgListTy Args;
6268 
6269     TargetLowering::CallLoweringInfo CLI(DAG);
6270     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6271         CallingConv::C, I.getType(),
6272         DAG.getExternalSymbol(TrapFuncName.data(),
6273                               TLI.getPointerTy(DAG.getDataLayout())),
6274         std::move(Args));
6275 
6276     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6277     DAG.setRoot(Result.second);
6278     return nullptr;
6279   }
6280 
6281   case Intrinsic::uadd_with_overflow:
6282   case Intrinsic::sadd_with_overflow:
6283   case Intrinsic::usub_with_overflow:
6284   case Intrinsic::ssub_with_overflow:
6285   case Intrinsic::umul_with_overflow:
6286   case Intrinsic::smul_with_overflow: {
6287     ISD::NodeType Op;
6288     switch (Intrinsic) {
6289     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6290     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6291     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6292     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6293     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6294     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6295     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6296     }
6297     SDValue Op1 = getValue(I.getArgOperand(0));
6298     SDValue Op2 = getValue(I.getArgOperand(1));
6299 
6300     EVT ResultVT = Op1.getValueType();
6301     EVT OverflowVT = MVT::i1;
6302     if (ResultVT.isVector())
6303       OverflowVT = EVT::getVectorVT(
6304           *Context, OverflowVT, ResultVT.getVectorNumElements());
6305 
6306     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6307     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6308     return nullptr;
6309   }
6310   case Intrinsic::prefetch: {
6311     SDValue Ops[5];
6312     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6313     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6314     Ops[0] = DAG.getRoot();
6315     Ops[1] = getValue(I.getArgOperand(0));
6316     Ops[2] = getValue(I.getArgOperand(1));
6317     Ops[3] = getValue(I.getArgOperand(2));
6318     Ops[4] = getValue(I.getArgOperand(3));
6319     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6320                                              DAG.getVTList(MVT::Other), Ops,
6321                                              EVT::getIntegerVT(*Context, 8),
6322                                              MachinePointerInfo(I.getArgOperand(0)),
6323                                              0, /* align */
6324                                              Flags);
6325 
6326     // Chain the prefetch in parallell with any pending loads, to stay out of
6327     // the way of later optimizations.
6328     PendingLoads.push_back(Result);
6329     Result = getRoot();
6330     DAG.setRoot(Result);
6331     return nullptr;
6332   }
6333   case Intrinsic::lifetime_start:
6334   case Intrinsic::lifetime_end: {
6335     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6336     // Stack coloring is not enabled in O0, discard region information.
6337     if (TM.getOptLevel() == CodeGenOpt::None)
6338       return nullptr;
6339 
6340     SmallVector<Value *, 4> Allocas;
6341     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
6342 
6343     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
6344            E = Allocas.end(); Object != E; ++Object) {
6345       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6346 
6347       // Could not find an Alloca.
6348       if (!LifetimeObject)
6349         continue;
6350 
6351       // First check that the Alloca is static, otherwise it won't have a
6352       // valid frame index.
6353       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6354       if (SI == FuncInfo.StaticAllocaMap.end())
6355         return nullptr;
6356 
6357       int FI = SI->second;
6358 
6359       SDValue Ops[2];
6360       Ops[0] = getRoot();
6361       Ops[1] =
6362           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
6363       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
6364 
6365       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
6366       DAG.setRoot(Res);
6367     }
6368     return nullptr;
6369   }
6370   case Intrinsic::invariant_start:
6371     // Discard region information.
6372     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6373     return nullptr;
6374   case Intrinsic::invariant_end:
6375     // Discard region information.
6376     return nullptr;
6377   case Intrinsic::clear_cache:
6378     return TLI.getClearCacheBuiltinName();
6379   case Intrinsic::donothing:
6380     // ignore
6381     return nullptr;
6382   case Intrinsic::experimental_stackmap:
6383     visitStackmap(I);
6384     return nullptr;
6385   case Intrinsic::experimental_patchpoint_void:
6386   case Intrinsic::experimental_patchpoint_i64:
6387     visitPatchpoint(&I);
6388     return nullptr;
6389   case Intrinsic::experimental_gc_statepoint:
6390     LowerStatepoint(ImmutableStatepoint(&I));
6391     return nullptr;
6392   case Intrinsic::experimental_gc_result:
6393     visitGCResult(cast<GCResultInst>(I));
6394     return nullptr;
6395   case Intrinsic::experimental_gc_relocate:
6396     visitGCRelocate(cast<GCRelocateInst>(I));
6397     return nullptr;
6398   case Intrinsic::instrprof_increment:
6399     llvm_unreachable("instrprof failed to lower an increment");
6400   case Intrinsic::instrprof_value_profile:
6401     llvm_unreachable("instrprof failed to lower a value profiling call");
6402   case Intrinsic::localescape: {
6403     MachineFunction &MF = DAG.getMachineFunction();
6404     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6405 
6406     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6407     // is the same on all targets.
6408     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6409       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6410       if (isa<ConstantPointerNull>(Arg))
6411         continue; // Skip null pointers. They represent a hole in index space.
6412       AllocaInst *Slot = cast<AllocaInst>(Arg);
6413       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6414              "can only escape static allocas");
6415       int FI = FuncInfo.StaticAllocaMap[Slot];
6416       MCSymbol *FrameAllocSym =
6417           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6418               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6419       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6420               TII->get(TargetOpcode::LOCAL_ESCAPE))
6421           .addSym(FrameAllocSym)
6422           .addFrameIndex(FI);
6423     }
6424 
6425     return nullptr;
6426   }
6427 
6428   case Intrinsic::localrecover: {
6429     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6430     MachineFunction &MF = DAG.getMachineFunction();
6431     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6432 
6433     // Get the symbol that defines the frame offset.
6434     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6435     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6436     unsigned IdxVal =
6437         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6438     MCSymbol *FrameAllocSym =
6439         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6440             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6441 
6442     // Create a MCSymbol for the label to avoid any target lowering
6443     // that would make this PC relative.
6444     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6445     SDValue OffsetVal =
6446         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6447 
6448     // Add the offset to the FP.
6449     Value *FP = I.getArgOperand(1);
6450     SDValue FPVal = getValue(FP);
6451     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6452     setValue(&I, Add);
6453 
6454     return nullptr;
6455   }
6456 
6457   case Intrinsic::eh_exceptionpointer:
6458   case Intrinsic::eh_exceptioncode: {
6459     // Get the exception pointer vreg, copy from it, and resize it to fit.
6460     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6461     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6462     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6463     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6464     SDValue N =
6465         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6466     if (Intrinsic == Intrinsic::eh_exceptioncode)
6467       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6468     setValue(&I, N);
6469     return nullptr;
6470   }
6471   case Intrinsic::xray_customevent: {
6472     // Here we want to make sure that the intrinsic behaves as if it has a
6473     // specific calling convention, and only for x86_64.
6474     // FIXME: Support other platforms later.
6475     const auto &Triple = DAG.getTarget().getTargetTriple();
6476     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6477       return nullptr;
6478 
6479     SDLoc DL = getCurSDLoc();
6480     SmallVector<SDValue, 8> Ops;
6481 
6482     // We want to say that we always want the arguments in registers.
6483     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6484     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6485     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6486     SDValue Chain = getRoot();
6487     Ops.push_back(LogEntryVal);
6488     Ops.push_back(StrSizeVal);
6489     Ops.push_back(Chain);
6490 
6491     // We need to enforce the calling convention for the callsite, so that
6492     // argument ordering is enforced correctly, and that register allocation can
6493     // see that some registers may be assumed clobbered and have to preserve
6494     // them across calls to the intrinsic.
6495     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6496                                            DL, NodeTys, Ops);
6497     SDValue patchableNode = SDValue(MN, 0);
6498     DAG.setRoot(patchableNode);
6499     setValue(&I, patchableNode);
6500     return nullptr;
6501   }
6502   case Intrinsic::xray_typedevent: {
6503     // Here we want to make sure that the intrinsic behaves as if it has a
6504     // specific calling convention, and only for x86_64.
6505     // FIXME: Support other platforms later.
6506     const auto &Triple = DAG.getTarget().getTargetTriple();
6507     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6508       return nullptr;
6509 
6510     SDLoc DL = getCurSDLoc();
6511     SmallVector<SDValue, 8> Ops;
6512 
6513     // We want to say that we always want the arguments in registers.
6514     // It's unclear to me how manipulating the selection DAG here forces callers
6515     // to provide arguments in registers instead of on the stack.
6516     SDValue LogTypeId = getValue(I.getArgOperand(0));
6517     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6518     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6519     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6520     SDValue Chain = getRoot();
6521     Ops.push_back(LogTypeId);
6522     Ops.push_back(LogEntryVal);
6523     Ops.push_back(StrSizeVal);
6524     Ops.push_back(Chain);
6525 
6526     // We need to enforce the calling convention for the callsite, so that
6527     // argument ordering is enforced correctly, and that register allocation can
6528     // see that some registers may be assumed clobbered and have to preserve
6529     // them across calls to the intrinsic.
6530     MachineSDNode *MN = DAG.getMachineNode(
6531         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6532     SDValue patchableNode = SDValue(MN, 0);
6533     DAG.setRoot(patchableNode);
6534     setValue(&I, patchableNode);
6535     return nullptr;
6536   }
6537   case Intrinsic::experimental_deoptimize:
6538     LowerDeoptimizeCall(&I);
6539     return nullptr;
6540 
6541   case Intrinsic::experimental_vector_reduce_fadd:
6542   case Intrinsic::experimental_vector_reduce_fmul:
6543   case Intrinsic::experimental_vector_reduce_add:
6544   case Intrinsic::experimental_vector_reduce_mul:
6545   case Intrinsic::experimental_vector_reduce_and:
6546   case Intrinsic::experimental_vector_reduce_or:
6547   case Intrinsic::experimental_vector_reduce_xor:
6548   case Intrinsic::experimental_vector_reduce_smax:
6549   case Intrinsic::experimental_vector_reduce_smin:
6550   case Intrinsic::experimental_vector_reduce_umax:
6551   case Intrinsic::experimental_vector_reduce_umin:
6552   case Intrinsic::experimental_vector_reduce_fmax:
6553   case Intrinsic::experimental_vector_reduce_fmin:
6554     visitVectorReduce(I, Intrinsic);
6555     return nullptr;
6556 
6557   case Intrinsic::icall_branch_funnel: {
6558     SmallVector<SDValue, 16> Ops;
6559     Ops.push_back(DAG.getRoot());
6560     Ops.push_back(getValue(I.getArgOperand(0)));
6561 
6562     int64_t Offset;
6563     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6564         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6565     if (!Base)
6566       report_fatal_error(
6567           "llvm.icall.branch.funnel operand must be a GlobalValue");
6568     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6569 
6570     struct BranchFunnelTarget {
6571       int64_t Offset;
6572       SDValue Target;
6573     };
6574     SmallVector<BranchFunnelTarget, 8> Targets;
6575 
6576     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6577       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6578           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6579       if (ElemBase != Base)
6580         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6581                            "to the same GlobalValue");
6582 
6583       SDValue Val = getValue(I.getArgOperand(Op + 1));
6584       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6585       if (!GA)
6586         report_fatal_error(
6587             "llvm.icall.branch.funnel operand must be a GlobalValue");
6588       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6589                                      GA->getGlobal(), getCurSDLoc(),
6590                                      Val.getValueType(), GA->getOffset())});
6591     }
6592     llvm::sort(Targets,
6593                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6594                  return T1.Offset < T2.Offset;
6595                });
6596 
6597     for (auto &T : Targets) {
6598       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6599       Ops.push_back(T.Target);
6600     }
6601 
6602     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6603                                  getCurSDLoc(), MVT::Other, Ops),
6604               0);
6605     DAG.setRoot(N);
6606     setValue(&I, N);
6607     HasTailCall = true;
6608     return nullptr;
6609   }
6610 
6611   case Intrinsic::wasm_landingpad_index:
6612     // Information this intrinsic contained has been transferred to
6613     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6614     // delete it now.
6615     return nullptr;
6616   }
6617 }
6618 
6619 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6620     const ConstrainedFPIntrinsic &FPI) {
6621   SDLoc sdl = getCurSDLoc();
6622   unsigned Opcode;
6623   switch (FPI.getIntrinsicID()) {
6624   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6625   case Intrinsic::experimental_constrained_fadd:
6626     Opcode = ISD::STRICT_FADD;
6627     break;
6628   case Intrinsic::experimental_constrained_fsub:
6629     Opcode = ISD::STRICT_FSUB;
6630     break;
6631   case Intrinsic::experimental_constrained_fmul:
6632     Opcode = ISD::STRICT_FMUL;
6633     break;
6634   case Intrinsic::experimental_constrained_fdiv:
6635     Opcode = ISD::STRICT_FDIV;
6636     break;
6637   case Intrinsic::experimental_constrained_frem:
6638     Opcode = ISD::STRICT_FREM;
6639     break;
6640   case Intrinsic::experimental_constrained_fma:
6641     Opcode = ISD::STRICT_FMA;
6642     break;
6643   case Intrinsic::experimental_constrained_sqrt:
6644     Opcode = ISD::STRICT_FSQRT;
6645     break;
6646   case Intrinsic::experimental_constrained_pow:
6647     Opcode = ISD::STRICT_FPOW;
6648     break;
6649   case Intrinsic::experimental_constrained_powi:
6650     Opcode = ISD::STRICT_FPOWI;
6651     break;
6652   case Intrinsic::experimental_constrained_sin:
6653     Opcode = ISD::STRICT_FSIN;
6654     break;
6655   case Intrinsic::experimental_constrained_cos:
6656     Opcode = ISD::STRICT_FCOS;
6657     break;
6658   case Intrinsic::experimental_constrained_exp:
6659     Opcode = ISD::STRICT_FEXP;
6660     break;
6661   case Intrinsic::experimental_constrained_exp2:
6662     Opcode = ISD::STRICT_FEXP2;
6663     break;
6664   case Intrinsic::experimental_constrained_log:
6665     Opcode = ISD::STRICT_FLOG;
6666     break;
6667   case Intrinsic::experimental_constrained_log10:
6668     Opcode = ISD::STRICT_FLOG10;
6669     break;
6670   case Intrinsic::experimental_constrained_log2:
6671     Opcode = ISD::STRICT_FLOG2;
6672     break;
6673   case Intrinsic::experimental_constrained_rint:
6674     Opcode = ISD::STRICT_FRINT;
6675     break;
6676   case Intrinsic::experimental_constrained_nearbyint:
6677     Opcode = ISD::STRICT_FNEARBYINT;
6678     break;
6679   case Intrinsic::experimental_constrained_maxnum:
6680     Opcode = ISD::STRICT_FMAXNUM;
6681     break;
6682   case Intrinsic::experimental_constrained_minnum:
6683     Opcode = ISD::STRICT_FMINNUM;
6684     break;
6685   case Intrinsic::experimental_constrained_ceil:
6686     Opcode = ISD::STRICT_FCEIL;
6687     break;
6688   case Intrinsic::experimental_constrained_floor:
6689     Opcode = ISD::STRICT_FFLOOR;
6690     break;
6691   case Intrinsic::experimental_constrained_round:
6692     Opcode = ISD::STRICT_FROUND;
6693     break;
6694   case Intrinsic::experimental_constrained_trunc:
6695     Opcode = ISD::STRICT_FTRUNC;
6696     break;
6697   }
6698   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6699   SDValue Chain = getRoot();
6700   SmallVector<EVT, 4> ValueVTs;
6701   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6702   ValueVTs.push_back(MVT::Other); // Out chain
6703 
6704   SDVTList VTs = DAG.getVTList(ValueVTs);
6705   SDValue Result;
6706   if (FPI.isUnaryOp())
6707     Result = DAG.getNode(Opcode, sdl, VTs,
6708                          { Chain, getValue(FPI.getArgOperand(0)) });
6709   else if (FPI.isTernaryOp())
6710     Result = DAG.getNode(Opcode, sdl, VTs,
6711                          { Chain, getValue(FPI.getArgOperand(0)),
6712                                   getValue(FPI.getArgOperand(1)),
6713                                   getValue(FPI.getArgOperand(2)) });
6714   else
6715     Result = DAG.getNode(Opcode, sdl, VTs,
6716                          { Chain, getValue(FPI.getArgOperand(0)),
6717                            getValue(FPI.getArgOperand(1))  });
6718 
6719   assert(Result.getNode()->getNumValues() == 2);
6720   SDValue OutChain = Result.getValue(1);
6721   DAG.setRoot(OutChain);
6722   SDValue FPResult = Result.getValue(0);
6723   setValue(&FPI, FPResult);
6724 }
6725 
6726 std::pair<SDValue, SDValue>
6727 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6728                                     const BasicBlock *EHPadBB) {
6729   MachineFunction &MF = DAG.getMachineFunction();
6730   MachineModuleInfo &MMI = MF.getMMI();
6731   MCSymbol *BeginLabel = nullptr;
6732 
6733   if (EHPadBB) {
6734     // Insert a label before the invoke call to mark the try range.  This can be
6735     // used to detect deletion of the invoke via the MachineModuleInfo.
6736     BeginLabel = MMI.getContext().createTempSymbol();
6737 
6738     // For SjLj, keep track of which landing pads go with which invokes
6739     // so as to maintain the ordering of pads in the LSDA.
6740     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6741     if (CallSiteIndex) {
6742       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6743       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6744 
6745       // Now that the call site is handled, stop tracking it.
6746       MMI.setCurrentCallSite(0);
6747     }
6748 
6749     // Both PendingLoads and PendingExports must be flushed here;
6750     // this call might not return.
6751     (void)getRoot();
6752     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6753 
6754     CLI.setChain(getRoot());
6755   }
6756   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6757   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6758 
6759   assert((CLI.IsTailCall || Result.second.getNode()) &&
6760          "Non-null chain expected with non-tail call!");
6761   assert((Result.second.getNode() || !Result.first.getNode()) &&
6762          "Null value expected with tail call!");
6763 
6764   if (!Result.second.getNode()) {
6765     // As a special case, a null chain means that a tail call has been emitted
6766     // and the DAG root is already updated.
6767     HasTailCall = true;
6768 
6769     // Since there's no actual continuation from this block, nothing can be
6770     // relying on us setting vregs for them.
6771     PendingExports.clear();
6772   } else {
6773     DAG.setRoot(Result.second);
6774   }
6775 
6776   if (EHPadBB) {
6777     // Insert a label at the end of the invoke call to mark the try range.  This
6778     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6779     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6780     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6781 
6782     // Inform MachineModuleInfo of range.
6783     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6784     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6785     // actually use outlined funclets and their LSDA info style.
6786     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6787       assert(CLI.CS);
6788       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6789       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6790                                 BeginLabel, EndLabel);
6791     } else if (!isScopedEHPersonality(Pers)) {
6792       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6793     }
6794   }
6795 
6796   return Result;
6797 }
6798 
6799 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6800                                       bool isTailCall,
6801                                       const BasicBlock *EHPadBB) {
6802   auto &DL = DAG.getDataLayout();
6803   FunctionType *FTy = CS.getFunctionType();
6804   Type *RetTy = CS.getType();
6805 
6806   TargetLowering::ArgListTy Args;
6807   Args.reserve(CS.arg_size());
6808 
6809   const Value *SwiftErrorVal = nullptr;
6810   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6811 
6812   // We can't tail call inside a function with a swifterror argument. Lowering
6813   // does not support this yet. It would have to move into the swifterror
6814   // register before the call.
6815   auto *Caller = CS.getInstruction()->getParent()->getParent();
6816   if (TLI.supportSwiftError() &&
6817       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6818     isTailCall = false;
6819 
6820   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6821        i != e; ++i) {
6822     TargetLowering::ArgListEntry Entry;
6823     const Value *V = *i;
6824 
6825     // Skip empty types
6826     if (V->getType()->isEmptyTy())
6827       continue;
6828 
6829     SDValue ArgNode = getValue(V);
6830     Entry.Node = ArgNode; Entry.Ty = V->getType();
6831 
6832     Entry.setAttributes(&CS, i - CS.arg_begin());
6833 
6834     // Use swifterror virtual register as input to the call.
6835     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6836       SwiftErrorVal = V;
6837       // We find the virtual register for the actual swifterror argument.
6838       // Instead of using the Value, we use the virtual register instead.
6839       Entry.Node = DAG.getRegister(FuncInfo
6840                                        .getOrCreateSwiftErrorVRegUseAt(
6841                                            CS.getInstruction(), FuncInfo.MBB, V)
6842                                        .first,
6843                                    EVT(TLI.getPointerTy(DL)));
6844     }
6845 
6846     Args.push_back(Entry);
6847 
6848     // If we have an explicit sret argument that is an Instruction, (i.e., it
6849     // might point to function-local memory), we can't meaningfully tail-call.
6850     if (Entry.IsSRet && isa<Instruction>(V))
6851       isTailCall = false;
6852   }
6853 
6854   // Check if target-independent constraints permit a tail call here.
6855   // Target-dependent constraints are checked within TLI->LowerCallTo.
6856   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6857     isTailCall = false;
6858 
6859   // Disable tail calls if there is an swifterror argument. Targets have not
6860   // been updated to support tail calls.
6861   if (TLI.supportSwiftError() && SwiftErrorVal)
6862     isTailCall = false;
6863 
6864   TargetLowering::CallLoweringInfo CLI(DAG);
6865   CLI.setDebugLoc(getCurSDLoc())
6866       .setChain(getRoot())
6867       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6868       .setTailCall(isTailCall)
6869       .setConvergent(CS.isConvergent());
6870   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6871 
6872   if (Result.first.getNode()) {
6873     const Instruction *Inst = CS.getInstruction();
6874     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6875     setValue(Inst, Result.first);
6876   }
6877 
6878   // The last element of CLI.InVals has the SDValue for swifterror return.
6879   // Here we copy it to a virtual register and update SwiftErrorMap for
6880   // book-keeping.
6881   if (SwiftErrorVal && TLI.supportSwiftError()) {
6882     // Get the last element of InVals.
6883     SDValue Src = CLI.InVals.back();
6884     unsigned VReg; bool CreatedVReg;
6885     std::tie(VReg, CreatedVReg) =
6886         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6887     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6888     // We update the virtual register for the actual swifterror argument.
6889     if (CreatedVReg)
6890       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6891     DAG.setRoot(CopyNode);
6892   }
6893 }
6894 
6895 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6896                              SelectionDAGBuilder &Builder) {
6897   // Check to see if this load can be trivially constant folded, e.g. if the
6898   // input is from a string literal.
6899   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6900     // Cast pointer to the type we really want to load.
6901     Type *LoadTy =
6902         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6903     if (LoadVT.isVector())
6904       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6905 
6906     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6907                                          PointerType::getUnqual(LoadTy));
6908 
6909     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6910             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6911       return Builder.getValue(LoadCst);
6912   }
6913 
6914   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6915   // still constant memory, the input chain can be the entry node.
6916   SDValue Root;
6917   bool ConstantMemory = false;
6918 
6919   // Do not serialize (non-volatile) loads of constant memory with anything.
6920   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6921     Root = Builder.DAG.getEntryNode();
6922     ConstantMemory = true;
6923   } else {
6924     // Do not serialize non-volatile loads against each other.
6925     Root = Builder.DAG.getRoot();
6926   }
6927 
6928   SDValue Ptr = Builder.getValue(PtrVal);
6929   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6930                                         Ptr, MachinePointerInfo(PtrVal),
6931                                         /* Alignment = */ 1);
6932 
6933   if (!ConstantMemory)
6934     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6935   return LoadVal;
6936 }
6937 
6938 /// Record the value for an instruction that produces an integer result,
6939 /// converting the type where necessary.
6940 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6941                                                   SDValue Value,
6942                                                   bool IsSigned) {
6943   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6944                                                     I.getType(), true);
6945   if (IsSigned)
6946     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6947   else
6948     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6949   setValue(&I, Value);
6950 }
6951 
6952 /// See if we can lower a memcmp call into an optimized form. If so, return
6953 /// true and lower it. Otherwise return false, and it will be lowered like a
6954 /// normal call.
6955 /// The caller already checked that \p I calls the appropriate LibFunc with a
6956 /// correct prototype.
6957 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6958   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6959   const Value *Size = I.getArgOperand(2);
6960   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6961   if (CSize && CSize->getZExtValue() == 0) {
6962     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6963                                                           I.getType(), true);
6964     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6965     return true;
6966   }
6967 
6968   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6969   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6970       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6971       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6972   if (Res.first.getNode()) {
6973     processIntegerCallValue(I, Res.first, true);
6974     PendingLoads.push_back(Res.second);
6975     return true;
6976   }
6977 
6978   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6979   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6980   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6981     return false;
6982 
6983   // If the target has a fast compare for the given size, it will return a
6984   // preferred load type for that size. Require that the load VT is legal and
6985   // that the target supports unaligned loads of that type. Otherwise, return
6986   // INVALID.
6987   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6988     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6989     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6990     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6991       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6992       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6993       // TODO: Check alignment of src and dest ptrs.
6994       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6995       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6996       if (!TLI.isTypeLegal(LVT) ||
6997           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6998           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6999         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7000     }
7001 
7002     return LVT;
7003   };
7004 
7005   // This turns into unaligned loads. We only do this if the target natively
7006   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7007   // we'll only produce a small number of byte loads.
7008   MVT LoadVT;
7009   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7010   switch (NumBitsToCompare) {
7011   default:
7012     return false;
7013   case 16:
7014     LoadVT = MVT::i16;
7015     break;
7016   case 32:
7017     LoadVT = MVT::i32;
7018     break;
7019   case 64:
7020   case 128:
7021   case 256:
7022     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7023     break;
7024   }
7025 
7026   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7027     return false;
7028 
7029   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7030   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7031 
7032   // Bitcast to a wide integer type if the loads are vectors.
7033   if (LoadVT.isVector()) {
7034     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7035     LoadL = DAG.getBitcast(CmpVT, LoadL);
7036     LoadR = DAG.getBitcast(CmpVT, LoadR);
7037   }
7038 
7039   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7040   processIntegerCallValue(I, Cmp, false);
7041   return true;
7042 }
7043 
7044 /// See if we can lower a memchr call into an optimized form. If so, return
7045 /// true and lower it. Otherwise return false, and it will be lowered like a
7046 /// normal call.
7047 /// The caller already checked that \p I calls the appropriate LibFunc with a
7048 /// correct prototype.
7049 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7050   const Value *Src = I.getArgOperand(0);
7051   const Value *Char = I.getArgOperand(1);
7052   const Value *Length = I.getArgOperand(2);
7053 
7054   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7055   std::pair<SDValue, SDValue> Res =
7056     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7057                                 getValue(Src), getValue(Char), getValue(Length),
7058                                 MachinePointerInfo(Src));
7059   if (Res.first.getNode()) {
7060     setValue(&I, Res.first);
7061     PendingLoads.push_back(Res.second);
7062     return true;
7063   }
7064 
7065   return false;
7066 }
7067 
7068 /// See if we can lower a mempcpy call into an optimized form. If so, return
7069 /// true and lower it. Otherwise return false, and it will be lowered like a
7070 /// normal call.
7071 /// The caller already checked that \p I calls the appropriate LibFunc with a
7072 /// correct prototype.
7073 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7074   SDValue Dst = getValue(I.getArgOperand(0));
7075   SDValue Src = getValue(I.getArgOperand(1));
7076   SDValue Size = getValue(I.getArgOperand(2));
7077 
7078   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7079   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7080   unsigned Align = std::min(DstAlign, SrcAlign);
7081   if (Align == 0) // Alignment of one or both could not be inferred.
7082     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7083 
7084   bool isVol = false;
7085   SDLoc sdl = getCurSDLoc();
7086 
7087   // In the mempcpy context we need to pass in a false value for isTailCall
7088   // because the return pointer needs to be adjusted by the size of
7089   // the copied memory.
7090   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7091                              false, /*isTailCall=*/false,
7092                              MachinePointerInfo(I.getArgOperand(0)),
7093                              MachinePointerInfo(I.getArgOperand(1)));
7094   assert(MC.getNode() != nullptr &&
7095          "** memcpy should not be lowered as TailCall in mempcpy context **");
7096   DAG.setRoot(MC);
7097 
7098   // Check if Size needs to be truncated or extended.
7099   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7100 
7101   // Adjust return pointer to point just past the last dst byte.
7102   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7103                                     Dst, Size);
7104   setValue(&I, DstPlusSize);
7105   return true;
7106 }
7107 
7108 /// See if we can lower a strcpy call into an optimized form.  If so, return
7109 /// true and lower it, otherwise return false and it will be lowered like a
7110 /// normal call.
7111 /// The caller already checked that \p I calls the appropriate LibFunc with a
7112 /// correct prototype.
7113 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7114   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7115 
7116   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7117   std::pair<SDValue, SDValue> Res =
7118     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7119                                 getValue(Arg0), getValue(Arg1),
7120                                 MachinePointerInfo(Arg0),
7121                                 MachinePointerInfo(Arg1), isStpcpy);
7122   if (Res.first.getNode()) {
7123     setValue(&I, Res.first);
7124     DAG.setRoot(Res.second);
7125     return true;
7126   }
7127 
7128   return false;
7129 }
7130 
7131 /// See if we can lower a strcmp call into an optimized form.  If so, return
7132 /// true and lower it, otherwise return false and it will be lowered like a
7133 /// normal call.
7134 /// The caller already checked that \p I calls the appropriate LibFunc with a
7135 /// correct prototype.
7136 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7137   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7138 
7139   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7140   std::pair<SDValue, SDValue> Res =
7141     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7142                                 getValue(Arg0), getValue(Arg1),
7143                                 MachinePointerInfo(Arg0),
7144                                 MachinePointerInfo(Arg1));
7145   if (Res.first.getNode()) {
7146     processIntegerCallValue(I, Res.first, true);
7147     PendingLoads.push_back(Res.second);
7148     return true;
7149   }
7150 
7151   return false;
7152 }
7153 
7154 /// See if we can lower a strlen call into an optimized form.  If so, return
7155 /// true and lower it, otherwise return false and it will be lowered like a
7156 /// normal call.
7157 /// The caller already checked that \p I calls the appropriate LibFunc with a
7158 /// correct prototype.
7159 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7160   const Value *Arg0 = I.getArgOperand(0);
7161 
7162   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7163   std::pair<SDValue, SDValue> Res =
7164     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7165                                 getValue(Arg0), MachinePointerInfo(Arg0));
7166   if (Res.first.getNode()) {
7167     processIntegerCallValue(I, Res.first, false);
7168     PendingLoads.push_back(Res.second);
7169     return true;
7170   }
7171 
7172   return false;
7173 }
7174 
7175 /// See if we can lower a strnlen call into an optimized form.  If so, return
7176 /// true and lower it, otherwise return false and it will be lowered like a
7177 /// normal call.
7178 /// The caller already checked that \p I calls the appropriate LibFunc with a
7179 /// correct prototype.
7180 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7181   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7182 
7183   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7184   std::pair<SDValue, SDValue> Res =
7185     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7186                                  getValue(Arg0), getValue(Arg1),
7187                                  MachinePointerInfo(Arg0));
7188   if (Res.first.getNode()) {
7189     processIntegerCallValue(I, Res.first, false);
7190     PendingLoads.push_back(Res.second);
7191     return true;
7192   }
7193 
7194   return false;
7195 }
7196 
7197 /// See if we can lower a unary floating-point operation into an SDNode with
7198 /// the specified Opcode.  If so, return true and lower it, otherwise return
7199 /// false and it will be lowered like a normal call.
7200 /// The caller already checked that \p I calls the appropriate LibFunc with a
7201 /// correct prototype.
7202 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7203                                               unsigned Opcode) {
7204   // We already checked this call's prototype; verify it doesn't modify errno.
7205   if (!I.onlyReadsMemory())
7206     return false;
7207 
7208   SDValue Tmp = getValue(I.getArgOperand(0));
7209   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7210   return true;
7211 }
7212 
7213 /// See if we can lower a binary floating-point operation into an SDNode with
7214 /// the specified Opcode. If so, return true and lower it. Otherwise return
7215 /// false, and it will be lowered like a normal call.
7216 /// The caller already checked that \p I calls the appropriate LibFunc with a
7217 /// correct prototype.
7218 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7219                                                unsigned Opcode) {
7220   // We already checked this call's prototype; verify it doesn't modify errno.
7221   if (!I.onlyReadsMemory())
7222     return false;
7223 
7224   SDValue Tmp0 = getValue(I.getArgOperand(0));
7225   SDValue Tmp1 = getValue(I.getArgOperand(1));
7226   EVT VT = Tmp0.getValueType();
7227   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7228   return true;
7229 }
7230 
7231 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7232   // Handle inline assembly differently.
7233   if (isa<InlineAsm>(I.getCalledValue())) {
7234     visitInlineAsm(&I);
7235     return;
7236   }
7237 
7238   const char *RenameFn = nullptr;
7239   if (Function *F = I.getCalledFunction()) {
7240     if (F->isDeclaration()) {
7241       // Is this an LLVM intrinsic or a target-specific intrinsic?
7242       unsigned IID = F->getIntrinsicID();
7243       if (!IID)
7244         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7245           IID = II->getIntrinsicID(F);
7246 
7247       if (IID) {
7248         RenameFn = visitIntrinsicCall(I, IID);
7249         if (!RenameFn)
7250           return;
7251       }
7252     }
7253 
7254     // Check for well-known libc/libm calls.  If the function is internal, it
7255     // can't be a library call.  Don't do the check if marked as nobuiltin for
7256     // some reason or the call site requires strict floating point semantics.
7257     LibFunc Func;
7258     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7259         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7260         LibInfo->hasOptimizedCodeGen(Func)) {
7261       switch (Func) {
7262       default: break;
7263       case LibFunc_copysign:
7264       case LibFunc_copysignf:
7265       case LibFunc_copysignl:
7266         // We already checked this call's prototype; verify it doesn't modify
7267         // errno.
7268         if (I.onlyReadsMemory()) {
7269           SDValue LHS = getValue(I.getArgOperand(0));
7270           SDValue RHS = getValue(I.getArgOperand(1));
7271           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7272                                    LHS.getValueType(), LHS, RHS));
7273           return;
7274         }
7275         break;
7276       case LibFunc_fabs:
7277       case LibFunc_fabsf:
7278       case LibFunc_fabsl:
7279         if (visitUnaryFloatCall(I, ISD::FABS))
7280           return;
7281         break;
7282       case LibFunc_fmin:
7283       case LibFunc_fminf:
7284       case LibFunc_fminl:
7285         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7286           return;
7287         break;
7288       case LibFunc_fmax:
7289       case LibFunc_fmaxf:
7290       case LibFunc_fmaxl:
7291         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7292           return;
7293         break;
7294       case LibFunc_sin:
7295       case LibFunc_sinf:
7296       case LibFunc_sinl:
7297         if (visitUnaryFloatCall(I, ISD::FSIN))
7298           return;
7299         break;
7300       case LibFunc_cos:
7301       case LibFunc_cosf:
7302       case LibFunc_cosl:
7303         if (visitUnaryFloatCall(I, ISD::FCOS))
7304           return;
7305         break;
7306       case LibFunc_sqrt:
7307       case LibFunc_sqrtf:
7308       case LibFunc_sqrtl:
7309       case LibFunc_sqrt_finite:
7310       case LibFunc_sqrtf_finite:
7311       case LibFunc_sqrtl_finite:
7312         if (visitUnaryFloatCall(I, ISD::FSQRT))
7313           return;
7314         break;
7315       case LibFunc_floor:
7316       case LibFunc_floorf:
7317       case LibFunc_floorl:
7318         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7319           return;
7320         break;
7321       case LibFunc_nearbyint:
7322       case LibFunc_nearbyintf:
7323       case LibFunc_nearbyintl:
7324         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7325           return;
7326         break;
7327       case LibFunc_ceil:
7328       case LibFunc_ceilf:
7329       case LibFunc_ceill:
7330         if (visitUnaryFloatCall(I, ISD::FCEIL))
7331           return;
7332         break;
7333       case LibFunc_rint:
7334       case LibFunc_rintf:
7335       case LibFunc_rintl:
7336         if (visitUnaryFloatCall(I, ISD::FRINT))
7337           return;
7338         break;
7339       case LibFunc_round:
7340       case LibFunc_roundf:
7341       case LibFunc_roundl:
7342         if (visitUnaryFloatCall(I, ISD::FROUND))
7343           return;
7344         break;
7345       case LibFunc_trunc:
7346       case LibFunc_truncf:
7347       case LibFunc_truncl:
7348         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7349           return;
7350         break;
7351       case LibFunc_log2:
7352       case LibFunc_log2f:
7353       case LibFunc_log2l:
7354         if (visitUnaryFloatCall(I, ISD::FLOG2))
7355           return;
7356         break;
7357       case LibFunc_exp2:
7358       case LibFunc_exp2f:
7359       case LibFunc_exp2l:
7360         if (visitUnaryFloatCall(I, ISD::FEXP2))
7361           return;
7362         break;
7363       case LibFunc_memcmp:
7364         if (visitMemCmpCall(I))
7365           return;
7366         break;
7367       case LibFunc_mempcpy:
7368         if (visitMemPCpyCall(I))
7369           return;
7370         break;
7371       case LibFunc_memchr:
7372         if (visitMemChrCall(I))
7373           return;
7374         break;
7375       case LibFunc_strcpy:
7376         if (visitStrCpyCall(I, false))
7377           return;
7378         break;
7379       case LibFunc_stpcpy:
7380         if (visitStrCpyCall(I, true))
7381           return;
7382         break;
7383       case LibFunc_strcmp:
7384         if (visitStrCmpCall(I))
7385           return;
7386         break;
7387       case LibFunc_strlen:
7388         if (visitStrLenCall(I))
7389           return;
7390         break;
7391       case LibFunc_strnlen:
7392         if (visitStrNLenCall(I))
7393           return;
7394         break;
7395       }
7396     }
7397   }
7398 
7399   SDValue Callee;
7400   if (!RenameFn)
7401     Callee = getValue(I.getCalledValue());
7402   else
7403     Callee = DAG.getExternalSymbol(
7404         RenameFn,
7405         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7406 
7407   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7408   // have to do anything here to lower funclet bundles.
7409   assert(!I.hasOperandBundlesOtherThan(
7410              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7411          "Cannot lower calls with arbitrary operand bundles!");
7412 
7413   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7414     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7415   else
7416     // Check if we can potentially perform a tail call. More detailed checking
7417     // is be done within LowerCallTo, after more information about the call is
7418     // known.
7419     LowerCallTo(&I, Callee, I.isTailCall());
7420 }
7421 
7422 namespace {
7423 
7424 /// AsmOperandInfo - This contains information for each constraint that we are
7425 /// lowering.
7426 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7427 public:
7428   /// CallOperand - If this is the result output operand or a clobber
7429   /// this is null, otherwise it is the incoming operand to the CallInst.
7430   /// This gets modified as the asm is processed.
7431   SDValue CallOperand;
7432 
7433   /// AssignedRegs - If this is a register or register class operand, this
7434   /// contains the set of register corresponding to the operand.
7435   RegsForValue AssignedRegs;
7436 
7437   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7438     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7439   }
7440 
7441   /// Whether or not this operand accesses memory
7442   bool hasMemory(const TargetLowering &TLI) const {
7443     // Indirect operand accesses access memory.
7444     if (isIndirect)
7445       return true;
7446 
7447     for (const auto &Code : Codes)
7448       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7449         return true;
7450 
7451     return false;
7452   }
7453 
7454   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7455   /// corresponds to.  If there is no Value* for this operand, it returns
7456   /// MVT::Other.
7457   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7458                            const DataLayout &DL) const {
7459     if (!CallOperandVal) return MVT::Other;
7460 
7461     if (isa<BasicBlock>(CallOperandVal))
7462       return TLI.getPointerTy(DL);
7463 
7464     llvm::Type *OpTy = CallOperandVal->getType();
7465 
7466     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7467     // If this is an indirect operand, the operand is a pointer to the
7468     // accessed type.
7469     if (isIndirect) {
7470       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7471       if (!PtrTy)
7472         report_fatal_error("Indirect operand for inline asm not a pointer!");
7473       OpTy = PtrTy->getElementType();
7474     }
7475 
7476     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7477     if (StructType *STy = dyn_cast<StructType>(OpTy))
7478       if (STy->getNumElements() == 1)
7479         OpTy = STy->getElementType(0);
7480 
7481     // If OpTy is not a single value, it may be a struct/union that we
7482     // can tile with integers.
7483     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7484       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7485       switch (BitSize) {
7486       default: break;
7487       case 1:
7488       case 8:
7489       case 16:
7490       case 32:
7491       case 64:
7492       case 128:
7493         OpTy = IntegerType::get(Context, BitSize);
7494         break;
7495       }
7496     }
7497 
7498     return TLI.getValueType(DL, OpTy, true);
7499   }
7500 };
7501 
7502 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7503 
7504 } // end anonymous namespace
7505 
7506 /// Make sure that the output operand \p OpInfo and its corresponding input
7507 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7508 /// out).
7509 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7510                                SDISelAsmOperandInfo &MatchingOpInfo,
7511                                SelectionDAG &DAG) {
7512   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7513     return;
7514 
7515   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7516   const auto &TLI = DAG.getTargetLoweringInfo();
7517 
7518   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7519       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7520                                        OpInfo.ConstraintVT);
7521   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7522       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7523                                        MatchingOpInfo.ConstraintVT);
7524   if ((OpInfo.ConstraintVT.isInteger() !=
7525        MatchingOpInfo.ConstraintVT.isInteger()) ||
7526       (MatchRC.second != InputRC.second)) {
7527     // FIXME: error out in a more elegant fashion
7528     report_fatal_error("Unsupported asm: input constraint"
7529                        " with a matching output constraint of"
7530                        " incompatible type!");
7531   }
7532   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7533 }
7534 
7535 /// Get a direct memory input to behave well as an indirect operand.
7536 /// This may introduce stores, hence the need for a \p Chain.
7537 /// \return The (possibly updated) chain.
7538 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7539                                         SDISelAsmOperandInfo &OpInfo,
7540                                         SelectionDAG &DAG) {
7541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7542 
7543   // If we don't have an indirect input, put it in the constpool if we can,
7544   // otherwise spill it to a stack slot.
7545   // TODO: This isn't quite right. We need to handle these according to
7546   // the addressing mode that the constraint wants. Also, this may take
7547   // an additional register for the computation and we don't want that
7548   // either.
7549 
7550   // If the operand is a float, integer, or vector constant, spill to a
7551   // constant pool entry to get its address.
7552   const Value *OpVal = OpInfo.CallOperandVal;
7553   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7554       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7555     OpInfo.CallOperand = DAG.getConstantPool(
7556         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7557     return Chain;
7558   }
7559 
7560   // Otherwise, create a stack slot and emit a store to it before the asm.
7561   Type *Ty = OpVal->getType();
7562   auto &DL = DAG.getDataLayout();
7563   uint64_t TySize = DL.getTypeAllocSize(Ty);
7564   unsigned Align = DL.getPrefTypeAlignment(Ty);
7565   MachineFunction &MF = DAG.getMachineFunction();
7566   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7567   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7568   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7569                        MachinePointerInfo::getFixedStack(MF, SSFI));
7570   OpInfo.CallOperand = StackSlot;
7571 
7572   return Chain;
7573 }
7574 
7575 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7576 /// specified operand.  We prefer to assign virtual registers, to allow the
7577 /// register allocator to handle the assignment process.  However, if the asm
7578 /// uses features that we can't model on machineinstrs, we have SDISel do the
7579 /// allocation.  This produces generally horrible, but correct, code.
7580 ///
7581 ///   OpInfo describes the operand
7582 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7583 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7584                                  SDISelAsmOperandInfo &OpInfo,
7585                                  SDISelAsmOperandInfo &RefOpInfo) {
7586   LLVMContext &Context = *DAG.getContext();
7587   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7588 
7589   MachineFunction &MF = DAG.getMachineFunction();
7590   SmallVector<unsigned, 4> Regs;
7591   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7592 
7593   // No work to do for memory operations.
7594   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7595     return;
7596 
7597   // If this is a constraint for a single physreg, or a constraint for a
7598   // register class, find it.
7599   unsigned AssignedReg;
7600   const TargetRegisterClass *RC;
7601   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7602       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7603   // RC is unset only on failure. Return immediately.
7604   if (!RC)
7605     return;
7606 
7607   // Get the actual register value type.  This is important, because the user
7608   // may have asked for (e.g.) the AX register in i32 type.  We need to
7609   // remember that AX is actually i16 to get the right extension.
7610   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7611 
7612   if (OpInfo.ConstraintVT != MVT::Other) {
7613     // If this is an FP operand in an integer register (or visa versa), or more
7614     // generally if the operand value disagrees with the register class we plan
7615     // to stick it in, fix the operand type.
7616     //
7617     // If this is an input value, the bitcast to the new type is done now.
7618     // Bitcast for output value is done at the end of visitInlineAsm().
7619     if ((OpInfo.Type == InlineAsm::isOutput ||
7620          OpInfo.Type == InlineAsm::isInput) &&
7621         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7622       // Try to convert to the first EVT that the reg class contains.  If the
7623       // types are identical size, use a bitcast to convert (e.g. two differing
7624       // vector types).  Note: output bitcast is done at the end of
7625       // visitInlineAsm().
7626       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7627         // Exclude indirect inputs while they are unsupported because the code
7628         // to perform the load is missing and thus OpInfo.CallOperand still
7629         // refers to the input address rather than the pointed-to value.
7630         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7631           OpInfo.CallOperand =
7632               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7633         OpInfo.ConstraintVT = RegVT;
7634         // If the operand is an FP value and we want it in integer registers,
7635         // use the corresponding integer type. This turns an f64 value into
7636         // i64, which can be passed with two i32 values on a 32-bit machine.
7637       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7638         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7639         if (OpInfo.Type == InlineAsm::isInput)
7640           OpInfo.CallOperand =
7641               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7642         OpInfo.ConstraintVT = VT;
7643       }
7644     }
7645   }
7646 
7647   // No need to allocate a matching input constraint since the constraint it's
7648   // matching to has already been allocated.
7649   if (OpInfo.isMatchingInputConstraint())
7650     return;
7651 
7652   EVT ValueVT = OpInfo.ConstraintVT;
7653   if (OpInfo.ConstraintVT == MVT::Other)
7654     ValueVT = RegVT;
7655 
7656   // Initialize NumRegs.
7657   unsigned NumRegs = 1;
7658   if (OpInfo.ConstraintVT != MVT::Other)
7659     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7660 
7661   // If this is a constraint for a specific physical register, like {r17},
7662   // assign it now.
7663 
7664   // If this associated to a specific register, initialize iterator to correct
7665   // place. If virtual, make sure we have enough registers
7666 
7667   // Initialize iterator if necessary
7668   TargetRegisterClass::iterator I = RC->begin();
7669   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7670 
7671   // Do not check for single registers.
7672   if (AssignedReg) {
7673       for (; *I != AssignedReg; ++I)
7674         assert(I != RC->end() && "AssignedReg should be member of RC");
7675   }
7676 
7677   for (; NumRegs; --NumRegs, ++I) {
7678     assert(I != RC->end() && "Ran out of registers to allocate!");
7679     auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC);
7680     Regs.push_back(R);
7681   }
7682 
7683   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7684 }
7685 
7686 static unsigned
7687 findMatchingInlineAsmOperand(unsigned OperandNo,
7688                              const std::vector<SDValue> &AsmNodeOperands) {
7689   // Scan until we find the definition we already emitted of this operand.
7690   unsigned CurOp = InlineAsm::Op_FirstOperand;
7691   for (; OperandNo; --OperandNo) {
7692     // Advance to the next operand.
7693     unsigned OpFlag =
7694         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7695     assert((InlineAsm::isRegDefKind(OpFlag) ||
7696             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7697             InlineAsm::isMemKind(OpFlag)) &&
7698            "Skipped past definitions?");
7699     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7700   }
7701   return CurOp;
7702 }
7703 
7704 namespace {
7705 
7706 class ExtraFlags {
7707   unsigned Flags = 0;
7708 
7709 public:
7710   explicit ExtraFlags(ImmutableCallSite CS) {
7711     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7712     if (IA->hasSideEffects())
7713       Flags |= InlineAsm::Extra_HasSideEffects;
7714     if (IA->isAlignStack())
7715       Flags |= InlineAsm::Extra_IsAlignStack;
7716     if (CS.isConvergent())
7717       Flags |= InlineAsm::Extra_IsConvergent;
7718     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7719   }
7720 
7721   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7722     // Ideally, we would only check against memory constraints.  However, the
7723     // meaning of an Other constraint can be target-specific and we can't easily
7724     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7725     // for Other constraints as well.
7726     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7727         OpInfo.ConstraintType == TargetLowering::C_Other) {
7728       if (OpInfo.Type == InlineAsm::isInput)
7729         Flags |= InlineAsm::Extra_MayLoad;
7730       else if (OpInfo.Type == InlineAsm::isOutput)
7731         Flags |= InlineAsm::Extra_MayStore;
7732       else if (OpInfo.Type == InlineAsm::isClobber)
7733         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7734     }
7735   }
7736 
7737   unsigned get() const { return Flags; }
7738 };
7739 
7740 } // end anonymous namespace
7741 
7742 /// visitInlineAsm - Handle a call to an InlineAsm object.
7743 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7744   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7745 
7746   /// ConstraintOperands - Information about all of the constraints.
7747   SDISelAsmOperandInfoVector ConstraintOperands;
7748 
7749   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7750   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7751       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7752 
7753   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7754   // AsmDialect, MayLoad, MayStore).
7755   bool HasSideEffect = IA->hasSideEffects();
7756   ExtraFlags ExtraInfo(CS);
7757 
7758   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7759   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7760   for (auto &T : TargetConstraints) {
7761     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7762     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7763 
7764     // Compute the value type for each operand.
7765     if (OpInfo.Type == InlineAsm::isInput ||
7766         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7767       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7768 
7769       // Process the call argument. BasicBlocks are labels, currently appearing
7770       // only in asm's.
7771       const Instruction *I = CS.getInstruction();
7772       if (isa<CallBrInst>(I) &&
7773           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
7774                           cast<CallBrInst>(I)->getNumIndirectDests())) {
7775         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
7776         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
7777         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
7778       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7779         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7780       } else {
7781         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7782       }
7783 
7784       OpInfo.ConstraintVT =
7785           OpInfo
7786               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7787               .getSimpleVT();
7788     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7789       // The return value of the call is this value.  As such, there is no
7790       // corresponding argument.
7791       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7792       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7793         OpInfo.ConstraintVT = TLI.getSimpleValueType(
7794             DAG.getDataLayout(), STy->getElementType(ResNo));
7795       } else {
7796         assert(ResNo == 0 && "Asm only has one result!");
7797         OpInfo.ConstraintVT =
7798             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7799       }
7800       ++ResNo;
7801     } else {
7802       OpInfo.ConstraintVT = MVT::Other;
7803     }
7804 
7805     if (!HasSideEffect)
7806       HasSideEffect = OpInfo.hasMemory(TLI);
7807 
7808     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7809     // FIXME: Could we compute this on OpInfo rather than T?
7810 
7811     // Compute the constraint code and ConstraintType to use.
7812     TLI.ComputeConstraintToUse(T, SDValue());
7813 
7814     ExtraInfo.update(T);
7815   }
7816 
7817   // We won't need to flush pending loads if this asm doesn't touch
7818   // memory and is nonvolatile.
7819   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
7820 
7821   // Second pass over the constraints: compute which constraint option to use.
7822   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7823     // If this is an output operand with a matching input operand, look up the
7824     // matching input. If their types mismatch, e.g. one is an integer, the
7825     // other is floating point, or their sizes are different, flag it as an
7826     // error.
7827     if (OpInfo.hasMatchingInput()) {
7828       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7829       patchMatchingInput(OpInfo, Input, DAG);
7830     }
7831 
7832     // Compute the constraint code and ConstraintType to use.
7833     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7834 
7835     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7836         OpInfo.Type == InlineAsm::isClobber)
7837       continue;
7838 
7839     // If this is a memory input, and if the operand is not indirect, do what we
7840     // need to provide an address for the memory input.
7841     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7842         !OpInfo.isIndirect) {
7843       assert((OpInfo.isMultipleAlternative ||
7844               (OpInfo.Type == InlineAsm::isInput)) &&
7845              "Can only indirectify direct input operands!");
7846 
7847       // Memory operands really want the address of the value.
7848       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7849 
7850       // There is no longer a Value* corresponding to this operand.
7851       OpInfo.CallOperandVal = nullptr;
7852 
7853       // It is now an indirect operand.
7854       OpInfo.isIndirect = true;
7855     }
7856 
7857   }
7858 
7859   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7860   std::vector<SDValue> AsmNodeOperands;
7861   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7862   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7863       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7864 
7865   // If we have a !srcloc metadata node associated with it, we want to attach
7866   // this to the ultimately generated inline asm machineinstr.  To do this, we
7867   // pass in the third operand as this (potentially null) inline asm MDNode.
7868   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7869   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7870 
7871   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7872   // bits as operand 3.
7873   AsmNodeOperands.push_back(DAG.getTargetConstant(
7874       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7875 
7876   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
7877   // this, assign virtual and physical registers for inputs and otput.
7878   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7879     // Assign Registers.
7880     SDISelAsmOperandInfo &RefOpInfo =
7881         OpInfo.isMatchingInputConstraint()
7882             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7883             : OpInfo;
7884     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
7885 
7886     switch (OpInfo.Type) {
7887     case InlineAsm::isOutput:
7888       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7889           (OpInfo.ConstraintType == TargetLowering::C_Other &&
7890            OpInfo.isIndirect)) {
7891         unsigned ConstraintID =
7892             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7893         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7894                "Failed to convert memory constraint code to constraint id.");
7895 
7896         // Add information to the INLINEASM node to know about this output.
7897         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7898         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7899         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7900                                                         MVT::i32));
7901         AsmNodeOperands.push_back(OpInfo.CallOperand);
7902         break;
7903       } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
7904                   !OpInfo.isIndirect) ||
7905                  OpInfo.ConstraintType == TargetLowering::C_Register ||
7906                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
7907         // Otherwise, this outputs to a register (directly for C_Register /
7908         // C_RegisterClass, and a target-defined fashion for C_Other). Find a
7909         // register that we can use.
7910         if (OpInfo.AssignedRegs.Regs.empty()) {
7911           emitInlineAsmError(
7912               CS, "couldn't allocate output register for constraint '" +
7913                       Twine(OpInfo.ConstraintCode) + "'");
7914           return;
7915         }
7916 
7917         // Add information to the INLINEASM node to know that this register is
7918         // set.
7919         OpInfo.AssignedRegs.AddInlineAsmOperands(
7920             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
7921                                   : InlineAsm::Kind_RegDef,
7922             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7923       }
7924       break;
7925 
7926     case InlineAsm::isInput: {
7927       SDValue InOperandVal = OpInfo.CallOperand;
7928 
7929       if (OpInfo.isMatchingInputConstraint()) {
7930         // If this is required to match an output register we have already set,
7931         // just use its register.
7932         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7933                                                   AsmNodeOperands);
7934         unsigned OpFlag =
7935           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7936         if (InlineAsm::isRegDefKind(OpFlag) ||
7937             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7938           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7939           if (OpInfo.isIndirect) {
7940             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7941             emitInlineAsmError(CS, "inline asm not supported yet:"
7942                                    " don't know how to handle tied "
7943                                    "indirect register inputs");
7944             return;
7945           }
7946 
7947           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7948           SmallVector<unsigned, 4> Regs;
7949 
7950           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
7951             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
7952             MachineRegisterInfo &RegInfo =
7953                 DAG.getMachineFunction().getRegInfo();
7954             for (unsigned i = 0; i != NumRegs; ++i)
7955               Regs.push_back(RegInfo.createVirtualRegister(RC));
7956           } else {
7957             emitInlineAsmError(CS, "inline asm error: This value type register "
7958                                    "class is not natively supported!");
7959             return;
7960           }
7961 
7962           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7963 
7964           SDLoc dl = getCurSDLoc();
7965           // Use the produced MatchedRegs object to
7966           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7967                                     CS.getInstruction());
7968           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7969                                            true, OpInfo.getMatchedOperand(), dl,
7970                                            DAG, AsmNodeOperands);
7971           break;
7972         }
7973 
7974         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7975         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7976                "Unexpected number of operands");
7977         // Add information to the INLINEASM node to know about this input.
7978         // See InlineAsm.h isUseOperandTiedToDef.
7979         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7980         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7981                                                     OpInfo.getMatchedOperand());
7982         AsmNodeOperands.push_back(DAG.getTargetConstant(
7983             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7984         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7985         break;
7986       }
7987 
7988       // Treat indirect 'X' constraint as memory.
7989       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7990           OpInfo.isIndirect)
7991         OpInfo.ConstraintType = TargetLowering::C_Memory;
7992 
7993       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7994         std::vector<SDValue> Ops;
7995         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7996                                           Ops, DAG);
7997         if (Ops.empty()) {
7998           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7999                                      Twine(OpInfo.ConstraintCode) + "'");
8000           return;
8001         }
8002 
8003         // Add information to the INLINEASM node to know about this input.
8004         unsigned ResOpType =
8005           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8006         AsmNodeOperands.push_back(DAG.getTargetConstant(
8007             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8008         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8009         break;
8010       }
8011 
8012       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8013         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8014         assert(InOperandVal.getValueType() ==
8015                    TLI.getPointerTy(DAG.getDataLayout()) &&
8016                "Memory operands expect pointer values");
8017 
8018         unsigned ConstraintID =
8019             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8020         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8021                "Failed to convert memory constraint code to constraint id.");
8022 
8023         // Add information to the INLINEASM node to know about this input.
8024         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8025         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8026         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8027                                                         getCurSDLoc(),
8028                                                         MVT::i32));
8029         AsmNodeOperands.push_back(InOperandVal);
8030         break;
8031       }
8032 
8033       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8034               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8035              "Unknown constraint type!");
8036 
8037       // TODO: Support this.
8038       if (OpInfo.isIndirect) {
8039         emitInlineAsmError(
8040             CS, "Don't know how to handle indirect register inputs yet "
8041                 "for constraint '" +
8042                     Twine(OpInfo.ConstraintCode) + "'");
8043         return;
8044       }
8045 
8046       // Copy the input into the appropriate registers.
8047       if (OpInfo.AssignedRegs.Regs.empty()) {
8048         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8049                                    Twine(OpInfo.ConstraintCode) + "'");
8050         return;
8051       }
8052 
8053       SDLoc dl = getCurSDLoc();
8054 
8055       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8056                                         Chain, &Flag, CS.getInstruction());
8057 
8058       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8059                                                dl, DAG, AsmNodeOperands);
8060       break;
8061     }
8062     case InlineAsm::isClobber:
8063       // Add the clobbered value to the operand list, so that the register
8064       // allocator is aware that the physreg got clobbered.
8065       if (!OpInfo.AssignedRegs.Regs.empty())
8066         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8067                                                  false, 0, getCurSDLoc(), DAG,
8068                                                  AsmNodeOperands);
8069       break;
8070     }
8071   }
8072 
8073   // Finish up input operands.  Set the input chain and add the flag last.
8074   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8075   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8076 
8077   unsigned ISDOpc = isa<CallBrInst>(CS.getInstruction()) ? ISD::INLINEASM_BR : ISD::INLINEASM;
8078   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8079                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8080   Flag = Chain.getValue(1);
8081 
8082   // Do additional work to generate outputs.
8083 
8084   SmallVector<EVT, 1> ResultVTs;
8085   SmallVector<SDValue, 1> ResultValues;
8086   SmallVector<SDValue, 8> OutChains;
8087 
8088   llvm::Type *CSResultType = CS.getType();
8089   ArrayRef<Type *> ResultTypes;
8090   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8091     ResultTypes = StructResult->elements();
8092   else if (!CSResultType->isVoidTy())
8093     ResultTypes = makeArrayRef(CSResultType);
8094 
8095   auto CurResultType = ResultTypes.begin();
8096   auto handleRegAssign = [&](SDValue V) {
8097     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8098     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8099     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8100     ++CurResultType;
8101     // If the type of the inline asm call site return value is different but has
8102     // same size as the type of the asm output bitcast it.  One example of this
8103     // is for vectors with different width / number of elements.  This can
8104     // happen for register classes that can contain multiple different value
8105     // types.  The preg or vreg allocated may not have the same VT as was
8106     // expected.
8107     //
8108     // This can also happen for a return value that disagrees with the register
8109     // class it is put in, eg. a double in a general-purpose register on a
8110     // 32-bit machine.
8111     if (ResultVT != V.getValueType() &&
8112         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8113       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8114     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8115              V.getValueType().isInteger()) {
8116       // If a result value was tied to an input value, the computed result
8117       // may have a wider width than the expected result.  Extract the
8118       // relevant portion.
8119       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8120     }
8121     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8122     ResultVTs.push_back(ResultVT);
8123     ResultValues.push_back(V);
8124   };
8125 
8126   // Deal with output operands.
8127   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8128     if (OpInfo.Type == InlineAsm::isOutput) {
8129       SDValue Val;
8130       // Skip trivial output operands.
8131       if (OpInfo.AssignedRegs.Regs.empty())
8132         continue;
8133 
8134       switch (OpInfo.ConstraintType) {
8135       case TargetLowering::C_Register:
8136       case TargetLowering::C_RegisterClass:
8137         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8138             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8139         break;
8140       case TargetLowering::C_Other:
8141         Val = TLI.LowerAsmOutputForConstraint(Chain, &Flag, getCurSDLoc(),
8142                                               OpInfo, DAG);
8143         break;
8144       case TargetLowering::C_Memory:
8145         break; // Already handled.
8146       case TargetLowering::C_Unknown:
8147         assert(false && "Unexpected unknown constraint");
8148       }
8149 
8150       // Indirect output manifest as stores. Record output chains.
8151       if (OpInfo.isIndirect) {
8152 
8153         const Value *Ptr = OpInfo.CallOperandVal;
8154         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8155         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8156                                      MachinePointerInfo(Ptr));
8157         OutChains.push_back(Store);
8158       } else {
8159         // generate CopyFromRegs to associated registers.
8160         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8161         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8162           for (const SDValue &V : Val->op_values())
8163             handleRegAssign(V);
8164         } else
8165           handleRegAssign(Val);
8166       }
8167     }
8168   }
8169 
8170   // Set results.
8171   if (!ResultValues.empty()) {
8172     assert(CurResultType == ResultTypes.end() &&
8173            "Mismatch in number of ResultTypes");
8174     assert(ResultValues.size() == ResultTypes.size() &&
8175            "Mismatch in number of output operands in asm result");
8176 
8177     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8178                             DAG.getVTList(ResultVTs), ResultValues);
8179     setValue(CS.getInstruction(), V);
8180   }
8181 
8182   // Collect store chains.
8183   if (!OutChains.empty())
8184     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8185 
8186   // Only Update Root if inline assembly has a memory effect.
8187   if (ResultValues.empty() || HasSideEffect || !OutChains.empty())
8188     DAG.setRoot(Chain);
8189 }
8190 
8191 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8192                                              const Twine &Message) {
8193   LLVMContext &Ctx = *DAG.getContext();
8194   Ctx.emitError(CS.getInstruction(), Message);
8195 
8196   // Make sure we leave the DAG in a valid state
8197   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8198   SmallVector<EVT, 1> ValueVTs;
8199   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8200 
8201   if (ValueVTs.empty())
8202     return;
8203 
8204   SmallVector<SDValue, 1> Ops;
8205   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8206     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8207 
8208   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8209 }
8210 
8211 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8212   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8213                           MVT::Other, getRoot(),
8214                           getValue(I.getArgOperand(0)),
8215                           DAG.getSrcValue(I.getArgOperand(0))));
8216 }
8217 
8218 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8219   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8220   const DataLayout &DL = DAG.getDataLayout();
8221   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
8222                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
8223                            DAG.getSrcValue(I.getOperand(0)),
8224                            DL.getABITypeAlignment(I.getType()));
8225   setValue(&I, V);
8226   DAG.setRoot(V.getValue(1));
8227 }
8228 
8229 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8230   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8231                           MVT::Other, getRoot(),
8232                           getValue(I.getArgOperand(0)),
8233                           DAG.getSrcValue(I.getArgOperand(0))));
8234 }
8235 
8236 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8237   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8238                           MVT::Other, getRoot(),
8239                           getValue(I.getArgOperand(0)),
8240                           getValue(I.getArgOperand(1)),
8241                           DAG.getSrcValue(I.getArgOperand(0)),
8242                           DAG.getSrcValue(I.getArgOperand(1))));
8243 }
8244 
8245 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8246                                                     const Instruction &I,
8247                                                     SDValue Op) {
8248   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8249   if (!Range)
8250     return Op;
8251 
8252   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8253   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
8254     return Op;
8255 
8256   APInt Lo = CR.getUnsignedMin();
8257   if (!Lo.isMinValue())
8258     return Op;
8259 
8260   APInt Hi = CR.getUnsignedMax();
8261   unsigned Bits = std::max(Hi.getActiveBits(),
8262                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8263 
8264   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8265 
8266   SDLoc SL = getCurSDLoc();
8267 
8268   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8269                              DAG.getValueType(SmallVT));
8270   unsigned NumVals = Op.getNode()->getNumValues();
8271   if (NumVals == 1)
8272     return ZExt;
8273 
8274   SmallVector<SDValue, 4> Ops;
8275 
8276   Ops.push_back(ZExt);
8277   for (unsigned I = 1; I != NumVals; ++I)
8278     Ops.push_back(Op.getValue(I));
8279 
8280   return DAG.getMergeValues(Ops, SL);
8281 }
8282 
8283 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8284 /// the call being lowered.
8285 ///
8286 /// This is a helper for lowering intrinsics that follow a target calling
8287 /// convention or require stack pointer adjustment. Only a subset of the
8288 /// intrinsic's operands need to participate in the calling convention.
8289 void SelectionDAGBuilder::populateCallLoweringInfo(
8290     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8291     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8292     bool IsPatchPoint) {
8293   TargetLowering::ArgListTy Args;
8294   Args.reserve(NumArgs);
8295 
8296   // Populate the argument list.
8297   // Attributes for args start at offset 1, after the return attribute.
8298   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8299        ArgI != ArgE; ++ArgI) {
8300     const Value *V = Call->getOperand(ArgI);
8301 
8302     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8303 
8304     TargetLowering::ArgListEntry Entry;
8305     Entry.Node = getValue(V);
8306     Entry.Ty = V->getType();
8307     Entry.setAttributes(Call, ArgI);
8308     Args.push_back(Entry);
8309   }
8310 
8311   CLI.setDebugLoc(getCurSDLoc())
8312       .setChain(getRoot())
8313       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8314       .setDiscardResult(Call->use_empty())
8315       .setIsPatchPoint(IsPatchPoint);
8316 }
8317 
8318 /// Add a stack map intrinsic call's live variable operands to a stackmap
8319 /// or patchpoint target node's operand list.
8320 ///
8321 /// Constants are converted to TargetConstants purely as an optimization to
8322 /// avoid constant materialization and register allocation.
8323 ///
8324 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8325 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8326 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8327 /// address materialization and register allocation, but may also be required
8328 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8329 /// alloca in the entry block, then the runtime may assume that the alloca's
8330 /// StackMap location can be read immediately after compilation and that the
8331 /// location is valid at any point during execution (this is similar to the
8332 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8333 /// only available in a register, then the runtime would need to trap when
8334 /// execution reaches the StackMap in order to read the alloca's location.
8335 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8336                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8337                                 SelectionDAGBuilder &Builder) {
8338   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8339     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8340     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8341       Ops.push_back(
8342         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8343       Ops.push_back(
8344         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8345     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8346       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8347       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8348           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8349     } else
8350       Ops.push_back(OpVal);
8351   }
8352 }
8353 
8354 /// Lower llvm.experimental.stackmap directly to its target opcode.
8355 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8356   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8357   //                                  [live variables...])
8358 
8359   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8360 
8361   SDValue Chain, InFlag, Callee, NullPtr;
8362   SmallVector<SDValue, 32> Ops;
8363 
8364   SDLoc DL = getCurSDLoc();
8365   Callee = getValue(CI.getCalledValue());
8366   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8367 
8368   // The stackmap intrinsic only records the live variables (the arguemnts
8369   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8370   // intrinsic, this won't be lowered to a function call. This means we don't
8371   // have to worry about calling conventions and target specific lowering code.
8372   // Instead we perform the call lowering right here.
8373   //
8374   // chain, flag = CALLSEQ_START(chain, 0, 0)
8375   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8376   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8377   //
8378   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8379   InFlag = Chain.getValue(1);
8380 
8381   // Add the <id> and <numBytes> constants.
8382   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8383   Ops.push_back(DAG.getTargetConstant(
8384                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8385   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8386   Ops.push_back(DAG.getTargetConstant(
8387                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8388                   MVT::i32));
8389 
8390   // Push live variables for the stack map.
8391   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8392 
8393   // We are not pushing any register mask info here on the operands list,
8394   // because the stackmap doesn't clobber anything.
8395 
8396   // Push the chain and the glue flag.
8397   Ops.push_back(Chain);
8398   Ops.push_back(InFlag);
8399 
8400   // Create the STACKMAP node.
8401   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8402   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8403   Chain = SDValue(SM, 0);
8404   InFlag = Chain.getValue(1);
8405 
8406   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8407 
8408   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8409 
8410   // Set the root to the target-lowered call chain.
8411   DAG.setRoot(Chain);
8412 
8413   // Inform the Frame Information that we have a stackmap in this function.
8414   FuncInfo.MF->getFrameInfo().setHasStackMap();
8415 }
8416 
8417 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8418 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8419                                           const BasicBlock *EHPadBB) {
8420   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8421   //                                                 i32 <numBytes>,
8422   //                                                 i8* <target>,
8423   //                                                 i32 <numArgs>,
8424   //                                                 [Args...],
8425   //                                                 [live variables...])
8426 
8427   CallingConv::ID CC = CS.getCallingConv();
8428   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8429   bool HasDef = !CS->getType()->isVoidTy();
8430   SDLoc dl = getCurSDLoc();
8431   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8432 
8433   // Handle immediate and symbolic callees.
8434   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8435     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8436                                    /*isTarget=*/true);
8437   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8438     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8439                                          SDLoc(SymbolicCallee),
8440                                          SymbolicCallee->getValueType(0));
8441 
8442   // Get the real number of arguments participating in the call <numArgs>
8443   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8444   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8445 
8446   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8447   // Intrinsics include all meta-operands up to but not including CC.
8448   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8449   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8450          "Not enough arguments provided to the patchpoint intrinsic");
8451 
8452   // For AnyRegCC the arguments are lowered later on manually.
8453   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8454   Type *ReturnTy =
8455     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8456 
8457   TargetLowering::CallLoweringInfo CLI(DAG);
8458   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8459                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8460   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8461 
8462   SDNode *CallEnd = Result.second.getNode();
8463   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8464     CallEnd = CallEnd->getOperand(0).getNode();
8465 
8466   /// Get a call instruction from the call sequence chain.
8467   /// Tail calls are not allowed.
8468   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8469          "Expected a callseq node.");
8470   SDNode *Call = CallEnd->getOperand(0).getNode();
8471   bool HasGlue = Call->getGluedNode();
8472 
8473   // Replace the target specific call node with the patchable intrinsic.
8474   SmallVector<SDValue, 8> Ops;
8475 
8476   // Add the <id> and <numBytes> constants.
8477   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8478   Ops.push_back(DAG.getTargetConstant(
8479                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8480   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8481   Ops.push_back(DAG.getTargetConstant(
8482                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8483                   MVT::i32));
8484 
8485   // Add the callee.
8486   Ops.push_back(Callee);
8487 
8488   // Adjust <numArgs> to account for any arguments that have been passed on the
8489   // stack instead.
8490   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8491   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8492   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8493   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8494 
8495   // Add the calling convention
8496   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8497 
8498   // Add the arguments we omitted previously. The register allocator should
8499   // place these in any free register.
8500   if (IsAnyRegCC)
8501     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8502       Ops.push_back(getValue(CS.getArgument(i)));
8503 
8504   // Push the arguments from the call instruction up to the register mask.
8505   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8506   Ops.append(Call->op_begin() + 2, e);
8507 
8508   // Push live variables for the stack map.
8509   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8510 
8511   // Push the register mask info.
8512   if (HasGlue)
8513     Ops.push_back(*(Call->op_end()-2));
8514   else
8515     Ops.push_back(*(Call->op_end()-1));
8516 
8517   // Push the chain (this is originally the first operand of the call, but
8518   // becomes now the last or second to last operand).
8519   Ops.push_back(*(Call->op_begin()));
8520 
8521   // Push the glue flag (last operand).
8522   if (HasGlue)
8523     Ops.push_back(*(Call->op_end()-1));
8524 
8525   SDVTList NodeTys;
8526   if (IsAnyRegCC && HasDef) {
8527     // Create the return types based on the intrinsic definition
8528     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8529     SmallVector<EVT, 3> ValueVTs;
8530     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8531     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8532 
8533     // There is always a chain and a glue type at the end
8534     ValueVTs.push_back(MVT::Other);
8535     ValueVTs.push_back(MVT::Glue);
8536     NodeTys = DAG.getVTList(ValueVTs);
8537   } else
8538     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8539 
8540   // Replace the target specific call node with a PATCHPOINT node.
8541   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8542                                          dl, NodeTys, Ops);
8543 
8544   // Update the NodeMap.
8545   if (HasDef) {
8546     if (IsAnyRegCC)
8547       setValue(CS.getInstruction(), SDValue(MN, 0));
8548     else
8549       setValue(CS.getInstruction(), Result.first);
8550   }
8551 
8552   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8553   // call sequence. Furthermore the location of the chain and glue can change
8554   // when the AnyReg calling convention is used and the intrinsic returns a
8555   // value.
8556   if (IsAnyRegCC && HasDef) {
8557     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8558     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8559     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8560   } else
8561     DAG.ReplaceAllUsesWith(Call, MN);
8562   DAG.DeleteNode(Call);
8563 
8564   // Inform the Frame Information that we have a patchpoint in this function.
8565   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8566 }
8567 
8568 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8569                                             unsigned Intrinsic) {
8570   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8571   SDValue Op1 = getValue(I.getArgOperand(0));
8572   SDValue Op2;
8573   if (I.getNumArgOperands() > 1)
8574     Op2 = getValue(I.getArgOperand(1));
8575   SDLoc dl = getCurSDLoc();
8576   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8577   SDValue Res;
8578   FastMathFlags FMF;
8579   if (isa<FPMathOperator>(I))
8580     FMF = I.getFastMathFlags();
8581 
8582   switch (Intrinsic) {
8583   case Intrinsic::experimental_vector_reduce_fadd:
8584     if (FMF.isFast())
8585       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8586     else
8587       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8588     break;
8589   case Intrinsic::experimental_vector_reduce_fmul:
8590     if (FMF.isFast())
8591       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8592     else
8593       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8594     break;
8595   case Intrinsic::experimental_vector_reduce_add:
8596     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8597     break;
8598   case Intrinsic::experimental_vector_reduce_mul:
8599     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8600     break;
8601   case Intrinsic::experimental_vector_reduce_and:
8602     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8603     break;
8604   case Intrinsic::experimental_vector_reduce_or:
8605     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8606     break;
8607   case Intrinsic::experimental_vector_reduce_xor:
8608     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8609     break;
8610   case Intrinsic::experimental_vector_reduce_smax:
8611     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8612     break;
8613   case Intrinsic::experimental_vector_reduce_smin:
8614     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8615     break;
8616   case Intrinsic::experimental_vector_reduce_umax:
8617     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8618     break;
8619   case Intrinsic::experimental_vector_reduce_umin:
8620     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8621     break;
8622   case Intrinsic::experimental_vector_reduce_fmax:
8623     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8624     break;
8625   case Intrinsic::experimental_vector_reduce_fmin:
8626     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8627     break;
8628   default:
8629     llvm_unreachable("Unhandled vector reduce intrinsic");
8630   }
8631   setValue(&I, Res);
8632 }
8633 
8634 /// Returns an AttributeList representing the attributes applied to the return
8635 /// value of the given call.
8636 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8637   SmallVector<Attribute::AttrKind, 2> Attrs;
8638   if (CLI.RetSExt)
8639     Attrs.push_back(Attribute::SExt);
8640   if (CLI.RetZExt)
8641     Attrs.push_back(Attribute::ZExt);
8642   if (CLI.IsInReg)
8643     Attrs.push_back(Attribute::InReg);
8644 
8645   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8646                             Attrs);
8647 }
8648 
8649 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8650 /// implementation, which just calls LowerCall.
8651 /// FIXME: When all targets are
8652 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8653 std::pair<SDValue, SDValue>
8654 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8655   // Handle the incoming return values from the call.
8656   CLI.Ins.clear();
8657   Type *OrigRetTy = CLI.RetTy;
8658   SmallVector<EVT, 4> RetTys;
8659   SmallVector<uint64_t, 4> Offsets;
8660   auto &DL = CLI.DAG.getDataLayout();
8661   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8662 
8663   if (CLI.IsPostTypeLegalization) {
8664     // If we are lowering a libcall after legalization, split the return type.
8665     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8666     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8667     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8668       EVT RetVT = OldRetTys[i];
8669       uint64_t Offset = OldOffsets[i];
8670       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8671       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8672       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8673       RetTys.append(NumRegs, RegisterVT);
8674       for (unsigned j = 0; j != NumRegs; ++j)
8675         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8676     }
8677   }
8678 
8679   SmallVector<ISD::OutputArg, 4> Outs;
8680   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8681 
8682   bool CanLowerReturn =
8683       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8684                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8685 
8686   SDValue DemoteStackSlot;
8687   int DemoteStackIdx = -100;
8688   if (!CanLowerReturn) {
8689     // FIXME: equivalent assert?
8690     // assert(!CS.hasInAllocaArgument() &&
8691     //        "sret demotion is incompatible with inalloca");
8692     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8693     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8694     MachineFunction &MF = CLI.DAG.getMachineFunction();
8695     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8696     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8697                                               DL.getAllocaAddrSpace());
8698 
8699     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8700     ArgListEntry Entry;
8701     Entry.Node = DemoteStackSlot;
8702     Entry.Ty = StackSlotPtrType;
8703     Entry.IsSExt = false;
8704     Entry.IsZExt = false;
8705     Entry.IsInReg = false;
8706     Entry.IsSRet = true;
8707     Entry.IsNest = false;
8708     Entry.IsByVal = false;
8709     Entry.IsReturned = false;
8710     Entry.IsSwiftSelf = false;
8711     Entry.IsSwiftError = false;
8712     Entry.Alignment = Align;
8713     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8714     CLI.NumFixedArgs += 1;
8715     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8716 
8717     // sret demotion isn't compatible with tail-calls, since the sret argument
8718     // points into the callers stack frame.
8719     CLI.IsTailCall = false;
8720   } else {
8721     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8722       EVT VT = RetTys[I];
8723       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8724                                                      CLI.CallConv, VT);
8725       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8726                                                        CLI.CallConv, VT);
8727       for (unsigned i = 0; i != NumRegs; ++i) {
8728         ISD::InputArg MyFlags;
8729         MyFlags.VT = RegisterVT;
8730         MyFlags.ArgVT = VT;
8731         MyFlags.Used = CLI.IsReturnValueUsed;
8732         if (CLI.RetSExt)
8733           MyFlags.Flags.setSExt();
8734         if (CLI.RetZExt)
8735           MyFlags.Flags.setZExt();
8736         if (CLI.IsInReg)
8737           MyFlags.Flags.setInReg();
8738         CLI.Ins.push_back(MyFlags);
8739       }
8740     }
8741   }
8742 
8743   // We push in swifterror return as the last element of CLI.Ins.
8744   ArgListTy &Args = CLI.getArgs();
8745   if (supportSwiftError()) {
8746     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8747       if (Args[i].IsSwiftError) {
8748         ISD::InputArg MyFlags;
8749         MyFlags.VT = getPointerTy(DL);
8750         MyFlags.ArgVT = EVT(getPointerTy(DL));
8751         MyFlags.Flags.setSwiftError();
8752         CLI.Ins.push_back(MyFlags);
8753       }
8754     }
8755   }
8756 
8757   // Handle all of the outgoing arguments.
8758   CLI.Outs.clear();
8759   CLI.OutVals.clear();
8760   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8761     SmallVector<EVT, 4> ValueVTs;
8762     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8763     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8764     Type *FinalType = Args[i].Ty;
8765     if (Args[i].IsByVal)
8766       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8767     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8768         FinalType, CLI.CallConv, CLI.IsVarArg);
8769     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8770          ++Value) {
8771       EVT VT = ValueVTs[Value];
8772       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8773       SDValue Op = SDValue(Args[i].Node.getNode(),
8774                            Args[i].Node.getResNo() + Value);
8775       ISD::ArgFlagsTy Flags;
8776 
8777       // Certain targets (such as MIPS), may have a different ABI alignment
8778       // for a type depending on the context. Give the target a chance to
8779       // specify the alignment it wants.
8780       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8781 
8782       if (Args[i].IsZExt)
8783         Flags.setZExt();
8784       if (Args[i].IsSExt)
8785         Flags.setSExt();
8786       if (Args[i].IsInReg) {
8787         // If we are using vectorcall calling convention, a structure that is
8788         // passed InReg - is surely an HVA
8789         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8790             isa<StructType>(FinalType)) {
8791           // The first value of a structure is marked
8792           if (0 == Value)
8793             Flags.setHvaStart();
8794           Flags.setHva();
8795         }
8796         // Set InReg Flag
8797         Flags.setInReg();
8798       }
8799       if (Args[i].IsSRet)
8800         Flags.setSRet();
8801       if (Args[i].IsSwiftSelf)
8802         Flags.setSwiftSelf();
8803       if (Args[i].IsSwiftError)
8804         Flags.setSwiftError();
8805       if (Args[i].IsByVal)
8806         Flags.setByVal();
8807       if (Args[i].IsInAlloca) {
8808         Flags.setInAlloca();
8809         // Set the byval flag for CCAssignFn callbacks that don't know about
8810         // inalloca.  This way we can know how many bytes we should've allocated
8811         // and how many bytes a callee cleanup function will pop.  If we port
8812         // inalloca to more targets, we'll have to add custom inalloca handling
8813         // in the various CC lowering callbacks.
8814         Flags.setByVal();
8815       }
8816       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8817         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8818         Type *ElementTy = Ty->getElementType();
8819         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8820         // For ByVal, alignment should come from FE.  BE will guess if this
8821         // info is not there but there are cases it cannot get right.
8822         unsigned FrameAlign;
8823         if (Args[i].Alignment)
8824           FrameAlign = Args[i].Alignment;
8825         else
8826           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8827         Flags.setByValAlign(FrameAlign);
8828       }
8829       if (Args[i].IsNest)
8830         Flags.setNest();
8831       if (NeedsRegBlock)
8832         Flags.setInConsecutiveRegs();
8833       Flags.setOrigAlign(OriginalAlignment);
8834 
8835       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8836                                                  CLI.CallConv, VT);
8837       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8838                                                         CLI.CallConv, VT);
8839       SmallVector<SDValue, 4> Parts(NumParts);
8840       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8841 
8842       if (Args[i].IsSExt)
8843         ExtendKind = ISD::SIGN_EXTEND;
8844       else if (Args[i].IsZExt)
8845         ExtendKind = ISD::ZERO_EXTEND;
8846 
8847       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8848       // for now.
8849       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8850           CanLowerReturn) {
8851         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8852                "unexpected use of 'returned'");
8853         // Before passing 'returned' to the target lowering code, ensure that
8854         // either the register MVT and the actual EVT are the same size or that
8855         // the return value and argument are extended in the same way; in these
8856         // cases it's safe to pass the argument register value unchanged as the
8857         // return register value (although it's at the target's option whether
8858         // to do so)
8859         // TODO: allow code generation to take advantage of partially preserved
8860         // registers rather than clobbering the entire register when the
8861         // parameter extension method is not compatible with the return
8862         // extension method
8863         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8864             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8865              CLI.RetZExt == Args[i].IsZExt))
8866           Flags.setReturned();
8867       }
8868 
8869       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8870                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
8871 
8872       for (unsigned j = 0; j != NumParts; ++j) {
8873         // if it isn't first piece, alignment must be 1
8874         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8875                                i < CLI.NumFixedArgs,
8876                                i, j*Parts[j].getValueType().getStoreSize());
8877         if (NumParts > 1 && j == 0)
8878           MyFlags.Flags.setSplit();
8879         else if (j != 0) {
8880           MyFlags.Flags.setOrigAlign(1);
8881           if (j == NumParts - 1)
8882             MyFlags.Flags.setSplitEnd();
8883         }
8884 
8885         CLI.Outs.push_back(MyFlags);
8886         CLI.OutVals.push_back(Parts[j]);
8887       }
8888 
8889       if (NeedsRegBlock && Value == NumValues - 1)
8890         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8891     }
8892   }
8893 
8894   SmallVector<SDValue, 4> InVals;
8895   CLI.Chain = LowerCall(CLI, InVals);
8896 
8897   // Update CLI.InVals to use outside of this function.
8898   CLI.InVals = InVals;
8899 
8900   // Verify that the target's LowerCall behaved as expected.
8901   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8902          "LowerCall didn't return a valid chain!");
8903   assert((!CLI.IsTailCall || InVals.empty()) &&
8904          "LowerCall emitted a return value for a tail call!");
8905   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8906          "LowerCall didn't emit the correct number of values!");
8907 
8908   // For a tail call, the return value is merely live-out and there aren't
8909   // any nodes in the DAG representing it. Return a special value to
8910   // indicate that a tail call has been emitted and no more Instructions
8911   // should be processed in the current block.
8912   if (CLI.IsTailCall) {
8913     CLI.DAG.setRoot(CLI.Chain);
8914     return std::make_pair(SDValue(), SDValue());
8915   }
8916 
8917 #ifndef NDEBUG
8918   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8919     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8920     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8921            "LowerCall emitted a value with the wrong type!");
8922   }
8923 #endif
8924 
8925   SmallVector<SDValue, 4> ReturnValues;
8926   if (!CanLowerReturn) {
8927     // The instruction result is the result of loading from the
8928     // hidden sret parameter.
8929     SmallVector<EVT, 1> PVTs;
8930     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8931 
8932     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8933     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8934     EVT PtrVT = PVTs[0];
8935 
8936     unsigned NumValues = RetTys.size();
8937     ReturnValues.resize(NumValues);
8938     SmallVector<SDValue, 4> Chains(NumValues);
8939 
8940     // An aggregate return value cannot wrap around the address space, so
8941     // offsets to its parts don't wrap either.
8942     SDNodeFlags Flags;
8943     Flags.setNoUnsignedWrap(true);
8944 
8945     for (unsigned i = 0; i < NumValues; ++i) {
8946       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8947                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8948                                                         PtrVT), Flags);
8949       SDValue L = CLI.DAG.getLoad(
8950           RetTys[i], CLI.DL, CLI.Chain, Add,
8951           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8952                                             DemoteStackIdx, Offsets[i]),
8953           /* Alignment = */ 1);
8954       ReturnValues[i] = L;
8955       Chains[i] = L.getValue(1);
8956     }
8957 
8958     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8959   } else {
8960     // Collect the legal value parts into potentially illegal values
8961     // that correspond to the original function's return values.
8962     Optional<ISD::NodeType> AssertOp;
8963     if (CLI.RetSExt)
8964       AssertOp = ISD::AssertSext;
8965     else if (CLI.RetZExt)
8966       AssertOp = ISD::AssertZext;
8967     unsigned CurReg = 0;
8968     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8969       EVT VT = RetTys[I];
8970       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8971                                                      CLI.CallConv, VT);
8972       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8973                                                        CLI.CallConv, VT);
8974 
8975       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8976                                               NumRegs, RegisterVT, VT, nullptr,
8977                                               CLI.CallConv, AssertOp));
8978       CurReg += NumRegs;
8979     }
8980 
8981     // For a function returning void, there is no return value. We can't create
8982     // such a node, so we just return a null return value in that case. In
8983     // that case, nothing will actually look at the value.
8984     if (ReturnValues.empty())
8985       return std::make_pair(SDValue(), CLI.Chain);
8986   }
8987 
8988   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8989                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8990   return std::make_pair(Res, CLI.Chain);
8991 }
8992 
8993 void TargetLowering::LowerOperationWrapper(SDNode *N,
8994                                            SmallVectorImpl<SDValue> &Results,
8995                                            SelectionDAG &DAG) const {
8996   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8997     Results.push_back(Res);
8998 }
8999 
9000 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9001   llvm_unreachable("LowerOperation not implemented for this target!");
9002 }
9003 
9004 void
9005 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9006   SDValue Op = getNonRegisterValue(V);
9007   assert((Op.getOpcode() != ISD::CopyFromReg ||
9008           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9009          "Copy from a reg to the same reg!");
9010   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
9011 
9012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9013   // If this is an InlineAsm we have to match the registers required, not the
9014   // notional registers required by the type.
9015 
9016   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9017                    None); // This is not an ABI copy.
9018   SDValue Chain = DAG.getEntryNode();
9019 
9020   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9021                               FuncInfo.PreferredExtendType.end())
9022                                  ? ISD::ANY_EXTEND
9023                                  : FuncInfo.PreferredExtendType[V];
9024   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9025   PendingExports.push_back(Chain);
9026 }
9027 
9028 #include "llvm/CodeGen/SelectionDAGISel.h"
9029 
9030 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9031 /// entry block, return true.  This includes arguments used by switches, since
9032 /// the switch may expand into multiple basic blocks.
9033 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9034   // With FastISel active, we may be splitting blocks, so force creation
9035   // of virtual registers for all non-dead arguments.
9036   if (FastISel)
9037     return A->use_empty();
9038 
9039   const BasicBlock &Entry = A->getParent()->front();
9040   for (const User *U : A->users())
9041     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9042       return false;  // Use not in entry block.
9043 
9044   return true;
9045 }
9046 
9047 using ArgCopyElisionMapTy =
9048     DenseMap<const Argument *,
9049              std::pair<const AllocaInst *, const StoreInst *>>;
9050 
9051 /// Scan the entry block of the function in FuncInfo for arguments that look
9052 /// like copies into a local alloca. Record any copied arguments in
9053 /// ArgCopyElisionCandidates.
9054 static void
9055 findArgumentCopyElisionCandidates(const DataLayout &DL,
9056                                   FunctionLoweringInfo *FuncInfo,
9057                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9058   // Record the state of every static alloca used in the entry block. Argument
9059   // allocas are all used in the entry block, so we need approximately as many
9060   // entries as we have arguments.
9061   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9062   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9063   unsigned NumArgs = FuncInfo->Fn->arg_size();
9064   StaticAllocas.reserve(NumArgs * 2);
9065 
9066   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9067     if (!V)
9068       return nullptr;
9069     V = V->stripPointerCasts();
9070     const auto *AI = dyn_cast<AllocaInst>(V);
9071     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9072       return nullptr;
9073     auto Iter = StaticAllocas.insert({AI, Unknown});
9074     return &Iter.first->second;
9075   };
9076 
9077   // Look for stores of arguments to static allocas. Look through bitcasts and
9078   // GEPs to handle type coercions, as long as the alloca is fully initialized
9079   // by the store. Any non-store use of an alloca escapes it and any subsequent
9080   // unanalyzed store might write it.
9081   // FIXME: Handle structs initialized with multiple stores.
9082   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9083     // Look for stores, and handle non-store uses conservatively.
9084     const auto *SI = dyn_cast<StoreInst>(&I);
9085     if (!SI) {
9086       // We will look through cast uses, so ignore them completely.
9087       if (I.isCast())
9088         continue;
9089       // Ignore debug info intrinsics, they don't escape or store to allocas.
9090       if (isa<DbgInfoIntrinsic>(I))
9091         continue;
9092       // This is an unknown instruction. Assume it escapes or writes to all
9093       // static alloca operands.
9094       for (const Use &U : I.operands()) {
9095         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9096           *Info = StaticAllocaInfo::Clobbered;
9097       }
9098       continue;
9099     }
9100 
9101     // If the stored value is a static alloca, mark it as escaped.
9102     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9103       *Info = StaticAllocaInfo::Clobbered;
9104 
9105     // Check if the destination is a static alloca.
9106     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9107     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9108     if (!Info)
9109       continue;
9110     const AllocaInst *AI = cast<AllocaInst>(Dst);
9111 
9112     // Skip allocas that have been initialized or clobbered.
9113     if (*Info != StaticAllocaInfo::Unknown)
9114       continue;
9115 
9116     // Check if the stored value is an argument, and that this store fully
9117     // initializes the alloca. Don't elide copies from the same argument twice.
9118     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9119     const auto *Arg = dyn_cast<Argument>(Val);
9120     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9121         Arg->getType()->isEmptyTy() ||
9122         DL.getTypeStoreSize(Arg->getType()) !=
9123             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9124         ArgCopyElisionCandidates.count(Arg)) {
9125       *Info = StaticAllocaInfo::Clobbered;
9126       continue;
9127     }
9128 
9129     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9130                       << '\n');
9131 
9132     // Mark this alloca and store for argument copy elision.
9133     *Info = StaticAllocaInfo::Elidable;
9134     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9135 
9136     // Stop scanning if we've seen all arguments. This will happen early in -O0
9137     // builds, which is useful, because -O0 builds have large entry blocks and
9138     // many allocas.
9139     if (ArgCopyElisionCandidates.size() == NumArgs)
9140       break;
9141   }
9142 }
9143 
9144 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9145 /// ArgVal is a load from a suitable fixed stack object.
9146 static void tryToElideArgumentCopy(
9147     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9148     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9149     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9150     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9151     SDValue ArgVal, bool &ArgHasUses) {
9152   // Check if this is a load from a fixed stack object.
9153   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9154   if (!LNode)
9155     return;
9156   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9157   if (!FINode)
9158     return;
9159 
9160   // Check that the fixed stack object is the right size and alignment.
9161   // Look at the alignment that the user wrote on the alloca instead of looking
9162   // at the stack object.
9163   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9164   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9165   const AllocaInst *AI = ArgCopyIter->second.first;
9166   int FixedIndex = FINode->getIndex();
9167   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9168   int OldIndex = AllocaIndex;
9169   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9170   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9171     LLVM_DEBUG(
9172         dbgs() << "  argument copy elision failed due to bad fixed stack "
9173                   "object size\n");
9174     return;
9175   }
9176   unsigned RequiredAlignment = AI->getAlignment();
9177   if (!RequiredAlignment) {
9178     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9179         AI->getAllocatedType());
9180   }
9181   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9182     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9183                          "greater than stack argument alignment ("
9184                       << RequiredAlignment << " vs "
9185                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9186     return;
9187   }
9188 
9189   // Perform the elision. Delete the old stack object and replace its only use
9190   // in the variable info map. Mark the stack object as mutable.
9191   LLVM_DEBUG({
9192     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9193            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9194            << '\n';
9195   });
9196   MFI.RemoveStackObject(OldIndex);
9197   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9198   AllocaIndex = FixedIndex;
9199   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9200   Chains.push_back(ArgVal.getValue(1));
9201 
9202   // Avoid emitting code for the store implementing the copy.
9203   const StoreInst *SI = ArgCopyIter->second.second;
9204   ElidedArgCopyInstrs.insert(SI);
9205 
9206   // Check for uses of the argument again so that we can avoid exporting ArgVal
9207   // if it is't used by anything other than the store.
9208   for (const Value *U : Arg.users()) {
9209     if (U != SI) {
9210       ArgHasUses = true;
9211       break;
9212     }
9213   }
9214 }
9215 
9216 void SelectionDAGISel::LowerArguments(const Function &F) {
9217   SelectionDAG &DAG = SDB->DAG;
9218   SDLoc dl = SDB->getCurSDLoc();
9219   const DataLayout &DL = DAG.getDataLayout();
9220   SmallVector<ISD::InputArg, 16> Ins;
9221 
9222   if (!FuncInfo->CanLowerReturn) {
9223     // Put in an sret pointer parameter before all the other parameters.
9224     SmallVector<EVT, 1> ValueVTs;
9225     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9226                     F.getReturnType()->getPointerTo(
9227                         DAG.getDataLayout().getAllocaAddrSpace()),
9228                     ValueVTs);
9229 
9230     // NOTE: Assuming that a pointer will never break down to more than one VT
9231     // or one register.
9232     ISD::ArgFlagsTy Flags;
9233     Flags.setSRet();
9234     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9235     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9236                          ISD::InputArg::NoArgIndex, 0);
9237     Ins.push_back(RetArg);
9238   }
9239 
9240   // Look for stores of arguments to static allocas. Mark such arguments with a
9241   // flag to ask the target to give us the memory location of that argument if
9242   // available.
9243   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9244   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9245 
9246   // Set up the incoming argument description vector.
9247   for (const Argument &Arg : F.args()) {
9248     unsigned ArgNo = Arg.getArgNo();
9249     SmallVector<EVT, 4> ValueVTs;
9250     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9251     bool isArgValueUsed = !Arg.use_empty();
9252     unsigned PartBase = 0;
9253     Type *FinalType = Arg.getType();
9254     if (Arg.hasAttribute(Attribute::ByVal))
9255       FinalType = cast<PointerType>(FinalType)->getElementType();
9256     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9257         FinalType, F.getCallingConv(), F.isVarArg());
9258     for (unsigned Value = 0, NumValues = ValueVTs.size();
9259          Value != NumValues; ++Value) {
9260       EVT VT = ValueVTs[Value];
9261       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9262       ISD::ArgFlagsTy Flags;
9263 
9264       // Certain targets (such as MIPS), may have a different ABI alignment
9265       // for a type depending on the context. Give the target a chance to
9266       // specify the alignment it wants.
9267       unsigned OriginalAlignment =
9268           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9269 
9270       if (Arg.hasAttribute(Attribute::ZExt))
9271         Flags.setZExt();
9272       if (Arg.hasAttribute(Attribute::SExt))
9273         Flags.setSExt();
9274       if (Arg.hasAttribute(Attribute::InReg)) {
9275         // If we are using vectorcall calling convention, a structure that is
9276         // passed InReg - is surely an HVA
9277         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9278             isa<StructType>(Arg.getType())) {
9279           // The first value of a structure is marked
9280           if (0 == Value)
9281             Flags.setHvaStart();
9282           Flags.setHva();
9283         }
9284         // Set InReg Flag
9285         Flags.setInReg();
9286       }
9287       if (Arg.hasAttribute(Attribute::StructRet))
9288         Flags.setSRet();
9289       if (Arg.hasAttribute(Attribute::SwiftSelf))
9290         Flags.setSwiftSelf();
9291       if (Arg.hasAttribute(Attribute::SwiftError))
9292         Flags.setSwiftError();
9293       if (Arg.hasAttribute(Attribute::ByVal))
9294         Flags.setByVal();
9295       if (Arg.hasAttribute(Attribute::InAlloca)) {
9296         Flags.setInAlloca();
9297         // Set the byval flag for CCAssignFn callbacks that don't know about
9298         // inalloca.  This way we can know how many bytes we should've allocated
9299         // and how many bytes a callee cleanup function will pop.  If we port
9300         // inalloca to more targets, we'll have to add custom inalloca handling
9301         // in the various CC lowering callbacks.
9302         Flags.setByVal();
9303       }
9304       if (F.getCallingConv() == CallingConv::X86_INTR) {
9305         // IA Interrupt passes frame (1st parameter) by value in the stack.
9306         if (ArgNo == 0)
9307           Flags.setByVal();
9308       }
9309       if (Flags.isByVal() || Flags.isInAlloca()) {
9310         PointerType *Ty = cast<PointerType>(Arg.getType());
9311         Type *ElementTy = Ty->getElementType();
9312         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
9313         // For ByVal, alignment should be passed from FE.  BE will guess if
9314         // this info is not there but there are cases it cannot get right.
9315         unsigned FrameAlign;
9316         if (Arg.getParamAlignment())
9317           FrameAlign = Arg.getParamAlignment();
9318         else
9319           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9320         Flags.setByValAlign(FrameAlign);
9321       }
9322       if (Arg.hasAttribute(Attribute::Nest))
9323         Flags.setNest();
9324       if (NeedsRegBlock)
9325         Flags.setInConsecutiveRegs();
9326       Flags.setOrigAlign(OriginalAlignment);
9327       if (ArgCopyElisionCandidates.count(&Arg))
9328         Flags.setCopyElisionCandidate();
9329 
9330       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9331           *CurDAG->getContext(), F.getCallingConv(), VT);
9332       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9333           *CurDAG->getContext(), F.getCallingConv(), VT);
9334       for (unsigned i = 0; i != NumRegs; ++i) {
9335         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9336                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9337         if (NumRegs > 1 && i == 0)
9338           MyFlags.Flags.setSplit();
9339         // if it isn't first piece, alignment must be 1
9340         else if (i > 0) {
9341           MyFlags.Flags.setOrigAlign(1);
9342           if (i == NumRegs - 1)
9343             MyFlags.Flags.setSplitEnd();
9344         }
9345         Ins.push_back(MyFlags);
9346       }
9347       if (NeedsRegBlock && Value == NumValues - 1)
9348         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9349       PartBase += VT.getStoreSize();
9350     }
9351   }
9352 
9353   // Call the target to set up the argument values.
9354   SmallVector<SDValue, 8> InVals;
9355   SDValue NewRoot = TLI->LowerFormalArguments(
9356       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9357 
9358   // Verify that the target's LowerFormalArguments behaved as expected.
9359   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9360          "LowerFormalArguments didn't return a valid chain!");
9361   assert(InVals.size() == Ins.size() &&
9362          "LowerFormalArguments didn't emit the correct number of values!");
9363   LLVM_DEBUG({
9364     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9365       assert(InVals[i].getNode() &&
9366              "LowerFormalArguments emitted a null value!");
9367       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9368              "LowerFormalArguments emitted a value with the wrong type!");
9369     }
9370   });
9371 
9372   // Update the DAG with the new chain value resulting from argument lowering.
9373   DAG.setRoot(NewRoot);
9374 
9375   // Set up the argument values.
9376   unsigned i = 0;
9377   if (!FuncInfo->CanLowerReturn) {
9378     // Create a virtual register for the sret pointer, and put in a copy
9379     // from the sret argument into it.
9380     SmallVector<EVT, 1> ValueVTs;
9381     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9382                     F.getReturnType()->getPointerTo(
9383                         DAG.getDataLayout().getAllocaAddrSpace()),
9384                     ValueVTs);
9385     MVT VT = ValueVTs[0].getSimpleVT();
9386     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9387     Optional<ISD::NodeType> AssertOp = None;
9388     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9389                                         nullptr, F.getCallingConv(), AssertOp);
9390 
9391     MachineFunction& MF = SDB->DAG.getMachineFunction();
9392     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9393     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9394     FuncInfo->DemoteRegister = SRetReg;
9395     NewRoot =
9396         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9397     DAG.setRoot(NewRoot);
9398 
9399     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9400     ++i;
9401   }
9402 
9403   SmallVector<SDValue, 4> Chains;
9404   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9405   for (const Argument &Arg : F.args()) {
9406     SmallVector<SDValue, 4> ArgValues;
9407     SmallVector<EVT, 4> ValueVTs;
9408     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9409     unsigned NumValues = ValueVTs.size();
9410     if (NumValues == 0)
9411       continue;
9412 
9413     bool ArgHasUses = !Arg.use_empty();
9414 
9415     // Elide the copying store if the target loaded this argument from a
9416     // suitable fixed stack object.
9417     if (Ins[i].Flags.isCopyElisionCandidate()) {
9418       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9419                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9420                              InVals[i], ArgHasUses);
9421     }
9422 
9423     // If this argument is unused then remember its value. It is used to generate
9424     // debugging information.
9425     bool isSwiftErrorArg =
9426         TLI->supportSwiftError() &&
9427         Arg.hasAttribute(Attribute::SwiftError);
9428     if (!ArgHasUses && !isSwiftErrorArg) {
9429       SDB->setUnusedArgValue(&Arg, InVals[i]);
9430 
9431       // Also remember any frame index for use in FastISel.
9432       if (FrameIndexSDNode *FI =
9433           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9434         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9435     }
9436 
9437     for (unsigned Val = 0; Val != NumValues; ++Val) {
9438       EVT VT = ValueVTs[Val];
9439       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9440                                                       F.getCallingConv(), VT);
9441       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9442           *CurDAG->getContext(), F.getCallingConv(), VT);
9443 
9444       // Even an apparant 'unused' swifterror argument needs to be returned. So
9445       // we do generate a copy for it that can be used on return from the
9446       // function.
9447       if (ArgHasUses || isSwiftErrorArg) {
9448         Optional<ISD::NodeType> AssertOp;
9449         if (Arg.hasAttribute(Attribute::SExt))
9450           AssertOp = ISD::AssertSext;
9451         else if (Arg.hasAttribute(Attribute::ZExt))
9452           AssertOp = ISD::AssertZext;
9453 
9454         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9455                                              PartVT, VT, nullptr,
9456                                              F.getCallingConv(), AssertOp));
9457       }
9458 
9459       i += NumParts;
9460     }
9461 
9462     // We don't need to do anything else for unused arguments.
9463     if (ArgValues.empty())
9464       continue;
9465 
9466     // Note down frame index.
9467     if (FrameIndexSDNode *FI =
9468         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9469       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9470 
9471     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9472                                      SDB->getCurSDLoc());
9473 
9474     SDB->setValue(&Arg, Res);
9475     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9476       // We want to associate the argument with the frame index, among
9477       // involved operands, that correspond to the lowest address. The
9478       // getCopyFromParts function, called earlier, is swapping the order of
9479       // the operands to BUILD_PAIR depending on endianness. The result of
9480       // that swapping is that the least significant bits of the argument will
9481       // be in the first operand of the BUILD_PAIR node, and the most
9482       // significant bits will be in the second operand.
9483       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9484       if (LoadSDNode *LNode =
9485           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9486         if (FrameIndexSDNode *FI =
9487             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9488           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9489     }
9490 
9491     // Update the SwiftErrorVRegDefMap.
9492     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9493       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9494       if (TargetRegisterInfo::isVirtualRegister(Reg))
9495         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9496                                            FuncInfo->SwiftErrorArg, Reg);
9497     }
9498 
9499     // If this argument is live outside of the entry block, insert a copy from
9500     // wherever we got it to the vreg that other BB's will reference it as.
9501     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9502       // If we can, though, try to skip creating an unnecessary vreg.
9503       // FIXME: This isn't very clean... it would be nice to make this more
9504       // general.  It's also subtly incompatible with the hacks FastISel
9505       // uses with vregs.
9506       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9507       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9508         FuncInfo->ValueMap[&Arg] = Reg;
9509         continue;
9510       }
9511     }
9512     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9513       FuncInfo->InitializeRegForValue(&Arg);
9514       SDB->CopyToExportRegsIfNeeded(&Arg);
9515     }
9516   }
9517 
9518   if (!Chains.empty()) {
9519     Chains.push_back(NewRoot);
9520     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9521   }
9522 
9523   DAG.setRoot(NewRoot);
9524 
9525   assert(i == InVals.size() && "Argument register count mismatch!");
9526 
9527   // If any argument copy elisions occurred and we have debug info, update the
9528   // stale frame indices used in the dbg.declare variable info table.
9529   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9530   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9531     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9532       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9533       if (I != ArgCopyElisionFrameIndexMap.end())
9534         VI.Slot = I->second;
9535     }
9536   }
9537 
9538   // Finally, if the target has anything special to do, allow it to do so.
9539   EmitFunctionEntryCode();
9540 }
9541 
9542 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9543 /// ensure constants are generated when needed.  Remember the virtual registers
9544 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9545 /// directly add them, because expansion might result in multiple MBB's for one
9546 /// BB.  As such, the start of the BB might correspond to a different MBB than
9547 /// the end.
9548 void
9549 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9550   const Instruction *TI = LLVMBB->getTerminator();
9551 
9552   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9553 
9554   // Check PHI nodes in successors that expect a value to be available from this
9555   // block.
9556   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9557     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9558     if (!isa<PHINode>(SuccBB->begin())) continue;
9559     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9560 
9561     // If this terminator has multiple identical successors (common for
9562     // switches), only handle each succ once.
9563     if (!SuccsHandled.insert(SuccMBB).second)
9564       continue;
9565 
9566     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9567 
9568     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9569     // nodes and Machine PHI nodes, but the incoming operands have not been
9570     // emitted yet.
9571     for (const PHINode &PN : SuccBB->phis()) {
9572       // Ignore dead phi's.
9573       if (PN.use_empty())
9574         continue;
9575 
9576       // Skip empty types
9577       if (PN.getType()->isEmptyTy())
9578         continue;
9579 
9580       unsigned Reg;
9581       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9582 
9583       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9584         unsigned &RegOut = ConstantsOut[C];
9585         if (RegOut == 0) {
9586           RegOut = FuncInfo.CreateRegs(C->getType());
9587           CopyValueToVirtualRegister(C, RegOut);
9588         }
9589         Reg = RegOut;
9590       } else {
9591         DenseMap<const Value *, unsigned>::iterator I =
9592           FuncInfo.ValueMap.find(PHIOp);
9593         if (I != FuncInfo.ValueMap.end())
9594           Reg = I->second;
9595         else {
9596           assert(isa<AllocaInst>(PHIOp) &&
9597                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9598                  "Didn't codegen value into a register!??");
9599           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9600           CopyValueToVirtualRegister(PHIOp, Reg);
9601         }
9602       }
9603 
9604       // Remember that this register needs to added to the machine PHI node as
9605       // the input for this MBB.
9606       SmallVector<EVT, 4> ValueVTs;
9607       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9608       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9609       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9610         EVT VT = ValueVTs[vti];
9611         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9612         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9613           FuncInfo.PHINodesToUpdate.push_back(
9614               std::make_pair(&*MBBI++, Reg + i));
9615         Reg += NumRegisters;
9616       }
9617     }
9618   }
9619 
9620   ConstantsOut.clear();
9621 }
9622 
9623 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9624 /// is 0.
9625 MachineBasicBlock *
9626 SelectionDAGBuilder::StackProtectorDescriptor::
9627 AddSuccessorMBB(const BasicBlock *BB,
9628                 MachineBasicBlock *ParentMBB,
9629                 bool IsLikely,
9630                 MachineBasicBlock *SuccMBB) {
9631   // If SuccBB has not been created yet, create it.
9632   if (!SuccMBB) {
9633     MachineFunction *MF = ParentMBB->getParent();
9634     MachineFunction::iterator BBI(ParentMBB);
9635     SuccMBB = MF->CreateMachineBasicBlock(BB);
9636     MF->insert(++BBI, SuccMBB);
9637   }
9638   // Add it as a successor of ParentMBB.
9639   ParentMBB->addSuccessor(
9640       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9641   return SuccMBB;
9642 }
9643 
9644 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9645   MachineFunction::iterator I(MBB);
9646   if (++I == FuncInfo.MF->end())
9647     return nullptr;
9648   return &*I;
9649 }
9650 
9651 /// During lowering new call nodes can be created (such as memset, etc.).
9652 /// Those will become new roots of the current DAG, but complications arise
9653 /// when they are tail calls. In such cases, the call lowering will update
9654 /// the root, but the builder still needs to know that a tail call has been
9655 /// lowered in order to avoid generating an additional return.
9656 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9657   // If the node is null, we do have a tail call.
9658   if (MaybeTC.getNode() != nullptr)
9659     DAG.setRoot(MaybeTC);
9660   else
9661     HasTailCall = true;
9662 }
9663 
9664 uint64_t
9665 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9666                                        unsigned First, unsigned Last) const {
9667   assert(Last >= First);
9668   const APInt &LowCase = Clusters[First].Low->getValue();
9669   const APInt &HighCase = Clusters[Last].High->getValue();
9670   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9671 
9672   // FIXME: A range of consecutive cases has 100% density, but only requires one
9673   // comparison to lower. We should discriminate against such consecutive ranges
9674   // in jump tables.
9675 
9676   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9677 }
9678 
9679 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9680     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9681     unsigned Last) const {
9682   assert(Last >= First);
9683   assert(TotalCases[Last] >= TotalCases[First]);
9684   uint64_t NumCases =
9685       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9686   return NumCases;
9687 }
9688 
9689 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9690                                          unsigned First, unsigned Last,
9691                                          const SwitchInst *SI,
9692                                          MachineBasicBlock *DefaultMBB,
9693                                          CaseCluster &JTCluster) {
9694   assert(First <= Last);
9695 
9696   auto Prob = BranchProbability::getZero();
9697   unsigned NumCmps = 0;
9698   std::vector<MachineBasicBlock*> Table;
9699   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9700 
9701   // Initialize probabilities in JTProbs.
9702   for (unsigned I = First; I <= Last; ++I)
9703     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9704 
9705   for (unsigned I = First; I <= Last; ++I) {
9706     assert(Clusters[I].Kind == CC_Range);
9707     Prob += Clusters[I].Prob;
9708     const APInt &Low = Clusters[I].Low->getValue();
9709     const APInt &High = Clusters[I].High->getValue();
9710     NumCmps += (Low == High) ? 1 : 2;
9711     if (I != First) {
9712       // Fill the gap between this and the previous cluster.
9713       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9714       assert(PreviousHigh.slt(Low));
9715       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9716       for (uint64_t J = 0; J < Gap; J++)
9717         Table.push_back(DefaultMBB);
9718     }
9719     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9720     for (uint64_t J = 0; J < ClusterSize; ++J)
9721       Table.push_back(Clusters[I].MBB);
9722     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9723   }
9724 
9725   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9726   unsigned NumDests = JTProbs.size();
9727   if (TLI.isSuitableForBitTests(
9728           NumDests, NumCmps, Clusters[First].Low->getValue(),
9729           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9730     // Clusters[First..Last] should be lowered as bit tests instead.
9731     return false;
9732   }
9733 
9734   // Create the MBB that will load from and jump through the table.
9735   // Note: We create it here, but it's not inserted into the function yet.
9736   MachineFunction *CurMF = FuncInfo.MF;
9737   MachineBasicBlock *JumpTableMBB =
9738       CurMF->CreateMachineBasicBlock(SI->getParent());
9739 
9740   // Add successors. Note: use table order for determinism.
9741   SmallPtrSet<MachineBasicBlock *, 8> Done;
9742   for (MachineBasicBlock *Succ : Table) {
9743     if (Done.count(Succ))
9744       continue;
9745     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9746     Done.insert(Succ);
9747   }
9748   JumpTableMBB->normalizeSuccProbs();
9749 
9750   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9751                      ->createJumpTableIndex(Table);
9752 
9753   // Set up the jump table info.
9754   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9755   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9756                       Clusters[Last].High->getValue(), SI->getCondition(),
9757                       nullptr, false);
9758   JTCases.emplace_back(std::move(JTH), std::move(JT));
9759 
9760   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9761                                      JTCases.size() - 1, Prob);
9762   return true;
9763 }
9764 
9765 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9766                                          const SwitchInst *SI,
9767                                          MachineBasicBlock *DefaultMBB) {
9768 #ifndef NDEBUG
9769   // Clusters must be non-empty, sorted, and only contain Range clusters.
9770   assert(!Clusters.empty());
9771   for (CaseCluster &C : Clusters)
9772     assert(C.Kind == CC_Range);
9773   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9774     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9775 #endif
9776 
9777   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9778   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9779     return;
9780 
9781   const int64_t N = Clusters.size();
9782   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9783   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9784 
9785   if (N < 2 || N < MinJumpTableEntries)
9786     return;
9787 
9788   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9789   SmallVector<unsigned, 8> TotalCases(N);
9790   for (unsigned i = 0; i < N; ++i) {
9791     const APInt &Hi = Clusters[i].High->getValue();
9792     const APInt &Lo = Clusters[i].Low->getValue();
9793     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9794     if (i != 0)
9795       TotalCases[i] += TotalCases[i - 1];
9796   }
9797 
9798   // Cheap case: the whole range may be suitable for jump table.
9799   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9800   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9801   assert(NumCases < UINT64_MAX / 100);
9802   assert(Range >= NumCases);
9803   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9804     CaseCluster JTCluster;
9805     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9806       Clusters[0] = JTCluster;
9807       Clusters.resize(1);
9808       return;
9809     }
9810   }
9811 
9812   // The algorithm below is not suitable for -O0.
9813   if (TM.getOptLevel() == CodeGenOpt::None)
9814     return;
9815 
9816   // Split Clusters into minimum number of dense partitions. The algorithm uses
9817   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9818   // for the Case Statement'" (1994), but builds the MinPartitions array in
9819   // reverse order to make it easier to reconstruct the partitions in ascending
9820   // order. In the choice between two optimal partitionings, it picks the one
9821   // which yields more jump tables.
9822 
9823   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9824   SmallVector<unsigned, 8> MinPartitions(N);
9825   // LastElement[i] is the last element of the partition starting at i.
9826   SmallVector<unsigned, 8> LastElement(N);
9827   // PartitionsScore[i] is used to break ties when choosing between two
9828   // partitionings resulting in the same number of partitions.
9829   SmallVector<unsigned, 8> PartitionsScore(N);
9830   // For PartitionsScore, a small number of comparisons is considered as good as
9831   // a jump table and a single comparison is considered better than a jump
9832   // table.
9833   enum PartitionScores : unsigned {
9834     NoTable = 0,
9835     Table = 1,
9836     FewCases = 1,
9837     SingleCase = 2
9838   };
9839 
9840   // Base case: There is only one way to partition Clusters[N-1].
9841   MinPartitions[N - 1] = 1;
9842   LastElement[N - 1] = N - 1;
9843   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9844 
9845   // Note: loop indexes are signed to avoid underflow.
9846   for (int64_t i = N - 2; i >= 0; i--) {
9847     // Find optimal partitioning of Clusters[i..N-1].
9848     // Baseline: Put Clusters[i] into a partition on its own.
9849     MinPartitions[i] = MinPartitions[i + 1] + 1;
9850     LastElement[i] = i;
9851     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9852 
9853     // Search for a solution that results in fewer partitions.
9854     for (int64_t j = N - 1; j > i; j--) {
9855       // Try building a partition from Clusters[i..j].
9856       uint64_t Range = getJumpTableRange(Clusters, i, j);
9857       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9858       assert(NumCases < UINT64_MAX / 100);
9859       assert(Range >= NumCases);
9860       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9861         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9862         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9863         int64_t NumEntries = j - i + 1;
9864 
9865         if (NumEntries == 1)
9866           Score += PartitionScores::SingleCase;
9867         else if (NumEntries <= SmallNumberOfEntries)
9868           Score += PartitionScores::FewCases;
9869         else if (NumEntries >= MinJumpTableEntries)
9870           Score += PartitionScores::Table;
9871 
9872         // If this leads to fewer partitions, or to the same number of
9873         // partitions with better score, it is a better partitioning.
9874         if (NumPartitions < MinPartitions[i] ||
9875             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9876           MinPartitions[i] = NumPartitions;
9877           LastElement[i] = j;
9878           PartitionsScore[i] = Score;
9879         }
9880       }
9881     }
9882   }
9883 
9884   // Iterate over the partitions, replacing some with jump tables in-place.
9885   unsigned DstIndex = 0;
9886   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9887     Last = LastElement[First];
9888     assert(Last >= First);
9889     assert(DstIndex <= First);
9890     unsigned NumClusters = Last - First + 1;
9891 
9892     CaseCluster JTCluster;
9893     if (NumClusters >= MinJumpTableEntries &&
9894         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9895       Clusters[DstIndex++] = JTCluster;
9896     } else {
9897       for (unsigned I = First; I <= Last; ++I)
9898         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9899     }
9900   }
9901   Clusters.resize(DstIndex);
9902 }
9903 
9904 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9905                                         unsigned First, unsigned Last,
9906                                         const SwitchInst *SI,
9907                                         CaseCluster &BTCluster) {
9908   assert(First <= Last);
9909   if (First == Last)
9910     return false;
9911 
9912   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9913   unsigned NumCmps = 0;
9914   for (int64_t I = First; I <= Last; ++I) {
9915     assert(Clusters[I].Kind == CC_Range);
9916     Dests.set(Clusters[I].MBB->getNumber());
9917     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9918   }
9919   unsigned NumDests = Dests.count();
9920 
9921   APInt Low = Clusters[First].Low->getValue();
9922   APInt High = Clusters[Last].High->getValue();
9923   assert(Low.slt(High));
9924 
9925   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9926   const DataLayout &DL = DAG.getDataLayout();
9927   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9928     return false;
9929 
9930   APInt LowBound;
9931   APInt CmpRange;
9932 
9933   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9934   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9935          "Case range must fit in bit mask!");
9936 
9937   // Check if the clusters cover a contiguous range such that no value in the
9938   // range will jump to the default statement.
9939   bool ContiguousRange = true;
9940   for (int64_t I = First + 1; I <= Last; ++I) {
9941     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9942       ContiguousRange = false;
9943       break;
9944     }
9945   }
9946 
9947   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9948     // Optimize the case where all the case values fit in a word without having
9949     // to subtract minValue. In this case, we can optimize away the subtraction.
9950     LowBound = APInt::getNullValue(Low.getBitWidth());
9951     CmpRange = High;
9952     ContiguousRange = false;
9953   } else {
9954     LowBound = Low;
9955     CmpRange = High - Low;
9956   }
9957 
9958   CaseBitsVector CBV;
9959   auto TotalProb = BranchProbability::getZero();
9960   for (unsigned i = First; i <= Last; ++i) {
9961     // Find the CaseBits for this destination.
9962     unsigned j;
9963     for (j = 0; j < CBV.size(); ++j)
9964       if (CBV[j].BB == Clusters[i].MBB)
9965         break;
9966     if (j == CBV.size())
9967       CBV.push_back(
9968           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9969     CaseBits *CB = &CBV[j];
9970 
9971     // Update Mask, Bits and ExtraProb.
9972     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9973     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9974     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9975     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9976     CB->Bits += Hi - Lo + 1;
9977     CB->ExtraProb += Clusters[i].Prob;
9978     TotalProb += Clusters[i].Prob;
9979   }
9980 
9981   BitTestInfo BTI;
9982   llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
9983     // Sort by probability first, number of bits second, bit mask third.
9984     if (a.ExtraProb != b.ExtraProb)
9985       return a.ExtraProb > b.ExtraProb;
9986     if (a.Bits != b.Bits)
9987       return a.Bits > b.Bits;
9988     return a.Mask < b.Mask;
9989   });
9990 
9991   for (auto &CB : CBV) {
9992     MachineBasicBlock *BitTestBB =
9993         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9994     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9995   }
9996   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9997                             SI->getCondition(), -1U, MVT::Other, false,
9998                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9999                             TotalProb);
10000 
10001   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
10002                                     BitTestCases.size() - 1, TotalProb);
10003   return true;
10004 }
10005 
10006 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
10007                                               const SwitchInst *SI) {
10008 // Partition Clusters into as few subsets as possible, where each subset has a
10009 // range that fits in a machine word and has <= 3 unique destinations.
10010 
10011 #ifndef NDEBUG
10012   // Clusters must be sorted and contain Range or JumpTable clusters.
10013   assert(!Clusters.empty());
10014   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
10015   for (const CaseCluster &C : Clusters)
10016     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
10017   for (unsigned i = 1; i < Clusters.size(); ++i)
10018     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
10019 #endif
10020 
10021   // The algorithm below is not suitable for -O0.
10022   if (TM.getOptLevel() == CodeGenOpt::None)
10023     return;
10024 
10025   // If target does not have legal shift left, do not emit bit tests at all.
10026   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10027   const DataLayout &DL = DAG.getDataLayout();
10028 
10029   EVT PTy = TLI.getPointerTy(DL);
10030   if (!TLI.isOperationLegal(ISD::SHL, PTy))
10031     return;
10032 
10033   int BitWidth = PTy.getSizeInBits();
10034   const int64_t N = Clusters.size();
10035 
10036   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
10037   SmallVector<unsigned, 8> MinPartitions(N);
10038   // LastElement[i] is the last element of the partition starting at i.
10039   SmallVector<unsigned, 8> LastElement(N);
10040 
10041   // FIXME: This might not be the best algorithm for finding bit test clusters.
10042 
10043   // Base case: There is only one way to partition Clusters[N-1].
10044   MinPartitions[N - 1] = 1;
10045   LastElement[N - 1] = N - 1;
10046 
10047   // Note: loop indexes are signed to avoid underflow.
10048   for (int64_t i = N - 2; i >= 0; --i) {
10049     // Find optimal partitioning of Clusters[i..N-1].
10050     // Baseline: Put Clusters[i] into a partition on its own.
10051     MinPartitions[i] = MinPartitions[i + 1] + 1;
10052     LastElement[i] = i;
10053 
10054     // Search for a solution that results in fewer partitions.
10055     // Note: the search is limited by BitWidth, reducing time complexity.
10056     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
10057       // Try building a partition from Clusters[i..j].
10058 
10059       // Check the range.
10060       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
10061                                Clusters[j].High->getValue(), DL))
10062         continue;
10063 
10064       // Check nbr of destinations and cluster types.
10065       // FIXME: This works, but doesn't seem very efficient.
10066       bool RangesOnly = true;
10067       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
10068       for (int64_t k = i; k <= j; k++) {
10069         if (Clusters[k].Kind != CC_Range) {
10070           RangesOnly = false;
10071           break;
10072         }
10073         Dests.set(Clusters[k].MBB->getNumber());
10074       }
10075       if (!RangesOnly || Dests.count() > 3)
10076         break;
10077 
10078       // Check if it's a better partition.
10079       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
10080       if (NumPartitions < MinPartitions[i]) {
10081         // Found a better partition.
10082         MinPartitions[i] = NumPartitions;
10083         LastElement[i] = j;
10084       }
10085     }
10086   }
10087 
10088   // Iterate over the partitions, replacing with bit-test clusters in-place.
10089   unsigned DstIndex = 0;
10090   for (unsigned First = 0, Last; First < N; First = Last + 1) {
10091     Last = LastElement[First];
10092     assert(First <= Last);
10093     assert(DstIndex <= First);
10094 
10095     CaseCluster BitTestCluster;
10096     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
10097       Clusters[DstIndex++] = BitTestCluster;
10098     } else {
10099       size_t NumClusters = Last - First + 1;
10100       std::memmove(&Clusters[DstIndex], &Clusters[First],
10101                    sizeof(Clusters[0]) * NumClusters);
10102       DstIndex += NumClusters;
10103     }
10104   }
10105   Clusters.resize(DstIndex);
10106 }
10107 
10108 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10109                                         MachineBasicBlock *SwitchMBB,
10110                                         MachineBasicBlock *DefaultMBB) {
10111   MachineFunction *CurMF = FuncInfo.MF;
10112   MachineBasicBlock *NextMBB = nullptr;
10113   MachineFunction::iterator BBI(W.MBB);
10114   if (++BBI != FuncInfo.MF->end())
10115     NextMBB = &*BBI;
10116 
10117   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10118 
10119   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10120 
10121   if (Size == 2 && W.MBB == SwitchMBB) {
10122     // If any two of the cases has the same destination, and if one value
10123     // is the same as the other, but has one bit unset that the other has set,
10124     // use bit manipulation to do two compares at once.  For example:
10125     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10126     // TODO: This could be extended to merge any 2 cases in switches with 3
10127     // cases.
10128     // TODO: Handle cases where W.CaseBB != SwitchBB.
10129     CaseCluster &Small = *W.FirstCluster;
10130     CaseCluster &Big = *W.LastCluster;
10131 
10132     if (Small.Low == Small.High && Big.Low == Big.High &&
10133         Small.MBB == Big.MBB) {
10134       const APInt &SmallValue = Small.Low->getValue();
10135       const APInt &BigValue = Big.Low->getValue();
10136 
10137       // Check that there is only one bit different.
10138       APInt CommonBit = BigValue ^ SmallValue;
10139       if (CommonBit.isPowerOf2()) {
10140         SDValue CondLHS = getValue(Cond);
10141         EVT VT = CondLHS.getValueType();
10142         SDLoc DL = getCurSDLoc();
10143 
10144         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10145                                  DAG.getConstant(CommonBit, DL, VT));
10146         SDValue Cond = DAG.getSetCC(
10147             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10148             ISD::SETEQ);
10149 
10150         // Update successor info.
10151         // Both Small and Big will jump to Small.BB, so we sum up the
10152         // probabilities.
10153         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10154         if (BPI)
10155           addSuccessorWithProb(
10156               SwitchMBB, DefaultMBB,
10157               // The default destination is the first successor in IR.
10158               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10159         else
10160           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10161 
10162         // Insert the true branch.
10163         SDValue BrCond =
10164             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10165                         DAG.getBasicBlock(Small.MBB));
10166         // Insert the false branch.
10167         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10168                              DAG.getBasicBlock(DefaultMBB));
10169 
10170         DAG.setRoot(BrCond);
10171         return;
10172       }
10173     }
10174   }
10175 
10176   if (TM.getOptLevel() != CodeGenOpt::None) {
10177     // Here, we order cases by probability so the most likely case will be
10178     // checked first. However, two clusters can have the same probability in
10179     // which case their relative ordering is non-deterministic. So we use Low
10180     // as a tie-breaker as clusters are guaranteed to never overlap.
10181     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10182                [](const CaseCluster &a, const CaseCluster &b) {
10183       return a.Prob != b.Prob ?
10184              a.Prob > b.Prob :
10185              a.Low->getValue().slt(b.Low->getValue());
10186     });
10187 
10188     // Rearrange the case blocks so that the last one falls through if possible
10189     // without changing the order of probabilities.
10190     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10191       --I;
10192       if (I->Prob > W.LastCluster->Prob)
10193         break;
10194       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10195         std::swap(*I, *W.LastCluster);
10196         break;
10197       }
10198     }
10199   }
10200 
10201   // Compute total probability.
10202   BranchProbability DefaultProb = W.DefaultProb;
10203   BranchProbability UnhandledProbs = DefaultProb;
10204   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10205     UnhandledProbs += I->Prob;
10206 
10207   MachineBasicBlock *CurMBB = W.MBB;
10208   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10209     MachineBasicBlock *Fallthrough;
10210     if (I == W.LastCluster) {
10211       // For the last cluster, fall through to the default destination.
10212       Fallthrough = DefaultMBB;
10213     } else {
10214       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10215       CurMF->insert(BBI, Fallthrough);
10216       // Put Cond in a virtual register to make it available from the new blocks.
10217       ExportFromCurrentBlock(Cond);
10218     }
10219     UnhandledProbs -= I->Prob;
10220 
10221     switch (I->Kind) {
10222       case CC_JumpTable: {
10223         // FIXME: Optimize away range check based on pivot comparisons.
10224         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
10225         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
10226 
10227         // The jump block hasn't been inserted yet; insert it here.
10228         MachineBasicBlock *JumpMBB = JT->MBB;
10229         CurMF->insert(BBI, JumpMBB);
10230 
10231         auto JumpProb = I->Prob;
10232         auto FallthroughProb = UnhandledProbs;
10233 
10234         // If the default statement is a target of the jump table, we evenly
10235         // distribute the default probability to successors of CurMBB. Also
10236         // update the probability on the edge from JumpMBB to Fallthrough.
10237         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10238                                               SE = JumpMBB->succ_end();
10239              SI != SE; ++SI) {
10240           if (*SI == DefaultMBB) {
10241             JumpProb += DefaultProb / 2;
10242             FallthroughProb -= DefaultProb / 2;
10243             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10244             JumpMBB->normalizeSuccProbs();
10245             break;
10246           }
10247         }
10248 
10249         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10250         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10251         CurMBB->normalizeSuccProbs();
10252 
10253         // The jump table header will be inserted in our current block, do the
10254         // range check, and fall through to our fallthrough block.
10255         JTH->HeaderBB = CurMBB;
10256         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10257 
10258         // If we're in the right place, emit the jump table header right now.
10259         if (CurMBB == SwitchMBB) {
10260           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10261           JTH->Emitted = true;
10262         }
10263         break;
10264       }
10265       case CC_BitTests: {
10266         // FIXME: Optimize away range check based on pivot comparisons.
10267         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
10268 
10269         // The bit test blocks haven't been inserted yet; insert them here.
10270         for (BitTestCase &BTC : BTB->Cases)
10271           CurMF->insert(BBI, BTC.ThisBB);
10272 
10273         // Fill in fields of the BitTestBlock.
10274         BTB->Parent = CurMBB;
10275         BTB->Default = Fallthrough;
10276 
10277         BTB->DefaultProb = UnhandledProbs;
10278         // If the cases in bit test don't form a contiguous range, we evenly
10279         // distribute the probability on the edge to Fallthrough to two
10280         // successors of CurMBB.
10281         if (!BTB->ContiguousRange) {
10282           BTB->Prob += DefaultProb / 2;
10283           BTB->DefaultProb -= DefaultProb / 2;
10284         }
10285 
10286         // If we're in the right place, emit the bit test header right now.
10287         if (CurMBB == SwitchMBB) {
10288           visitBitTestHeader(*BTB, SwitchMBB);
10289           BTB->Emitted = true;
10290         }
10291         break;
10292       }
10293       case CC_Range: {
10294         const Value *RHS, *LHS, *MHS;
10295         ISD::CondCode CC;
10296         if (I->Low == I->High) {
10297           // Check Cond == I->Low.
10298           CC = ISD::SETEQ;
10299           LHS = Cond;
10300           RHS=I->Low;
10301           MHS = nullptr;
10302         } else {
10303           // Check I->Low <= Cond <= I->High.
10304           CC = ISD::SETLE;
10305           LHS = I->Low;
10306           MHS = Cond;
10307           RHS = I->High;
10308         }
10309 
10310         // The false probability is the sum of all unhandled cases.
10311         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10312                      getCurSDLoc(), I->Prob, UnhandledProbs);
10313 
10314         if (CurMBB == SwitchMBB)
10315           visitSwitchCase(CB, SwitchMBB);
10316         else
10317           SwitchCases.push_back(CB);
10318 
10319         break;
10320       }
10321     }
10322     CurMBB = Fallthrough;
10323   }
10324 }
10325 
10326 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10327                                               CaseClusterIt First,
10328                                               CaseClusterIt Last) {
10329   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10330     if (X.Prob != CC.Prob)
10331       return X.Prob > CC.Prob;
10332 
10333     // Ties are broken by comparing the case value.
10334     return X.Low->getValue().slt(CC.Low->getValue());
10335   });
10336 }
10337 
10338 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10339                                         const SwitchWorkListItem &W,
10340                                         Value *Cond,
10341                                         MachineBasicBlock *SwitchMBB) {
10342   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10343          "Clusters not sorted?");
10344 
10345   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10346 
10347   // Balance the tree based on branch probabilities to create a near-optimal (in
10348   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10349   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10350   CaseClusterIt LastLeft = W.FirstCluster;
10351   CaseClusterIt FirstRight = W.LastCluster;
10352   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10353   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10354 
10355   // Move LastLeft and FirstRight towards each other from opposite directions to
10356   // find a partitioning of the clusters which balances the probability on both
10357   // sides. If LeftProb and RightProb are equal, alternate which side is
10358   // taken to ensure 0-probability nodes are distributed evenly.
10359   unsigned I = 0;
10360   while (LastLeft + 1 < FirstRight) {
10361     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10362       LeftProb += (++LastLeft)->Prob;
10363     else
10364       RightProb += (--FirstRight)->Prob;
10365     I++;
10366   }
10367 
10368   while (true) {
10369     // Our binary search tree differs from a typical BST in that ours can have up
10370     // to three values in each leaf. The pivot selection above doesn't take that
10371     // into account, which means the tree might require more nodes and be less
10372     // efficient. We compensate for this here.
10373 
10374     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10375     unsigned NumRight = W.LastCluster - FirstRight + 1;
10376 
10377     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10378       // If one side has less than 3 clusters, and the other has more than 3,
10379       // consider taking a cluster from the other side.
10380 
10381       if (NumLeft < NumRight) {
10382         // Consider moving the first cluster on the right to the left side.
10383         CaseCluster &CC = *FirstRight;
10384         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10385         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10386         if (LeftSideRank <= RightSideRank) {
10387           // Moving the cluster to the left does not demote it.
10388           ++LastLeft;
10389           ++FirstRight;
10390           continue;
10391         }
10392       } else {
10393         assert(NumRight < NumLeft);
10394         // Consider moving the last element on the left to the right side.
10395         CaseCluster &CC = *LastLeft;
10396         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10397         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10398         if (RightSideRank <= LeftSideRank) {
10399           // Moving the cluster to the right does not demot it.
10400           --LastLeft;
10401           --FirstRight;
10402           continue;
10403         }
10404       }
10405     }
10406     break;
10407   }
10408 
10409   assert(LastLeft + 1 == FirstRight);
10410   assert(LastLeft >= W.FirstCluster);
10411   assert(FirstRight <= W.LastCluster);
10412 
10413   // Use the first element on the right as pivot since we will make less-than
10414   // comparisons against it.
10415   CaseClusterIt PivotCluster = FirstRight;
10416   assert(PivotCluster > W.FirstCluster);
10417   assert(PivotCluster <= W.LastCluster);
10418 
10419   CaseClusterIt FirstLeft = W.FirstCluster;
10420   CaseClusterIt LastRight = W.LastCluster;
10421 
10422   const ConstantInt *Pivot = PivotCluster->Low;
10423 
10424   // New blocks will be inserted immediately after the current one.
10425   MachineFunction::iterator BBI(W.MBB);
10426   ++BBI;
10427 
10428   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10429   // we can branch to its destination directly if it's squeezed exactly in
10430   // between the known lower bound and Pivot - 1.
10431   MachineBasicBlock *LeftMBB;
10432   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10433       FirstLeft->Low == W.GE &&
10434       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10435     LeftMBB = FirstLeft->MBB;
10436   } else {
10437     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10438     FuncInfo.MF->insert(BBI, LeftMBB);
10439     WorkList.push_back(
10440         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10441     // Put Cond in a virtual register to make it available from the new blocks.
10442     ExportFromCurrentBlock(Cond);
10443   }
10444 
10445   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10446   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10447   // directly if RHS.High equals the current upper bound.
10448   MachineBasicBlock *RightMBB;
10449   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10450       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10451     RightMBB = FirstRight->MBB;
10452   } else {
10453     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10454     FuncInfo.MF->insert(BBI, RightMBB);
10455     WorkList.push_back(
10456         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10457     // Put Cond in a virtual register to make it available from the new blocks.
10458     ExportFromCurrentBlock(Cond);
10459   }
10460 
10461   // Create the CaseBlock record that will be used to lower the branch.
10462   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10463                getCurSDLoc(), LeftProb, RightProb);
10464 
10465   if (W.MBB == SwitchMBB)
10466     visitSwitchCase(CB, SwitchMBB);
10467   else
10468     SwitchCases.push_back(CB);
10469 }
10470 
10471 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10472 // from the swith statement.
10473 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10474                                             BranchProbability PeeledCaseProb) {
10475   if (PeeledCaseProb == BranchProbability::getOne())
10476     return BranchProbability::getZero();
10477   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10478 
10479   uint32_t Numerator = CaseProb.getNumerator();
10480   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10481   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10482 }
10483 
10484 // Try to peel the top probability case if it exceeds the threshold.
10485 // Return current MachineBasicBlock for the switch statement if the peeling
10486 // does not occur.
10487 // If the peeling is performed, return the newly created MachineBasicBlock
10488 // for the peeled switch statement. Also update Clusters to remove the peeled
10489 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10490 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10491     const SwitchInst &SI, CaseClusterVector &Clusters,
10492     BranchProbability &PeeledCaseProb) {
10493   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10494   // Don't perform if there is only one cluster or optimizing for size.
10495   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10496       TM.getOptLevel() == CodeGenOpt::None ||
10497       SwitchMBB->getParent()->getFunction().optForMinSize())
10498     return SwitchMBB;
10499 
10500   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10501   unsigned PeeledCaseIndex = 0;
10502   bool SwitchPeeled = false;
10503   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10504     CaseCluster &CC = Clusters[Index];
10505     if (CC.Prob < TopCaseProb)
10506       continue;
10507     TopCaseProb = CC.Prob;
10508     PeeledCaseIndex = Index;
10509     SwitchPeeled = true;
10510   }
10511   if (!SwitchPeeled)
10512     return SwitchMBB;
10513 
10514   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10515                     << TopCaseProb << "\n");
10516 
10517   // Record the MBB for the peeled switch statement.
10518   MachineFunction::iterator BBI(SwitchMBB);
10519   ++BBI;
10520   MachineBasicBlock *PeeledSwitchMBB =
10521       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10522   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10523 
10524   ExportFromCurrentBlock(SI.getCondition());
10525   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10526   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10527                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10528   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10529 
10530   Clusters.erase(PeeledCaseIt);
10531   for (CaseCluster &CC : Clusters) {
10532     LLVM_DEBUG(
10533         dbgs() << "Scale the probablity for one cluster, before scaling: "
10534                << CC.Prob << "\n");
10535     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10536     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10537   }
10538   PeeledCaseProb = TopCaseProb;
10539   return PeeledSwitchMBB;
10540 }
10541 
10542 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10543   // Extract cases from the switch.
10544   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10545   CaseClusterVector Clusters;
10546   Clusters.reserve(SI.getNumCases());
10547   for (auto I : SI.cases()) {
10548     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10549     const ConstantInt *CaseVal = I.getCaseValue();
10550     BranchProbability Prob =
10551         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10552             : BranchProbability(1, SI.getNumCases() + 1);
10553     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10554   }
10555 
10556   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10557 
10558   // Cluster adjacent cases with the same destination. We do this at all
10559   // optimization levels because it's cheap to do and will make codegen faster
10560   // if there are many clusters.
10561   sortAndRangeify(Clusters);
10562 
10563   if (TM.getOptLevel() != CodeGenOpt::None) {
10564     // Replace an unreachable default with the most popular destination.
10565     // FIXME: Exploit unreachable default more aggressively.
10566     bool UnreachableDefault =
10567         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10568     if (UnreachableDefault && !Clusters.empty()) {
10569       DenseMap<const BasicBlock *, unsigned> Popularity;
10570       unsigned MaxPop = 0;
10571       const BasicBlock *MaxBB = nullptr;
10572       for (auto I : SI.cases()) {
10573         const BasicBlock *BB = I.getCaseSuccessor();
10574         if (++Popularity[BB] > MaxPop) {
10575           MaxPop = Popularity[BB];
10576           MaxBB = BB;
10577         }
10578       }
10579       // Set new default.
10580       assert(MaxPop > 0 && MaxBB);
10581       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10582 
10583       // Remove cases that were pointing to the destination that is now the
10584       // default.
10585       CaseClusterVector New;
10586       New.reserve(Clusters.size());
10587       for (CaseCluster &CC : Clusters) {
10588         if (CC.MBB != DefaultMBB)
10589           New.push_back(CC);
10590       }
10591       Clusters = std::move(New);
10592     }
10593   }
10594 
10595   // The branch probablity of the peeled case.
10596   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10597   MachineBasicBlock *PeeledSwitchMBB =
10598       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10599 
10600   // If there is only the default destination, jump there directly.
10601   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10602   if (Clusters.empty()) {
10603     assert(PeeledSwitchMBB == SwitchMBB);
10604     SwitchMBB->addSuccessor(DefaultMBB);
10605     if (DefaultMBB != NextBlock(SwitchMBB)) {
10606       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10607                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10608     }
10609     return;
10610   }
10611 
10612   findJumpTables(Clusters, &SI, DefaultMBB);
10613   findBitTestClusters(Clusters, &SI);
10614 
10615   LLVM_DEBUG({
10616     dbgs() << "Case clusters: ";
10617     for (const CaseCluster &C : Clusters) {
10618       if (C.Kind == CC_JumpTable)
10619         dbgs() << "JT:";
10620       if (C.Kind == CC_BitTests)
10621         dbgs() << "BT:";
10622 
10623       C.Low->getValue().print(dbgs(), true);
10624       if (C.Low != C.High) {
10625         dbgs() << '-';
10626         C.High->getValue().print(dbgs(), true);
10627       }
10628       dbgs() << ' ';
10629     }
10630     dbgs() << '\n';
10631   });
10632 
10633   assert(!Clusters.empty());
10634   SwitchWorkList WorkList;
10635   CaseClusterIt First = Clusters.begin();
10636   CaseClusterIt Last = Clusters.end() - 1;
10637   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10638   // Scale the branchprobability for DefaultMBB if the peel occurs and
10639   // DefaultMBB is not replaced.
10640   if (PeeledCaseProb != BranchProbability::getZero() &&
10641       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10642     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10643   WorkList.push_back(
10644       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10645 
10646   while (!WorkList.empty()) {
10647     SwitchWorkListItem W = WorkList.back();
10648     WorkList.pop_back();
10649     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10650 
10651     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10652         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10653       // For optimized builds, lower large range as a balanced binary tree.
10654       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10655       continue;
10656     }
10657 
10658     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10659   }
10660 }
10661