xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 57f34dbd3e2f995ed3da855ba3cb4e2908b03acf)
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 SuccessOrdering = I.getSuccessOrdering();
4409   AtomicOrdering FailureOrdering = 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 
4417   auto Alignment = DAG.getEVTAlignment(MemVT);
4418 
4419   // FIXME: Volatile isn't really correct; we should keep track of atomic
4420   // orderings in the memoperand.
4421   auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
4422                MachineMemOperand::MOStore;
4423 
4424   MachineFunction &MF = DAG.getMachineFunction();
4425   MachineMemOperand *MMO =
4426     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4427                             Flags, MemVT.getStoreSize(), Alignment,
4428                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4429                             FailureOrdering);
4430 
4431   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4432                                    dl, MemVT, VTs, InChain,
4433                                    getValue(I.getPointerOperand()),
4434                                    getValue(I.getCompareOperand()),
4435                                    getValue(I.getNewValOperand()), MMO);
4436 
4437   SDValue OutChain = L.getValue(2);
4438 
4439   setValue(&I, L);
4440   DAG.setRoot(OutChain);
4441 }
4442 
4443 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4444   SDLoc dl = getCurSDLoc();
4445   ISD::NodeType NT;
4446   switch (I.getOperation()) {
4447   default: llvm_unreachable("Unknown atomicrmw operation");
4448   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4449   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4450   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4451   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4452   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4453   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4454   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4455   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4456   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4457   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4458   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4459   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4460   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4461   }
4462   AtomicOrdering Ordering = I.getOrdering();
4463   SyncScope::ID SSID = I.getSyncScopeID();
4464 
4465   SDValue InChain = getRoot();
4466 
4467   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4468   auto Alignment = DAG.getEVTAlignment(MemVT);
4469 
4470   // For now, atomics are considered to be volatile always, and they are
4471   // chained as such.
4472   // FIXME: Volatile isn't really correct; we should keep track of atomic
4473   // orderings in the memoperand.
4474   auto Flags = MachineMemOperand::MOVolatile |
4475     MachineMemOperand::MOLoad |  MachineMemOperand::MOStore;
4476 
4477   MachineFunction &MF = DAG.getMachineFunction();
4478   MachineMemOperand *MMO =
4479     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4480                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4481                             nullptr, SSID, Ordering);
4482 
4483   SDValue L =
4484     DAG.getAtomic(NT, dl, MemVT, InChain,
4485                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4486                   MMO);
4487 
4488   SDValue OutChain = L.getValue(1);
4489 
4490   setValue(&I, L);
4491   DAG.setRoot(OutChain);
4492 }
4493 
4494 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4495   SDLoc dl = getCurSDLoc();
4496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4497   SDValue Ops[3];
4498   Ops[0] = getRoot();
4499   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4500                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4501   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4502                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4503   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4504 }
4505 
4506 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4507   SDLoc dl = getCurSDLoc();
4508   AtomicOrdering Order = I.getOrdering();
4509   SyncScope::ID SSID = I.getSyncScopeID();
4510 
4511   SDValue InChain = getRoot();
4512 
4513   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4514   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4515 
4516   if (!TLI.supportsUnalignedAtomics() &&
4517       I.getAlignment() < VT.getStoreSize())
4518     report_fatal_error("Cannot generate unaligned atomic load");
4519 
4520   MachineMemOperand *MMO =
4521       DAG.getMachineFunction().
4522       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4523                            MachineMemOperand::MOVolatile |
4524                            MachineMemOperand::MOLoad,
4525                            VT.getStoreSize(),
4526                            I.getAlignment() ? I.getAlignment() :
4527                                               DAG.getEVTAlignment(VT),
4528                            AAMDNodes(), nullptr, SSID, Order);
4529 
4530   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4531   SDValue L =
4532       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4533                     getValue(I.getPointerOperand()), MMO);
4534 
4535   SDValue OutChain = L.getValue(1);
4536 
4537   setValue(&I, L);
4538   DAG.setRoot(OutChain);
4539 }
4540 
4541 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4542   SDLoc dl = getCurSDLoc();
4543 
4544   AtomicOrdering Ordering = I.getOrdering();
4545   SyncScope::ID SSID = I.getSyncScopeID();
4546 
4547   SDValue InChain = getRoot();
4548 
4549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4550   EVT VT =
4551       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4552 
4553   if (I.getAlignment() < VT.getStoreSize())
4554     report_fatal_error("Cannot generate unaligned atomic store");
4555 
4556   // For now, atomics are considered to be volatile always, and they are
4557   // chained as such.
4558   // FIXME: Volatile isn't really correct; we should keep track of atomic
4559   // orderings in the memoperand.
4560   auto Flags = MachineMemOperand::MOVolatile |  MachineMemOperand::MOStore;
4561 
4562   MachineFunction &MF = DAG.getMachineFunction();
4563   MachineMemOperand *MMO =
4564     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4565                             VT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4566                             nullptr, SSID, Ordering);
4567   SDValue OutChain =
4568     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, InChain,
4569               getValue(I.getPointerOperand()), getValue(I.getValueOperand()),
4570               MMO);
4571 
4572 
4573   DAG.setRoot(OutChain);
4574 }
4575 
4576 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4577 /// node.
4578 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4579                                                unsigned Intrinsic) {
4580   // Ignore the callsite's attributes. A specific call site may be marked with
4581   // readnone, but the lowering code will expect the chain based on the
4582   // definition.
4583   const Function *F = I.getCalledFunction();
4584   bool HasChain = !F->doesNotAccessMemory();
4585   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4586 
4587   // Build the operand list.
4588   SmallVector<SDValue, 8> Ops;
4589   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4590     if (OnlyLoad) {
4591       // We don't need to serialize loads against other loads.
4592       Ops.push_back(DAG.getRoot());
4593     } else {
4594       Ops.push_back(getRoot());
4595     }
4596   }
4597 
4598   // Info is set by getTgtMemInstrinsic
4599   TargetLowering::IntrinsicInfo Info;
4600   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4601   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4602                                                DAG.getMachineFunction(),
4603                                                Intrinsic);
4604 
4605   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4606   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4607       Info.opc == ISD::INTRINSIC_W_CHAIN)
4608     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4609                                         TLI.getPointerTy(DAG.getDataLayout())));
4610 
4611   // Add all operands of the call to the operand list.
4612   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4613     SDValue Op = getValue(I.getArgOperand(i));
4614     Ops.push_back(Op);
4615   }
4616 
4617   SmallVector<EVT, 4> ValueVTs;
4618   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4619 
4620   if (HasChain)
4621     ValueVTs.push_back(MVT::Other);
4622 
4623   SDVTList VTs = DAG.getVTList(ValueVTs);
4624 
4625   // Create the node.
4626   SDValue Result;
4627   if (IsTgtIntrinsic) {
4628     // This is target intrinsic that touches memory
4629     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4630       Ops, Info.memVT,
4631       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4632       Info.flags, Info.size);
4633   } else if (!HasChain) {
4634     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4635   } else if (!I.getType()->isVoidTy()) {
4636     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4637   } else {
4638     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4639   }
4640 
4641   if (HasChain) {
4642     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4643     if (OnlyLoad)
4644       PendingLoads.push_back(Chain);
4645     else
4646       DAG.setRoot(Chain);
4647   }
4648 
4649   if (!I.getType()->isVoidTy()) {
4650     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4651       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4652       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4653     } else
4654       Result = lowerRangeToAssertZExt(DAG, I, Result);
4655 
4656     setValue(&I, Result);
4657   }
4658 }
4659 
4660 /// GetSignificand - Get the significand and build it into a floating-point
4661 /// number with exponent of 1:
4662 ///
4663 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4664 ///
4665 /// where Op is the hexadecimal representation of floating point value.
4666 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4667   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4668                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4669   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4670                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4671   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4672 }
4673 
4674 /// GetExponent - Get the exponent:
4675 ///
4676 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4677 ///
4678 /// where Op is the hexadecimal representation of floating point value.
4679 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4680                            const TargetLowering &TLI, const SDLoc &dl) {
4681   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4682                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4683   SDValue t1 = DAG.getNode(
4684       ISD::SRL, dl, MVT::i32, t0,
4685       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4686   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4687                            DAG.getConstant(127, dl, MVT::i32));
4688   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4689 }
4690 
4691 /// getF32Constant - Get 32-bit floating point constant.
4692 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4693                               const SDLoc &dl) {
4694   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4695                            MVT::f32);
4696 }
4697 
4698 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4699                                        SelectionDAG &DAG) {
4700   // TODO: What fast-math-flags should be set on the floating-point nodes?
4701 
4702   //   IntegerPartOfX = ((int32_t)(t0);
4703   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4704 
4705   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4706   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4707   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4708 
4709   //   IntegerPartOfX <<= 23;
4710   IntegerPartOfX = DAG.getNode(
4711       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4712       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4713                                   DAG.getDataLayout())));
4714 
4715   SDValue TwoToFractionalPartOfX;
4716   if (LimitFloatPrecision <= 6) {
4717     // For floating-point precision of 6:
4718     //
4719     //   TwoToFractionalPartOfX =
4720     //     0.997535578f +
4721     //       (0.735607626f + 0.252464424f * x) * x;
4722     //
4723     // error 0.0144103317, which is 6 bits
4724     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4725                              getF32Constant(DAG, 0x3e814304, dl));
4726     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4727                              getF32Constant(DAG, 0x3f3c50c8, dl));
4728     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4729     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4730                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4731   } else if (LimitFloatPrecision <= 12) {
4732     // For floating-point precision of 12:
4733     //
4734     //   TwoToFractionalPartOfX =
4735     //     0.999892986f +
4736     //       (0.696457318f +
4737     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4738     //
4739     // error 0.000107046256, which is 13 to 14 bits
4740     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4741                              getF32Constant(DAG, 0x3da235e3, dl));
4742     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4743                              getF32Constant(DAG, 0x3e65b8f3, dl));
4744     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4745     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4746                              getF32Constant(DAG, 0x3f324b07, dl));
4747     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4748     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4749                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4750   } else { // LimitFloatPrecision <= 18
4751     // For floating-point precision of 18:
4752     //
4753     //   TwoToFractionalPartOfX =
4754     //     0.999999982f +
4755     //       (0.693148872f +
4756     //         (0.240227044f +
4757     //           (0.554906021e-1f +
4758     //             (0.961591928e-2f +
4759     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4760     // error 2.47208000*10^(-7), which is better than 18 bits
4761     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4762                              getF32Constant(DAG, 0x3924b03e, dl));
4763     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4764                              getF32Constant(DAG, 0x3ab24b87, dl));
4765     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4766     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4767                              getF32Constant(DAG, 0x3c1d8c17, dl));
4768     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4769     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4770                              getF32Constant(DAG, 0x3d634a1d, dl));
4771     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4772     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4773                              getF32Constant(DAG, 0x3e75fe14, dl));
4774     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4775     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4776                               getF32Constant(DAG, 0x3f317234, dl));
4777     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4778     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4779                                          getF32Constant(DAG, 0x3f800000, dl));
4780   }
4781 
4782   // Add the exponent into the result in integer domain.
4783   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4784   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4785                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4786 }
4787 
4788 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4789 /// limited-precision mode.
4790 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4791                          const TargetLowering &TLI) {
4792   if (Op.getValueType() == MVT::f32 &&
4793       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4794 
4795     // Put the exponent in the right bit position for later addition to the
4796     // final result:
4797     //
4798     //   #define LOG2OFe 1.4426950f
4799     //   t0 = Op * LOG2OFe
4800 
4801     // TODO: What fast-math-flags should be set here?
4802     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4803                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4804     return getLimitedPrecisionExp2(t0, dl, DAG);
4805   }
4806 
4807   // No special expansion.
4808   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4809 }
4810 
4811 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4812 /// limited-precision mode.
4813 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4814                          const TargetLowering &TLI) {
4815   // TODO: What fast-math-flags should be set on the floating-point nodes?
4816 
4817   if (Op.getValueType() == MVT::f32 &&
4818       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4819     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4820 
4821     // Scale the exponent by log(2) [0.69314718f].
4822     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4823     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4824                                         getF32Constant(DAG, 0x3f317218, dl));
4825 
4826     // Get the significand and build it into a floating-point number with
4827     // exponent of 1.
4828     SDValue X = GetSignificand(DAG, Op1, dl);
4829 
4830     SDValue LogOfMantissa;
4831     if (LimitFloatPrecision <= 6) {
4832       // For floating-point precision of 6:
4833       //
4834       //   LogofMantissa =
4835       //     -1.1609546f +
4836       //       (1.4034025f - 0.23903021f * x) * x;
4837       //
4838       // error 0.0034276066, which is better than 8 bits
4839       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4840                                getF32Constant(DAG, 0xbe74c456, dl));
4841       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4842                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4843       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4844       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4845                                   getF32Constant(DAG, 0x3f949a29, dl));
4846     } else if (LimitFloatPrecision <= 12) {
4847       // For floating-point precision of 12:
4848       //
4849       //   LogOfMantissa =
4850       //     -1.7417939f +
4851       //       (2.8212026f +
4852       //         (-1.4699568f +
4853       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4854       //
4855       // error 0.000061011436, which is 14 bits
4856       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4857                                getF32Constant(DAG, 0xbd67b6d6, dl));
4858       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4859                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4860       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4861       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4862                                getF32Constant(DAG, 0x3fbc278b, dl));
4863       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4864       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4865                                getF32Constant(DAG, 0x40348e95, dl));
4866       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4867       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4868                                   getF32Constant(DAG, 0x3fdef31a, dl));
4869     } else { // LimitFloatPrecision <= 18
4870       // For floating-point precision of 18:
4871       //
4872       //   LogOfMantissa =
4873       //     -2.1072184f +
4874       //       (4.2372794f +
4875       //         (-3.7029485f +
4876       //           (2.2781945f +
4877       //             (-0.87823314f +
4878       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4879       //
4880       // error 0.0000023660568, which is better than 18 bits
4881       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4882                                getF32Constant(DAG, 0xbc91e5ac, dl));
4883       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4884                                getF32Constant(DAG, 0x3e4350aa, dl));
4885       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4886       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4887                                getF32Constant(DAG, 0x3f60d3e3, dl));
4888       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4889       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4890                                getF32Constant(DAG, 0x4011cdf0, dl));
4891       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4892       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4893                                getF32Constant(DAG, 0x406cfd1c, dl));
4894       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4895       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4896                                getF32Constant(DAG, 0x408797cb, dl));
4897       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4898       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4899                                   getF32Constant(DAG, 0x4006dcab, dl));
4900     }
4901 
4902     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4903   }
4904 
4905   // No special expansion.
4906   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4907 }
4908 
4909 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4910 /// limited-precision mode.
4911 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4912                           const TargetLowering &TLI) {
4913   // TODO: What fast-math-flags should be set on the floating-point nodes?
4914 
4915   if (Op.getValueType() == MVT::f32 &&
4916       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4917     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4918 
4919     // Get the exponent.
4920     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4921 
4922     // Get the significand and build it into a floating-point number with
4923     // exponent of 1.
4924     SDValue X = GetSignificand(DAG, Op1, dl);
4925 
4926     // Different possible minimax approximations of significand in
4927     // floating-point for various degrees of accuracy over [1,2].
4928     SDValue Log2ofMantissa;
4929     if (LimitFloatPrecision <= 6) {
4930       // For floating-point precision of 6:
4931       //
4932       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4933       //
4934       // error 0.0049451742, which is more than 7 bits
4935       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4936                                getF32Constant(DAG, 0xbeb08fe0, dl));
4937       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4938                                getF32Constant(DAG, 0x40019463, dl));
4939       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4940       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4941                                    getF32Constant(DAG, 0x3fd6633d, dl));
4942     } else if (LimitFloatPrecision <= 12) {
4943       // For floating-point precision of 12:
4944       //
4945       //   Log2ofMantissa =
4946       //     -2.51285454f +
4947       //       (4.07009056f +
4948       //         (-2.12067489f +
4949       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4950       //
4951       // error 0.0000876136000, which is better than 13 bits
4952       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4953                                getF32Constant(DAG, 0xbda7262e, dl));
4954       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4955                                getF32Constant(DAG, 0x3f25280b, dl));
4956       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4957       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4958                                getF32Constant(DAG, 0x4007b923, dl));
4959       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4960       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4961                                getF32Constant(DAG, 0x40823e2f, dl));
4962       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4963       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4964                                    getF32Constant(DAG, 0x4020d29c, dl));
4965     } else { // LimitFloatPrecision <= 18
4966       // For floating-point precision of 18:
4967       //
4968       //   Log2ofMantissa =
4969       //     -3.0400495f +
4970       //       (6.1129976f +
4971       //         (-5.3420409f +
4972       //           (3.2865683f +
4973       //             (-1.2669343f +
4974       //               (0.27515199f -
4975       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4976       //
4977       // error 0.0000018516, which is better than 18 bits
4978       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4979                                getF32Constant(DAG, 0xbcd2769e, dl));
4980       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4981                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4982       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4983       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4984                                getF32Constant(DAG, 0x3fa22ae7, dl));
4985       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4986       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4987                                getF32Constant(DAG, 0x40525723, dl));
4988       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4989       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4990                                getF32Constant(DAG, 0x40aaf200, dl));
4991       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4992       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4993                                getF32Constant(DAG, 0x40c39dad, dl));
4994       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4995       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4996                                    getF32Constant(DAG, 0x4042902c, dl));
4997     }
4998 
4999     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5000   }
5001 
5002   // No special expansion.
5003   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5004 }
5005 
5006 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5007 /// limited-precision mode.
5008 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5009                            const TargetLowering &TLI) {
5010   // TODO: What fast-math-flags should be set on the floating-point nodes?
5011 
5012   if (Op.getValueType() == MVT::f32 &&
5013       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5014     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5015 
5016     // Scale the exponent by log10(2) [0.30102999f].
5017     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5018     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5019                                         getF32Constant(DAG, 0x3e9a209a, dl));
5020 
5021     // Get the significand and build it into a floating-point number with
5022     // exponent of 1.
5023     SDValue X = GetSignificand(DAG, Op1, dl);
5024 
5025     SDValue Log10ofMantissa;
5026     if (LimitFloatPrecision <= 6) {
5027       // For floating-point precision of 6:
5028       //
5029       //   Log10ofMantissa =
5030       //     -0.50419619f +
5031       //       (0.60948995f - 0.10380950f * x) * x;
5032       //
5033       // error 0.0014886165, which is 6 bits
5034       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5035                                getF32Constant(DAG, 0xbdd49a13, dl));
5036       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5037                                getF32Constant(DAG, 0x3f1c0789, dl));
5038       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5039       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5040                                     getF32Constant(DAG, 0x3f011300, dl));
5041     } else if (LimitFloatPrecision <= 12) {
5042       // For floating-point precision of 12:
5043       //
5044       //   Log10ofMantissa =
5045       //     -0.64831180f +
5046       //       (0.91751397f +
5047       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5048       //
5049       // error 0.00019228036, which is better than 12 bits
5050       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5051                                getF32Constant(DAG, 0x3d431f31, dl));
5052       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5053                                getF32Constant(DAG, 0x3ea21fb2, dl));
5054       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5055       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5056                                getF32Constant(DAG, 0x3f6ae232, dl));
5057       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5058       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5059                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5060     } else { // LimitFloatPrecision <= 18
5061       // For floating-point precision of 18:
5062       //
5063       //   Log10ofMantissa =
5064       //     -0.84299375f +
5065       //       (1.5327582f +
5066       //         (-1.0688956f +
5067       //           (0.49102474f +
5068       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5069       //
5070       // error 0.0000037995730, which is better than 18 bits
5071       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5072                                getF32Constant(DAG, 0x3c5d51ce, dl));
5073       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5074                                getF32Constant(DAG, 0x3e00685a, dl));
5075       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5076       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5077                                getF32Constant(DAG, 0x3efb6798, dl));
5078       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5079       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5080                                getF32Constant(DAG, 0x3f88d192, dl));
5081       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5082       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5083                                getF32Constant(DAG, 0x3fc4316c, dl));
5084       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5085       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5086                                     getF32Constant(DAG, 0x3f57ce70, dl));
5087     }
5088 
5089     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5090   }
5091 
5092   // No special expansion.
5093   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5094 }
5095 
5096 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5097 /// limited-precision mode.
5098 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5099                           const TargetLowering &TLI) {
5100   if (Op.getValueType() == MVT::f32 &&
5101       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5102     return getLimitedPrecisionExp2(Op, dl, DAG);
5103 
5104   // No special expansion.
5105   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5106 }
5107 
5108 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5109 /// limited-precision mode with x == 10.0f.
5110 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5111                          SelectionDAG &DAG, const TargetLowering &TLI) {
5112   bool IsExp10 = false;
5113   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5114       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5115     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5116       APFloat Ten(10.0f);
5117       IsExp10 = LHSC->isExactlyValue(Ten);
5118     }
5119   }
5120 
5121   // TODO: What fast-math-flags should be set on the FMUL node?
5122   if (IsExp10) {
5123     // Put the exponent in the right bit position for later addition to the
5124     // final result:
5125     //
5126     //   #define LOG2OF10 3.3219281f
5127     //   t0 = Op * LOG2OF10;
5128     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5129                              getF32Constant(DAG, 0x40549a78, dl));
5130     return getLimitedPrecisionExp2(t0, dl, DAG);
5131   }
5132 
5133   // No special expansion.
5134   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5135 }
5136 
5137 /// ExpandPowI - Expand a llvm.powi intrinsic.
5138 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5139                           SelectionDAG &DAG) {
5140   // If RHS is a constant, we can expand this out to a multiplication tree,
5141   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5142   // optimizing for size, we only want to do this if the expansion would produce
5143   // a small number of multiplies, otherwise we do the full expansion.
5144   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5145     // Get the exponent as a positive value.
5146     unsigned Val = RHSC->getSExtValue();
5147     if ((int)Val < 0) Val = -Val;
5148 
5149     // powi(x, 0) -> 1.0
5150     if (Val == 0)
5151       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5152 
5153     const Function &F = DAG.getMachineFunction().getFunction();
5154     if (!F.optForSize() ||
5155         // If optimizing for size, don't insert too many multiplies.
5156         // This inserts up to 5 multiplies.
5157         countPopulation(Val) + Log2_32(Val) < 7) {
5158       // We use the simple binary decomposition method to generate the multiply
5159       // sequence.  There are more optimal ways to do this (for example,
5160       // powi(x,15) generates one more multiply than it should), but this has
5161       // the benefit of being both really simple and much better than a libcall.
5162       SDValue Res;  // Logically starts equal to 1.0
5163       SDValue CurSquare = LHS;
5164       // TODO: Intrinsics should have fast-math-flags that propagate to these
5165       // nodes.
5166       while (Val) {
5167         if (Val & 1) {
5168           if (Res.getNode())
5169             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5170           else
5171             Res = CurSquare;  // 1.0*CurSquare.
5172         }
5173 
5174         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5175                                 CurSquare, CurSquare);
5176         Val >>= 1;
5177       }
5178 
5179       // If the original was negative, invert the result, producing 1/(x*x*x).
5180       if (RHSC->getSExtValue() < 0)
5181         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5182                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5183       return Res;
5184     }
5185   }
5186 
5187   // Otherwise, expand to a libcall.
5188   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5189 }
5190 
5191 // getUnderlyingArgReg - Find underlying register used for a truncated or
5192 // bitcasted argument.
5193 static unsigned getUnderlyingArgReg(const SDValue &N) {
5194   switch (N.getOpcode()) {
5195   case ISD::CopyFromReg:
5196     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
5197   case ISD::BITCAST:
5198   case ISD::AssertZext:
5199   case ISD::AssertSext:
5200   case ISD::TRUNCATE:
5201     return getUnderlyingArgReg(N.getOperand(0));
5202   default:
5203     return 0;
5204   }
5205 }
5206 
5207 /// If the DbgValueInst is a dbg_value of a function argument, create the
5208 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5209 /// instruction selection, they will be inserted to the entry BB.
5210 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5211     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5212     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5213   const Argument *Arg = dyn_cast<Argument>(V);
5214   if (!Arg)
5215     return false;
5216 
5217   if (!IsDbgDeclare) {
5218     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5219     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5220     // the entry block.
5221     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5222     if (!IsInEntryBlock)
5223       return false;
5224 
5225     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5226     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5227     // variable that also is a param.
5228     //
5229     // Although, if we are at the top of the entry block already, we can still
5230     // emit using ArgDbgValue. This might catch some situations when the
5231     // dbg.value refers to an argument that isn't used in the entry block, so
5232     // any CopyToReg node would be optimized out and the only way to express
5233     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5234     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5235     // we should only emit as ArgDbgValue if the Variable is an argument to the
5236     // current function, and the dbg.value intrinsic is found in the entry
5237     // block.
5238     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5239         !DL->getInlinedAt();
5240     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5241     if (!IsInPrologue && !VariableIsFunctionInputArg)
5242       return false;
5243 
5244     // Here we assume that a function argument on IR level only can be used to
5245     // describe one input parameter on source level. If we for example have
5246     // source code like this
5247     //
5248     //    struct A { long x, y; };
5249     //    void foo(struct A a, long b) {
5250     //      ...
5251     //      b = a.x;
5252     //      ...
5253     //    }
5254     //
5255     // and IR like this
5256     //
5257     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5258     //  entry:
5259     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5260     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5261     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5262     //    ...
5263     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5264     //    ...
5265     //
5266     // then the last dbg.value is describing a parameter "b" using a value that
5267     // is an argument. But since we already has used %a1 to describe a parameter
5268     // we should not handle that last dbg.value here (that would result in an
5269     // incorrect hoisting of the DBG_VALUE to the function entry).
5270     // Notice that we allow one dbg.value per IR level argument, to accomodate
5271     // for the situation with fragments above.
5272     if (VariableIsFunctionInputArg) {
5273       unsigned ArgNo = Arg->getArgNo();
5274       if (ArgNo >= FuncInfo.DescribedArgs.size())
5275         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5276       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5277         return false;
5278       FuncInfo.DescribedArgs.set(ArgNo);
5279     }
5280   }
5281 
5282   MachineFunction &MF = DAG.getMachineFunction();
5283   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5284 
5285   bool IsIndirect = false;
5286   Optional<MachineOperand> Op;
5287   // Some arguments' frame index is recorded during argument lowering.
5288   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5289   if (FI != std::numeric_limits<int>::max())
5290     Op = MachineOperand::CreateFI(FI);
5291 
5292   if (!Op && N.getNode()) {
5293     unsigned Reg = getUnderlyingArgReg(N);
5294     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
5295       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5296       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
5297       if (PR)
5298         Reg = PR;
5299     }
5300     if (Reg) {
5301       Op = MachineOperand::CreateReg(Reg, false);
5302       IsIndirect = IsDbgDeclare;
5303     }
5304   }
5305 
5306   if (!Op && N.getNode())
5307     // Check if frame index is available.
5308     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
5309       if (FrameIndexSDNode *FINode =
5310           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5311         Op = MachineOperand::CreateFI(FINode->getIndex());
5312 
5313   if (!Op) {
5314     // Check if ValueMap has reg number.
5315     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
5316     if (VMI != FuncInfo.ValueMap.end()) {
5317       const auto &TLI = DAG.getTargetLoweringInfo();
5318       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5319                        V->getType(), getABIRegCopyCC(V));
5320       if (RFV.occupiesMultipleRegs()) {
5321         unsigned Offset = 0;
5322         for (auto RegAndSize : RFV.getRegsAndSizes()) {
5323           Op = MachineOperand::CreateReg(RegAndSize.first, false);
5324           auto FragmentExpr = DIExpression::createFragmentExpression(
5325               Expr, Offset, RegAndSize.second);
5326           if (!FragmentExpr)
5327             continue;
5328           FuncInfo.ArgDbgValues.push_back(
5329               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5330                       Op->getReg(), Variable, *FragmentExpr));
5331           Offset += RegAndSize.second;
5332         }
5333         return true;
5334       }
5335       Op = MachineOperand::CreateReg(VMI->second, false);
5336       IsIndirect = IsDbgDeclare;
5337     }
5338   }
5339 
5340   if (!Op)
5341     return false;
5342 
5343   assert(Variable->isValidLocationForIntrinsic(DL) &&
5344          "Expected inlined-at fields to agree");
5345   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5346   FuncInfo.ArgDbgValues.push_back(
5347       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5348               *Op, Variable, Expr));
5349 
5350   return true;
5351 }
5352 
5353 /// Return the appropriate SDDbgValue based on N.
5354 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5355                                              DILocalVariable *Variable,
5356                                              DIExpression *Expr,
5357                                              const DebugLoc &dl,
5358                                              unsigned DbgSDNodeOrder) {
5359   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5360     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5361     // stack slot locations.
5362     //
5363     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5364     // debug values here after optimization:
5365     //
5366     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5367     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5368     //
5369     // Both describe the direct values of their associated variables.
5370     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5371                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5372   }
5373   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5374                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5375 }
5376 
5377 // VisualStudio defines setjmp as _setjmp
5378 #if defined(_MSC_VER) && defined(setjmp) && \
5379                          !defined(setjmp_undefined_for_msvc)
5380 #  pragma push_macro("setjmp")
5381 #  undef setjmp
5382 #  define setjmp_undefined_for_msvc
5383 #endif
5384 
5385 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5386   switch (Intrinsic) {
5387   case Intrinsic::smul_fix:
5388     return ISD::SMULFIX;
5389   case Intrinsic::umul_fix:
5390     return ISD::UMULFIX;
5391   default:
5392     llvm_unreachable("Unhandled fixed point intrinsic");
5393   }
5394 }
5395 
5396 /// Lower the call to the specified intrinsic function. If we want to emit this
5397 /// as a call to a named external function, return the name. Otherwise, lower it
5398 /// and return null.
5399 const char *
5400 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
5401   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5402   SDLoc sdl = getCurSDLoc();
5403   DebugLoc dl = getCurDebugLoc();
5404   SDValue Res;
5405 
5406   switch (Intrinsic) {
5407   default:
5408     // By default, turn this into a target intrinsic node.
5409     visitTargetIntrinsic(I, Intrinsic);
5410     return nullptr;
5411   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5412   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5413   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5414   case Intrinsic::returnaddress:
5415     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5416                              TLI.getPointerTy(DAG.getDataLayout()),
5417                              getValue(I.getArgOperand(0))));
5418     return nullptr;
5419   case Intrinsic::addressofreturnaddress:
5420     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5421                              TLI.getPointerTy(DAG.getDataLayout())));
5422     return nullptr;
5423   case Intrinsic::sponentry:
5424     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5425                              TLI.getPointerTy(DAG.getDataLayout())));
5426     return nullptr;
5427   case Intrinsic::frameaddress:
5428     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5429                              TLI.getPointerTy(DAG.getDataLayout()),
5430                              getValue(I.getArgOperand(0))));
5431     return nullptr;
5432   case Intrinsic::read_register: {
5433     Value *Reg = I.getArgOperand(0);
5434     SDValue Chain = getRoot();
5435     SDValue RegName =
5436         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5437     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5438     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5439       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5440     setValue(&I, Res);
5441     DAG.setRoot(Res.getValue(1));
5442     return nullptr;
5443   }
5444   case Intrinsic::write_register: {
5445     Value *Reg = I.getArgOperand(0);
5446     Value *RegValue = I.getArgOperand(1);
5447     SDValue Chain = getRoot();
5448     SDValue RegName =
5449         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5450     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5451                             RegName, getValue(RegValue)));
5452     return nullptr;
5453   }
5454   case Intrinsic::setjmp:
5455     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5456   case Intrinsic::longjmp:
5457     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5458   case Intrinsic::memcpy: {
5459     const auto &MCI = cast<MemCpyInst>(I);
5460     SDValue Op1 = getValue(I.getArgOperand(0));
5461     SDValue Op2 = getValue(I.getArgOperand(1));
5462     SDValue Op3 = getValue(I.getArgOperand(2));
5463     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5464     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5465     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5466     unsigned Align = MinAlign(DstAlign, SrcAlign);
5467     bool isVol = MCI.isVolatile();
5468     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5469     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5470     // node.
5471     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5472                                false, isTC,
5473                                MachinePointerInfo(I.getArgOperand(0)),
5474                                MachinePointerInfo(I.getArgOperand(1)));
5475     updateDAGForMaybeTailCall(MC);
5476     return nullptr;
5477   }
5478   case Intrinsic::memset: {
5479     const auto &MSI = cast<MemSetInst>(I);
5480     SDValue Op1 = getValue(I.getArgOperand(0));
5481     SDValue Op2 = getValue(I.getArgOperand(1));
5482     SDValue Op3 = getValue(I.getArgOperand(2));
5483     // @llvm.memset defines 0 and 1 to both mean no alignment.
5484     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5485     bool isVol = MSI.isVolatile();
5486     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5487     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5488                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5489     updateDAGForMaybeTailCall(MS);
5490     return nullptr;
5491   }
5492   case Intrinsic::memmove: {
5493     const auto &MMI = cast<MemMoveInst>(I);
5494     SDValue Op1 = getValue(I.getArgOperand(0));
5495     SDValue Op2 = getValue(I.getArgOperand(1));
5496     SDValue Op3 = getValue(I.getArgOperand(2));
5497     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5498     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5499     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5500     unsigned Align = MinAlign(DstAlign, SrcAlign);
5501     bool isVol = MMI.isVolatile();
5502     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5503     // FIXME: Support passing different dest/src alignments to the memmove DAG
5504     // node.
5505     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5506                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5507                                 MachinePointerInfo(I.getArgOperand(1)));
5508     updateDAGForMaybeTailCall(MM);
5509     return nullptr;
5510   }
5511   case Intrinsic::memcpy_element_unordered_atomic: {
5512     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5513     SDValue Dst = getValue(MI.getRawDest());
5514     SDValue Src = getValue(MI.getRawSource());
5515     SDValue Length = getValue(MI.getLength());
5516 
5517     unsigned DstAlign = MI.getDestAlignment();
5518     unsigned SrcAlign = MI.getSourceAlignment();
5519     Type *LengthTy = MI.getLength()->getType();
5520     unsigned ElemSz = MI.getElementSizeInBytes();
5521     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5522     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5523                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5524                                      MachinePointerInfo(MI.getRawDest()),
5525                                      MachinePointerInfo(MI.getRawSource()));
5526     updateDAGForMaybeTailCall(MC);
5527     return nullptr;
5528   }
5529   case Intrinsic::memmove_element_unordered_atomic: {
5530     auto &MI = cast<AtomicMemMoveInst>(I);
5531     SDValue Dst = getValue(MI.getRawDest());
5532     SDValue Src = getValue(MI.getRawSource());
5533     SDValue Length = getValue(MI.getLength());
5534 
5535     unsigned DstAlign = MI.getDestAlignment();
5536     unsigned SrcAlign = MI.getSourceAlignment();
5537     Type *LengthTy = MI.getLength()->getType();
5538     unsigned ElemSz = MI.getElementSizeInBytes();
5539     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5540     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5541                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5542                                       MachinePointerInfo(MI.getRawDest()),
5543                                       MachinePointerInfo(MI.getRawSource()));
5544     updateDAGForMaybeTailCall(MC);
5545     return nullptr;
5546   }
5547   case Intrinsic::memset_element_unordered_atomic: {
5548     auto &MI = cast<AtomicMemSetInst>(I);
5549     SDValue Dst = getValue(MI.getRawDest());
5550     SDValue Val = getValue(MI.getValue());
5551     SDValue Length = getValue(MI.getLength());
5552 
5553     unsigned DstAlign = MI.getDestAlignment();
5554     Type *LengthTy = MI.getLength()->getType();
5555     unsigned ElemSz = MI.getElementSizeInBytes();
5556     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5557     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5558                                      LengthTy, ElemSz, isTC,
5559                                      MachinePointerInfo(MI.getRawDest()));
5560     updateDAGForMaybeTailCall(MC);
5561     return nullptr;
5562   }
5563   case Intrinsic::dbg_addr:
5564   case Intrinsic::dbg_declare: {
5565     const auto &DI = cast<DbgVariableIntrinsic>(I);
5566     DILocalVariable *Variable = DI.getVariable();
5567     DIExpression *Expression = DI.getExpression();
5568     dropDanglingDebugInfo(Variable, Expression);
5569     assert(Variable && "Missing variable");
5570 
5571     // Check if address has undef value.
5572     const Value *Address = DI.getVariableLocation();
5573     if (!Address || isa<UndefValue>(Address) ||
5574         (Address->use_empty() && !isa<Argument>(Address))) {
5575       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5576       return nullptr;
5577     }
5578 
5579     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5580 
5581     // Check if this variable can be described by a frame index, typically
5582     // either as a static alloca or a byval parameter.
5583     int FI = std::numeric_limits<int>::max();
5584     if (const auto *AI =
5585             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5586       if (AI->isStaticAlloca()) {
5587         auto I = FuncInfo.StaticAllocaMap.find(AI);
5588         if (I != FuncInfo.StaticAllocaMap.end())
5589           FI = I->second;
5590       }
5591     } else if (const auto *Arg = dyn_cast<Argument>(
5592                    Address->stripInBoundsConstantOffsets())) {
5593       FI = FuncInfo.getArgumentFrameIndex(Arg);
5594     }
5595 
5596     // llvm.dbg.addr is control dependent and always generates indirect
5597     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5598     // the MachineFunction variable table.
5599     if (FI != std::numeric_limits<int>::max()) {
5600       if (Intrinsic == Intrinsic::dbg_addr) {
5601         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5602             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5603         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5604       }
5605       return nullptr;
5606     }
5607 
5608     SDValue &N = NodeMap[Address];
5609     if (!N.getNode() && isa<Argument>(Address))
5610       // Check unused arguments map.
5611       N = UnusedArgNodeMap[Address];
5612     SDDbgValue *SDV;
5613     if (N.getNode()) {
5614       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5615         Address = BCI->getOperand(0);
5616       // Parameters are handled specially.
5617       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5618       if (isParameter && FINode) {
5619         // Byval parameter. We have a frame index at this point.
5620         SDV =
5621             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5622                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5623       } else if (isa<Argument>(Address)) {
5624         // Address is an argument, so try to emit its dbg value using
5625         // virtual register info from the FuncInfo.ValueMap.
5626         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5627         return nullptr;
5628       } else {
5629         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5630                               true, dl, SDNodeOrder);
5631       }
5632       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5633     } else {
5634       // If Address is an argument then try to emit its dbg value using
5635       // virtual register info from the FuncInfo.ValueMap.
5636       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5637                                     N)) {
5638         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5639       }
5640     }
5641     return nullptr;
5642   }
5643   case Intrinsic::dbg_label: {
5644     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5645     DILabel *Label = DI.getLabel();
5646     assert(Label && "Missing label");
5647 
5648     SDDbgLabel *SDV;
5649     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5650     DAG.AddDbgLabel(SDV);
5651     return nullptr;
5652   }
5653   case Intrinsic::dbg_value: {
5654     const DbgValueInst &DI = cast<DbgValueInst>(I);
5655     assert(DI.getVariable() && "Missing variable");
5656 
5657     DILocalVariable *Variable = DI.getVariable();
5658     DIExpression *Expression = DI.getExpression();
5659     dropDanglingDebugInfo(Variable, Expression);
5660     const Value *V = DI.getValue();
5661     if (!V)
5662       return nullptr;
5663 
5664     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5665         SDNodeOrder))
5666       return nullptr;
5667 
5668     // TODO: Dangling debug info will eventually either be resolved or produce
5669     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5670     // between the original dbg.value location and its resolved DBG_VALUE, which
5671     // we should ideally fill with an extra Undef DBG_VALUE.
5672 
5673     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5674     return nullptr;
5675   }
5676 
5677   case Intrinsic::eh_typeid_for: {
5678     // Find the type id for the given typeinfo.
5679     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5680     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5681     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5682     setValue(&I, Res);
5683     return nullptr;
5684   }
5685 
5686   case Intrinsic::eh_return_i32:
5687   case Intrinsic::eh_return_i64:
5688     DAG.getMachineFunction().setCallsEHReturn(true);
5689     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5690                             MVT::Other,
5691                             getControlRoot(),
5692                             getValue(I.getArgOperand(0)),
5693                             getValue(I.getArgOperand(1))));
5694     return nullptr;
5695   case Intrinsic::eh_unwind_init:
5696     DAG.getMachineFunction().setCallsUnwindInit(true);
5697     return nullptr;
5698   case Intrinsic::eh_dwarf_cfa:
5699     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5700                              TLI.getPointerTy(DAG.getDataLayout()),
5701                              getValue(I.getArgOperand(0))));
5702     return nullptr;
5703   case Intrinsic::eh_sjlj_callsite: {
5704     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5705     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5706     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5707     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5708 
5709     MMI.setCurrentCallSite(CI->getZExtValue());
5710     return nullptr;
5711   }
5712   case Intrinsic::eh_sjlj_functioncontext: {
5713     // Get and store the index of the function context.
5714     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5715     AllocaInst *FnCtx =
5716       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5717     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5718     MFI.setFunctionContextIndex(FI);
5719     return nullptr;
5720   }
5721   case Intrinsic::eh_sjlj_setjmp: {
5722     SDValue Ops[2];
5723     Ops[0] = getRoot();
5724     Ops[1] = getValue(I.getArgOperand(0));
5725     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5726                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5727     setValue(&I, Op.getValue(0));
5728     DAG.setRoot(Op.getValue(1));
5729     return nullptr;
5730   }
5731   case Intrinsic::eh_sjlj_longjmp:
5732     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5733                             getRoot(), getValue(I.getArgOperand(0))));
5734     return nullptr;
5735   case Intrinsic::eh_sjlj_setup_dispatch:
5736     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5737                             getRoot()));
5738     return nullptr;
5739   case Intrinsic::masked_gather:
5740     visitMaskedGather(I);
5741     return nullptr;
5742   case Intrinsic::masked_load:
5743     visitMaskedLoad(I);
5744     return nullptr;
5745   case Intrinsic::masked_scatter:
5746     visitMaskedScatter(I);
5747     return nullptr;
5748   case Intrinsic::masked_store:
5749     visitMaskedStore(I);
5750     return nullptr;
5751   case Intrinsic::masked_expandload:
5752     visitMaskedLoad(I, true /* IsExpanding */);
5753     return nullptr;
5754   case Intrinsic::masked_compressstore:
5755     visitMaskedStore(I, true /* IsCompressing */);
5756     return nullptr;
5757   case Intrinsic::x86_mmx_pslli_w:
5758   case Intrinsic::x86_mmx_pslli_d:
5759   case Intrinsic::x86_mmx_pslli_q:
5760   case Intrinsic::x86_mmx_psrli_w:
5761   case Intrinsic::x86_mmx_psrli_d:
5762   case Intrinsic::x86_mmx_psrli_q:
5763   case Intrinsic::x86_mmx_psrai_w:
5764   case Intrinsic::x86_mmx_psrai_d: {
5765     SDValue ShAmt = getValue(I.getArgOperand(1));
5766     if (isa<ConstantSDNode>(ShAmt)) {
5767       visitTargetIntrinsic(I, Intrinsic);
5768       return nullptr;
5769     }
5770     unsigned NewIntrinsic = 0;
5771     EVT ShAmtVT = MVT::v2i32;
5772     switch (Intrinsic) {
5773     case Intrinsic::x86_mmx_pslli_w:
5774       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5775       break;
5776     case Intrinsic::x86_mmx_pslli_d:
5777       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5778       break;
5779     case Intrinsic::x86_mmx_pslli_q:
5780       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5781       break;
5782     case Intrinsic::x86_mmx_psrli_w:
5783       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5784       break;
5785     case Intrinsic::x86_mmx_psrli_d:
5786       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5787       break;
5788     case Intrinsic::x86_mmx_psrli_q:
5789       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5790       break;
5791     case Intrinsic::x86_mmx_psrai_w:
5792       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5793       break;
5794     case Intrinsic::x86_mmx_psrai_d:
5795       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5796       break;
5797     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5798     }
5799 
5800     // The vector shift intrinsics with scalars uses 32b shift amounts but
5801     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5802     // to be zero.
5803     // We must do this early because v2i32 is not a legal type.
5804     SDValue ShOps[2];
5805     ShOps[0] = ShAmt;
5806     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5807     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5808     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5809     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5810     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5811                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5812                        getValue(I.getArgOperand(0)), ShAmt);
5813     setValue(&I, Res);
5814     return nullptr;
5815   }
5816   case Intrinsic::powi:
5817     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5818                             getValue(I.getArgOperand(1)), DAG));
5819     return nullptr;
5820   case Intrinsic::log:
5821     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5822     return nullptr;
5823   case Intrinsic::log2:
5824     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5825     return nullptr;
5826   case Intrinsic::log10:
5827     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5828     return nullptr;
5829   case Intrinsic::exp:
5830     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5831     return nullptr;
5832   case Intrinsic::exp2:
5833     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5834     return nullptr;
5835   case Intrinsic::pow:
5836     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5837                            getValue(I.getArgOperand(1)), DAG, TLI));
5838     return nullptr;
5839   case Intrinsic::sqrt:
5840   case Intrinsic::fabs:
5841   case Intrinsic::sin:
5842   case Intrinsic::cos:
5843   case Intrinsic::floor:
5844   case Intrinsic::ceil:
5845   case Intrinsic::trunc:
5846   case Intrinsic::rint:
5847   case Intrinsic::nearbyint:
5848   case Intrinsic::round:
5849   case Intrinsic::canonicalize: {
5850     unsigned Opcode;
5851     switch (Intrinsic) {
5852     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5853     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5854     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5855     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5856     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5857     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5858     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5859     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5860     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5861     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5862     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5863     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5864     }
5865 
5866     setValue(&I, DAG.getNode(Opcode, sdl,
5867                              getValue(I.getArgOperand(0)).getValueType(),
5868                              getValue(I.getArgOperand(0))));
5869     return nullptr;
5870   }
5871   case Intrinsic::minnum: {
5872     auto VT = getValue(I.getArgOperand(0)).getValueType();
5873     unsigned Opc =
5874         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
5875             ? ISD::FMINIMUM
5876             : ISD::FMINNUM;
5877     setValue(&I, DAG.getNode(Opc, sdl, VT,
5878                              getValue(I.getArgOperand(0)),
5879                              getValue(I.getArgOperand(1))));
5880     return nullptr;
5881   }
5882   case Intrinsic::maxnum: {
5883     auto VT = getValue(I.getArgOperand(0)).getValueType();
5884     unsigned Opc =
5885         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
5886             ? ISD::FMAXIMUM
5887             : ISD::FMAXNUM;
5888     setValue(&I, DAG.getNode(Opc, sdl, VT,
5889                              getValue(I.getArgOperand(0)),
5890                              getValue(I.getArgOperand(1))));
5891     return nullptr;
5892   }
5893   case Intrinsic::minimum:
5894     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
5895                              getValue(I.getArgOperand(0)).getValueType(),
5896                              getValue(I.getArgOperand(0)),
5897                              getValue(I.getArgOperand(1))));
5898     return nullptr;
5899   case Intrinsic::maximum:
5900     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
5901                              getValue(I.getArgOperand(0)).getValueType(),
5902                              getValue(I.getArgOperand(0)),
5903                              getValue(I.getArgOperand(1))));
5904     return nullptr;
5905   case Intrinsic::copysign:
5906     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5907                              getValue(I.getArgOperand(0)).getValueType(),
5908                              getValue(I.getArgOperand(0)),
5909                              getValue(I.getArgOperand(1))));
5910     return nullptr;
5911   case Intrinsic::fma:
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     return nullptr;
5918   case Intrinsic::experimental_constrained_fadd:
5919   case Intrinsic::experimental_constrained_fsub:
5920   case Intrinsic::experimental_constrained_fmul:
5921   case Intrinsic::experimental_constrained_fdiv:
5922   case Intrinsic::experimental_constrained_frem:
5923   case Intrinsic::experimental_constrained_fma:
5924   case Intrinsic::experimental_constrained_sqrt:
5925   case Intrinsic::experimental_constrained_pow:
5926   case Intrinsic::experimental_constrained_powi:
5927   case Intrinsic::experimental_constrained_sin:
5928   case Intrinsic::experimental_constrained_cos:
5929   case Intrinsic::experimental_constrained_exp:
5930   case Intrinsic::experimental_constrained_exp2:
5931   case Intrinsic::experimental_constrained_log:
5932   case Intrinsic::experimental_constrained_log10:
5933   case Intrinsic::experimental_constrained_log2:
5934   case Intrinsic::experimental_constrained_rint:
5935   case Intrinsic::experimental_constrained_nearbyint:
5936   case Intrinsic::experimental_constrained_maxnum:
5937   case Intrinsic::experimental_constrained_minnum:
5938   case Intrinsic::experimental_constrained_ceil:
5939   case Intrinsic::experimental_constrained_floor:
5940   case Intrinsic::experimental_constrained_round:
5941   case Intrinsic::experimental_constrained_trunc:
5942     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5943     return nullptr;
5944   case Intrinsic::fmuladd: {
5945     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5946     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5947         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5948       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5949                                getValue(I.getArgOperand(0)).getValueType(),
5950                                getValue(I.getArgOperand(0)),
5951                                getValue(I.getArgOperand(1)),
5952                                getValue(I.getArgOperand(2))));
5953     } else {
5954       // TODO: Intrinsic calls should have fast-math-flags.
5955       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5956                                 getValue(I.getArgOperand(0)).getValueType(),
5957                                 getValue(I.getArgOperand(0)),
5958                                 getValue(I.getArgOperand(1)));
5959       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5960                                 getValue(I.getArgOperand(0)).getValueType(),
5961                                 Mul,
5962                                 getValue(I.getArgOperand(2)));
5963       setValue(&I, Add);
5964     }
5965     return nullptr;
5966   }
5967   case Intrinsic::convert_to_fp16:
5968     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5969                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5970                                          getValue(I.getArgOperand(0)),
5971                                          DAG.getTargetConstant(0, sdl,
5972                                                                MVT::i32))));
5973     return nullptr;
5974   case Intrinsic::convert_from_fp16:
5975     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5976                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5977                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5978                                          getValue(I.getArgOperand(0)))));
5979     return nullptr;
5980   case Intrinsic::pcmarker: {
5981     SDValue Tmp = getValue(I.getArgOperand(0));
5982     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5983     return nullptr;
5984   }
5985   case Intrinsic::readcyclecounter: {
5986     SDValue Op = getRoot();
5987     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5988                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5989     setValue(&I, Res);
5990     DAG.setRoot(Res.getValue(1));
5991     return nullptr;
5992   }
5993   case Intrinsic::bitreverse:
5994     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5995                              getValue(I.getArgOperand(0)).getValueType(),
5996                              getValue(I.getArgOperand(0))));
5997     return nullptr;
5998   case Intrinsic::bswap:
5999     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6000                              getValue(I.getArgOperand(0)).getValueType(),
6001                              getValue(I.getArgOperand(0))));
6002     return nullptr;
6003   case Intrinsic::cttz: {
6004     SDValue Arg = getValue(I.getArgOperand(0));
6005     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6006     EVT Ty = Arg.getValueType();
6007     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6008                              sdl, Ty, Arg));
6009     return nullptr;
6010   }
6011   case Intrinsic::ctlz: {
6012     SDValue Arg = getValue(I.getArgOperand(0));
6013     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6014     EVT Ty = Arg.getValueType();
6015     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6016                              sdl, Ty, Arg));
6017     return nullptr;
6018   }
6019   case Intrinsic::ctpop: {
6020     SDValue Arg = getValue(I.getArgOperand(0));
6021     EVT Ty = Arg.getValueType();
6022     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6023     return nullptr;
6024   }
6025   case Intrinsic::fshl:
6026   case Intrinsic::fshr: {
6027     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6028     SDValue X = getValue(I.getArgOperand(0));
6029     SDValue Y = getValue(I.getArgOperand(1));
6030     SDValue Z = getValue(I.getArgOperand(2));
6031     EVT VT = X.getValueType();
6032     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6033     SDValue Zero = DAG.getConstant(0, sdl, VT);
6034     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6035 
6036     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6037     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6038       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6039       return nullptr;
6040     }
6041 
6042     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6043     // avoid the select that is necessary in the general case to filter out
6044     // the 0-shift possibility that leads to UB.
6045     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6046       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6047       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6048         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6049         return nullptr;
6050       }
6051 
6052       // Some targets only rotate one way. Try the opposite direction.
6053       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6054       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6055         // Negate the shift amount because it is safe to ignore the high bits.
6056         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6057         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6058         return nullptr;
6059       }
6060 
6061       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6062       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6063       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6064       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6065       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6066       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6067       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6068       return nullptr;
6069     }
6070 
6071     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6072     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6073     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6074     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6075     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6076     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6077 
6078     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6079     // and that is undefined. We must compare and select to avoid UB.
6080     EVT CCVT = MVT::i1;
6081     if (VT.isVector())
6082       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6083 
6084     // For fshl, 0-shift returns the 1st arg (X).
6085     // For fshr, 0-shift returns the 2nd arg (Y).
6086     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6087     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6088     return nullptr;
6089   }
6090   case Intrinsic::sadd_sat: {
6091     SDValue Op1 = getValue(I.getArgOperand(0));
6092     SDValue Op2 = getValue(I.getArgOperand(1));
6093     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6094     return nullptr;
6095   }
6096   case Intrinsic::uadd_sat: {
6097     SDValue Op1 = getValue(I.getArgOperand(0));
6098     SDValue Op2 = getValue(I.getArgOperand(1));
6099     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6100     return nullptr;
6101   }
6102   case Intrinsic::ssub_sat: {
6103     SDValue Op1 = getValue(I.getArgOperand(0));
6104     SDValue Op2 = getValue(I.getArgOperand(1));
6105     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6106     return nullptr;
6107   }
6108   case Intrinsic::usub_sat: {
6109     SDValue Op1 = getValue(I.getArgOperand(0));
6110     SDValue Op2 = getValue(I.getArgOperand(1));
6111     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6112     return nullptr;
6113   }
6114   case Intrinsic::smul_fix:
6115   case Intrinsic::umul_fix: {
6116     SDValue Op1 = getValue(I.getArgOperand(0));
6117     SDValue Op2 = getValue(I.getArgOperand(1));
6118     SDValue Op3 = getValue(I.getArgOperand(2));
6119     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6120                              Op1.getValueType(), Op1, Op2, Op3));
6121     return nullptr;
6122   }
6123   case Intrinsic::stacksave: {
6124     SDValue Op = getRoot();
6125     Res = DAG.getNode(
6126         ISD::STACKSAVE, sdl,
6127         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6128     setValue(&I, Res);
6129     DAG.setRoot(Res.getValue(1));
6130     return nullptr;
6131   }
6132   case Intrinsic::stackrestore:
6133     Res = getValue(I.getArgOperand(0));
6134     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6135     return nullptr;
6136   case Intrinsic::get_dynamic_area_offset: {
6137     SDValue Op = getRoot();
6138     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6139     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6140     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6141     // target.
6142     if (PtrTy != ResTy)
6143       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6144                          " intrinsic!");
6145     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6146                       Op);
6147     DAG.setRoot(Op);
6148     setValue(&I, Res);
6149     return nullptr;
6150   }
6151   case Intrinsic::stackguard: {
6152     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6153     MachineFunction &MF = DAG.getMachineFunction();
6154     const Module &M = *MF.getFunction().getParent();
6155     SDValue Chain = getRoot();
6156     if (TLI.useLoadStackGuardNode()) {
6157       Res = getLoadStackGuard(DAG, sdl, Chain);
6158     } else {
6159       const Value *Global = TLI.getSDagStackGuard(M);
6160       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6161       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6162                         MachinePointerInfo(Global, 0), Align,
6163                         MachineMemOperand::MOVolatile);
6164     }
6165     if (TLI.useStackGuardXorFP())
6166       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6167     DAG.setRoot(Chain);
6168     setValue(&I, Res);
6169     return nullptr;
6170   }
6171   case Intrinsic::stackprotector: {
6172     // Emit code into the DAG to store the stack guard onto the stack.
6173     MachineFunction &MF = DAG.getMachineFunction();
6174     MachineFrameInfo &MFI = MF.getFrameInfo();
6175     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6176     SDValue Src, Chain = getRoot();
6177 
6178     if (TLI.useLoadStackGuardNode())
6179       Src = getLoadStackGuard(DAG, sdl, Chain);
6180     else
6181       Src = getValue(I.getArgOperand(0));   // The guard's value.
6182 
6183     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6184 
6185     int FI = FuncInfo.StaticAllocaMap[Slot];
6186     MFI.setStackProtectorIndex(FI);
6187 
6188     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6189 
6190     // Store the stack protector onto the stack.
6191     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6192                                                  DAG.getMachineFunction(), FI),
6193                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6194     setValue(&I, Res);
6195     DAG.setRoot(Res);
6196     return nullptr;
6197   }
6198   case Intrinsic::objectsize: {
6199     // If we don't know by now, we're never going to know.
6200     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
6201 
6202     assert(CI && "Non-constant type in __builtin_object_size?");
6203 
6204     SDValue Arg = getValue(I.getCalledValue());
6205     EVT Ty = Arg.getValueType();
6206 
6207     if (CI->isZero())
6208       Res = DAG.getConstant(-1ULL, sdl, Ty);
6209     else
6210       Res = DAG.getConstant(0, sdl, Ty);
6211 
6212     setValue(&I, Res);
6213     return nullptr;
6214   }
6215 
6216   case Intrinsic::is_constant:
6217     // If this wasn't constant-folded away by now, then it's not a
6218     // constant.
6219     setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
6220     return nullptr;
6221 
6222   case Intrinsic::annotation:
6223   case Intrinsic::ptr_annotation:
6224   case Intrinsic::launder_invariant_group:
6225   case Intrinsic::strip_invariant_group:
6226     // Drop the intrinsic, but forward the value
6227     setValue(&I, getValue(I.getOperand(0)));
6228     return nullptr;
6229   case Intrinsic::assume:
6230   case Intrinsic::var_annotation:
6231   case Intrinsic::sideeffect:
6232     // Discard annotate attributes, assumptions, and artificial side-effects.
6233     return nullptr;
6234 
6235   case Intrinsic::codeview_annotation: {
6236     // Emit a label associated with this metadata.
6237     MachineFunction &MF = DAG.getMachineFunction();
6238     MCSymbol *Label =
6239         MF.getMMI().getContext().createTempSymbol("annotation", true);
6240     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6241     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6242     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6243     DAG.setRoot(Res);
6244     return nullptr;
6245   }
6246 
6247   case Intrinsic::init_trampoline: {
6248     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6249 
6250     SDValue Ops[6];
6251     Ops[0] = getRoot();
6252     Ops[1] = getValue(I.getArgOperand(0));
6253     Ops[2] = getValue(I.getArgOperand(1));
6254     Ops[3] = getValue(I.getArgOperand(2));
6255     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6256     Ops[5] = DAG.getSrcValue(F);
6257 
6258     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6259 
6260     DAG.setRoot(Res);
6261     return nullptr;
6262   }
6263   case Intrinsic::adjust_trampoline:
6264     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6265                              TLI.getPointerTy(DAG.getDataLayout()),
6266                              getValue(I.getArgOperand(0))));
6267     return nullptr;
6268   case Intrinsic::gcroot: {
6269     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6270            "only valid in functions with gc specified, enforced by Verifier");
6271     assert(GFI && "implied by previous");
6272     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6273     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6274 
6275     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6276     GFI->addStackRoot(FI->getIndex(), TypeMap);
6277     return nullptr;
6278   }
6279   case Intrinsic::gcread:
6280   case Intrinsic::gcwrite:
6281     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6282   case Intrinsic::flt_rounds:
6283     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6284     return nullptr;
6285 
6286   case Intrinsic::expect:
6287     // Just replace __builtin_expect(exp, c) with EXP.
6288     setValue(&I, getValue(I.getArgOperand(0)));
6289     return nullptr;
6290 
6291   case Intrinsic::debugtrap:
6292   case Intrinsic::trap: {
6293     StringRef TrapFuncName =
6294         I.getAttributes()
6295             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6296             .getValueAsString();
6297     if (TrapFuncName.empty()) {
6298       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6299         ISD::TRAP : ISD::DEBUGTRAP;
6300       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6301       return nullptr;
6302     }
6303     TargetLowering::ArgListTy Args;
6304 
6305     TargetLowering::CallLoweringInfo CLI(DAG);
6306     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6307         CallingConv::C, I.getType(),
6308         DAG.getExternalSymbol(TrapFuncName.data(),
6309                               TLI.getPointerTy(DAG.getDataLayout())),
6310         std::move(Args));
6311 
6312     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6313     DAG.setRoot(Result.second);
6314     return nullptr;
6315   }
6316 
6317   case Intrinsic::uadd_with_overflow:
6318   case Intrinsic::sadd_with_overflow:
6319   case Intrinsic::usub_with_overflow:
6320   case Intrinsic::ssub_with_overflow:
6321   case Intrinsic::umul_with_overflow:
6322   case Intrinsic::smul_with_overflow: {
6323     ISD::NodeType Op;
6324     switch (Intrinsic) {
6325     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6326     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6327     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6328     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6329     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6330     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6331     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6332     }
6333     SDValue Op1 = getValue(I.getArgOperand(0));
6334     SDValue Op2 = getValue(I.getArgOperand(1));
6335 
6336     EVT ResultVT = Op1.getValueType();
6337     EVT OverflowVT = MVT::i1;
6338     if (ResultVT.isVector())
6339       OverflowVT = EVT::getVectorVT(
6340           *Context, OverflowVT, ResultVT.getVectorNumElements());
6341 
6342     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6343     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6344     return nullptr;
6345   }
6346   case Intrinsic::prefetch: {
6347     SDValue Ops[5];
6348     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6349     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6350     Ops[0] = DAG.getRoot();
6351     Ops[1] = getValue(I.getArgOperand(0));
6352     Ops[2] = getValue(I.getArgOperand(1));
6353     Ops[3] = getValue(I.getArgOperand(2));
6354     Ops[4] = getValue(I.getArgOperand(3));
6355     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6356                                              DAG.getVTList(MVT::Other), Ops,
6357                                              EVT::getIntegerVT(*Context, 8),
6358                                              MachinePointerInfo(I.getArgOperand(0)),
6359                                              0, /* align */
6360                                              Flags);
6361 
6362     // Chain the prefetch in parallell with any pending loads, to stay out of
6363     // the way of later optimizations.
6364     PendingLoads.push_back(Result);
6365     Result = getRoot();
6366     DAG.setRoot(Result);
6367     return nullptr;
6368   }
6369   case Intrinsic::lifetime_start:
6370   case Intrinsic::lifetime_end: {
6371     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6372     // Stack coloring is not enabled in O0, discard region information.
6373     if (TM.getOptLevel() == CodeGenOpt::None)
6374       return nullptr;
6375 
6376     const int64_t ObjectSize =
6377         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6378     Value *const ObjectPtr = I.getArgOperand(1);
6379     SmallVector<Value *, 4> Allocas;
6380     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6381 
6382     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
6383            E = Allocas.end(); Object != E; ++Object) {
6384       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6385 
6386       // Could not find an Alloca.
6387       if (!LifetimeObject)
6388         continue;
6389 
6390       // First check that the Alloca is static, otherwise it won't have a
6391       // valid frame index.
6392       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6393       if (SI == FuncInfo.StaticAllocaMap.end())
6394         return nullptr;
6395 
6396       const int FrameIndex = SI->second;
6397       int64_t Offset;
6398       if (GetPointerBaseWithConstantOffset(
6399               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6400         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6401       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6402                                 Offset);
6403       DAG.setRoot(Res);
6404     }
6405     return nullptr;
6406   }
6407   case Intrinsic::invariant_start:
6408     // Discard region information.
6409     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6410     return nullptr;
6411   case Intrinsic::invariant_end:
6412     // Discard region information.
6413     return nullptr;
6414   case Intrinsic::clear_cache:
6415     return TLI.getClearCacheBuiltinName();
6416   case Intrinsic::donothing:
6417     // ignore
6418     return nullptr;
6419   case Intrinsic::experimental_stackmap:
6420     visitStackmap(I);
6421     return nullptr;
6422   case Intrinsic::experimental_patchpoint_void:
6423   case Intrinsic::experimental_patchpoint_i64:
6424     visitPatchpoint(&I);
6425     return nullptr;
6426   case Intrinsic::experimental_gc_statepoint:
6427     LowerStatepoint(ImmutableStatepoint(&I));
6428     return nullptr;
6429   case Intrinsic::experimental_gc_result:
6430     visitGCResult(cast<GCResultInst>(I));
6431     return nullptr;
6432   case Intrinsic::experimental_gc_relocate:
6433     visitGCRelocate(cast<GCRelocateInst>(I));
6434     return nullptr;
6435   case Intrinsic::instrprof_increment:
6436     llvm_unreachable("instrprof failed to lower an increment");
6437   case Intrinsic::instrprof_value_profile:
6438     llvm_unreachable("instrprof failed to lower a value profiling call");
6439   case Intrinsic::localescape: {
6440     MachineFunction &MF = DAG.getMachineFunction();
6441     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6442 
6443     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6444     // is the same on all targets.
6445     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6446       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6447       if (isa<ConstantPointerNull>(Arg))
6448         continue; // Skip null pointers. They represent a hole in index space.
6449       AllocaInst *Slot = cast<AllocaInst>(Arg);
6450       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6451              "can only escape static allocas");
6452       int FI = FuncInfo.StaticAllocaMap[Slot];
6453       MCSymbol *FrameAllocSym =
6454           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6455               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6456       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6457               TII->get(TargetOpcode::LOCAL_ESCAPE))
6458           .addSym(FrameAllocSym)
6459           .addFrameIndex(FI);
6460     }
6461 
6462     return nullptr;
6463   }
6464 
6465   case Intrinsic::localrecover: {
6466     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6467     MachineFunction &MF = DAG.getMachineFunction();
6468     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6469 
6470     // Get the symbol that defines the frame offset.
6471     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6472     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6473     unsigned IdxVal =
6474         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6475     MCSymbol *FrameAllocSym =
6476         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6477             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6478 
6479     // Create a MCSymbol for the label to avoid any target lowering
6480     // that would make this PC relative.
6481     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6482     SDValue OffsetVal =
6483         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6484 
6485     // Add the offset to the FP.
6486     Value *FP = I.getArgOperand(1);
6487     SDValue FPVal = getValue(FP);
6488     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6489     setValue(&I, Add);
6490 
6491     return nullptr;
6492   }
6493 
6494   case Intrinsic::eh_exceptionpointer:
6495   case Intrinsic::eh_exceptioncode: {
6496     // Get the exception pointer vreg, copy from it, and resize it to fit.
6497     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6498     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6499     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6500     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6501     SDValue N =
6502         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6503     if (Intrinsic == Intrinsic::eh_exceptioncode)
6504       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6505     setValue(&I, N);
6506     return nullptr;
6507   }
6508   case Intrinsic::xray_customevent: {
6509     // Here we want to make sure that the intrinsic behaves as if it has a
6510     // specific calling convention, and only for x86_64.
6511     // FIXME: Support other platforms later.
6512     const auto &Triple = DAG.getTarget().getTargetTriple();
6513     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6514       return nullptr;
6515 
6516     SDLoc DL = getCurSDLoc();
6517     SmallVector<SDValue, 8> Ops;
6518 
6519     // We want to say that we always want the arguments in registers.
6520     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6521     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6522     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6523     SDValue Chain = getRoot();
6524     Ops.push_back(LogEntryVal);
6525     Ops.push_back(StrSizeVal);
6526     Ops.push_back(Chain);
6527 
6528     // We need to enforce the calling convention for the callsite, so that
6529     // argument ordering is enforced correctly, and that register allocation can
6530     // see that some registers may be assumed clobbered and have to preserve
6531     // them across calls to the intrinsic.
6532     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6533                                            DL, NodeTys, Ops);
6534     SDValue patchableNode = SDValue(MN, 0);
6535     DAG.setRoot(patchableNode);
6536     setValue(&I, patchableNode);
6537     return nullptr;
6538   }
6539   case Intrinsic::xray_typedevent: {
6540     // Here we want to make sure that the intrinsic behaves as if it has a
6541     // specific calling convention, and only for x86_64.
6542     // FIXME: Support other platforms later.
6543     const auto &Triple = DAG.getTarget().getTargetTriple();
6544     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6545       return nullptr;
6546 
6547     SDLoc DL = getCurSDLoc();
6548     SmallVector<SDValue, 8> Ops;
6549 
6550     // We want to say that we always want the arguments in registers.
6551     // It's unclear to me how manipulating the selection DAG here forces callers
6552     // to provide arguments in registers instead of on the stack.
6553     SDValue LogTypeId = getValue(I.getArgOperand(0));
6554     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6555     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6556     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6557     SDValue Chain = getRoot();
6558     Ops.push_back(LogTypeId);
6559     Ops.push_back(LogEntryVal);
6560     Ops.push_back(StrSizeVal);
6561     Ops.push_back(Chain);
6562 
6563     // We need to enforce the calling convention for the callsite, so that
6564     // argument ordering is enforced correctly, and that register allocation can
6565     // see that some registers may be assumed clobbered and have to preserve
6566     // them across calls to the intrinsic.
6567     MachineSDNode *MN = DAG.getMachineNode(
6568         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6569     SDValue patchableNode = SDValue(MN, 0);
6570     DAG.setRoot(patchableNode);
6571     setValue(&I, patchableNode);
6572     return nullptr;
6573   }
6574   case Intrinsic::experimental_deoptimize:
6575     LowerDeoptimizeCall(&I);
6576     return nullptr;
6577 
6578   case Intrinsic::experimental_vector_reduce_fadd:
6579   case Intrinsic::experimental_vector_reduce_fmul:
6580   case Intrinsic::experimental_vector_reduce_add:
6581   case Intrinsic::experimental_vector_reduce_mul:
6582   case Intrinsic::experimental_vector_reduce_and:
6583   case Intrinsic::experimental_vector_reduce_or:
6584   case Intrinsic::experimental_vector_reduce_xor:
6585   case Intrinsic::experimental_vector_reduce_smax:
6586   case Intrinsic::experimental_vector_reduce_smin:
6587   case Intrinsic::experimental_vector_reduce_umax:
6588   case Intrinsic::experimental_vector_reduce_umin:
6589   case Intrinsic::experimental_vector_reduce_fmax:
6590   case Intrinsic::experimental_vector_reduce_fmin:
6591     visitVectorReduce(I, Intrinsic);
6592     return nullptr;
6593 
6594   case Intrinsic::icall_branch_funnel: {
6595     SmallVector<SDValue, 16> Ops;
6596     Ops.push_back(DAG.getRoot());
6597     Ops.push_back(getValue(I.getArgOperand(0)));
6598 
6599     int64_t Offset;
6600     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6601         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6602     if (!Base)
6603       report_fatal_error(
6604           "llvm.icall.branch.funnel operand must be a GlobalValue");
6605     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6606 
6607     struct BranchFunnelTarget {
6608       int64_t Offset;
6609       SDValue Target;
6610     };
6611     SmallVector<BranchFunnelTarget, 8> Targets;
6612 
6613     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6614       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6615           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6616       if (ElemBase != Base)
6617         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6618                            "to the same GlobalValue");
6619 
6620       SDValue Val = getValue(I.getArgOperand(Op + 1));
6621       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6622       if (!GA)
6623         report_fatal_error(
6624             "llvm.icall.branch.funnel operand must be a GlobalValue");
6625       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6626                                      GA->getGlobal(), getCurSDLoc(),
6627                                      Val.getValueType(), GA->getOffset())});
6628     }
6629     llvm::sort(Targets,
6630                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6631                  return T1.Offset < T2.Offset;
6632                });
6633 
6634     for (auto &T : Targets) {
6635       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6636       Ops.push_back(T.Target);
6637     }
6638 
6639     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6640                                  getCurSDLoc(), MVT::Other, Ops),
6641               0);
6642     DAG.setRoot(N);
6643     setValue(&I, N);
6644     HasTailCall = true;
6645     return nullptr;
6646   }
6647 
6648   case Intrinsic::wasm_landingpad_index:
6649     // Information this intrinsic contained has been transferred to
6650     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6651     // delete it now.
6652     return nullptr;
6653   }
6654 }
6655 
6656 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6657     const ConstrainedFPIntrinsic &FPI) {
6658   SDLoc sdl = getCurSDLoc();
6659   unsigned Opcode;
6660   switch (FPI.getIntrinsicID()) {
6661   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6662   case Intrinsic::experimental_constrained_fadd:
6663     Opcode = ISD::STRICT_FADD;
6664     break;
6665   case Intrinsic::experimental_constrained_fsub:
6666     Opcode = ISD::STRICT_FSUB;
6667     break;
6668   case Intrinsic::experimental_constrained_fmul:
6669     Opcode = ISD::STRICT_FMUL;
6670     break;
6671   case Intrinsic::experimental_constrained_fdiv:
6672     Opcode = ISD::STRICT_FDIV;
6673     break;
6674   case Intrinsic::experimental_constrained_frem:
6675     Opcode = ISD::STRICT_FREM;
6676     break;
6677   case Intrinsic::experimental_constrained_fma:
6678     Opcode = ISD::STRICT_FMA;
6679     break;
6680   case Intrinsic::experimental_constrained_sqrt:
6681     Opcode = ISD::STRICT_FSQRT;
6682     break;
6683   case Intrinsic::experimental_constrained_pow:
6684     Opcode = ISD::STRICT_FPOW;
6685     break;
6686   case Intrinsic::experimental_constrained_powi:
6687     Opcode = ISD::STRICT_FPOWI;
6688     break;
6689   case Intrinsic::experimental_constrained_sin:
6690     Opcode = ISD::STRICT_FSIN;
6691     break;
6692   case Intrinsic::experimental_constrained_cos:
6693     Opcode = ISD::STRICT_FCOS;
6694     break;
6695   case Intrinsic::experimental_constrained_exp:
6696     Opcode = ISD::STRICT_FEXP;
6697     break;
6698   case Intrinsic::experimental_constrained_exp2:
6699     Opcode = ISD::STRICT_FEXP2;
6700     break;
6701   case Intrinsic::experimental_constrained_log:
6702     Opcode = ISD::STRICT_FLOG;
6703     break;
6704   case Intrinsic::experimental_constrained_log10:
6705     Opcode = ISD::STRICT_FLOG10;
6706     break;
6707   case Intrinsic::experimental_constrained_log2:
6708     Opcode = ISD::STRICT_FLOG2;
6709     break;
6710   case Intrinsic::experimental_constrained_rint:
6711     Opcode = ISD::STRICT_FRINT;
6712     break;
6713   case Intrinsic::experimental_constrained_nearbyint:
6714     Opcode = ISD::STRICT_FNEARBYINT;
6715     break;
6716   case Intrinsic::experimental_constrained_maxnum:
6717     Opcode = ISD::STRICT_FMAXNUM;
6718     break;
6719   case Intrinsic::experimental_constrained_minnum:
6720     Opcode = ISD::STRICT_FMINNUM;
6721     break;
6722   case Intrinsic::experimental_constrained_ceil:
6723     Opcode = ISD::STRICT_FCEIL;
6724     break;
6725   case Intrinsic::experimental_constrained_floor:
6726     Opcode = ISD::STRICT_FFLOOR;
6727     break;
6728   case Intrinsic::experimental_constrained_round:
6729     Opcode = ISD::STRICT_FROUND;
6730     break;
6731   case Intrinsic::experimental_constrained_trunc:
6732     Opcode = ISD::STRICT_FTRUNC;
6733     break;
6734   }
6735   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6736   SDValue Chain = getRoot();
6737   SmallVector<EVT, 4> ValueVTs;
6738   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6739   ValueVTs.push_back(MVT::Other); // Out chain
6740 
6741   SDVTList VTs = DAG.getVTList(ValueVTs);
6742   SDValue Result;
6743   if (FPI.isUnaryOp())
6744     Result = DAG.getNode(Opcode, sdl, VTs,
6745                          { Chain, getValue(FPI.getArgOperand(0)) });
6746   else if (FPI.isTernaryOp())
6747     Result = DAG.getNode(Opcode, sdl, VTs,
6748                          { Chain, getValue(FPI.getArgOperand(0)),
6749                                   getValue(FPI.getArgOperand(1)),
6750                                   getValue(FPI.getArgOperand(2)) });
6751   else
6752     Result = DAG.getNode(Opcode, sdl, VTs,
6753                          { Chain, getValue(FPI.getArgOperand(0)),
6754                            getValue(FPI.getArgOperand(1))  });
6755 
6756   assert(Result.getNode()->getNumValues() == 2);
6757   SDValue OutChain = Result.getValue(1);
6758   DAG.setRoot(OutChain);
6759   SDValue FPResult = Result.getValue(0);
6760   setValue(&FPI, FPResult);
6761 }
6762 
6763 std::pair<SDValue, SDValue>
6764 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6765                                     const BasicBlock *EHPadBB) {
6766   MachineFunction &MF = DAG.getMachineFunction();
6767   MachineModuleInfo &MMI = MF.getMMI();
6768   MCSymbol *BeginLabel = nullptr;
6769 
6770   if (EHPadBB) {
6771     // Insert a label before the invoke call to mark the try range.  This can be
6772     // used to detect deletion of the invoke via the MachineModuleInfo.
6773     BeginLabel = MMI.getContext().createTempSymbol();
6774 
6775     // For SjLj, keep track of which landing pads go with which invokes
6776     // so as to maintain the ordering of pads in the LSDA.
6777     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6778     if (CallSiteIndex) {
6779       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6780       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6781 
6782       // Now that the call site is handled, stop tracking it.
6783       MMI.setCurrentCallSite(0);
6784     }
6785 
6786     // Both PendingLoads and PendingExports must be flushed here;
6787     // this call might not return.
6788     (void)getRoot();
6789     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6790 
6791     CLI.setChain(getRoot());
6792   }
6793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6794   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6795 
6796   assert((CLI.IsTailCall || Result.second.getNode()) &&
6797          "Non-null chain expected with non-tail call!");
6798   assert((Result.second.getNode() || !Result.first.getNode()) &&
6799          "Null value expected with tail call!");
6800 
6801   if (!Result.second.getNode()) {
6802     // As a special case, a null chain means that a tail call has been emitted
6803     // and the DAG root is already updated.
6804     HasTailCall = true;
6805 
6806     // Since there's no actual continuation from this block, nothing can be
6807     // relying on us setting vregs for them.
6808     PendingExports.clear();
6809   } else {
6810     DAG.setRoot(Result.second);
6811   }
6812 
6813   if (EHPadBB) {
6814     // Insert a label at the end of the invoke call to mark the try range.  This
6815     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6816     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6817     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6818 
6819     // Inform MachineModuleInfo of range.
6820     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6821     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6822     // actually use outlined funclets and their LSDA info style.
6823     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6824       assert(CLI.CS);
6825       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6826       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6827                                 BeginLabel, EndLabel);
6828     } else if (!isScopedEHPersonality(Pers)) {
6829       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6830     }
6831   }
6832 
6833   return Result;
6834 }
6835 
6836 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6837                                       bool isTailCall,
6838                                       const BasicBlock *EHPadBB) {
6839   auto &DL = DAG.getDataLayout();
6840   FunctionType *FTy = CS.getFunctionType();
6841   Type *RetTy = CS.getType();
6842 
6843   TargetLowering::ArgListTy Args;
6844   Args.reserve(CS.arg_size());
6845 
6846   const Value *SwiftErrorVal = nullptr;
6847   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6848 
6849   // We can't tail call inside a function with a swifterror argument. Lowering
6850   // does not support this yet. It would have to move into the swifterror
6851   // register before the call.
6852   auto *Caller = CS.getInstruction()->getParent()->getParent();
6853   if (TLI.supportSwiftError() &&
6854       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6855     isTailCall = false;
6856 
6857   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6858        i != e; ++i) {
6859     TargetLowering::ArgListEntry Entry;
6860     const Value *V = *i;
6861 
6862     // Skip empty types
6863     if (V->getType()->isEmptyTy())
6864       continue;
6865 
6866     SDValue ArgNode = getValue(V);
6867     Entry.Node = ArgNode; Entry.Ty = V->getType();
6868 
6869     Entry.setAttributes(&CS, i - CS.arg_begin());
6870 
6871     // Use swifterror virtual register as input to the call.
6872     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6873       SwiftErrorVal = V;
6874       // We find the virtual register for the actual swifterror argument.
6875       // Instead of using the Value, we use the virtual register instead.
6876       Entry.Node = DAG.getRegister(FuncInfo
6877                                        .getOrCreateSwiftErrorVRegUseAt(
6878                                            CS.getInstruction(), FuncInfo.MBB, V)
6879                                        .first,
6880                                    EVT(TLI.getPointerTy(DL)));
6881     }
6882 
6883     Args.push_back(Entry);
6884 
6885     // If we have an explicit sret argument that is an Instruction, (i.e., it
6886     // might point to function-local memory), we can't meaningfully tail-call.
6887     if (Entry.IsSRet && isa<Instruction>(V))
6888       isTailCall = false;
6889   }
6890 
6891   // Check if target-independent constraints permit a tail call here.
6892   // Target-dependent constraints are checked within TLI->LowerCallTo.
6893   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6894     isTailCall = false;
6895 
6896   // Disable tail calls if there is an swifterror argument. Targets have not
6897   // been updated to support tail calls.
6898   if (TLI.supportSwiftError() && SwiftErrorVal)
6899     isTailCall = false;
6900 
6901   TargetLowering::CallLoweringInfo CLI(DAG);
6902   CLI.setDebugLoc(getCurSDLoc())
6903       .setChain(getRoot())
6904       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6905       .setTailCall(isTailCall)
6906       .setConvergent(CS.isConvergent());
6907   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6908 
6909   if (Result.first.getNode()) {
6910     const Instruction *Inst = CS.getInstruction();
6911     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6912     setValue(Inst, Result.first);
6913   }
6914 
6915   // The last element of CLI.InVals has the SDValue for swifterror return.
6916   // Here we copy it to a virtual register and update SwiftErrorMap for
6917   // book-keeping.
6918   if (SwiftErrorVal && TLI.supportSwiftError()) {
6919     // Get the last element of InVals.
6920     SDValue Src = CLI.InVals.back();
6921     unsigned VReg; bool CreatedVReg;
6922     std::tie(VReg, CreatedVReg) =
6923         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6924     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6925     // We update the virtual register for the actual swifterror argument.
6926     if (CreatedVReg)
6927       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6928     DAG.setRoot(CopyNode);
6929   }
6930 }
6931 
6932 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6933                              SelectionDAGBuilder &Builder) {
6934   // Check to see if this load can be trivially constant folded, e.g. if the
6935   // input is from a string literal.
6936   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6937     // Cast pointer to the type we really want to load.
6938     Type *LoadTy =
6939         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6940     if (LoadVT.isVector())
6941       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6942 
6943     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6944                                          PointerType::getUnqual(LoadTy));
6945 
6946     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6947             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6948       return Builder.getValue(LoadCst);
6949   }
6950 
6951   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6952   // still constant memory, the input chain can be the entry node.
6953   SDValue Root;
6954   bool ConstantMemory = false;
6955 
6956   // Do not serialize (non-volatile) loads of constant memory with anything.
6957   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6958     Root = Builder.DAG.getEntryNode();
6959     ConstantMemory = true;
6960   } else {
6961     // Do not serialize non-volatile loads against each other.
6962     Root = Builder.DAG.getRoot();
6963   }
6964 
6965   SDValue Ptr = Builder.getValue(PtrVal);
6966   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6967                                         Ptr, MachinePointerInfo(PtrVal),
6968                                         /* Alignment = */ 1);
6969 
6970   if (!ConstantMemory)
6971     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6972   return LoadVal;
6973 }
6974 
6975 /// Record the value for an instruction that produces an integer result,
6976 /// converting the type where necessary.
6977 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6978                                                   SDValue Value,
6979                                                   bool IsSigned) {
6980   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6981                                                     I.getType(), true);
6982   if (IsSigned)
6983     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6984   else
6985     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6986   setValue(&I, Value);
6987 }
6988 
6989 /// See if we can lower a memcmp call into an optimized form. If so, return
6990 /// true and lower it. Otherwise return false, and it will be lowered like a
6991 /// normal call.
6992 /// The caller already checked that \p I calls the appropriate LibFunc with a
6993 /// correct prototype.
6994 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6995   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6996   const Value *Size = I.getArgOperand(2);
6997   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6998   if (CSize && CSize->getZExtValue() == 0) {
6999     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7000                                                           I.getType(), true);
7001     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7002     return true;
7003   }
7004 
7005   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7006   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7007       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7008       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7009   if (Res.first.getNode()) {
7010     processIntegerCallValue(I, Res.first, true);
7011     PendingLoads.push_back(Res.second);
7012     return true;
7013   }
7014 
7015   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7016   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7017   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7018     return false;
7019 
7020   // If the target has a fast compare for the given size, it will return a
7021   // preferred load type for that size. Require that the load VT is legal and
7022   // that the target supports unaligned loads of that type. Otherwise, return
7023   // INVALID.
7024   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7025     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7026     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7027     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7028       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7029       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7030       // TODO: Check alignment of src and dest ptrs.
7031       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7032       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7033       if (!TLI.isTypeLegal(LVT) ||
7034           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7035           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7036         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7037     }
7038 
7039     return LVT;
7040   };
7041 
7042   // This turns into unaligned loads. We only do this if the target natively
7043   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7044   // we'll only produce a small number of byte loads.
7045   MVT LoadVT;
7046   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7047   switch (NumBitsToCompare) {
7048   default:
7049     return false;
7050   case 16:
7051     LoadVT = MVT::i16;
7052     break;
7053   case 32:
7054     LoadVT = MVT::i32;
7055     break;
7056   case 64:
7057   case 128:
7058   case 256:
7059     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7060     break;
7061   }
7062 
7063   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7064     return false;
7065 
7066   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7067   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7068 
7069   // Bitcast to a wide integer type if the loads are vectors.
7070   if (LoadVT.isVector()) {
7071     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7072     LoadL = DAG.getBitcast(CmpVT, LoadL);
7073     LoadR = DAG.getBitcast(CmpVT, LoadR);
7074   }
7075 
7076   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7077   processIntegerCallValue(I, Cmp, false);
7078   return true;
7079 }
7080 
7081 /// See if we can lower a memchr call into an optimized form. If so, return
7082 /// true and lower it. Otherwise return false, and it will be lowered like a
7083 /// normal call.
7084 /// The caller already checked that \p I calls the appropriate LibFunc with a
7085 /// correct prototype.
7086 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7087   const Value *Src = I.getArgOperand(0);
7088   const Value *Char = I.getArgOperand(1);
7089   const Value *Length = I.getArgOperand(2);
7090 
7091   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7092   std::pair<SDValue, SDValue> Res =
7093     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7094                                 getValue(Src), getValue(Char), getValue(Length),
7095                                 MachinePointerInfo(Src));
7096   if (Res.first.getNode()) {
7097     setValue(&I, Res.first);
7098     PendingLoads.push_back(Res.second);
7099     return true;
7100   }
7101 
7102   return false;
7103 }
7104 
7105 /// See if we can lower a mempcpy call into an optimized form. If so, return
7106 /// true and lower it. Otherwise return false, and it will be lowered like a
7107 /// normal call.
7108 /// The caller already checked that \p I calls the appropriate LibFunc with a
7109 /// correct prototype.
7110 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7111   SDValue Dst = getValue(I.getArgOperand(0));
7112   SDValue Src = getValue(I.getArgOperand(1));
7113   SDValue Size = getValue(I.getArgOperand(2));
7114 
7115   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7116   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7117   unsigned Align = std::min(DstAlign, SrcAlign);
7118   if (Align == 0) // Alignment of one or both could not be inferred.
7119     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7120 
7121   bool isVol = false;
7122   SDLoc sdl = getCurSDLoc();
7123 
7124   // In the mempcpy context we need to pass in a false value for isTailCall
7125   // because the return pointer needs to be adjusted by the size of
7126   // the copied memory.
7127   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7128                              false, /*isTailCall=*/false,
7129                              MachinePointerInfo(I.getArgOperand(0)),
7130                              MachinePointerInfo(I.getArgOperand(1)));
7131   assert(MC.getNode() != nullptr &&
7132          "** memcpy should not be lowered as TailCall in mempcpy context **");
7133   DAG.setRoot(MC);
7134 
7135   // Check if Size needs to be truncated or extended.
7136   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7137 
7138   // Adjust return pointer to point just past the last dst byte.
7139   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7140                                     Dst, Size);
7141   setValue(&I, DstPlusSize);
7142   return true;
7143 }
7144 
7145 /// See if we can lower a strcpy call into an optimized form.  If so, return
7146 /// true and lower it, otherwise return false and it will be lowered like a
7147 /// normal call.
7148 /// The caller already checked that \p I calls the appropriate LibFunc with a
7149 /// correct prototype.
7150 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7151   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7152 
7153   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7154   std::pair<SDValue, SDValue> Res =
7155     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7156                                 getValue(Arg0), getValue(Arg1),
7157                                 MachinePointerInfo(Arg0),
7158                                 MachinePointerInfo(Arg1), isStpcpy);
7159   if (Res.first.getNode()) {
7160     setValue(&I, Res.first);
7161     DAG.setRoot(Res.second);
7162     return true;
7163   }
7164 
7165   return false;
7166 }
7167 
7168 /// See if we can lower a strcmp call into an optimized form.  If so, return
7169 /// true and lower it, otherwise return false and it will be lowered like a
7170 /// normal call.
7171 /// The caller already checked that \p I calls the appropriate LibFunc with a
7172 /// correct prototype.
7173 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7174   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7175 
7176   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7177   std::pair<SDValue, SDValue> Res =
7178     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7179                                 getValue(Arg0), getValue(Arg1),
7180                                 MachinePointerInfo(Arg0),
7181                                 MachinePointerInfo(Arg1));
7182   if (Res.first.getNode()) {
7183     processIntegerCallValue(I, Res.first, true);
7184     PendingLoads.push_back(Res.second);
7185     return true;
7186   }
7187 
7188   return false;
7189 }
7190 
7191 /// See if we can lower a strlen call into an optimized form.  If so, return
7192 /// true and lower it, otherwise return false and it will be lowered like a
7193 /// normal call.
7194 /// The caller already checked that \p I calls the appropriate LibFunc with a
7195 /// correct prototype.
7196 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7197   const Value *Arg0 = I.getArgOperand(0);
7198 
7199   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7200   std::pair<SDValue, SDValue> Res =
7201     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7202                                 getValue(Arg0), MachinePointerInfo(Arg0));
7203   if (Res.first.getNode()) {
7204     processIntegerCallValue(I, Res.first, false);
7205     PendingLoads.push_back(Res.second);
7206     return true;
7207   }
7208 
7209   return false;
7210 }
7211 
7212 /// See if we can lower a strnlen call into an optimized form.  If so, return
7213 /// true and lower it, otherwise return false and it will be lowered like a
7214 /// normal call.
7215 /// The caller already checked that \p I calls the appropriate LibFunc with a
7216 /// correct prototype.
7217 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7218   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7219 
7220   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7221   std::pair<SDValue, SDValue> Res =
7222     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7223                                  getValue(Arg0), getValue(Arg1),
7224                                  MachinePointerInfo(Arg0));
7225   if (Res.first.getNode()) {
7226     processIntegerCallValue(I, Res.first, false);
7227     PendingLoads.push_back(Res.second);
7228     return true;
7229   }
7230 
7231   return false;
7232 }
7233 
7234 /// See if we can lower a unary floating-point operation into an SDNode with
7235 /// the specified Opcode.  If so, return true and lower it, otherwise return
7236 /// false and it will be lowered like a normal call.
7237 /// The caller already checked that \p I calls the appropriate LibFunc with a
7238 /// correct prototype.
7239 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7240                                               unsigned Opcode) {
7241   // We already checked this call's prototype; verify it doesn't modify errno.
7242   if (!I.onlyReadsMemory())
7243     return false;
7244 
7245   SDValue Tmp = getValue(I.getArgOperand(0));
7246   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7247   return true;
7248 }
7249 
7250 /// See if we can lower a binary floating-point operation into an SDNode with
7251 /// the specified Opcode. If so, return true and lower it. Otherwise return
7252 /// false, and it will be lowered like a normal call.
7253 /// The caller already checked that \p I calls the appropriate LibFunc with a
7254 /// correct prototype.
7255 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7256                                                unsigned Opcode) {
7257   // We already checked this call's prototype; verify it doesn't modify errno.
7258   if (!I.onlyReadsMemory())
7259     return false;
7260 
7261   SDValue Tmp0 = getValue(I.getArgOperand(0));
7262   SDValue Tmp1 = getValue(I.getArgOperand(1));
7263   EVT VT = Tmp0.getValueType();
7264   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7265   return true;
7266 }
7267 
7268 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7269   // Handle inline assembly differently.
7270   if (isa<InlineAsm>(I.getCalledValue())) {
7271     visitInlineAsm(&I);
7272     return;
7273   }
7274 
7275   const char *RenameFn = nullptr;
7276   if (Function *F = I.getCalledFunction()) {
7277     if (F->isDeclaration()) {
7278       // Is this an LLVM intrinsic or a target-specific intrinsic?
7279       unsigned IID = F->getIntrinsicID();
7280       if (!IID)
7281         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7282           IID = II->getIntrinsicID(F);
7283 
7284       if (IID) {
7285         RenameFn = visitIntrinsicCall(I, IID);
7286         if (!RenameFn)
7287           return;
7288       }
7289     }
7290 
7291     // Check for well-known libc/libm calls.  If the function is internal, it
7292     // can't be a library call.  Don't do the check if marked as nobuiltin for
7293     // some reason or the call site requires strict floating point semantics.
7294     LibFunc Func;
7295     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7296         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7297         LibInfo->hasOptimizedCodeGen(Func)) {
7298       switch (Func) {
7299       default: break;
7300       case LibFunc_copysign:
7301       case LibFunc_copysignf:
7302       case LibFunc_copysignl:
7303         // We already checked this call's prototype; verify it doesn't modify
7304         // errno.
7305         if (I.onlyReadsMemory()) {
7306           SDValue LHS = getValue(I.getArgOperand(0));
7307           SDValue RHS = getValue(I.getArgOperand(1));
7308           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7309                                    LHS.getValueType(), LHS, RHS));
7310           return;
7311         }
7312         break;
7313       case LibFunc_fabs:
7314       case LibFunc_fabsf:
7315       case LibFunc_fabsl:
7316         if (visitUnaryFloatCall(I, ISD::FABS))
7317           return;
7318         break;
7319       case LibFunc_fmin:
7320       case LibFunc_fminf:
7321       case LibFunc_fminl:
7322         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7323           return;
7324         break;
7325       case LibFunc_fmax:
7326       case LibFunc_fmaxf:
7327       case LibFunc_fmaxl:
7328         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7329           return;
7330         break;
7331       case LibFunc_sin:
7332       case LibFunc_sinf:
7333       case LibFunc_sinl:
7334         if (visitUnaryFloatCall(I, ISD::FSIN))
7335           return;
7336         break;
7337       case LibFunc_cos:
7338       case LibFunc_cosf:
7339       case LibFunc_cosl:
7340         if (visitUnaryFloatCall(I, ISD::FCOS))
7341           return;
7342         break;
7343       case LibFunc_sqrt:
7344       case LibFunc_sqrtf:
7345       case LibFunc_sqrtl:
7346       case LibFunc_sqrt_finite:
7347       case LibFunc_sqrtf_finite:
7348       case LibFunc_sqrtl_finite:
7349         if (visitUnaryFloatCall(I, ISD::FSQRT))
7350           return;
7351         break;
7352       case LibFunc_floor:
7353       case LibFunc_floorf:
7354       case LibFunc_floorl:
7355         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7356           return;
7357         break;
7358       case LibFunc_nearbyint:
7359       case LibFunc_nearbyintf:
7360       case LibFunc_nearbyintl:
7361         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7362           return;
7363         break;
7364       case LibFunc_ceil:
7365       case LibFunc_ceilf:
7366       case LibFunc_ceill:
7367         if (visitUnaryFloatCall(I, ISD::FCEIL))
7368           return;
7369         break;
7370       case LibFunc_rint:
7371       case LibFunc_rintf:
7372       case LibFunc_rintl:
7373         if (visitUnaryFloatCall(I, ISD::FRINT))
7374           return;
7375         break;
7376       case LibFunc_round:
7377       case LibFunc_roundf:
7378       case LibFunc_roundl:
7379         if (visitUnaryFloatCall(I, ISD::FROUND))
7380           return;
7381         break;
7382       case LibFunc_trunc:
7383       case LibFunc_truncf:
7384       case LibFunc_truncl:
7385         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7386           return;
7387         break;
7388       case LibFunc_log2:
7389       case LibFunc_log2f:
7390       case LibFunc_log2l:
7391         if (visitUnaryFloatCall(I, ISD::FLOG2))
7392           return;
7393         break;
7394       case LibFunc_exp2:
7395       case LibFunc_exp2f:
7396       case LibFunc_exp2l:
7397         if (visitUnaryFloatCall(I, ISD::FEXP2))
7398           return;
7399         break;
7400       case LibFunc_memcmp:
7401         if (visitMemCmpCall(I))
7402           return;
7403         break;
7404       case LibFunc_mempcpy:
7405         if (visitMemPCpyCall(I))
7406           return;
7407         break;
7408       case LibFunc_memchr:
7409         if (visitMemChrCall(I))
7410           return;
7411         break;
7412       case LibFunc_strcpy:
7413         if (visitStrCpyCall(I, false))
7414           return;
7415         break;
7416       case LibFunc_stpcpy:
7417         if (visitStrCpyCall(I, true))
7418           return;
7419         break;
7420       case LibFunc_strcmp:
7421         if (visitStrCmpCall(I))
7422           return;
7423         break;
7424       case LibFunc_strlen:
7425         if (visitStrLenCall(I))
7426           return;
7427         break;
7428       case LibFunc_strnlen:
7429         if (visitStrNLenCall(I))
7430           return;
7431         break;
7432       }
7433     }
7434   }
7435 
7436   SDValue Callee;
7437   if (!RenameFn)
7438     Callee = getValue(I.getCalledValue());
7439   else
7440     Callee = DAG.getExternalSymbol(
7441         RenameFn,
7442         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7443 
7444   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7445   // have to do anything here to lower funclet bundles.
7446   assert(!I.hasOperandBundlesOtherThan(
7447              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7448          "Cannot lower calls with arbitrary operand bundles!");
7449 
7450   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7451     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7452   else
7453     // Check if we can potentially perform a tail call. More detailed checking
7454     // is be done within LowerCallTo, after more information about the call is
7455     // known.
7456     LowerCallTo(&I, Callee, I.isTailCall());
7457 }
7458 
7459 namespace {
7460 
7461 /// AsmOperandInfo - This contains information for each constraint that we are
7462 /// lowering.
7463 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7464 public:
7465   /// CallOperand - If this is the result output operand or a clobber
7466   /// this is null, otherwise it is the incoming operand to the CallInst.
7467   /// This gets modified as the asm is processed.
7468   SDValue CallOperand;
7469 
7470   /// AssignedRegs - If this is a register or register class operand, this
7471   /// contains the set of register corresponding to the operand.
7472   RegsForValue AssignedRegs;
7473 
7474   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7475     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7476   }
7477 
7478   /// Whether or not this operand accesses memory
7479   bool hasMemory(const TargetLowering &TLI) const {
7480     // Indirect operand accesses access memory.
7481     if (isIndirect)
7482       return true;
7483 
7484     for (const auto &Code : Codes)
7485       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7486         return true;
7487 
7488     return false;
7489   }
7490 
7491   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7492   /// corresponds to.  If there is no Value* for this operand, it returns
7493   /// MVT::Other.
7494   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7495                            const DataLayout &DL) const {
7496     if (!CallOperandVal) return MVT::Other;
7497 
7498     if (isa<BasicBlock>(CallOperandVal))
7499       return TLI.getPointerTy(DL);
7500 
7501     llvm::Type *OpTy = CallOperandVal->getType();
7502 
7503     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7504     // If this is an indirect operand, the operand is a pointer to the
7505     // accessed type.
7506     if (isIndirect) {
7507       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7508       if (!PtrTy)
7509         report_fatal_error("Indirect operand for inline asm not a pointer!");
7510       OpTy = PtrTy->getElementType();
7511     }
7512 
7513     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7514     if (StructType *STy = dyn_cast<StructType>(OpTy))
7515       if (STy->getNumElements() == 1)
7516         OpTy = STy->getElementType(0);
7517 
7518     // If OpTy is not a single value, it may be a struct/union that we
7519     // can tile with integers.
7520     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7521       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7522       switch (BitSize) {
7523       default: break;
7524       case 1:
7525       case 8:
7526       case 16:
7527       case 32:
7528       case 64:
7529       case 128:
7530         OpTy = IntegerType::get(Context, BitSize);
7531         break;
7532       }
7533     }
7534 
7535     return TLI.getValueType(DL, OpTy, true);
7536   }
7537 };
7538 
7539 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7540 
7541 } // end anonymous namespace
7542 
7543 /// Make sure that the output operand \p OpInfo and its corresponding input
7544 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7545 /// out).
7546 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7547                                SDISelAsmOperandInfo &MatchingOpInfo,
7548                                SelectionDAG &DAG) {
7549   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7550     return;
7551 
7552   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7553   const auto &TLI = DAG.getTargetLoweringInfo();
7554 
7555   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7556       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7557                                        OpInfo.ConstraintVT);
7558   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7559       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7560                                        MatchingOpInfo.ConstraintVT);
7561   if ((OpInfo.ConstraintVT.isInteger() !=
7562        MatchingOpInfo.ConstraintVT.isInteger()) ||
7563       (MatchRC.second != InputRC.second)) {
7564     // FIXME: error out in a more elegant fashion
7565     report_fatal_error("Unsupported asm: input constraint"
7566                        " with a matching output constraint of"
7567                        " incompatible type!");
7568   }
7569   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7570 }
7571 
7572 /// Get a direct memory input to behave well as an indirect operand.
7573 /// This may introduce stores, hence the need for a \p Chain.
7574 /// \return The (possibly updated) chain.
7575 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7576                                         SDISelAsmOperandInfo &OpInfo,
7577                                         SelectionDAG &DAG) {
7578   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7579 
7580   // If we don't have an indirect input, put it in the constpool if we can,
7581   // otherwise spill it to a stack slot.
7582   // TODO: This isn't quite right. We need to handle these according to
7583   // the addressing mode that the constraint wants. Also, this may take
7584   // an additional register for the computation and we don't want that
7585   // either.
7586 
7587   // If the operand is a float, integer, or vector constant, spill to a
7588   // constant pool entry to get its address.
7589   const Value *OpVal = OpInfo.CallOperandVal;
7590   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7591       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7592     OpInfo.CallOperand = DAG.getConstantPool(
7593         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7594     return Chain;
7595   }
7596 
7597   // Otherwise, create a stack slot and emit a store to it before the asm.
7598   Type *Ty = OpVal->getType();
7599   auto &DL = DAG.getDataLayout();
7600   uint64_t TySize = DL.getTypeAllocSize(Ty);
7601   unsigned Align = DL.getPrefTypeAlignment(Ty);
7602   MachineFunction &MF = DAG.getMachineFunction();
7603   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7604   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7605   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7606                        MachinePointerInfo::getFixedStack(MF, SSFI));
7607   OpInfo.CallOperand = StackSlot;
7608 
7609   return Chain;
7610 }
7611 
7612 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7613 /// specified operand.  We prefer to assign virtual registers, to allow the
7614 /// register allocator to handle the assignment process.  However, if the asm
7615 /// uses features that we can't model on machineinstrs, we have SDISel do the
7616 /// allocation.  This produces generally horrible, but correct, code.
7617 ///
7618 ///   OpInfo describes the operand
7619 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7620 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7621                                  SDISelAsmOperandInfo &OpInfo,
7622                                  SDISelAsmOperandInfo &RefOpInfo) {
7623   LLVMContext &Context = *DAG.getContext();
7624   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7625 
7626   MachineFunction &MF = DAG.getMachineFunction();
7627   SmallVector<unsigned, 4> Regs;
7628   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7629 
7630   // No work to do for memory operations.
7631   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7632     return;
7633 
7634   // If this is a constraint for a single physreg, or a constraint for a
7635   // register class, find it.
7636   unsigned AssignedReg;
7637   const TargetRegisterClass *RC;
7638   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7639       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7640   // RC is unset only on failure. Return immediately.
7641   if (!RC)
7642     return;
7643 
7644   // Get the actual register value type.  This is important, because the user
7645   // may have asked for (e.g.) the AX register in i32 type.  We need to
7646   // remember that AX is actually i16 to get the right extension.
7647   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7648 
7649   if (OpInfo.ConstraintVT != MVT::Other) {
7650     // If this is an FP operand in an integer register (or visa versa), or more
7651     // generally if the operand value disagrees with the register class we plan
7652     // to stick it in, fix the operand type.
7653     //
7654     // If this is an input value, the bitcast to the new type is done now.
7655     // Bitcast for output value is done at the end of visitInlineAsm().
7656     if ((OpInfo.Type == InlineAsm::isOutput ||
7657          OpInfo.Type == InlineAsm::isInput) &&
7658         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7659       // Try to convert to the first EVT that the reg class contains.  If the
7660       // types are identical size, use a bitcast to convert (e.g. two differing
7661       // vector types).  Note: output bitcast is done at the end of
7662       // visitInlineAsm().
7663       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7664         // Exclude indirect inputs while they are unsupported because the code
7665         // to perform the load is missing and thus OpInfo.CallOperand still
7666         // refers to the input address rather than the pointed-to value.
7667         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7668           OpInfo.CallOperand =
7669               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7670         OpInfo.ConstraintVT = RegVT;
7671         // If the operand is an FP value and we want it in integer registers,
7672         // use the corresponding integer type. This turns an f64 value into
7673         // i64, which can be passed with two i32 values on a 32-bit machine.
7674       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7675         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7676         if (OpInfo.Type == InlineAsm::isInput)
7677           OpInfo.CallOperand =
7678               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7679         OpInfo.ConstraintVT = VT;
7680       }
7681     }
7682   }
7683 
7684   // No need to allocate a matching input constraint since the constraint it's
7685   // matching to has already been allocated.
7686   if (OpInfo.isMatchingInputConstraint())
7687     return;
7688 
7689   EVT ValueVT = OpInfo.ConstraintVT;
7690   if (OpInfo.ConstraintVT == MVT::Other)
7691     ValueVT = RegVT;
7692 
7693   // Initialize NumRegs.
7694   unsigned NumRegs = 1;
7695   if (OpInfo.ConstraintVT != MVT::Other)
7696     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7697 
7698   // If this is a constraint for a specific physical register, like {r17},
7699   // assign it now.
7700 
7701   // If this associated to a specific register, initialize iterator to correct
7702   // place. If virtual, make sure we have enough registers
7703 
7704   // Initialize iterator if necessary
7705   TargetRegisterClass::iterator I = RC->begin();
7706   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7707 
7708   // Do not check for single registers.
7709   if (AssignedReg) {
7710       for (; *I != AssignedReg; ++I)
7711         assert(I != RC->end() && "AssignedReg should be member of RC");
7712   }
7713 
7714   for (; NumRegs; --NumRegs, ++I) {
7715     assert(I != RC->end() && "Ran out of registers to allocate!");
7716     auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC);
7717     Regs.push_back(R);
7718   }
7719 
7720   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7721 }
7722 
7723 static unsigned
7724 findMatchingInlineAsmOperand(unsigned OperandNo,
7725                              const std::vector<SDValue> &AsmNodeOperands) {
7726   // Scan until we find the definition we already emitted of this operand.
7727   unsigned CurOp = InlineAsm::Op_FirstOperand;
7728   for (; OperandNo; --OperandNo) {
7729     // Advance to the next operand.
7730     unsigned OpFlag =
7731         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7732     assert((InlineAsm::isRegDefKind(OpFlag) ||
7733             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7734             InlineAsm::isMemKind(OpFlag)) &&
7735            "Skipped past definitions?");
7736     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7737   }
7738   return CurOp;
7739 }
7740 
7741 namespace {
7742 
7743 class ExtraFlags {
7744   unsigned Flags = 0;
7745 
7746 public:
7747   explicit ExtraFlags(ImmutableCallSite CS) {
7748     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7749     if (IA->hasSideEffects())
7750       Flags |= InlineAsm::Extra_HasSideEffects;
7751     if (IA->isAlignStack())
7752       Flags |= InlineAsm::Extra_IsAlignStack;
7753     if (CS.isConvergent())
7754       Flags |= InlineAsm::Extra_IsConvergent;
7755     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7756   }
7757 
7758   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7759     // Ideally, we would only check against memory constraints.  However, the
7760     // meaning of an Other constraint can be target-specific and we can't easily
7761     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7762     // for Other constraints as well.
7763     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7764         OpInfo.ConstraintType == TargetLowering::C_Other) {
7765       if (OpInfo.Type == InlineAsm::isInput)
7766         Flags |= InlineAsm::Extra_MayLoad;
7767       else if (OpInfo.Type == InlineAsm::isOutput)
7768         Flags |= InlineAsm::Extra_MayStore;
7769       else if (OpInfo.Type == InlineAsm::isClobber)
7770         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7771     }
7772   }
7773 
7774   unsigned get() const { return Flags; }
7775 };
7776 
7777 } // end anonymous namespace
7778 
7779 /// visitInlineAsm - Handle a call to an InlineAsm object.
7780 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7781   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7782 
7783   /// ConstraintOperands - Information about all of the constraints.
7784   SDISelAsmOperandInfoVector ConstraintOperands;
7785 
7786   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7787   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7788       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7789 
7790   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7791   // AsmDialect, MayLoad, MayStore).
7792   bool HasSideEffect = IA->hasSideEffects();
7793   ExtraFlags ExtraInfo(CS);
7794 
7795   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7796   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7797   for (auto &T : TargetConstraints) {
7798     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7799     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7800 
7801     // Compute the value type for each operand.
7802     if (OpInfo.Type == InlineAsm::isInput ||
7803         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7804       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7805 
7806       // Process the call argument. BasicBlocks are labels, currently appearing
7807       // only in asm's.
7808       const Instruction *I = CS.getInstruction();
7809       if (isa<CallBrInst>(I) &&
7810           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
7811                           cast<CallBrInst>(I)->getNumIndirectDests())) {
7812         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
7813         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
7814         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
7815       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7816         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7817       } else {
7818         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7819       }
7820 
7821       OpInfo.ConstraintVT =
7822           OpInfo
7823               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7824               .getSimpleVT();
7825     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7826       // The return value of the call is this value.  As such, there is no
7827       // corresponding argument.
7828       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7829       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7830         OpInfo.ConstraintVT = TLI.getSimpleValueType(
7831             DAG.getDataLayout(), STy->getElementType(ResNo));
7832       } else {
7833         assert(ResNo == 0 && "Asm only has one result!");
7834         OpInfo.ConstraintVT =
7835             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7836       }
7837       ++ResNo;
7838     } else {
7839       OpInfo.ConstraintVT = MVT::Other;
7840     }
7841 
7842     if (!HasSideEffect)
7843       HasSideEffect = OpInfo.hasMemory(TLI);
7844 
7845     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7846     // FIXME: Could we compute this on OpInfo rather than T?
7847 
7848     // Compute the constraint code and ConstraintType to use.
7849     TLI.ComputeConstraintToUse(T, SDValue());
7850 
7851     ExtraInfo.update(T);
7852   }
7853 
7854   // We won't need to flush pending loads if this asm doesn't touch
7855   // memory and is nonvolatile.
7856   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
7857 
7858   // Second pass over the constraints: compute which constraint option to use.
7859   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7860     // If this is an output operand with a matching input operand, look up the
7861     // matching input. If their types mismatch, e.g. one is an integer, the
7862     // other is floating point, or their sizes are different, flag it as an
7863     // error.
7864     if (OpInfo.hasMatchingInput()) {
7865       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7866       patchMatchingInput(OpInfo, Input, DAG);
7867     }
7868 
7869     // Compute the constraint code and ConstraintType to use.
7870     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7871 
7872     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7873         OpInfo.Type == InlineAsm::isClobber)
7874       continue;
7875 
7876     // If this is a memory input, and if the operand is not indirect, do what we
7877     // need to provide an address for the memory input.
7878     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7879         !OpInfo.isIndirect) {
7880       assert((OpInfo.isMultipleAlternative ||
7881               (OpInfo.Type == InlineAsm::isInput)) &&
7882              "Can only indirectify direct input operands!");
7883 
7884       // Memory operands really want the address of the value.
7885       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7886 
7887       // There is no longer a Value* corresponding to this operand.
7888       OpInfo.CallOperandVal = nullptr;
7889 
7890       // It is now an indirect operand.
7891       OpInfo.isIndirect = true;
7892     }
7893 
7894   }
7895 
7896   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7897   std::vector<SDValue> AsmNodeOperands;
7898   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7899   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7900       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7901 
7902   // If we have a !srcloc metadata node associated with it, we want to attach
7903   // this to the ultimately generated inline asm machineinstr.  To do this, we
7904   // pass in the third operand as this (potentially null) inline asm MDNode.
7905   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7906   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7907 
7908   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7909   // bits as operand 3.
7910   AsmNodeOperands.push_back(DAG.getTargetConstant(
7911       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7912 
7913   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
7914   // this, assign virtual and physical registers for inputs and otput.
7915   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7916     // Assign Registers.
7917     SDISelAsmOperandInfo &RefOpInfo =
7918         OpInfo.isMatchingInputConstraint()
7919             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7920             : OpInfo;
7921     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
7922 
7923     switch (OpInfo.Type) {
7924     case InlineAsm::isOutput:
7925       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7926           (OpInfo.ConstraintType == TargetLowering::C_Other &&
7927            OpInfo.isIndirect)) {
7928         unsigned ConstraintID =
7929             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7930         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7931                "Failed to convert memory constraint code to constraint id.");
7932 
7933         // Add information to the INLINEASM node to know about this output.
7934         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7935         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7936         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7937                                                         MVT::i32));
7938         AsmNodeOperands.push_back(OpInfo.CallOperand);
7939         break;
7940       } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
7941                   !OpInfo.isIndirect) ||
7942                  OpInfo.ConstraintType == TargetLowering::C_Register ||
7943                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
7944         // Otherwise, this outputs to a register (directly for C_Register /
7945         // C_RegisterClass, and a target-defined fashion for C_Other). Find a
7946         // register that we can use.
7947         if (OpInfo.AssignedRegs.Regs.empty()) {
7948           emitInlineAsmError(
7949               CS, "couldn't allocate output register for constraint '" +
7950                       Twine(OpInfo.ConstraintCode) + "'");
7951           return;
7952         }
7953 
7954         // Add information to the INLINEASM node to know that this register is
7955         // set.
7956         OpInfo.AssignedRegs.AddInlineAsmOperands(
7957             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
7958                                   : InlineAsm::Kind_RegDef,
7959             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7960       }
7961       break;
7962 
7963     case InlineAsm::isInput: {
7964       SDValue InOperandVal = OpInfo.CallOperand;
7965 
7966       if (OpInfo.isMatchingInputConstraint()) {
7967         // If this is required to match an output register we have already set,
7968         // just use its register.
7969         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7970                                                   AsmNodeOperands);
7971         unsigned OpFlag =
7972           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7973         if (InlineAsm::isRegDefKind(OpFlag) ||
7974             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7975           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7976           if (OpInfo.isIndirect) {
7977             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7978             emitInlineAsmError(CS, "inline asm not supported yet:"
7979                                    " don't know how to handle tied "
7980                                    "indirect register inputs");
7981             return;
7982           }
7983 
7984           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7985           SmallVector<unsigned, 4> Regs;
7986 
7987           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
7988             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
7989             MachineRegisterInfo &RegInfo =
7990                 DAG.getMachineFunction().getRegInfo();
7991             for (unsigned i = 0; i != NumRegs; ++i)
7992               Regs.push_back(RegInfo.createVirtualRegister(RC));
7993           } else {
7994             emitInlineAsmError(CS, "inline asm error: This value type register "
7995                                    "class is not natively supported!");
7996             return;
7997           }
7998 
7999           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8000 
8001           SDLoc dl = getCurSDLoc();
8002           // Use the produced MatchedRegs object to
8003           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8004                                     CS.getInstruction());
8005           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8006                                            true, OpInfo.getMatchedOperand(), dl,
8007                                            DAG, AsmNodeOperands);
8008           break;
8009         }
8010 
8011         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8012         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8013                "Unexpected number of operands");
8014         // Add information to the INLINEASM node to know about this input.
8015         // See InlineAsm.h isUseOperandTiedToDef.
8016         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8017         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8018                                                     OpInfo.getMatchedOperand());
8019         AsmNodeOperands.push_back(DAG.getTargetConstant(
8020             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8021         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8022         break;
8023       }
8024 
8025       // Treat indirect 'X' constraint as memory.
8026       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8027           OpInfo.isIndirect)
8028         OpInfo.ConstraintType = TargetLowering::C_Memory;
8029 
8030       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
8031         std::vector<SDValue> Ops;
8032         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8033                                           Ops, DAG);
8034         if (Ops.empty()) {
8035           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8036                                      Twine(OpInfo.ConstraintCode) + "'");
8037           return;
8038         }
8039 
8040         // Add information to the INLINEASM node to know about this input.
8041         unsigned ResOpType =
8042           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8043         AsmNodeOperands.push_back(DAG.getTargetConstant(
8044             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8045         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8046         break;
8047       }
8048 
8049       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8050         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8051         assert(InOperandVal.getValueType() ==
8052                    TLI.getPointerTy(DAG.getDataLayout()) &&
8053                "Memory operands expect pointer values");
8054 
8055         unsigned ConstraintID =
8056             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8057         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8058                "Failed to convert memory constraint code to constraint id.");
8059 
8060         // Add information to the INLINEASM node to know about this input.
8061         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8062         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8063         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8064                                                         getCurSDLoc(),
8065                                                         MVT::i32));
8066         AsmNodeOperands.push_back(InOperandVal);
8067         break;
8068       }
8069 
8070       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8071               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8072              "Unknown constraint type!");
8073 
8074       // TODO: Support this.
8075       if (OpInfo.isIndirect) {
8076         emitInlineAsmError(
8077             CS, "Don't know how to handle indirect register inputs yet "
8078                 "for constraint '" +
8079                     Twine(OpInfo.ConstraintCode) + "'");
8080         return;
8081       }
8082 
8083       // Copy the input into the appropriate registers.
8084       if (OpInfo.AssignedRegs.Regs.empty()) {
8085         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8086                                    Twine(OpInfo.ConstraintCode) + "'");
8087         return;
8088       }
8089 
8090       SDLoc dl = getCurSDLoc();
8091 
8092       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8093                                         Chain, &Flag, CS.getInstruction());
8094 
8095       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8096                                                dl, DAG, AsmNodeOperands);
8097       break;
8098     }
8099     case InlineAsm::isClobber:
8100       // Add the clobbered value to the operand list, so that the register
8101       // allocator is aware that the physreg got clobbered.
8102       if (!OpInfo.AssignedRegs.Regs.empty())
8103         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8104                                                  false, 0, getCurSDLoc(), DAG,
8105                                                  AsmNodeOperands);
8106       break;
8107     }
8108   }
8109 
8110   // Finish up input operands.  Set the input chain and add the flag last.
8111   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8112   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8113 
8114   unsigned ISDOpc = isa<CallBrInst>(CS.getInstruction()) ? ISD::INLINEASM_BR : ISD::INLINEASM;
8115   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8116                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8117   Flag = Chain.getValue(1);
8118 
8119   // Do additional work to generate outputs.
8120 
8121   SmallVector<EVT, 1> ResultVTs;
8122   SmallVector<SDValue, 1> ResultValues;
8123   SmallVector<SDValue, 8> OutChains;
8124 
8125   llvm::Type *CSResultType = CS.getType();
8126   ArrayRef<Type *> ResultTypes;
8127   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8128     ResultTypes = StructResult->elements();
8129   else if (!CSResultType->isVoidTy())
8130     ResultTypes = makeArrayRef(CSResultType);
8131 
8132   auto CurResultType = ResultTypes.begin();
8133   auto handleRegAssign = [&](SDValue V) {
8134     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8135     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8136     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8137     ++CurResultType;
8138     // If the type of the inline asm call site return value is different but has
8139     // same size as the type of the asm output bitcast it.  One example of this
8140     // is for vectors with different width / number of elements.  This can
8141     // happen for register classes that can contain multiple different value
8142     // types.  The preg or vreg allocated may not have the same VT as was
8143     // expected.
8144     //
8145     // This can also happen for a return value that disagrees with the register
8146     // class it is put in, eg. a double in a general-purpose register on a
8147     // 32-bit machine.
8148     if (ResultVT != V.getValueType() &&
8149         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8150       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8151     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8152              V.getValueType().isInteger()) {
8153       // If a result value was tied to an input value, the computed result
8154       // may have a wider width than the expected result.  Extract the
8155       // relevant portion.
8156       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8157     }
8158     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8159     ResultVTs.push_back(ResultVT);
8160     ResultValues.push_back(V);
8161   };
8162 
8163   // Deal with output operands.
8164   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8165     if (OpInfo.Type == InlineAsm::isOutput) {
8166       SDValue Val;
8167       // Skip trivial output operands.
8168       if (OpInfo.AssignedRegs.Regs.empty())
8169         continue;
8170 
8171       switch (OpInfo.ConstraintType) {
8172       case TargetLowering::C_Register:
8173       case TargetLowering::C_RegisterClass:
8174         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8175             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8176         break;
8177       case TargetLowering::C_Other:
8178         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8179                                               OpInfo, DAG);
8180         break;
8181       case TargetLowering::C_Memory:
8182         break; // Already handled.
8183       case TargetLowering::C_Unknown:
8184         assert(false && "Unexpected unknown constraint");
8185       }
8186 
8187       // Indirect output manifest as stores. Record output chains.
8188       if (OpInfo.isIndirect) {
8189         const Value *Ptr = OpInfo.CallOperandVal;
8190         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8191         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8192                                      MachinePointerInfo(Ptr));
8193         OutChains.push_back(Store);
8194       } else {
8195         // generate CopyFromRegs to associated registers.
8196         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8197         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8198           for (const SDValue &V : Val->op_values())
8199             handleRegAssign(V);
8200         } else
8201           handleRegAssign(Val);
8202       }
8203     }
8204   }
8205 
8206   // Set results.
8207   if (!ResultValues.empty()) {
8208     assert(CurResultType == ResultTypes.end() &&
8209            "Mismatch in number of ResultTypes");
8210     assert(ResultValues.size() == ResultTypes.size() &&
8211            "Mismatch in number of output operands in asm result");
8212 
8213     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8214                             DAG.getVTList(ResultVTs), ResultValues);
8215     setValue(CS.getInstruction(), V);
8216   }
8217 
8218   // Collect store chains.
8219   if (!OutChains.empty())
8220     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8221 
8222   // Only Update Root if inline assembly has a memory effect.
8223   if (ResultValues.empty() || HasSideEffect || !OutChains.empty())
8224     DAG.setRoot(Chain);
8225 }
8226 
8227 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8228                                              const Twine &Message) {
8229   LLVMContext &Ctx = *DAG.getContext();
8230   Ctx.emitError(CS.getInstruction(), Message);
8231 
8232   // Make sure we leave the DAG in a valid state
8233   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8234   SmallVector<EVT, 1> ValueVTs;
8235   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8236 
8237   if (ValueVTs.empty())
8238     return;
8239 
8240   SmallVector<SDValue, 1> Ops;
8241   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8242     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8243 
8244   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8245 }
8246 
8247 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8248   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8249                           MVT::Other, getRoot(),
8250                           getValue(I.getArgOperand(0)),
8251                           DAG.getSrcValue(I.getArgOperand(0))));
8252 }
8253 
8254 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8255   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8256   const DataLayout &DL = DAG.getDataLayout();
8257   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
8258                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
8259                            DAG.getSrcValue(I.getOperand(0)),
8260                            DL.getABITypeAlignment(I.getType()));
8261   setValue(&I, V);
8262   DAG.setRoot(V.getValue(1));
8263 }
8264 
8265 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8266   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8267                           MVT::Other, getRoot(),
8268                           getValue(I.getArgOperand(0)),
8269                           DAG.getSrcValue(I.getArgOperand(0))));
8270 }
8271 
8272 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8273   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8274                           MVT::Other, getRoot(),
8275                           getValue(I.getArgOperand(0)),
8276                           getValue(I.getArgOperand(1)),
8277                           DAG.getSrcValue(I.getArgOperand(0)),
8278                           DAG.getSrcValue(I.getArgOperand(1))));
8279 }
8280 
8281 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8282                                                     const Instruction &I,
8283                                                     SDValue Op) {
8284   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8285   if (!Range)
8286     return Op;
8287 
8288   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8289   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
8290     return Op;
8291 
8292   APInt Lo = CR.getUnsignedMin();
8293   if (!Lo.isMinValue())
8294     return Op;
8295 
8296   APInt Hi = CR.getUnsignedMax();
8297   unsigned Bits = std::max(Hi.getActiveBits(),
8298                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8299 
8300   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8301 
8302   SDLoc SL = getCurSDLoc();
8303 
8304   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8305                              DAG.getValueType(SmallVT));
8306   unsigned NumVals = Op.getNode()->getNumValues();
8307   if (NumVals == 1)
8308     return ZExt;
8309 
8310   SmallVector<SDValue, 4> Ops;
8311 
8312   Ops.push_back(ZExt);
8313   for (unsigned I = 1; I != NumVals; ++I)
8314     Ops.push_back(Op.getValue(I));
8315 
8316   return DAG.getMergeValues(Ops, SL);
8317 }
8318 
8319 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8320 /// the call being lowered.
8321 ///
8322 /// This is a helper for lowering intrinsics that follow a target calling
8323 /// convention or require stack pointer adjustment. Only a subset of the
8324 /// intrinsic's operands need to participate in the calling convention.
8325 void SelectionDAGBuilder::populateCallLoweringInfo(
8326     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8327     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8328     bool IsPatchPoint) {
8329   TargetLowering::ArgListTy Args;
8330   Args.reserve(NumArgs);
8331 
8332   // Populate the argument list.
8333   // Attributes for args start at offset 1, after the return attribute.
8334   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8335        ArgI != ArgE; ++ArgI) {
8336     const Value *V = Call->getOperand(ArgI);
8337 
8338     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8339 
8340     TargetLowering::ArgListEntry Entry;
8341     Entry.Node = getValue(V);
8342     Entry.Ty = V->getType();
8343     Entry.setAttributes(Call, ArgI);
8344     Args.push_back(Entry);
8345   }
8346 
8347   CLI.setDebugLoc(getCurSDLoc())
8348       .setChain(getRoot())
8349       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8350       .setDiscardResult(Call->use_empty())
8351       .setIsPatchPoint(IsPatchPoint);
8352 }
8353 
8354 /// Add a stack map intrinsic call's live variable operands to a stackmap
8355 /// or patchpoint target node's operand list.
8356 ///
8357 /// Constants are converted to TargetConstants purely as an optimization to
8358 /// avoid constant materialization and register allocation.
8359 ///
8360 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8361 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8362 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8363 /// address materialization and register allocation, but may also be required
8364 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8365 /// alloca in the entry block, then the runtime may assume that the alloca's
8366 /// StackMap location can be read immediately after compilation and that the
8367 /// location is valid at any point during execution (this is similar to the
8368 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8369 /// only available in a register, then the runtime would need to trap when
8370 /// execution reaches the StackMap in order to read the alloca's location.
8371 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8372                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8373                                 SelectionDAGBuilder &Builder) {
8374   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8375     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8376     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8377       Ops.push_back(
8378         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8379       Ops.push_back(
8380         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8381     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8382       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8383       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8384           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8385     } else
8386       Ops.push_back(OpVal);
8387   }
8388 }
8389 
8390 /// Lower llvm.experimental.stackmap directly to its target opcode.
8391 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8392   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8393   //                                  [live variables...])
8394 
8395   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8396 
8397   SDValue Chain, InFlag, Callee, NullPtr;
8398   SmallVector<SDValue, 32> Ops;
8399 
8400   SDLoc DL = getCurSDLoc();
8401   Callee = getValue(CI.getCalledValue());
8402   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8403 
8404   // The stackmap intrinsic only records the live variables (the arguemnts
8405   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8406   // intrinsic, this won't be lowered to a function call. This means we don't
8407   // have to worry about calling conventions and target specific lowering code.
8408   // Instead we perform the call lowering right here.
8409   //
8410   // chain, flag = CALLSEQ_START(chain, 0, 0)
8411   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8412   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8413   //
8414   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8415   InFlag = Chain.getValue(1);
8416 
8417   // Add the <id> and <numBytes> constants.
8418   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8419   Ops.push_back(DAG.getTargetConstant(
8420                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8421   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8422   Ops.push_back(DAG.getTargetConstant(
8423                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8424                   MVT::i32));
8425 
8426   // Push live variables for the stack map.
8427   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8428 
8429   // We are not pushing any register mask info here on the operands list,
8430   // because the stackmap doesn't clobber anything.
8431 
8432   // Push the chain and the glue flag.
8433   Ops.push_back(Chain);
8434   Ops.push_back(InFlag);
8435 
8436   // Create the STACKMAP node.
8437   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8438   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8439   Chain = SDValue(SM, 0);
8440   InFlag = Chain.getValue(1);
8441 
8442   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8443 
8444   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8445 
8446   // Set the root to the target-lowered call chain.
8447   DAG.setRoot(Chain);
8448 
8449   // Inform the Frame Information that we have a stackmap in this function.
8450   FuncInfo.MF->getFrameInfo().setHasStackMap();
8451 }
8452 
8453 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8454 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8455                                           const BasicBlock *EHPadBB) {
8456   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8457   //                                                 i32 <numBytes>,
8458   //                                                 i8* <target>,
8459   //                                                 i32 <numArgs>,
8460   //                                                 [Args...],
8461   //                                                 [live variables...])
8462 
8463   CallingConv::ID CC = CS.getCallingConv();
8464   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8465   bool HasDef = !CS->getType()->isVoidTy();
8466   SDLoc dl = getCurSDLoc();
8467   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8468 
8469   // Handle immediate and symbolic callees.
8470   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8471     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8472                                    /*isTarget=*/true);
8473   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8474     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8475                                          SDLoc(SymbolicCallee),
8476                                          SymbolicCallee->getValueType(0));
8477 
8478   // Get the real number of arguments participating in the call <numArgs>
8479   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8480   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8481 
8482   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8483   // Intrinsics include all meta-operands up to but not including CC.
8484   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8485   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8486          "Not enough arguments provided to the patchpoint intrinsic");
8487 
8488   // For AnyRegCC the arguments are lowered later on manually.
8489   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8490   Type *ReturnTy =
8491     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8492 
8493   TargetLowering::CallLoweringInfo CLI(DAG);
8494   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8495                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8496   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8497 
8498   SDNode *CallEnd = Result.second.getNode();
8499   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8500     CallEnd = CallEnd->getOperand(0).getNode();
8501 
8502   /// Get a call instruction from the call sequence chain.
8503   /// Tail calls are not allowed.
8504   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8505          "Expected a callseq node.");
8506   SDNode *Call = CallEnd->getOperand(0).getNode();
8507   bool HasGlue = Call->getGluedNode();
8508 
8509   // Replace the target specific call node with the patchable intrinsic.
8510   SmallVector<SDValue, 8> Ops;
8511 
8512   // Add the <id> and <numBytes> constants.
8513   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8514   Ops.push_back(DAG.getTargetConstant(
8515                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8516   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8517   Ops.push_back(DAG.getTargetConstant(
8518                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8519                   MVT::i32));
8520 
8521   // Add the callee.
8522   Ops.push_back(Callee);
8523 
8524   // Adjust <numArgs> to account for any arguments that have been passed on the
8525   // stack instead.
8526   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8527   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8528   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8529   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8530 
8531   // Add the calling convention
8532   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8533 
8534   // Add the arguments we omitted previously. The register allocator should
8535   // place these in any free register.
8536   if (IsAnyRegCC)
8537     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8538       Ops.push_back(getValue(CS.getArgument(i)));
8539 
8540   // Push the arguments from the call instruction up to the register mask.
8541   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8542   Ops.append(Call->op_begin() + 2, e);
8543 
8544   // Push live variables for the stack map.
8545   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8546 
8547   // Push the register mask info.
8548   if (HasGlue)
8549     Ops.push_back(*(Call->op_end()-2));
8550   else
8551     Ops.push_back(*(Call->op_end()-1));
8552 
8553   // Push the chain (this is originally the first operand of the call, but
8554   // becomes now the last or second to last operand).
8555   Ops.push_back(*(Call->op_begin()));
8556 
8557   // Push the glue flag (last operand).
8558   if (HasGlue)
8559     Ops.push_back(*(Call->op_end()-1));
8560 
8561   SDVTList NodeTys;
8562   if (IsAnyRegCC && HasDef) {
8563     // Create the return types based on the intrinsic definition
8564     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8565     SmallVector<EVT, 3> ValueVTs;
8566     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8567     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8568 
8569     // There is always a chain and a glue type at the end
8570     ValueVTs.push_back(MVT::Other);
8571     ValueVTs.push_back(MVT::Glue);
8572     NodeTys = DAG.getVTList(ValueVTs);
8573   } else
8574     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8575 
8576   // Replace the target specific call node with a PATCHPOINT node.
8577   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8578                                          dl, NodeTys, Ops);
8579 
8580   // Update the NodeMap.
8581   if (HasDef) {
8582     if (IsAnyRegCC)
8583       setValue(CS.getInstruction(), SDValue(MN, 0));
8584     else
8585       setValue(CS.getInstruction(), Result.first);
8586   }
8587 
8588   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8589   // call sequence. Furthermore the location of the chain and glue can change
8590   // when the AnyReg calling convention is used and the intrinsic returns a
8591   // value.
8592   if (IsAnyRegCC && HasDef) {
8593     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8594     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8595     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8596   } else
8597     DAG.ReplaceAllUsesWith(Call, MN);
8598   DAG.DeleteNode(Call);
8599 
8600   // Inform the Frame Information that we have a patchpoint in this function.
8601   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8602 }
8603 
8604 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8605                                             unsigned Intrinsic) {
8606   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8607   SDValue Op1 = getValue(I.getArgOperand(0));
8608   SDValue Op2;
8609   if (I.getNumArgOperands() > 1)
8610     Op2 = getValue(I.getArgOperand(1));
8611   SDLoc dl = getCurSDLoc();
8612   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8613   SDValue Res;
8614   FastMathFlags FMF;
8615   if (isa<FPMathOperator>(I))
8616     FMF = I.getFastMathFlags();
8617 
8618   switch (Intrinsic) {
8619   case Intrinsic::experimental_vector_reduce_fadd:
8620     if (FMF.isFast())
8621       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8622     else
8623       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8624     break;
8625   case Intrinsic::experimental_vector_reduce_fmul:
8626     if (FMF.isFast())
8627       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8628     else
8629       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8630     break;
8631   case Intrinsic::experimental_vector_reduce_add:
8632     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8633     break;
8634   case Intrinsic::experimental_vector_reduce_mul:
8635     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8636     break;
8637   case Intrinsic::experimental_vector_reduce_and:
8638     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8639     break;
8640   case Intrinsic::experimental_vector_reduce_or:
8641     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8642     break;
8643   case Intrinsic::experimental_vector_reduce_xor:
8644     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8645     break;
8646   case Intrinsic::experimental_vector_reduce_smax:
8647     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8648     break;
8649   case Intrinsic::experimental_vector_reduce_smin:
8650     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8651     break;
8652   case Intrinsic::experimental_vector_reduce_umax:
8653     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8654     break;
8655   case Intrinsic::experimental_vector_reduce_umin:
8656     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8657     break;
8658   case Intrinsic::experimental_vector_reduce_fmax:
8659     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8660     break;
8661   case Intrinsic::experimental_vector_reduce_fmin:
8662     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8663     break;
8664   default:
8665     llvm_unreachable("Unhandled vector reduce intrinsic");
8666   }
8667   setValue(&I, Res);
8668 }
8669 
8670 /// Returns an AttributeList representing the attributes applied to the return
8671 /// value of the given call.
8672 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8673   SmallVector<Attribute::AttrKind, 2> Attrs;
8674   if (CLI.RetSExt)
8675     Attrs.push_back(Attribute::SExt);
8676   if (CLI.RetZExt)
8677     Attrs.push_back(Attribute::ZExt);
8678   if (CLI.IsInReg)
8679     Attrs.push_back(Attribute::InReg);
8680 
8681   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8682                             Attrs);
8683 }
8684 
8685 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8686 /// implementation, which just calls LowerCall.
8687 /// FIXME: When all targets are
8688 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8689 std::pair<SDValue, SDValue>
8690 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8691   // Handle the incoming return values from the call.
8692   CLI.Ins.clear();
8693   Type *OrigRetTy = CLI.RetTy;
8694   SmallVector<EVT, 4> RetTys;
8695   SmallVector<uint64_t, 4> Offsets;
8696   auto &DL = CLI.DAG.getDataLayout();
8697   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8698 
8699   if (CLI.IsPostTypeLegalization) {
8700     // If we are lowering a libcall after legalization, split the return type.
8701     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8702     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8703     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8704       EVT RetVT = OldRetTys[i];
8705       uint64_t Offset = OldOffsets[i];
8706       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8707       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8708       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8709       RetTys.append(NumRegs, RegisterVT);
8710       for (unsigned j = 0; j != NumRegs; ++j)
8711         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8712     }
8713   }
8714 
8715   SmallVector<ISD::OutputArg, 4> Outs;
8716   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8717 
8718   bool CanLowerReturn =
8719       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8720                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8721 
8722   SDValue DemoteStackSlot;
8723   int DemoteStackIdx = -100;
8724   if (!CanLowerReturn) {
8725     // FIXME: equivalent assert?
8726     // assert(!CS.hasInAllocaArgument() &&
8727     //        "sret demotion is incompatible with inalloca");
8728     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8729     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8730     MachineFunction &MF = CLI.DAG.getMachineFunction();
8731     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8732     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8733                                               DL.getAllocaAddrSpace());
8734 
8735     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8736     ArgListEntry Entry;
8737     Entry.Node = DemoteStackSlot;
8738     Entry.Ty = StackSlotPtrType;
8739     Entry.IsSExt = false;
8740     Entry.IsZExt = false;
8741     Entry.IsInReg = false;
8742     Entry.IsSRet = true;
8743     Entry.IsNest = false;
8744     Entry.IsByVal = false;
8745     Entry.IsReturned = false;
8746     Entry.IsSwiftSelf = false;
8747     Entry.IsSwiftError = false;
8748     Entry.Alignment = Align;
8749     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8750     CLI.NumFixedArgs += 1;
8751     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8752 
8753     // sret demotion isn't compatible with tail-calls, since the sret argument
8754     // points into the callers stack frame.
8755     CLI.IsTailCall = false;
8756   } else {
8757     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8758       EVT VT = RetTys[I];
8759       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8760                                                      CLI.CallConv, VT);
8761       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8762                                                        CLI.CallConv, VT);
8763       for (unsigned i = 0; i != NumRegs; ++i) {
8764         ISD::InputArg MyFlags;
8765         MyFlags.VT = RegisterVT;
8766         MyFlags.ArgVT = VT;
8767         MyFlags.Used = CLI.IsReturnValueUsed;
8768         if (CLI.RetSExt)
8769           MyFlags.Flags.setSExt();
8770         if (CLI.RetZExt)
8771           MyFlags.Flags.setZExt();
8772         if (CLI.IsInReg)
8773           MyFlags.Flags.setInReg();
8774         CLI.Ins.push_back(MyFlags);
8775       }
8776     }
8777   }
8778 
8779   // We push in swifterror return as the last element of CLI.Ins.
8780   ArgListTy &Args = CLI.getArgs();
8781   if (supportSwiftError()) {
8782     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8783       if (Args[i].IsSwiftError) {
8784         ISD::InputArg MyFlags;
8785         MyFlags.VT = getPointerTy(DL);
8786         MyFlags.ArgVT = EVT(getPointerTy(DL));
8787         MyFlags.Flags.setSwiftError();
8788         CLI.Ins.push_back(MyFlags);
8789       }
8790     }
8791   }
8792 
8793   // Handle all of the outgoing arguments.
8794   CLI.Outs.clear();
8795   CLI.OutVals.clear();
8796   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8797     SmallVector<EVT, 4> ValueVTs;
8798     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8799     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8800     Type *FinalType = Args[i].Ty;
8801     if (Args[i].IsByVal)
8802       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8803     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8804         FinalType, CLI.CallConv, CLI.IsVarArg);
8805     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8806          ++Value) {
8807       EVT VT = ValueVTs[Value];
8808       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8809       SDValue Op = SDValue(Args[i].Node.getNode(),
8810                            Args[i].Node.getResNo() + Value);
8811       ISD::ArgFlagsTy Flags;
8812 
8813       // Certain targets (such as MIPS), may have a different ABI alignment
8814       // for a type depending on the context. Give the target a chance to
8815       // specify the alignment it wants.
8816       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8817 
8818       if (Args[i].IsZExt)
8819         Flags.setZExt();
8820       if (Args[i].IsSExt)
8821         Flags.setSExt();
8822       if (Args[i].IsInReg) {
8823         // If we are using vectorcall calling convention, a structure that is
8824         // passed InReg - is surely an HVA
8825         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8826             isa<StructType>(FinalType)) {
8827           // The first value of a structure is marked
8828           if (0 == Value)
8829             Flags.setHvaStart();
8830           Flags.setHva();
8831         }
8832         // Set InReg Flag
8833         Flags.setInReg();
8834       }
8835       if (Args[i].IsSRet)
8836         Flags.setSRet();
8837       if (Args[i].IsSwiftSelf)
8838         Flags.setSwiftSelf();
8839       if (Args[i].IsSwiftError)
8840         Flags.setSwiftError();
8841       if (Args[i].IsByVal)
8842         Flags.setByVal();
8843       if (Args[i].IsInAlloca) {
8844         Flags.setInAlloca();
8845         // Set the byval flag for CCAssignFn callbacks that don't know about
8846         // inalloca.  This way we can know how many bytes we should've allocated
8847         // and how many bytes a callee cleanup function will pop.  If we port
8848         // inalloca to more targets, we'll have to add custom inalloca handling
8849         // in the various CC lowering callbacks.
8850         Flags.setByVal();
8851       }
8852       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8853         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8854         Type *ElementTy = Ty->getElementType();
8855         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8856         // For ByVal, alignment should come from FE.  BE will guess if this
8857         // info is not there but there are cases it cannot get right.
8858         unsigned FrameAlign;
8859         if (Args[i].Alignment)
8860           FrameAlign = Args[i].Alignment;
8861         else
8862           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8863         Flags.setByValAlign(FrameAlign);
8864       }
8865       if (Args[i].IsNest)
8866         Flags.setNest();
8867       if (NeedsRegBlock)
8868         Flags.setInConsecutiveRegs();
8869       Flags.setOrigAlign(OriginalAlignment);
8870 
8871       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8872                                                  CLI.CallConv, VT);
8873       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8874                                                         CLI.CallConv, VT);
8875       SmallVector<SDValue, 4> Parts(NumParts);
8876       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8877 
8878       if (Args[i].IsSExt)
8879         ExtendKind = ISD::SIGN_EXTEND;
8880       else if (Args[i].IsZExt)
8881         ExtendKind = ISD::ZERO_EXTEND;
8882 
8883       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8884       // for now.
8885       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8886           CanLowerReturn) {
8887         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8888                "unexpected use of 'returned'");
8889         // Before passing 'returned' to the target lowering code, ensure that
8890         // either the register MVT and the actual EVT are the same size or that
8891         // the return value and argument are extended in the same way; in these
8892         // cases it's safe to pass the argument register value unchanged as the
8893         // return register value (although it's at the target's option whether
8894         // to do so)
8895         // TODO: allow code generation to take advantage of partially preserved
8896         // registers rather than clobbering the entire register when the
8897         // parameter extension method is not compatible with the return
8898         // extension method
8899         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8900             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8901              CLI.RetZExt == Args[i].IsZExt))
8902           Flags.setReturned();
8903       }
8904 
8905       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8906                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
8907 
8908       for (unsigned j = 0; j != NumParts; ++j) {
8909         // if it isn't first piece, alignment must be 1
8910         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8911                                i < CLI.NumFixedArgs,
8912                                i, j*Parts[j].getValueType().getStoreSize());
8913         if (NumParts > 1 && j == 0)
8914           MyFlags.Flags.setSplit();
8915         else if (j != 0) {
8916           MyFlags.Flags.setOrigAlign(1);
8917           if (j == NumParts - 1)
8918             MyFlags.Flags.setSplitEnd();
8919         }
8920 
8921         CLI.Outs.push_back(MyFlags);
8922         CLI.OutVals.push_back(Parts[j]);
8923       }
8924 
8925       if (NeedsRegBlock && Value == NumValues - 1)
8926         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8927     }
8928   }
8929 
8930   SmallVector<SDValue, 4> InVals;
8931   CLI.Chain = LowerCall(CLI, InVals);
8932 
8933   // Update CLI.InVals to use outside of this function.
8934   CLI.InVals = InVals;
8935 
8936   // Verify that the target's LowerCall behaved as expected.
8937   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8938          "LowerCall didn't return a valid chain!");
8939   assert((!CLI.IsTailCall || InVals.empty()) &&
8940          "LowerCall emitted a return value for a tail call!");
8941   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8942          "LowerCall didn't emit the correct number of values!");
8943 
8944   // For a tail call, the return value is merely live-out and there aren't
8945   // any nodes in the DAG representing it. Return a special value to
8946   // indicate that a tail call has been emitted and no more Instructions
8947   // should be processed in the current block.
8948   if (CLI.IsTailCall) {
8949     CLI.DAG.setRoot(CLI.Chain);
8950     return std::make_pair(SDValue(), SDValue());
8951   }
8952 
8953 #ifndef NDEBUG
8954   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8955     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8956     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8957            "LowerCall emitted a value with the wrong type!");
8958   }
8959 #endif
8960 
8961   SmallVector<SDValue, 4> ReturnValues;
8962   if (!CanLowerReturn) {
8963     // The instruction result is the result of loading from the
8964     // hidden sret parameter.
8965     SmallVector<EVT, 1> PVTs;
8966     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8967 
8968     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8969     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8970     EVT PtrVT = PVTs[0];
8971 
8972     unsigned NumValues = RetTys.size();
8973     ReturnValues.resize(NumValues);
8974     SmallVector<SDValue, 4> Chains(NumValues);
8975 
8976     // An aggregate return value cannot wrap around the address space, so
8977     // offsets to its parts don't wrap either.
8978     SDNodeFlags Flags;
8979     Flags.setNoUnsignedWrap(true);
8980 
8981     for (unsigned i = 0; i < NumValues; ++i) {
8982       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8983                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8984                                                         PtrVT), Flags);
8985       SDValue L = CLI.DAG.getLoad(
8986           RetTys[i], CLI.DL, CLI.Chain, Add,
8987           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8988                                             DemoteStackIdx, Offsets[i]),
8989           /* Alignment = */ 1);
8990       ReturnValues[i] = L;
8991       Chains[i] = L.getValue(1);
8992     }
8993 
8994     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8995   } else {
8996     // Collect the legal value parts into potentially illegal values
8997     // that correspond to the original function's return values.
8998     Optional<ISD::NodeType> AssertOp;
8999     if (CLI.RetSExt)
9000       AssertOp = ISD::AssertSext;
9001     else if (CLI.RetZExt)
9002       AssertOp = ISD::AssertZext;
9003     unsigned CurReg = 0;
9004     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9005       EVT VT = RetTys[I];
9006       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9007                                                      CLI.CallConv, VT);
9008       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9009                                                        CLI.CallConv, VT);
9010 
9011       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9012                                               NumRegs, RegisterVT, VT, nullptr,
9013                                               CLI.CallConv, AssertOp));
9014       CurReg += NumRegs;
9015     }
9016 
9017     // For a function returning void, there is no return value. We can't create
9018     // such a node, so we just return a null return value in that case. In
9019     // that case, nothing will actually look at the value.
9020     if (ReturnValues.empty())
9021       return std::make_pair(SDValue(), CLI.Chain);
9022   }
9023 
9024   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9025                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9026   return std::make_pair(Res, CLI.Chain);
9027 }
9028 
9029 void TargetLowering::LowerOperationWrapper(SDNode *N,
9030                                            SmallVectorImpl<SDValue> &Results,
9031                                            SelectionDAG &DAG) const {
9032   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9033     Results.push_back(Res);
9034 }
9035 
9036 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9037   llvm_unreachable("LowerOperation not implemented for this target!");
9038 }
9039 
9040 void
9041 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9042   SDValue Op = getNonRegisterValue(V);
9043   assert((Op.getOpcode() != ISD::CopyFromReg ||
9044           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9045          "Copy from a reg to the same reg!");
9046   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
9047 
9048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9049   // If this is an InlineAsm we have to match the registers required, not the
9050   // notional registers required by the type.
9051 
9052   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9053                    None); // This is not an ABI copy.
9054   SDValue Chain = DAG.getEntryNode();
9055 
9056   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9057                               FuncInfo.PreferredExtendType.end())
9058                                  ? ISD::ANY_EXTEND
9059                                  : FuncInfo.PreferredExtendType[V];
9060   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9061   PendingExports.push_back(Chain);
9062 }
9063 
9064 #include "llvm/CodeGen/SelectionDAGISel.h"
9065 
9066 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9067 /// entry block, return true.  This includes arguments used by switches, since
9068 /// the switch may expand into multiple basic blocks.
9069 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9070   // With FastISel active, we may be splitting blocks, so force creation
9071   // of virtual registers for all non-dead arguments.
9072   if (FastISel)
9073     return A->use_empty();
9074 
9075   const BasicBlock &Entry = A->getParent()->front();
9076   for (const User *U : A->users())
9077     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9078       return false;  // Use not in entry block.
9079 
9080   return true;
9081 }
9082 
9083 using ArgCopyElisionMapTy =
9084     DenseMap<const Argument *,
9085              std::pair<const AllocaInst *, const StoreInst *>>;
9086 
9087 /// Scan the entry block of the function in FuncInfo for arguments that look
9088 /// like copies into a local alloca. Record any copied arguments in
9089 /// ArgCopyElisionCandidates.
9090 static void
9091 findArgumentCopyElisionCandidates(const DataLayout &DL,
9092                                   FunctionLoweringInfo *FuncInfo,
9093                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9094   // Record the state of every static alloca used in the entry block. Argument
9095   // allocas are all used in the entry block, so we need approximately as many
9096   // entries as we have arguments.
9097   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9098   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9099   unsigned NumArgs = FuncInfo->Fn->arg_size();
9100   StaticAllocas.reserve(NumArgs * 2);
9101 
9102   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9103     if (!V)
9104       return nullptr;
9105     V = V->stripPointerCasts();
9106     const auto *AI = dyn_cast<AllocaInst>(V);
9107     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9108       return nullptr;
9109     auto Iter = StaticAllocas.insert({AI, Unknown});
9110     return &Iter.first->second;
9111   };
9112 
9113   // Look for stores of arguments to static allocas. Look through bitcasts and
9114   // GEPs to handle type coercions, as long as the alloca is fully initialized
9115   // by the store. Any non-store use of an alloca escapes it and any subsequent
9116   // unanalyzed store might write it.
9117   // FIXME: Handle structs initialized with multiple stores.
9118   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9119     // Look for stores, and handle non-store uses conservatively.
9120     const auto *SI = dyn_cast<StoreInst>(&I);
9121     if (!SI) {
9122       // We will look through cast uses, so ignore them completely.
9123       if (I.isCast())
9124         continue;
9125       // Ignore debug info intrinsics, they don't escape or store to allocas.
9126       if (isa<DbgInfoIntrinsic>(I))
9127         continue;
9128       // This is an unknown instruction. Assume it escapes or writes to all
9129       // static alloca operands.
9130       for (const Use &U : I.operands()) {
9131         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9132           *Info = StaticAllocaInfo::Clobbered;
9133       }
9134       continue;
9135     }
9136 
9137     // If the stored value is a static alloca, mark it as escaped.
9138     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9139       *Info = StaticAllocaInfo::Clobbered;
9140 
9141     // Check if the destination is a static alloca.
9142     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9143     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9144     if (!Info)
9145       continue;
9146     const AllocaInst *AI = cast<AllocaInst>(Dst);
9147 
9148     // Skip allocas that have been initialized or clobbered.
9149     if (*Info != StaticAllocaInfo::Unknown)
9150       continue;
9151 
9152     // Check if the stored value is an argument, and that this store fully
9153     // initializes the alloca. Don't elide copies from the same argument twice.
9154     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9155     const auto *Arg = dyn_cast<Argument>(Val);
9156     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9157         Arg->getType()->isEmptyTy() ||
9158         DL.getTypeStoreSize(Arg->getType()) !=
9159             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9160         ArgCopyElisionCandidates.count(Arg)) {
9161       *Info = StaticAllocaInfo::Clobbered;
9162       continue;
9163     }
9164 
9165     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9166                       << '\n');
9167 
9168     // Mark this alloca and store for argument copy elision.
9169     *Info = StaticAllocaInfo::Elidable;
9170     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9171 
9172     // Stop scanning if we've seen all arguments. This will happen early in -O0
9173     // builds, which is useful, because -O0 builds have large entry blocks and
9174     // many allocas.
9175     if (ArgCopyElisionCandidates.size() == NumArgs)
9176       break;
9177   }
9178 }
9179 
9180 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9181 /// ArgVal is a load from a suitable fixed stack object.
9182 static void tryToElideArgumentCopy(
9183     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9184     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9185     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9186     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9187     SDValue ArgVal, bool &ArgHasUses) {
9188   // Check if this is a load from a fixed stack object.
9189   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9190   if (!LNode)
9191     return;
9192   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9193   if (!FINode)
9194     return;
9195 
9196   // Check that the fixed stack object is the right size and alignment.
9197   // Look at the alignment that the user wrote on the alloca instead of looking
9198   // at the stack object.
9199   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9200   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9201   const AllocaInst *AI = ArgCopyIter->second.first;
9202   int FixedIndex = FINode->getIndex();
9203   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9204   int OldIndex = AllocaIndex;
9205   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9206   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9207     LLVM_DEBUG(
9208         dbgs() << "  argument copy elision failed due to bad fixed stack "
9209                   "object size\n");
9210     return;
9211   }
9212   unsigned RequiredAlignment = AI->getAlignment();
9213   if (!RequiredAlignment) {
9214     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9215         AI->getAllocatedType());
9216   }
9217   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9218     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9219                          "greater than stack argument alignment ("
9220                       << RequiredAlignment << " vs "
9221                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9222     return;
9223   }
9224 
9225   // Perform the elision. Delete the old stack object and replace its only use
9226   // in the variable info map. Mark the stack object as mutable.
9227   LLVM_DEBUG({
9228     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9229            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9230            << '\n';
9231   });
9232   MFI.RemoveStackObject(OldIndex);
9233   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9234   AllocaIndex = FixedIndex;
9235   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9236   Chains.push_back(ArgVal.getValue(1));
9237 
9238   // Avoid emitting code for the store implementing the copy.
9239   const StoreInst *SI = ArgCopyIter->second.second;
9240   ElidedArgCopyInstrs.insert(SI);
9241 
9242   // Check for uses of the argument again so that we can avoid exporting ArgVal
9243   // if it is't used by anything other than the store.
9244   for (const Value *U : Arg.users()) {
9245     if (U != SI) {
9246       ArgHasUses = true;
9247       break;
9248     }
9249   }
9250 }
9251 
9252 void SelectionDAGISel::LowerArguments(const Function &F) {
9253   SelectionDAG &DAG = SDB->DAG;
9254   SDLoc dl = SDB->getCurSDLoc();
9255   const DataLayout &DL = DAG.getDataLayout();
9256   SmallVector<ISD::InputArg, 16> Ins;
9257 
9258   if (!FuncInfo->CanLowerReturn) {
9259     // Put in an sret pointer parameter before all the other parameters.
9260     SmallVector<EVT, 1> ValueVTs;
9261     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9262                     F.getReturnType()->getPointerTo(
9263                         DAG.getDataLayout().getAllocaAddrSpace()),
9264                     ValueVTs);
9265 
9266     // NOTE: Assuming that a pointer will never break down to more than one VT
9267     // or one register.
9268     ISD::ArgFlagsTy Flags;
9269     Flags.setSRet();
9270     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9271     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9272                          ISD::InputArg::NoArgIndex, 0);
9273     Ins.push_back(RetArg);
9274   }
9275 
9276   // Look for stores of arguments to static allocas. Mark such arguments with a
9277   // flag to ask the target to give us the memory location of that argument if
9278   // available.
9279   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9280   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9281 
9282   // Set up the incoming argument description vector.
9283   for (const Argument &Arg : F.args()) {
9284     unsigned ArgNo = Arg.getArgNo();
9285     SmallVector<EVT, 4> ValueVTs;
9286     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9287     bool isArgValueUsed = !Arg.use_empty();
9288     unsigned PartBase = 0;
9289     Type *FinalType = Arg.getType();
9290     if (Arg.hasAttribute(Attribute::ByVal))
9291       FinalType = cast<PointerType>(FinalType)->getElementType();
9292     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9293         FinalType, F.getCallingConv(), F.isVarArg());
9294     for (unsigned Value = 0, NumValues = ValueVTs.size();
9295          Value != NumValues; ++Value) {
9296       EVT VT = ValueVTs[Value];
9297       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9298       ISD::ArgFlagsTy Flags;
9299 
9300       // Certain targets (such as MIPS), may have a different ABI alignment
9301       // for a type depending on the context. Give the target a chance to
9302       // specify the alignment it wants.
9303       unsigned OriginalAlignment =
9304           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9305 
9306       if (Arg.hasAttribute(Attribute::ZExt))
9307         Flags.setZExt();
9308       if (Arg.hasAttribute(Attribute::SExt))
9309         Flags.setSExt();
9310       if (Arg.hasAttribute(Attribute::InReg)) {
9311         // If we are using vectorcall calling convention, a structure that is
9312         // passed InReg - is surely an HVA
9313         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9314             isa<StructType>(Arg.getType())) {
9315           // The first value of a structure is marked
9316           if (0 == Value)
9317             Flags.setHvaStart();
9318           Flags.setHva();
9319         }
9320         // Set InReg Flag
9321         Flags.setInReg();
9322       }
9323       if (Arg.hasAttribute(Attribute::StructRet))
9324         Flags.setSRet();
9325       if (Arg.hasAttribute(Attribute::SwiftSelf))
9326         Flags.setSwiftSelf();
9327       if (Arg.hasAttribute(Attribute::SwiftError))
9328         Flags.setSwiftError();
9329       if (Arg.hasAttribute(Attribute::ByVal))
9330         Flags.setByVal();
9331       if (Arg.hasAttribute(Attribute::InAlloca)) {
9332         Flags.setInAlloca();
9333         // Set the byval flag for CCAssignFn callbacks that don't know about
9334         // inalloca.  This way we can know how many bytes we should've allocated
9335         // and how many bytes a callee cleanup function will pop.  If we port
9336         // inalloca to more targets, we'll have to add custom inalloca handling
9337         // in the various CC lowering callbacks.
9338         Flags.setByVal();
9339       }
9340       if (F.getCallingConv() == CallingConv::X86_INTR) {
9341         // IA Interrupt passes frame (1st parameter) by value in the stack.
9342         if (ArgNo == 0)
9343           Flags.setByVal();
9344       }
9345       if (Flags.isByVal() || Flags.isInAlloca()) {
9346         PointerType *Ty = cast<PointerType>(Arg.getType());
9347         Type *ElementTy = Ty->getElementType();
9348         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
9349         // For ByVal, alignment should be passed from FE.  BE will guess if
9350         // this info is not there but there are cases it cannot get right.
9351         unsigned FrameAlign;
9352         if (Arg.getParamAlignment())
9353           FrameAlign = Arg.getParamAlignment();
9354         else
9355           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9356         Flags.setByValAlign(FrameAlign);
9357       }
9358       if (Arg.hasAttribute(Attribute::Nest))
9359         Flags.setNest();
9360       if (NeedsRegBlock)
9361         Flags.setInConsecutiveRegs();
9362       Flags.setOrigAlign(OriginalAlignment);
9363       if (ArgCopyElisionCandidates.count(&Arg))
9364         Flags.setCopyElisionCandidate();
9365 
9366       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9367           *CurDAG->getContext(), F.getCallingConv(), VT);
9368       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9369           *CurDAG->getContext(), F.getCallingConv(), VT);
9370       for (unsigned i = 0; i != NumRegs; ++i) {
9371         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9372                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9373         if (NumRegs > 1 && i == 0)
9374           MyFlags.Flags.setSplit();
9375         // if it isn't first piece, alignment must be 1
9376         else if (i > 0) {
9377           MyFlags.Flags.setOrigAlign(1);
9378           if (i == NumRegs - 1)
9379             MyFlags.Flags.setSplitEnd();
9380         }
9381         Ins.push_back(MyFlags);
9382       }
9383       if (NeedsRegBlock && Value == NumValues - 1)
9384         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9385       PartBase += VT.getStoreSize();
9386     }
9387   }
9388 
9389   // Call the target to set up the argument values.
9390   SmallVector<SDValue, 8> InVals;
9391   SDValue NewRoot = TLI->LowerFormalArguments(
9392       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9393 
9394   // Verify that the target's LowerFormalArguments behaved as expected.
9395   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9396          "LowerFormalArguments didn't return a valid chain!");
9397   assert(InVals.size() == Ins.size() &&
9398          "LowerFormalArguments didn't emit the correct number of values!");
9399   LLVM_DEBUG({
9400     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9401       assert(InVals[i].getNode() &&
9402              "LowerFormalArguments emitted a null value!");
9403       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9404              "LowerFormalArguments emitted a value with the wrong type!");
9405     }
9406   });
9407 
9408   // Update the DAG with the new chain value resulting from argument lowering.
9409   DAG.setRoot(NewRoot);
9410 
9411   // Set up the argument values.
9412   unsigned i = 0;
9413   if (!FuncInfo->CanLowerReturn) {
9414     // Create a virtual register for the sret pointer, and put in a copy
9415     // from the sret argument into it.
9416     SmallVector<EVT, 1> ValueVTs;
9417     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9418                     F.getReturnType()->getPointerTo(
9419                         DAG.getDataLayout().getAllocaAddrSpace()),
9420                     ValueVTs);
9421     MVT VT = ValueVTs[0].getSimpleVT();
9422     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9423     Optional<ISD::NodeType> AssertOp = None;
9424     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9425                                         nullptr, F.getCallingConv(), AssertOp);
9426 
9427     MachineFunction& MF = SDB->DAG.getMachineFunction();
9428     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9429     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9430     FuncInfo->DemoteRegister = SRetReg;
9431     NewRoot =
9432         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9433     DAG.setRoot(NewRoot);
9434 
9435     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9436     ++i;
9437   }
9438 
9439   SmallVector<SDValue, 4> Chains;
9440   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9441   for (const Argument &Arg : F.args()) {
9442     SmallVector<SDValue, 4> ArgValues;
9443     SmallVector<EVT, 4> ValueVTs;
9444     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9445     unsigned NumValues = ValueVTs.size();
9446     if (NumValues == 0)
9447       continue;
9448 
9449     bool ArgHasUses = !Arg.use_empty();
9450 
9451     // Elide the copying store if the target loaded this argument from a
9452     // suitable fixed stack object.
9453     if (Ins[i].Flags.isCopyElisionCandidate()) {
9454       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9455                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9456                              InVals[i], ArgHasUses);
9457     }
9458 
9459     // If this argument is unused then remember its value. It is used to generate
9460     // debugging information.
9461     bool isSwiftErrorArg =
9462         TLI->supportSwiftError() &&
9463         Arg.hasAttribute(Attribute::SwiftError);
9464     if (!ArgHasUses && !isSwiftErrorArg) {
9465       SDB->setUnusedArgValue(&Arg, InVals[i]);
9466 
9467       // Also remember any frame index for use in FastISel.
9468       if (FrameIndexSDNode *FI =
9469           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9470         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9471     }
9472 
9473     for (unsigned Val = 0; Val != NumValues; ++Val) {
9474       EVT VT = ValueVTs[Val];
9475       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9476                                                       F.getCallingConv(), VT);
9477       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9478           *CurDAG->getContext(), F.getCallingConv(), VT);
9479 
9480       // Even an apparant 'unused' swifterror argument needs to be returned. So
9481       // we do generate a copy for it that can be used on return from the
9482       // function.
9483       if (ArgHasUses || isSwiftErrorArg) {
9484         Optional<ISD::NodeType> AssertOp;
9485         if (Arg.hasAttribute(Attribute::SExt))
9486           AssertOp = ISD::AssertSext;
9487         else if (Arg.hasAttribute(Attribute::ZExt))
9488           AssertOp = ISD::AssertZext;
9489 
9490         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9491                                              PartVT, VT, nullptr,
9492                                              F.getCallingConv(), AssertOp));
9493       }
9494 
9495       i += NumParts;
9496     }
9497 
9498     // We don't need to do anything else for unused arguments.
9499     if (ArgValues.empty())
9500       continue;
9501 
9502     // Note down frame index.
9503     if (FrameIndexSDNode *FI =
9504         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9505       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9506 
9507     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9508                                      SDB->getCurSDLoc());
9509 
9510     SDB->setValue(&Arg, Res);
9511     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9512       // We want to associate the argument with the frame index, among
9513       // involved operands, that correspond to the lowest address. The
9514       // getCopyFromParts function, called earlier, is swapping the order of
9515       // the operands to BUILD_PAIR depending on endianness. The result of
9516       // that swapping is that the least significant bits of the argument will
9517       // be in the first operand of the BUILD_PAIR node, and the most
9518       // significant bits will be in the second operand.
9519       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9520       if (LoadSDNode *LNode =
9521           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9522         if (FrameIndexSDNode *FI =
9523             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9524           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9525     }
9526 
9527     // Update the SwiftErrorVRegDefMap.
9528     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9529       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9530       if (TargetRegisterInfo::isVirtualRegister(Reg))
9531         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9532                                            FuncInfo->SwiftErrorArg, Reg);
9533     }
9534 
9535     // If this argument is live outside of the entry block, insert a copy from
9536     // wherever we got it to the vreg that other BB's will reference it as.
9537     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9538       // If we can, though, try to skip creating an unnecessary vreg.
9539       // FIXME: This isn't very clean... it would be nice to make this more
9540       // general.  It's also subtly incompatible with the hacks FastISel
9541       // uses with vregs.
9542       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9543       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9544         FuncInfo->ValueMap[&Arg] = Reg;
9545         continue;
9546       }
9547     }
9548     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9549       FuncInfo->InitializeRegForValue(&Arg);
9550       SDB->CopyToExportRegsIfNeeded(&Arg);
9551     }
9552   }
9553 
9554   if (!Chains.empty()) {
9555     Chains.push_back(NewRoot);
9556     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9557   }
9558 
9559   DAG.setRoot(NewRoot);
9560 
9561   assert(i == InVals.size() && "Argument register count mismatch!");
9562 
9563   // If any argument copy elisions occurred and we have debug info, update the
9564   // stale frame indices used in the dbg.declare variable info table.
9565   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9566   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9567     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9568       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9569       if (I != ArgCopyElisionFrameIndexMap.end())
9570         VI.Slot = I->second;
9571     }
9572   }
9573 
9574   // Finally, if the target has anything special to do, allow it to do so.
9575   EmitFunctionEntryCode();
9576 }
9577 
9578 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9579 /// ensure constants are generated when needed.  Remember the virtual registers
9580 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9581 /// directly add them, because expansion might result in multiple MBB's for one
9582 /// BB.  As such, the start of the BB might correspond to a different MBB than
9583 /// the end.
9584 void
9585 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9586   const Instruction *TI = LLVMBB->getTerminator();
9587 
9588   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9589 
9590   // Check PHI nodes in successors that expect a value to be available from this
9591   // block.
9592   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9593     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9594     if (!isa<PHINode>(SuccBB->begin())) continue;
9595     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9596 
9597     // If this terminator has multiple identical successors (common for
9598     // switches), only handle each succ once.
9599     if (!SuccsHandled.insert(SuccMBB).second)
9600       continue;
9601 
9602     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9603 
9604     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9605     // nodes and Machine PHI nodes, but the incoming operands have not been
9606     // emitted yet.
9607     for (const PHINode &PN : SuccBB->phis()) {
9608       // Ignore dead phi's.
9609       if (PN.use_empty())
9610         continue;
9611 
9612       // Skip empty types
9613       if (PN.getType()->isEmptyTy())
9614         continue;
9615 
9616       unsigned Reg;
9617       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9618 
9619       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9620         unsigned &RegOut = ConstantsOut[C];
9621         if (RegOut == 0) {
9622           RegOut = FuncInfo.CreateRegs(C->getType());
9623           CopyValueToVirtualRegister(C, RegOut);
9624         }
9625         Reg = RegOut;
9626       } else {
9627         DenseMap<const Value *, unsigned>::iterator I =
9628           FuncInfo.ValueMap.find(PHIOp);
9629         if (I != FuncInfo.ValueMap.end())
9630           Reg = I->second;
9631         else {
9632           assert(isa<AllocaInst>(PHIOp) &&
9633                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9634                  "Didn't codegen value into a register!??");
9635           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9636           CopyValueToVirtualRegister(PHIOp, Reg);
9637         }
9638       }
9639 
9640       // Remember that this register needs to added to the machine PHI node as
9641       // the input for this MBB.
9642       SmallVector<EVT, 4> ValueVTs;
9643       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9644       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9645       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9646         EVT VT = ValueVTs[vti];
9647         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9648         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9649           FuncInfo.PHINodesToUpdate.push_back(
9650               std::make_pair(&*MBBI++, Reg + i));
9651         Reg += NumRegisters;
9652       }
9653     }
9654   }
9655 
9656   ConstantsOut.clear();
9657 }
9658 
9659 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9660 /// is 0.
9661 MachineBasicBlock *
9662 SelectionDAGBuilder::StackProtectorDescriptor::
9663 AddSuccessorMBB(const BasicBlock *BB,
9664                 MachineBasicBlock *ParentMBB,
9665                 bool IsLikely,
9666                 MachineBasicBlock *SuccMBB) {
9667   // If SuccBB has not been created yet, create it.
9668   if (!SuccMBB) {
9669     MachineFunction *MF = ParentMBB->getParent();
9670     MachineFunction::iterator BBI(ParentMBB);
9671     SuccMBB = MF->CreateMachineBasicBlock(BB);
9672     MF->insert(++BBI, SuccMBB);
9673   }
9674   // Add it as a successor of ParentMBB.
9675   ParentMBB->addSuccessor(
9676       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9677   return SuccMBB;
9678 }
9679 
9680 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9681   MachineFunction::iterator I(MBB);
9682   if (++I == FuncInfo.MF->end())
9683     return nullptr;
9684   return &*I;
9685 }
9686 
9687 /// During lowering new call nodes can be created (such as memset, etc.).
9688 /// Those will become new roots of the current DAG, but complications arise
9689 /// when they are tail calls. In such cases, the call lowering will update
9690 /// the root, but the builder still needs to know that a tail call has been
9691 /// lowered in order to avoid generating an additional return.
9692 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9693   // If the node is null, we do have a tail call.
9694   if (MaybeTC.getNode() != nullptr)
9695     DAG.setRoot(MaybeTC);
9696   else
9697     HasTailCall = true;
9698 }
9699 
9700 uint64_t
9701 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9702                                        unsigned First, unsigned Last) const {
9703   assert(Last >= First);
9704   const APInt &LowCase = Clusters[First].Low->getValue();
9705   const APInt &HighCase = Clusters[Last].High->getValue();
9706   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9707 
9708   // FIXME: A range of consecutive cases has 100% density, but only requires one
9709   // comparison to lower. We should discriminate against such consecutive ranges
9710   // in jump tables.
9711 
9712   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9713 }
9714 
9715 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9716     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9717     unsigned Last) const {
9718   assert(Last >= First);
9719   assert(TotalCases[Last] >= TotalCases[First]);
9720   uint64_t NumCases =
9721       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9722   return NumCases;
9723 }
9724 
9725 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9726                                          unsigned First, unsigned Last,
9727                                          const SwitchInst *SI,
9728                                          MachineBasicBlock *DefaultMBB,
9729                                          CaseCluster &JTCluster) {
9730   assert(First <= Last);
9731 
9732   auto Prob = BranchProbability::getZero();
9733   unsigned NumCmps = 0;
9734   std::vector<MachineBasicBlock*> Table;
9735   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9736 
9737   // Initialize probabilities in JTProbs.
9738   for (unsigned I = First; I <= Last; ++I)
9739     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9740 
9741   for (unsigned I = First; I <= Last; ++I) {
9742     assert(Clusters[I].Kind == CC_Range);
9743     Prob += Clusters[I].Prob;
9744     const APInt &Low = Clusters[I].Low->getValue();
9745     const APInt &High = Clusters[I].High->getValue();
9746     NumCmps += (Low == High) ? 1 : 2;
9747     if (I != First) {
9748       // Fill the gap between this and the previous cluster.
9749       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9750       assert(PreviousHigh.slt(Low));
9751       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9752       for (uint64_t J = 0; J < Gap; J++)
9753         Table.push_back(DefaultMBB);
9754     }
9755     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9756     for (uint64_t J = 0; J < ClusterSize; ++J)
9757       Table.push_back(Clusters[I].MBB);
9758     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9759   }
9760 
9761   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9762   unsigned NumDests = JTProbs.size();
9763   if (TLI.isSuitableForBitTests(
9764           NumDests, NumCmps, Clusters[First].Low->getValue(),
9765           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9766     // Clusters[First..Last] should be lowered as bit tests instead.
9767     return false;
9768   }
9769 
9770   // Create the MBB that will load from and jump through the table.
9771   // Note: We create it here, but it's not inserted into the function yet.
9772   MachineFunction *CurMF = FuncInfo.MF;
9773   MachineBasicBlock *JumpTableMBB =
9774       CurMF->CreateMachineBasicBlock(SI->getParent());
9775 
9776   // Add successors. Note: use table order for determinism.
9777   SmallPtrSet<MachineBasicBlock *, 8> Done;
9778   for (MachineBasicBlock *Succ : Table) {
9779     if (Done.count(Succ))
9780       continue;
9781     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9782     Done.insert(Succ);
9783   }
9784   JumpTableMBB->normalizeSuccProbs();
9785 
9786   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9787                      ->createJumpTableIndex(Table);
9788 
9789   // Set up the jump table info.
9790   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9791   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9792                       Clusters[Last].High->getValue(), SI->getCondition(),
9793                       nullptr, false);
9794   JTCases.emplace_back(std::move(JTH), std::move(JT));
9795 
9796   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9797                                      JTCases.size() - 1, Prob);
9798   return true;
9799 }
9800 
9801 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9802                                          const SwitchInst *SI,
9803                                          MachineBasicBlock *DefaultMBB) {
9804 #ifndef NDEBUG
9805   // Clusters must be non-empty, sorted, and only contain Range clusters.
9806   assert(!Clusters.empty());
9807   for (CaseCluster &C : Clusters)
9808     assert(C.Kind == CC_Range);
9809   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9810     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9811 #endif
9812 
9813   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9814   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9815     return;
9816 
9817   const int64_t N = Clusters.size();
9818   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9819   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9820 
9821   if (N < 2 || N < MinJumpTableEntries)
9822     return;
9823 
9824   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9825   SmallVector<unsigned, 8> TotalCases(N);
9826   for (unsigned i = 0; i < N; ++i) {
9827     const APInt &Hi = Clusters[i].High->getValue();
9828     const APInt &Lo = Clusters[i].Low->getValue();
9829     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9830     if (i != 0)
9831       TotalCases[i] += TotalCases[i - 1];
9832   }
9833 
9834   // Cheap case: the whole range may be suitable for jump table.
9835   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9836   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9837   assert(NumCases < UINT64_MAX / 100);
9838   assert(Range >= NumCases);
9839   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9840     CaseCluster JTCluster;
9841     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9842       Clusters[0] = JTCluster;
9843       Clusters.resize(1);
9844       return;
9845     }
9846   }
9847 
9848   // The algorithm below is not suitable for -O0.
9849   if (TM.getOptLevel() == CodeGenOpt::None)
9850     return;
9851 
9852   // Split Clusters into minimum number of dense partitions. The algorithm uses
9853   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9854   // for the Case Statement'" (1994), but builds the MinPartitions array in
9855   // reverse order to make it easier to reconstruct the partitions in ascending
9856   // order. In the choice between two optimal partitionings, it picks the one
9857   // which yields more jump tables.
9858 
9859   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9860   SmallVector<unsigned, 8> MinPartitions(N);
9861   // LastElement[i] is the last element of the partition starting at i.
9862   SmallVector<unsigned, 8> LastElement(N);
9863   // PartitionsScore[i] is used to break ties when choosing between two
9864   // partitionings resulting in the same number of partitions.
9865   SmallVector<unsigned, 8> PartitionsScore(N);
9866   // For PartitionsScore, a small number of comparisons is considered as good as
9867   // a jump table and a single comparison is considered better than a jump
9868   // table.
9869   enum PartitionScores : unsigned {
9870     NoTable = 0,
9871     Table = 1,
9872     FewCases = 1,
9873     SingleCase = 2
9874   };
9875 
9876   // Base case: There is only one way to partition Clusters[N-1].
9877   MinPartitions[N - 1] = 1;
9878   LastElement[N - 1] = N - 1;
9879   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9880 
9881   // Note: loop indexes are signed to avoid underflow.
9882   for (int64_t i = N - 2; i >= 0; i--) {
9883     // Find optimal partitioning of Clusters[i..N-1].
9884     // Baseline: Put Clusters[i] into a partition on its own.
9885     MinPartitions[i] = MinPartitions[i + 1] + 1;
9886     LastElement[i] = i;
9887     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9888 
9889     // Search for a solution that results in fewer partitions.
9890     for (int64_t j = N - 1; j > i; j--) {
9891       // Try building a partition from Clusters[i..j].
9892       uint64_t Range = getJumpTableRange(Clusters, i, j);
9893       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9894       assert(NumCases < UINT64_MAX / 100);
9895       assert(Range >= NumCases);
9896       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9897         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9898         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9899         int64_t NumEntries = j - i + 1;
9900 
9901         if (NumEntries == 1)
9902           Score += PartitionScores::SingleCase;
9903         else if (NumEntries <= SmallNumberOfEntries)
9904           Score += PartitionScores::FewCases;
9905         else if (NumEntries >= MinJumpTableEntries)
9906           Score += PartitionScores::Table;
9907 
9908         // If this leads to fewer partitions, or to the same number of
9909         // partitions with better score, it is a better partitioning.
9910         if (NumPartitions < MinPartitions[i] ||
9911             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9912           MinPartitions[i] = NumPartitions;
9913           LastElement[i] = j;
9914           PartitionsScore[i] = Score;
9915         }
9916       }
9917     }
9918   }
9919 
9920   // Iterate over the partitions, replacing some with jump tables in-place.
9921   unsigned DstIndex = 0;
9922   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9923     Last = LastElement[First];
9924     assert(Last >= First);
9925     assert(DstIndex <= First);
9926     unsigned NumClusters = Last - First + 1;
9927 
9928     CaseCluster JTCluster;
9929     if (NumClusters >= MinJumpTableEntries &&
9930         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9931       Clusters[DstIndex++] = JTCluster;
9932     } else {
9933       for (unsigned I = First; I <= Last; ++I)
9934         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9935     }
9936   }
9937   Clusters.resize(DstIndex);
9938 }
9939 
9940 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9941                                         unsigned First, unsigned Last,
9942                                         const SwitchInst *SI,
9943                                         CaseCluster &BTCluster) {
9944   assert(First <= Last);
9945   if (First == Last)
9946     return false;
9947 
9948   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9949   unsigned NumCmps = 0;
9950   for (int64_t I = First; I <= Last; ++I) {
9951     assert(Clusters[I].Kind == CC_Range);
9952     Dests.set(Clusters[I].MBB->getNumber());
9953     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9954   }
9955   unsigned NumDests = Dests.count();
9956 
9957   APInt Low = Clusters[First].Low->getValue();
9958   APInt High = Clusters[Last].High->getValue();
9959   assert(Low.slt(High));
9960 
9961   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9962   const DataLayout &DL = DAG.getDataLayout();
9963   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9964     return false;
9965 
9966   APInt LowBound;
9967   APInt CmpRange;
9968 
9969   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9970   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9971          "Case range must fit in bit mask!");
9972 
9973   // Check if the clusters cover a contiguous range such that no value in the
9974   // range will jump to the default statement.
9975   bool ContiguousRange = true;
9976   for (int64_t I = First + 1; I <= Last; ++I) {
9977     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9978       ContiguousRange = false;
9979       break;
9980     }
9981   }
9982 
9983   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9984     // Optimize the case where all the case values fit in a word without having
9985     // to subtract minValue. In this case, we can optimize away the subtraction.
9986     LowBound = APInt::getNullValue(Low.getBitWidth());
9987     CmpRange = High;
9988     ContiguousRange = false;
9989   } else {
9990     LowBound = Low;
9991     CmpRange = High - Low;
9992   }
9993 
9994   CaseBitsVector CBV;
9995   auto TotalProb = BranchProbability::getZero();
9996   for (unsigned i = First; i <= Last; ++i) {
9997     // Find the CaseBits for this destination.
9998     unsigned j;
9999     for (j = 0; j < CBV.size(); ++j)
10000       if (CBV[j].BB == Clusters[i].MBB)
10001         break;
10002     if (j == CBV.size())
10003       CBV.push_back(
10004           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
10005     CaseBits *CB = &CBV[j];
10006 
10007     // Update Mask, Bits and ExtraProb.
10008     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
10009     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
10010     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
10011     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
10012     CB->Bits += Hi - Lo + 1;
10013     CB->ExtraProb += Clusters[i].Prob;
10014     TotalProb += Clusters[i].Prob;
10015   }
10016 
10017   BitTestInfo BTI;
10018   llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
10019     // Sort by probability first, number of bits second, bit mask third.
10020     if (a.ExtraProb != b.ExtraProb)
10021       return a.ExtraProb > b.ExtraProb;
10022     if (a.Bits != b.Bits)
10023       return a.Bits > b.Bits;
10024     return a.Mask < b.Mask;
10025   });
10026 
10027   for (auto &CB : CBV) {
10028     MachineBasicBlock *BitTestBB =
10029         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
10030     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
10031   }
10032   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
10033                             SI->getCondition(), -1U, MVT::Other, false,
10034                             ContiguousRange, nullptr, nullptr, std::move(BTI),
10035                             TotalProb);
10036 
10037   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
10038                                     BitTestCases.size() - 1, TotalProb);
10039   return true;
10040 }
10041 
10042 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
10043                                               const SwitchInst *SI) {
10044 // Partition Clusters into as few subsets as possible, where each subset has a
10045 // range that fits in a machine word and has <= 3 unique destinations.
10046 
10047 #ifndef NDEBUG
10048   // Clusters must be sorted and contain Range or JumpTable clusters.
10049   assert(!Clusters.empty());
10050   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
10051   for (const CaseCluster &C : Clusters)
10052     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
10053   for (unsigned i = 1; i < Clusters.size(); ++i)
10054     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
10055 #endif
10056 
10057   // The algorithm below is not suitable for -O0.
10058   if (TM.getOptLevel() == CodeGenOpt::None)
10059     return;
10060 
10061   // If target does not have legal shift left, do not emit bit tests at all.
10062   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10063   const DataLayout &DL = DAG.getDataLayout();
10064 
10065   EVT PTy = TLI.getPointerTy(DL);
10066   if (!TLI.isOperationLegal(ISD::SHL, PTy))
10067     return;
10068 
10069   int BitWidth = PTy.getSizeInBits();
10070   const int64_t N = Clusters.size();
10071 
10072   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
10073   SmallVector<unsigned, 8> MinPartitions(N);
10074   // LastElement[i] is the last element of the partition starting at i.
10075   SmallVector<unsigned, 8> LastElement(N);
10076 
10077   // FIXME: This might not be the best algorithm for finding bit test clusters.
10078 
10079   // Base case: There is only one way to partition Clusters[N-1].
10080   MinPartitions[N - 1] = 1;
10081   LastElement[N - 1] = N - 1;
10082 
10083   // Note: loop indexes are signed to avoid underflow.
10084   for (int64_t i = N - 2; i >= 0; --i) {
10085     // Find optimal partitioning of Clusters[i..N-1].
10086     // Baseline: Put Clusters[i] into a partition on its own.
10087     MinPartitions[i] = MinPartitions[i + 1] + 1;
10088     LastElement[i] = i;
10089 
10090     // Search for a solution that results in fewer partitions.
10091     // Note: the search is limited by BitWidth, reducing time complexity.
10092     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
10093       // Try building a partition from Clusters[i..j].
10094 
10095       // Check the range.
10096       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
10097                                Clusters[j].High->getValue(), DL))
10098         continue;
10099 
10100       // Check nbr of destinations and cluster types.
10101       // FIXME: This works, but doesn't seem very efficient.
10102       bool RangesOnly = true;
10103       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
10104       for (int64_t k = i; k <= j; k++) {
10105         if (Clusters[k].Kind != CC_Range) {
10106           RangesOnly = false;
10107           break;
10108         }
10109         Dests.set(Clusters[k].MBB->getNumber());
10110       }
10111       if (!RangesOnly || Dests.count() > 3)
10112         break;
10113 
10114       // Check if it's a better partition.
10115       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
10116       if (NumPartitions < MinPartitions[i]) {
10117         // Found a better partition.
10118         MinPartitions[i] = NumPartitions;
10119         LastElement[i] = j;
10120       }
10121     }
10122   }
10123 
10124   // Iterate over the partitions, replacing with bit-test clusters in-place.
10125   unsigned DstIndex = 0;
10126   for (unsigned First = 0, Last; First < N; First = Last + 1) {
10127     Last = LastElement[First];
10128     assert(First <= Last);
10129     assert(DstIndex <= First);
10130 
10131     CaseCluster BitTestCluster;
10132     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
10133       Clusters[DstIndex++] = BitTestCluster;
10134     } else {
10135       size_t NumClusters = Last - First + 1;
10136       std::memmove(&Clusters[DstIndex], &Clusters[First],
10137                    sizeof(Clusters[0]) * NumClusters);
10138       DstIndex += NumClusters;
10139     }
10140   }
10141   Clusters.resize(DstIndex);
10142 }
10143 
10144 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10145                                         MachineBasicBlock *SwitchMBB,
10146                                         MachineBasicBlock *DefaultMBB) {
10147   MachineFunction *CurMF = FuncInfo.MF;
10148   MachineBasicBlock *NextMBB = nullptr;
10149   MachineFunction::iterator BBI(W.MBB);
10150   if (++BBI != FuncInfo.MF->end())
10151     NextMBB = &*BBI;
10152 
10153   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10154 
10155   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10156 
10157   if (Size == 2 && W.MBB == SwitchMBB) {
10158     // If any two of the cases has the same destination, and if one value
10159     // is the same as the other, but has one bit unset that the other has set,
10160     // use bit manipulation to do two compares at once.  For example:
10161     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10162     // TODO: This could be extended to merge any 2 cases in switches with 3
10163     // cases.
10164     // TODO: Handle cases where W.CaseBB != SwitchBB.
10165     CaseCluster &Small = *W.FirstCluster;
10166     CaseCluster &Big = *W.LastCluster;
10167 
10168     if (Small.Low == Small.High && Big.Low == Big.High &&
10169         Small.MBB == Big.MBB) {
10170       const APInt &SmallValue = Small.Low->getValue();
10171       const APInt &BigValue = Big.Low->getValue();
10172 
10173       // Check that there is only one bit different.
10174       APInt CommonBit = BigValue ^ SmallValue;
10175       if (CommonBit.isPowerOf2()) {
10176         SDValue CondLHS = getValue(Cond);
10177         EVT VT = CondLHS.getValueType();
10178         SDLoc DL = getCurSDLoc();
10179 
10180         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10181                                  DAG.getConstant(CommonBit, DL, VT));
10182         SDValue Cond = DAG.getSetCC(
10183             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10184             ISD::SETEQ);
10185 
10186         // Update successor info.
10187         // Both Small and Big will jump to Small.BB, so we sum up the
10188         // probabilities.
10189         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10190         if (BPI)
10191           addSuccessorWithProb(
10192               SwitchMBB, DefaultMBB,
10193               // The default destination is the first successor in IR.
10194               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10195         else
10196           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10197 
10198         // Insert the true branch.
10199         SDValue BrCond =
10200             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10201                         DAG.getBasicBlock(Small.MBB));
10202         // Insert the false branch.
10203         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10204                              DAG.getBasicBlock(DefaultMBB));
10205 
10206         DAG.setRoot(BrCond);
10207         return;
10208       }
10209     }
10210   }
10211 
10212   if (TM.getOptLevel() != CodeGenOpt::None) {
10213     // Here, we order cases by probability so the most likely case will be
10214     // checked first. However, two clusters can have the same probability in
10215     // which case their relative ordering is non-deterministic. So we use Low
10216     // as a tie-breaker as clusters are guaranteed to never overlap.
10217     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10218                [](const CaseCluster &a, const CaseCluster &b) {
10219       return a.Prob != b.Prob ?
10220              a.Prob > b.Prob :
10221              a.Low->getValue().slt(b.Low->getValue());
10222     });
10223 
10224     // Rearrange the case blocks so that the last one falls through if possible
10225     // without changing the order of probabilities.
10226     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10227       --I;
10228       if (I->Prob > W.LastCluster->Prob)
10229         break;
10230       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10231         std::swap(*I, *W.LastCluster);
10232         break;
10233       }
10234     }
10235   }
10236 
10237   // Compute total probability.
10238   BranchProbability DefaultProb = W.DefaultProb;
10239   BranchProbability UnhandledProbs = DefaultProb;
10240   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10241     UnhandledProbs += I->Prob;
10242 
10243   MachineBasicBlock *CurMBB = W.MBB;
10244   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10245     MachineBasicBlock *Fallthrough;
10246     if (I == W.LastCluster) {
10247       // For the last cluster, fall through to the default destination.
10248       Fallthrough = DefaultMBB;
10249     } else {
10250       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10251       CurMF->insert(BBI, Fallthrough);
10252       // Put Cond in a virtual register to make it available from the new blocks.
10253       ExportFromCurrentBlock(Cond);
10254     }
10255     UnhandledProbs -= I->Prob;
10256 
10257     switch (I->Kind) {
10258       case CC_JumpTable: {
10259         // FIXME: Optimize away range check based on pivot comparisons.
10260         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
10261         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
10262 
10263         // The jump block hasn't been inserted yet; insert it here.
10264         MachineBasicBlock *JumpMBB = JT->MBB;
10265         CurMF->insert(BBI, JumpMBB);
10266 
10267         auto JumpProb = I->Prob;
10268         auto FallthroughProb = UnhandledProbs;
10269 
10270         // If the default statement is a target of the jump table, we evenly
10271         // distribute the default probability to successors of CurMBB. Also
10272         // update the probability on the edge from JumpMBB to Fallthrough.
10273         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10274                                               SE = JumpMBB->succ_end();
10275              SI != SE; ++SI) {
10276           if (*SI == DefaultMBB) {
10277             JumpProb += DefaultProb / 2;
10278             FallthroughProb -= DefaultProb / 2;
10279             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10280             JumpMBB->normalizeSuccProbs();
10281             break;
10282           }
10283         }
10284 
10285         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10286         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10287         CurMBB->normalizeSuccProbs();
10288 
10289         // The jump table header will be inserted in our current block, do the
10290         // range check, and fall through to our fallthrough block.
10291         JTH->HeaderBB = CurMBB;
10292         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10293 
10294         // If we're in the right place, emit the jump table header right now.
10295         if (CurMBB == SwitchMBB) {
10296           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10297           JTH->Emitted = true;
10298         }
10299         break;
10300       }
10301       case CC_BitTests: {
10302         // FIXME: Optimize away range check based on pivot comparisons.
10303         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
10304 
10305         // The bit test blocks haven't been inserted yet; insert them here.
10306         for (BitTestCase &BTC : BTB->Cases)
10307           CurMF->insert(BBI, BTC.ThisBB);
10308 
10309         // Fill in fields of the BitTestBlock.
10310         BTB->Parent = CurMBB;
10311         BTB->Default = Fallthrough;
10312 
10313         BTB->DefaultProb = UnhandledProbs;
10314         // If the cases in bit test don't form a contiguous range, we evenly
10315         // distribute the probability on the edge to Fallthrough to two
10316         // successors of CurMBB.
10317         if (!BTB->ContiguousRange) {
10318           BTB->Prob += DefaultProb / 2;
10319           BTB->DefaultProb -= DefaultProb / 2;
10320         }
10321 
10322         // If we're in the right place, emit the bit test header right now.
10323         if (CurMBB == SwitchMBB) {
10324           visitBitTestHeader(*BTB, SwitchMBB);
10325           BTB->Emitted = true;
10326         }
10327         break;
10328       }
10329       case CC_Range: {
10330         const Value *RHS, *LHS, *MHS;
10331         ISD::CondCode CC;
10332         if (I->Low == I->High) {
10333           // Check Cond == I->Low.
10334           CC = ISD::SETEQ;
10335           LHS = Cond;
10336           RHS=I->Low;
10337           MHS = nullptr;
10338         } else {
10339           // Check I->Low <= Cond <= I->High.
10340           CC = ISD::SETLE;
10341           LHS = I->Low;
10342           MHS = Cond;
10343           RHS = I->High;
10344         }
10345 
10346         // The false probability is the sum of all unhandled cases.
10347         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10348                      getCurSDLoc(), I->Prob, UnhandledProbs);
10349 
10350         if (CurMBB == SwitchMBB)
10351           visitSwitchCase(CB, SwitchMBB);
10352         else
10353           SwitchCases.push_back(CB);
10354 
10355         break;
10356       }
10357     }
10358     CurMBB = Fallthrough;
10359   }
10360 }
10361 
10362 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10363                                               CaseClusterIt First,
10364                                               CaseClusterIt Last) {
10365   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10366     if (X.Prob != CC.Prob)
10367       return X.Prob > CC.Prob;
10368 
10369     // Ties are broken by comparing the case value.
10370     return X.Low->getValue().slt(CC.Low->getValue());
10371   });
10372 }
10373 
10374 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10375                                         const SwitchWorkListItem &W,
10376                                         Value *Cond,
10377                                         MachineBasicBlock *SwitchMBB) {
10378   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10379          "Clusters not sorted?");
10380 
10381   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10382 
10383   // Balance the tree based on branch probabilities to create a near-optimal (in
10384   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10385   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10386   CaseClusterIt LastLeft = W.FirstCluster;
10387   CaseClusterIt FirstRight = W.LastCluster;
10388   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10389   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10390 
10391   // Move LastLeft and FirstRight towards each other from opposite directions to
10392   // find a partitioning of the clusters which balances the probability on both
10393   // sides. If LeftProb and RightProb are equal, alternate which side is
10394   // taken to ensure 0-probability nodes are distributed evenly.
10395   unsigned I = 0;
10396   while (LastLeft + 1 < FirstRight) {
10397     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10398       LeftProb += (++LastLeft)->Prob;
10399     else
10400       RightProb += (--FirstRight)->Prob;
10401     I++;
10402   }
10403 
10404   while (true) {
10405     // Our binary search tree differs from a typical BST in that ours can have up
10406     // to three values in each leaf. The pivot selection above doesn't take that
10407     // into account, which means the tree might require more nodes and be less
10408     // efficient. We compensate for this here.
10409 
10410     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10411     unsigned NumRight = W.LastCluster - FirstRight + 1;
10412 
10413     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10414       // If one side has less than 3 clusters, and the other has more than 3,
10415       // consider taking a cluster from the other side.
10416 
10417       if (NumLeft < NumRight) {
10418         // Consider moving the first cluster on the right to the left side.
10419         CaseCluster &CC = *FirstRight;
10420         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10421         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10422         if (LeftSideRank <= RightSideRank) {
10423           // Moving the cluster to the left does not demote it.
10424           ++LastLeft;
10425           ++FirstRight;
10426           continue;
10427         }
10428       } else {
10429         assert(NumRight < NumLeft);
10430         // Consider moving the last element on the left to the right side.
10431         CaseCluster &CC = *LastLeft;
10432         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10433         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10434         if (RightSideRank <= LeftSideRank) {
10435           // Moving the cluster to the right does not demot it.
10436           --LastLeft;
10437           --FirstRight;
10438           continue;
10439         }
10440       }
10441     }
10442     break;
10443   }
10444 
10445   assert(LastLeft + 1 == FirstRight);
10446   assert(LastLeft >= W.FirstCluster);
10447   assert(FirstRight <= W.LastCluster);
10448 
10449   // Use the first element on the right as pivot since we will make less-than
10450   // comparisons against it.
10451   CaseClusterIt PivotCluster = FirstRight;
10452   assert(PivotCluster > W.FirstCluster);
10453   assert(PivotCluster <= W.LastCluster);
10454 
10455   CaseClusterIt FirstLeft = W.FirstCluster;
10456   CaseClusterIt LastRight = W.LastCluster;
10457 
10458   const ConstantInt *Pivot = PivotCluster->Low;
10459 
10460   // New blocks will be inserted immediately after the current one.
10461   MachineFunction::iterator BBI(W.MBB);
10462   ++BBI;
10463 
10464   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10465   // we can branch to its destination directly if it's squeezed exactly in
10466   // between the known lower bound and Pivot - 1.
10467   MachineBasicBlock *LeftMBB;
10468   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10469       FirstLeft->Low == W.GE &&
10470       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10471     LeftMBB = FirstLeft->MBB;
10472   } else {
10473     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10474     FuncInfo.MF->insert(BBI, LeftMBB);
10475     WorkList.push_back(
10476         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10477     // Put Cond in a virtual register to make it available from the new blocks.
10478     ExportFromCurrentBlock(Cond);
10479   }
10480 
10481   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10482   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10483   // directly if RHS.High equals the current upper bound.
10484   MachineBasicBlock *RightMBB;
10485   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10486       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10487     RightMBB = FirstRight->MBB;
10488   } else {
10489     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10490     FuncInfo.MF->insert(BBI, RightMBB);
10491     WorkList.push_back(
10492         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10493     // Put Cond in a virtual register to make it available from the new blocks.
10494     ExportFromCurrentBlock(Cond);
10495   }
10496 
10497   // Create the CaseBlock record that will be used to lower the branch.
10498   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10499                getCurSDLoc(), LeftProb, RightProb);
10500 
10501   if (W.MBB == SwitchMBB)
10502     visitSwitchCase(CB, SwitchMBB);
10503   else
10504     SwitchCases.push_back(CB);
10505 }
10506 
10507 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10508 // from the swith statement.
10509 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10510                                             BranchProbability PeeledCaseProb) {
10511   if (PeeledCaseProb == BranchProbability::getOne())
10512     return BranchProbability::getZero();
10513   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10514 
10515   uint32_t Numerator = CaseProb.getNumerator();
10516   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10517   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10518 }
10519 
10520 // Try to peel the top probability case if it exceeds the threshold.
10521 // Return current MachineBasicBlock for the switch statement if the peeling
10522 // does not occur.
10523 // If the peeling is performed, return the newly created MachineBasicBlock
10524 // for the peeled switch statement. Also update Clusters to remove the peeled
10525 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10526 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10527     const SwitchInst &SI, CaseClusterVector &Clusters,
10528     BranchProbability &PeeledCaseProb) {
10529   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10530   // Don't perform if there is only one cluster or optimizing for size.
10531   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10532       TM.getOptLevel() == CodeGenOpt::None ||
10533       SwitchMBB->getParent()->getFunction().optForMinSize())
10534     return SwitchMBB;
10535 
10536   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10537   unsigned PeeledCaseIndex = 0;
10538   bool SwitchPeeled = false;
10539   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10540     CaseCluster &CC = Clusters[Index];
10541     if (CC.Prob < TopCaseProb)
10542       continue;
10543     TopCaseProb = CC.Prob;
10544     PeeledCaseIndex = Index;
10545     SwitchPeeled = true;
10546   }
10547   if (!SwitchPeeled)
10548     return SwitchMBB;
10549 
10550   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10551                     << TopCaseProb << "\n");
10552 
10553   // Record the MBB for the peeled switch statement.
10554   MachineFunction::iterator BBI(SwitchMBB);
10555   ++BBI;
10556   MachineBasicBlock *PeeledSwitchMBB =
10557       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10558   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10559 
10560   ExportFromCurrentBlock(SI.getCondition());
10561   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10562   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10563                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10564   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10565 
10566   Clusters.erase(PeeledCaseIt);
10567   for (CaseCluster &CC : Clusters) {
10568     LLVM_DEBUG(
10569         dbgs() << "Scale the probablity for one cluster, before scaling: "
10570                << CC.Prob << "\n");
10571     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10572     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10573   }
10574   PeeledCaseProb = TopCaseProb;
10575   return PeeledSwitchMBB;
10576 }
10577 
10578 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10579   // Extract cases from the switch.
10580   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10581   CaseClusterVector Clusters;
10582   Clusters.reserve(SI.getNumCases());
10583   for (auto I : SI.cases()) {
10584     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10585     const ConstantInt *CaseVal = I.getCaseValue();
10586     BranchProbability Prob =
10587         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10588             : BranchProbability(1, SI.getNumCases() + 1);
10589     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10590   }
10591 
10592   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10593 
10594   // Cluster adjacent cases with the same destination. We do this at all
10595   // optimization levels because it's cheap to do and will make codegen faster
10596   // if there are many clusters.
10597   sortAndRangeify(Clusters);
10598 
10599   if (TM.getOptLevel() != CodeGenOpt::None) {
10600     // Replace an unreachable default with the most popular destination.
10601     // FIXME: Exploit unreachable default more aggressively.
10602     bool UnreachableDefault =
10603         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10604     if (UnreachableDefault && !Clusters.empty()) {
10605       DenseMap<const BasicBlock *, unsigned> Popularity;
10606       unsigned MaxPop = 0;
10607       const BasicBlock *MaxBB = nullptr;
10608       for (auto I : SI.cases()) {
10609         const BasicBlock *BB = I.getCaseSuccessor();
10610         if (++Popularity[BB] > MaxPop) {
10611           MaxPop = Popularity[BB];
10612           MaxBB = BB;
10613         }
10614       }
10615       // Set new default.
10616       assert(MaxPop > 0 && MaxBB);
10617       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10618 
10619       // Remove cases that were pointing to the destination that is now the
10620       // default.
10621       CaseClusterVector New;
10622       New.reserve(Clusters.size());
10623       for (CaseCluster &CC : Clusters) {
10624         if (CC.MBB != DefaultMBB)
10625           New.push_back(CC);
10626       }
10627       Clusters = std::move(New);
10628     }
10629   }
10630 
10631   // The branch probablity of the peeled case.
10632   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10633   MachineBasicBlock *PeeledSwitchMBB =
10634       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10635 
10636   // If there is only the default destination, jump there directly.
10637   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10638   if (Clusters.empty()) {
10639     assert(PeeledSwitchMBB == SwitchMBB);
10640     SwitchMBB->addSuccessor(DefaultMBB);
10641     if (DefaultMBB != NextBlock(SwitchMBB)) {
10642       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10643                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10644     }
10645     return;
10646   }
10647 
10648   findJumpTables(Clusters, &SI, DefaultMBB);
10649   findBitTestClusters(Clusters, &SI);
10650 
10651   LLVM_DEBUG({
10652     dbgs() << "Case clusters: ";
10653     for (const CaseCluster &C : Clusters) {
10654       if (C.Kind == CC_JumpTable)
10655         dbgs() << "JT:";
10656       if (C.Kind == CC_BitTests)
10657         dbgs() << "BT:";
10658 
10659       C.Low->getValue().print(dbgs(), true);
10660       if (C.Low != C.High) {
10661         dbgs() << '-';
10662         C.High->getValue().print(dbgs(), true);
10663       }
10664       dbgs() << ' ';
10665     }
10666     dbgs() << '\n';
10667   });
10668 
10669   assert(!Clusters.empty());
10670   SwitchWorkList WorkList;
10671   CaseClusterIt First = Clusters.begin();
10672   CaseClusterIt Last = Clusters.end() - 1;
10673   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10674   // Scale the branchprobability for DefaultMBB if the peel occurs and
10675   // DefaultMBB is not replaced.
10676   if (PeeledCaseProb != BranchProbability::getZero() &&
10677       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10678     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10679   WorkList.push_back(
10680       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10681 
10682   while (!WorkList.empty()) {
10683     SwitchWorkListItem W = WorkList.back();
10684     WorkList.pop_back();
10685     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10686 
10687     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10688         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10689       // For optimized builds, lower large range as a balanced binary tree.
10690       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10691       continue;
10692     }
10693 
10694     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10695   }
10696 }
10697