xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 85bd3978ae4e1c16fa8fa4bc27d0393d1d2265ea)
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.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
577 
578     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
579                    CallConv);
580 
581     if (DAG.getDataLayout().isBigEndian())
582       // The odd parts were reversed by getCopyToParts - unreverse them.
583       std::reverse(Parts + RoundParts, Parts + NumParts);
584 
585     NumParts = RoundParts;
586     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
587     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
588   }
589 
590   // The number of parts is a power of 2.  Repeatedly bisect the value using
591   // EXTRACT_ELEMENT.
592   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
593                          EVT::getIntegerVT(*DAG.getContext(),
594                                            ValueVT.getSizeInBits()),
595                          Val);
596 
597   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
598     for (unsigned i = 0; i < NumParts; i += StepSize) {
599       unsigned ThisBits = StepSize * PartBits / 2;
600       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
601       SDValue &Part0 = Parts[i];
602       SDValue &Part1 = Parts[i+StepSize/2];
603 
604       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
605                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
606       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
607                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
608 
609       if (ThisBits == PartBits && ThisVT != PartVT) {
610         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
611         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
612       }
613     }
614   }
615 
616   if (DAG.getDataLayout().isBigEndian())
617     std::reverse(Parts, Parts + OrigNumParts);
618 }
619 
620 static SDValue widenVectorToPartType(SelectionDAG &DAG,
621                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
622   if (!PartVT.isVector())
623     return SDValue();
624 
625   EVT ValueVT = Val.getValueType();
626   unsigned PartNumElts = PartVT.getVectorNumElements();
627   unsigned ValueNumElts = ValueVT.getVectorNumElements();
628   if (PartNumElts > ValueNumElts &&
629       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
630     EVT ElementVT = PartVT.getVectorElementType();
631     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
632     // undef elements.
633     SmallVector<SDValue, 16> Ops;
634     DAG.ExtractVectorElements(Val, Ops);
635     SDValue EltUndef = DAG.getUNDEF(ElementVT);
636     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
637       Ops.push_back(EltUndef);
638 
639     // FIXME: Use CONCAT for 2x -> 4x.
640     return DAG.getBuildVector(PartVT, DL, Ops);
641   }
642 
643   return SDValue();
644 }
645 
646 /// getCopyToPartsVector - Create a series of nodes that contain the specified
647 /// value split into legal parts.
648 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
649                                  SDValue Val, SDValue *Parts, unsigned NumParts,
650                                  MVT PartVT, const Value *V,
651                                  Optional<CallingConv::ID> CallConv) {
652   EVT ValueVT = Val.getValueType();
653   assert(ValueVT.isVector() && "Not a vector");
654   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
655   const bool IsABIRegCopy = CallConv.hasValue();
656 
657   if (NumParts == 1) {
658     EVT PartEVT = PartVT;
659     if (PartEVT == ValueVT) {
660       // Nothing to do.
661     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
662       // Bitconvert vector->vector case.
663       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
664     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
665       Val = Widened;
666     } else if (PartVT.isVector() &&
667                PartEVT.getVectorElementType().bitsGE(
668                  ValueVT.getVectorElementType()) &&
669                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
670 
671       // Promoted vector extract
672       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
673     } else {
674       if (ValueVT.getVectorNumElements() == 1) {
675         Val = DAG.getNode(
676             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
677             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
678       } else {
679         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
680                "lossy conversion of vector to scalar type");
681         EVT IntermediateType =
682             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
683         Val = DAG.getBitcast(IntermediateType, Val);
684         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
685       }
686     }
687 
688     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
689     Parts[0] = Val;
690     return;
691   }
692 
693   // Handle a multi-element vector.
694   EVT IntermediateVT;
695   MVT RegisterVT;
696   unsigned NumIntermediates;
697   unsigned NumRegs;
698   if (IsABIRegCopy) {
699     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
700         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
701         NumIntermediates, RegisterVT);
702   } else {
703     NumRegs =
704         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
705                                    NumIntermediates, RegisterVT);
706   }
707 
708   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
709   NumParts = NumRegs; // Silence a compiler warning.
710   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
711 
712   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
713     IntermediateVT.getVectorNumElements() : 1;
714 
715   // Convert the vector to the appropiate type if necessary.
716   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
717 
718   EVT BuiltVectorTy = EVT::getVectorVT(
719       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
720   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
721   if (ValueVT != BuiltVectorTy) {
722     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
723       Val = Widened;
724 
725     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
726   }
727 
728   // Split the vector into intermediate operands.
729   SmallVector<SDValue, 8> Ops(NumIntermediates);
730   for (unsigned i = 0; i != NumIntermediates; ++i) {
731     if (IntermediateVT.isVector()) {
732       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
733                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
734     } else {
735       Ops[i] = DAG.getNode(
736           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
737           DAG.getConstant(i, DL, IdxVT));
738     }
739   }
740 
741   // Split the intermediate operands into legal parts.
742   if (NumParts == NumIntermediates) {
743     // If the register was not expanded, promote or copy the value,
744     // as appropriate.
745     for (unsigned i = 0; i != NumParts; ++i)
746       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
747   } else if (NumParts > 0) {
748     // If the intermediate type was expanded, split each the value into
749     // legal parts.
750     assert(NumIntermediates != 0 && "division by zero");
751     assert(NumParts % NumIntermediates == 0 &&
752            "Must expand into a divisible number of parts!");
753     unsigned Factor = NumParts / NumIntermediates;
754     for (unsigned i = 0; i != NumIntermediates; ++i)
755       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
756                      CallConv);
757   }
758 }
759 
760 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
761                            EVT valuevt, Optional<CallingConv::ID> CC)
762     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
763       RegCount(1, regs.size()), CallConv(CC) {}
764 
765 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
766                            const DataLayout &DL, unsigned Reg, Type *Ty,
767                            Optional<CallingConv::ID> CC) {
768   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
769 
770   CallConv = CC;
771 
772   for (EVT ValueVT : ValueVTs) {
773     unsigned NumRegs =
774         isABIMangled()
775             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
776             : TLI.getNumRegisters(Context, ValueVT);
777     MVT RegisterVT =
778         isABIMangled()
779             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
780             : TLI.getRegisterType(Context, ValueVT);
781     for (unsigned i = 0; i != NumRegs; ++i)
782       Regs.push_back(Reg + i);
783     RegVTs.push_back(RegisterVT);
784     RegCount.push_back(NumRegs);
785     Reg += NumRegs;
786   }
787 }
788 
789 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
790                                       FunctionLoweringInfo &FuncInfo,
791                                       const SDLoc &dl, SDValue &Chain,
792                                       SDValue *Flag, const Value *V) const {
793   // A Value with type {} or [0 x %t] needs no registers.
794   if (ValueVTs.empty())
795     return SDValue();
796 
797   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
798 
799   // Assemble the legal parts into the final values.
800   SmallVector<SDValue, 4> Values(ValueVTs.size());
801   SmallVector<SDValue, 8> Parts;
802   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
803     // Copy the legal parts from the registers.
804     EVT ValueVT = ValueVTs[Value];
805     unsigned NumRegs = RegCount[Value];
806     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
807                                           *DAG.getContext(),
808                                           CallConv.getValue(), RegVTs[Value])
809                                     : RegVTs[Value];
810 
811     Parts.resize(NumRegs);
812     for (unsigned i = 0; i != NumRegs; ++i) {
813       SDValue P;
814       if (!Flag) {
815         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
816       } else {
817         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
818         *Flag = P.getValue(2);
819       }
820 
821       Chain = P.getValue(1);
822       Parts[i] = P;
823 
824       // If the source register was virtual and if we know something about it,
825       // add an assert node.
826       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
827           !RegisterVT.isInteger())
828         continue;
829 
830       const FunctionLoweringInfo::LiveOutInfo *LOI =
831         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
832       if (!LOI)
833         continue;
834 
835       unsigned RegSize = RegisterVT.getScalarSizeInBits();
836       unsigned NumSignBits = LOI->NumSignBits;
837       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
838 
839       if (NumZeroBits == RegSize) {
840         // The current value is a zero.
841         // Explicitly express that as it would be easier for
842         // optimizations to kick in.
843         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
844         continue;
845       }
846 
847       // FIXME: We capture more information than the dag can represent.  For
848       // now, just use the tightest assertzext/assertsext possible.
849       bool isSExt;
850       EVT FromVT(MVT::Other);
851       if (NumZeroBits) {
852         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
853         isSExt = false;
854       } else if (NumSignBits > 1) {
855         FromVT =
856             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
857         isSExt = true;
858       } else {
859         continue;
860       }
861       // Add an assertion node.
862       assert(FromVT != MVT::Other);
863       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
864                              RegisterVT, P, DAG.getValueType(FromVT));
865     }
866 
867     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
868                                      RegisterVT, ValueVT, V, CallConv);
869     Part += NumRegs;
870     Parts.clear();
871   }
872 
873   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
874 }
875 
876 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
877                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
878                                  const Value *V,
879                                  ISD::NodeType PreferredExtendType) const {
880   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
881   ISD::NodeType ExtendKind = PreferredExtendType;
882 
883   // Get the list of the values's legal parts.
884   unsigned NumRegs = Regs.size();
885   SmallVector<SDValue, 8> Parts(NumRegs);
886   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
887     unsigned NumParts = RegCount[Value];
888 
889     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
890                                           *DAG.getContext(),
891                                           CallConv.getValue(), RegVTs[Value])
892                                     : RegVTs[Value];
893 
894     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
895       ExtendKind = ISD::ZERO_EXTEND;
896 
897     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
898                    NumParts, RegisterVT, V, CallConv, ExtendKind);
899     Part += NumParts;
900   }
901 
902   // Copy the parts into the registers.
903   SmallVector<SDValue, 8> Chains(NumRegs);
904   for (unsigned i = 0; i != NumRegs; ++i) {
905     SDValue Part;
906     if (!Flag) {
907       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
908     } else {
909       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
910       *Flag = Part.getValue(1);
911     }
912 
913     Chains[i] = Part.getValue(0);
914   }
915 
916   if (NumRegs == 1 || Flag)
917     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
918     // flagged to it. That is the CopyToReg nodes and the user are considered
919     // a single scheduling unit. If we create a TokenFactor and return it as
920     // chain, then the TokenFactor is both a predecessor (operand) of the
921     // user as well as a successor (the TF operands are flagged to the user).
922     // c1, f1 = CopyToReg
923     // c2, f2 = CopyToReg
924     // c3     = TokenFactor c1, c2
925     // ...
926     //        = op c3, ..., f2
927     Chain = Chains[NumRegs-1];
928   else
929     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
930 }
931 
932 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
933                                         unsigned MatchingIdx, const SDLoc &dl,
934                                         SelectionDAG &DAG,
935                                         std::vector<SDValue> &Ops) const {
936   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
937 
938   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
939   if (HasMatching)
940     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
941   else if (!Regs.empty() &&
942            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
943     // Put the register class of the virtual registers in the flag word.  That
944     // way, later passes can recompute register class constraints for inline
945     // assembly as well as normal instructions.
946     // Don't do this for tied operands that can use the regclass information
947     // from the def.
948     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
949     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
950     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
951   }
952 
953   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
954   Ops.push_back(Res);
955 
956   if (Code == InlineAsm::Kind_Clobber) {
957     // Clobbers should always have a 1:1 mapping with registers, and may
958     // reference registers that have illegal (e.g. vector) types. Hence, we
959     // shouldn't try to apply any sort of splitting logic to them.
960     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
961            "No 1:1 mapping from clobbers to regs?");
962     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
963     (void)SP;
964     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
965       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
966       assert(
967           (Regs[I] != SP ||
968            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
969           "If we clobbered the stack pointer, MFI should know about it.");
970     }
971     return;
972   }
973 
974   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
975     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
976     MVT RegisterVT = RegVTs[Value];
977     for (unsigned i = 0; i != NumRegs; ++i) {
978       assert(Reg < Regs.size() && "Mismatch in # registers expected");
979       unsigned TheReg = Regs[Reg++];
980       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
981     }
982   }
983 }
984 
985 SmallVector<std::pair<unsigned, unsigned>, 4>
986 RegsForValue::getRegsAndSizes() const {
987   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
988   unsigned I = 0;
989   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
990     unsigned RegCount = std::get<0>(CountAndVT);
991     MVT RegisterVT = std::get<1>(CountAndVT);
992     unsigned RegisterSize = RegisterVT.getSizeInBits();
993     for (unsigned E = I + RegCount; I != E; ++I)
994       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
995   }
996   return OutVec;
997 }
998 
999 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1000                                const TargetLibraryInfo *li) {
1001   AA = aa;
1002   GFI = gfi;
1003   LibInfo = li;
1004   DL = &DAG.getDataLayout();
1005   Context = DAG.getContext();
1006   LPadToCallSiteMap.clear();
1007 }
1008 
1009 void SelectionDAGBuilder::clear() {
1010   NodeMap.clear();
1011   UnusedArgNodeMap.clear();
1012   PendingLoads.clear();
1013   PendingExports.clear();
1014   CurInst = nullptr;
1015   HasTailCall = false;
1016   SDNodeOrder = LowestSDNodeOrder;
1017   StatepointLowering.clear();
1018 }
1019 
1020 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1021   DanglingDebugInfoMap.clear();
1022 }
1023 
1024 SDValue SelectionDAGBuilder::getRoot() {
1025   if (PendingLoads.empty())
1026     return DAG.getRoot();
1027 
1028   if (PendingLoads.size() == 1) {
1029     SDValue Root = PendingLoads[0];
1030     DAG.setRoot(Root);
1031     PendingLoads.clear();
1032     return Root;
1033   }
1034 
1035   // Otherwise, we have to make a token factor node.
1036   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1037   PendingLoads.clear();
1038   DAG.setRoot(Root);
1039   return Root;
1040 }
1041 
1042 SDValue SelectionDAGBuilder::getControlRoot() {
1043   SDValue Root = DAG.getRoot();
1044 
1045   if (PendingExports.empty())
1046     return Root;
1047 
1048   // Turn all of the CopyToReg chains into one factored node.
1049   if (Root.getOpcode() != ISD::EntryToken) {
1050     unsigned i = 0, e = PendingExports.size();
1051     for (; i != e; ++i) {
1052       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1053       if (PendingExports[i].getNode()->getOperand(0) == Root)
1054         break;  // Don't add the root if we already indirectly depend on it.
1055     }
1056 
1057     if (i == e)
1058       PendingExports.push_back(Root);
1059   }
1060 
1061   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1062                      PendingExports);
1063   PendingExports.clear();
1064   DAG.setRoot(Root);
1065   return Root;
1066 }
1067 
1068 void SelectionDAGBuilder::visit(const Instruction &I) {
1069   // Set up outgoing PHI node register values before emitting the terminator.
1070   if (I.isTerminator()) {
1071     HandlePHINodesInSuccessorBlocks(I.getParent());
1072   }
1073 
1074   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1075   if (!isa<DbgInfoIntrinsic>(I))
1076     ++SDNodeOrder;
1077 
1078   CurInst = &I;
1079 
1080   visit(I.getOpcode(), I);
1081 
1082   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1083     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1084     // maps to this instruction.
1085     // TODO: We could handle all flags (nsw, etc) here.
1086     // TODO: If an IR instruction maps to >1 node, only the final node will have
1087     //       flags set.
1088     if (SDNode *Node = getNodeForIRValue(&I)) {
1089       SDNodeFlags IncomingFlags;
1090       IncomingFlags.copyFMF(*FPMO);
1091       if (!Node->getFlags().isDefined())
1092         Node->setFlags(IncomingFlags);
1093       else
1094         Node->intersectFlagsWith(IncomingFlags);
1095     }
1096   }
1097 
1098   if (!I.isTerminator() && !HasTailCall &&
1099       !isStatepoint(&I)) // statepoints handle their exports internally
1100     CopyToExportRegsIfNeeded(&I);
1101 
1102   CurInst = nullptr;
1103 }
1104 
1105 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1106   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1107 }
1108 
1109 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1110   // Note: this doesn't use InstVisitor, because it has to work with
1111   // ConstantExpr's in addition to instructions.
1112   switch (Opcode) {
1113   default: llvm_unreachable("Unknown instruction type encountered!");
1114     // Build the switch statement using the Instruction.def file.
1115 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1116     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1117 #include "llvm/IR/Instruction.def"
1118   }
1119 }
1120 
1121 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1122                                                 const DIExpression *Expr) {
1123   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1124     const DbgValueInst *DI = DDI.getDI();
1125     DIVariable *DanglingVariable = DI->getVariable();
1126     DIExpression *DanglingExpr = DI->getExpression();
1127     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1128       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1129       return true;
1130     }
1131     return false;
1132   };
1133 
1134   for (auto &DDIMI : DanglingDebugInfoMap) {
1135     DanglingDebugInfoVector &DDIV = DDIMI.second;
1136 
1137     // If debug info is to be dropped, run it through final checks to see
1138     // whether it can be salvaged.
1139     for (auto &DDI : DDIV)
1140       if (isMatchingDbgValue(DDI))
1141         salvageUnresolvedDbgValue(DDI);
1142 
1143     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1144   }
1145 }
1146 
1147 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1148 // generate the debug data structures now that we've seen its definition.
1149 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1150                                                    SDValue Val) {
1151   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1152   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1153     return;
1154 
1155   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1156   for (auto &DDI : DDIV) {
1157     const DbgValueInst *DI = DDI.getDI();
1158     assert(DI && "Ill-formed DanglingDebugInfo");
1159     DebugLoc dl = DDI.getdl();
1160     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1161     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1162     DILocalVariable *Variable = DI->getVariable();
1163     DIExpression *Expr = DI->getExpression();
1164     assert(Variable->isValidLocationForIntrinsic(dl) &&
1165            "Expected inlined-at fields to agree");
1166     SDDbgValue *SDV;
1167     if (Val.getNode()) {
1168       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1169       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1170       // we couldn't resolve it directly when examining the DbgValue intrinsic
1171       // in the first place we should not be more successful here). Unless we
1172       // have some test case that prove this to be correct we should avoid
1173       // calling EmitFuncArgumentDbgValue here.
1174       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1175         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1176                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1177         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1178         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1179         // inserted after the definition of Val when emitting the instructions
1180         // after ISel. An alternative could be to teach
1181         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1182         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1183                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1184                    << ValSDNodeOrder << "\n");
1185         SDV = getDbgValue(Val, Variable, Expr, dl,
1186                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1187         DAG.AddDbgValue(SDV, Val.getNode(), false);
1188       } else
1189         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1190                           << "in EmitFuncArgumentDbgValue\n");
1191     } else {
1192       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1193       auto Undef =
1194           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1195       auto SDV =
1196           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1197       DAG.AddDbgValue(SDV, nullptr, false);
1198     }
1199   }
1200   DDIV.clear();
1201 }
1202 
1203 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1204   Value *V = DDI.getDI()->getValue();
1205   DILocalVariable *Var = DDI.getDI()->getVariable();
1206   DIExpression *Expr = DDI.getDI()->getExpression();
1207   DebugLoc DL = DDI.getdl();
1208   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1209   unsigned SDOrder = DDI.getSDNodeOrder();
1210 
1211   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1212   // that DW_OP_stack_value is desired.
1213   assert(isa<DbgValueInst>(DDI.getDI()));
1214   bool StackValue = true;
1215 
1216   // Can this Value can be encoded without any further work?
1217   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1218     return;
1219 
1220   // Attempt to salvage back through as many instructions as possible. Bail if
1221   // a non-instruction is seen, such as a constant expression or global
1222   // variable. FIXME: Further work could recover those too.
1223   while (isa<Instruction>(V)) {
1224     Instruction &VAsInst = *cast<Instruction>(V);
1225     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1226 
1227     // If we cannot salvage any further, and haven't yet found a suitable debug
1228     // expression, bail out.
1229     if (!NewExpr)
1230       break;
1231 
1232     // New value and expr now represent this debuginfo.
1233     V = VAsInst.getOperand(0);
1234     Expr = NewExpr;
1235 
1236     // Some kind of simplification occurred: check whether the operand of the
1237     // salvaged debug expression can be encoded in this DAG.
1238     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1239       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1240                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1241       return;
1242     }
1243   }
1244 
1245   // This was the final opportunity to salvage this debug information, and it
1246   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1247   // any earlier variable location.
1248   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1249   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1250   DAG.AddDbgValue(SDV, nullptr, false);
1251 
1252   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1253                     << "\n");
1254   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1255                     << "\n");
1256 }
1257 
1258 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1259                                            DIExpression *Expr, DebugLoc dl,
1260                                            DebugLoc InstDL, unsigned Order) {
1261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1262   SDDbgValue *SDV;
1263   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1264       isa<ConstantPointerNull>(V)) {
1265     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1266     DAG.AddDbgValue(SDV, nullptr, false);
1267     return true;
1268   }
1269 
1270   // If the Value is a frame index, we can create a FrameIndex debug value
1271   // without relying on the DAG at all.
1272   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1273     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1274     if (SI != FuncInfo.StaticAllocaMap.end()) {
1275       auto SDV =
1276           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1277                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1278       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1279       // is still available even if the SDNode gets optimized out.
1280       DAG.AddDbgValue(SDV, nullptr, false);
1281       return true;
1282     }
1283   }
1284 
1285   // Do not use getValue() in here; we don't want to generate code at
1286   // this point if it hasn't been done yet.
1287   SDValue N = NodeMap[V];
1288   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1289     N = UnusedArgNodeMap[V];
1290   if (N.getNode()) {
1291     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1292       return true;
1293     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1294     DAG.AddDbgValue(SDV, N.getNode(), false);
1295     return true;
1296   }
1297 
1298   // Special rules apply for the first dbg.values of parameter variables in a
1299   // function. Identify them by the fact they reference Argument Values, that
1300   // they're parameters, and they are parameters of the current function. We
1301   // need to let them dangle until they get an SDNode.
1302   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1303                        !InstDL.getInlinedAt();
1304   if (!IsParamOfFunc) {
1305     // The value is not used in this block yet (or it would have an SDNode).
1306     // We still want the value to appear for the user if possible -- if it has
1307     // an associated VReg, we can refer to that instead.
1308     auto VMI = FuncInfo.ValueMap.find(V);
1309     if (VMI != FuncInfo.ValueMap.end()) {
1310       unsigned Reg = VMI->second;
1311       // If this is a PHI node, it may be split up into several MI PHI nodes
1312       // (in FunctionLoweringInfo::set).
1313       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1314                        V->getType(), None);
1315       if (RFV.occupiesMultipleRegs()) {
1316         unsigned Offset = 0;
1317         unsigned BitsToDescribe = 0;
1318         if (auto VarSize = Var->getSizeInBits())
1319           BitsToDescribe = *VarSize;
1320         if (auto Fragment = Expr->getFragmentInfo())
1321           BitsToDescribe = Fragment->SizeInBits;
1322         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1323           unsigned RegisterSize = RegAndSize.second;
1324           // Bail out if all bits are described already.
1325           if (Offset >= BitsToDescribe)
1326             break;
1327           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1328               ? BitsToDescribe - Offset
1329               : RegisterSize;
1330           auto FragmentExpr = DIExpression::createFragmentExpression(
1331               Expr, Offset, FragmentSize);
1332           if (!FragmentExpr)
1333               continue;
1334           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1335                                     false, dl, SDNodeOrder);
1336           DAG.AddDbgValue(SDV, nullptr, false);
1337           Offset += RegisterSize;
1338         }
1339       } else {
1340         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1341         DAG.AddDbgValue(SDV, nullptr, false);
1342       }
1343       return true;
1344     }
1345   }
1346 
1347   return false;
1348 }
1349 
1350 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1351   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1352   for (auto &Pair : DanglingDebugInfoMap)
1353     for (auto &DDI : Pair.second)
1354       salvageUnresolvedDbgValue(DDI);
1355   clearDanglingDebugInfo();
1356 }
1357 
1358 /// getCopyFromRegs - If there was virtual register allocated for the value V
1359 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1360 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1361   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1362   SDValue Result;
1363 
1364   if (It != FuncInfo.ValueMap.end()) {
1365     unsigned InReg = It->second;
1366 
1367     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1368                      DAG.getDataLayout(), InReg, Ty,
1369                      None); // This is not an ABI copy.
1370     SDValue Chain = DAG.getEntryNode();
1371     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1372                                  V);
1373     resolveDanglingDebugInfo(V, Result);
1374   }
1375 
1376   return Result;
1377 }
1378 
1379 /// getValue - Return an SDValue for the given Value.
1380 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1381   // If we already have an SDValue for this value, use it. It's important
1382   // to do this first, so that we don't create a CopyFromReg if we already
1383   // have a regular SDValue.
1384   SDValue &N = NodeMap[V];
1385   if (N.getNode()) return N;
1386 
1387   // If there's a virtual register allocated and initialized for this
1388   // value, use it.
1389   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1390     return copyFromReg;
1391 
1392   // Otherwise create a new SDValue and remember it.
1393   SDValue Val = getValueImpl(V);
1394   NodeMap[V] = Val;
1395   resolveDanglingDebugInfo(V, Val);
1396   return Val;
1397 }
1398 
1399 // Return true if SDValue exists for the given Value
1400 bool SelectionDAGBuilder::findValue(const Value *V) const {
1401   return (NodeMap.find(V) != NodeMap.end()) ||
1402     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1403 }
1404 
1405 /// getNonRegisterValue - Return an SDValue for the given Value, but
1406 /// don't look in FuncInfo.ValueMap for a virtual register.
1407 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1408   // If we already have an SDValue for this value, use it.
1409   SDValue &N = NodeMap[V];
1410   if (N.getNode()) {
1411     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1412       // Remove the debug location from the node as the node is about to be used
1413       // in a location which may differ from the original debug location.  This
1414       // is relevant to Constant and ConstantFP nodes because they can appear
1415       // as constant expressions inside PHI nodes.
1416       N->setDebugLoc(DebugLoc());
1417     }
1418     return N;
1419   }
1420 
1421   // Otherwise create a new SDValue and remember it.
1422   SDValue Val = getValueImpl(V);
1423   NodeMap[V] = Val;
1424   resolveDanglingDebugInfo(V, Val);
1425   return Val;
1426 }
1427 
1428 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1429 /// Create an SDValue for the given value.
1430 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1431   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1432 
1433   if (const Constant *C = dyn_cast<Constant>(V)) {
1434     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1435 
1436     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1437       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1438 
1439     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1440       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1441 
1442     if (isa<ConstantPointerNull>(C)) {
1443       unsigned AS = V->getType()->getPointerAddressSpace();
1444       return DAG.getConstant(0, getCurSDLoc(),
1445                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1446     }
1447 
1448     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1449       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1450 
1451     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1452       return DAG.getUNDEF(VT);
1453 
1454     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1455       visit(CE->getOpcode(), *CE);
1456       SDValue N1 = NodeMap[V];
1457       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1458       return N1;
1459     }
1460 
1461     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1462       SmallVector<SDValue, 4> Constants;
1463       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1464            OI != OE; ++OI) {
1465         SDNode *Val = getValue(*OI).getNode();
1466         // If the operand is an empty aggregate, there are no values.
1467         if (!Val) continue;
1468         // Add each leaf value from the operand to the Constants list
1469         // to form a flattened list of all the values.
1470         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1471           Constants.push_back(SDValue(Val, i));
1472       }
1473 
1474       return DAG.getMergeValues(Constants, getCurSDLoc());
1475     }
1476 
1477     if (const ConstantDataSequential *CDS =
1478           dyn_cast<ConstantDataSequential>(C)) {
1479       SmallVector<SDValue, 4> Ops;
1480       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1481         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1482         // Add each leaf value from the operand to the Constants list
1483         // to form a flattened list of all the values.
1484         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1485           Ops.push_back(SDValue(Val, i));
1486       }
1487 
1488       if (isa<ArrayType>(CDS->getType()))
1489         return DAG.getMergeValues(Ops, getCurSDLoc());
1490       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1491     }
1492 
1493     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1494       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1495              "Unknown struct or array constant!");
1496 
1497       SmallVector<EVT, 4> ValueVTs;
1498       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1499       unsigned NumElts = ValueVTs.size();
1500       if (NumElts == 0)
1501         return SDValue(); // empty struct
1502       SmallVector<SDValue, 4> Constants(NumElts);
1503       for (unsigned i = 0; i != NumElts; ++i) {
1504         EVT EltVT = ValueVTs[i];
1505         if (isa<UndefValue>(C))
1506           Constants[i] = DAG.getUNDEF(EltVT);
1507         else if (EltVT.isFloatingPoint())
1508           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1509         else
1510           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1511       }
1512 
1513       return DAG.getMergeValues(Constants, getCurSDLoc());
1514     }
1515 
1516     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1517       return DAG.getBlockAddress(BA, VT);
1518 
1519     VectorType *VecTy = cast<VectorType>(V->getType());
1520     unsigned NumElements = VecTy->getNumElements();
1521 
1522     // Now that we know the number and type of the elements, get that number of
1523     // elements into the Ops array based on what kind of constant it is.
1524     SmallVector<SDValue, 16> Ops;
1525     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1526       for (unsigned i = 0; i != NumElements; ++i)
1527         Ops.push_back(getValue(CV->getOperand(i)));
1528     } else {
1529       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1530       EVT EltVT =
1531           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1532 
1533       SDValue Op;
1534       if (EltVT.isFloatingPoint())
1535         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1536       else
1537         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1538       Ops.assign(NumElements, Op);
1539     }
1540 
1541     // Create a BUILD_VECTOR node.
1542     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1543   }
1544 
1545   // If this is a static alloca, generate it as the frameindex instead of
1546   // computation.
1547   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1548     DenseMap<const AllocaInst*, int>::iterator SI =
1549       FuncInfo.StaticAllocaMap.find(AI);
1550     if (SI != FuncInfo.StaticAllocaMap.end())
1551       return DAG.getFrameIndex(SI->second,
1552                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1553   }
1554 
1555   // If this is an instruction which fast-isel has deferred, select it now.
1556   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1557     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1558 
1559     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1560                      Inst->getType(), getABIRegCopyCC(V));
1561     SDValue Chain = DAG.getEntryNode();
1562     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1563   }
1564 
1565   llvm_unreachable("Can't get register for value!");
1566 }
1567 
1568 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1569   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1570   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1571   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1572   bool IsSEH = isAsynchronousEHPersonality(Pers);
1573   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1574   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1575   if (!IsSEH)
1576     CatchPadMBB->setIsEHScopeEntry();
1577   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1578   if (IsMSVCCXX || IsCoreCLR)
1579     CatchPadMBB->setIsEHFuncletEntry();
1580   // Wasm does not need catchpads anymore
1581   if (!IsWasmCXX)
1582     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1583                             getControlRoot()));
1584 }
1585 
1586 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1587   // Update machine-CFG edge.
1588   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1589   FuncInfo.MBB->addSuccessor(TargetMBB);
1590 
1591   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1592   bool IsSEH = isAsynchronousEHPersonality(Pers);
1593   if (IsSEH) {
1594     // If this is not a fall-through branch or optimizations are switched off,
1595     // emit the branch.
1596     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1597         TM.getOptLevel() == CodeGenOpt::None)
1598       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1599                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1600     return;
1601   }
1602 
1603   // Figure out the funclet membership for the catchret's successor.
1604   // This will be used by the FuncletLayout pass to determine how to order the
1605   // BB's.
1606   // A 'catchret' returns to the outer scope's color.
1607   Value *ParentPad = I.getCatchSwitchParentPad();
1608   const BasicBlock *SuccessorColor;
1609   if (isa<ConstantTokenNone>(ParentPad))
1610     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1611   else
1612     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1613   assert(SuccessorColor && "No parent funclet for catchret!");
1614   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1615   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1616 
1617   // Create the terminator node.
1618   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1619                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1620                             DAG.getBasicBlock(SuccessorColorMBB));
1621   DAG.setRoot(Ret);
1622 }
1623 
1624 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1625   // Don't emit any special code for the cleanuppad instruction. It just marks
1626   // the start of an EH scope/funclet.
1627   FuncInfo.MBB->setIsEHScopeEntry();
1628   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1629   if (Pers != EHPersonality::Wasm_CXX) {
1630     FuncInfo.MBB->setIsEHFuncletEntry();
1631     FuncInfo.MBB->setIsCleanupFuncletEntry();
1632   }
1633 }
1634 
1635 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1636 // the control flow always stops at the single catch pad, as it does for a
1637 // cleanup pad. In case the exception caught is not of the types the catch pad
1638 // catches, it will be rethrown by a rethrow.
1639 static void findWasmUnwindDestinations(
1640     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1641     BranchProbability Prob,
1642     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1643         &UnwindDests) {
1644   while (EHPadBB) {
1645     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1646     if (isa<CleanupPadInst>(Pad)) {
1647       // Stop on cleanup pads.
1648       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1649       UnwindDests.back().first->setIsEHScopeEntry();
1650       break;
1651     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1652       // Add the catchpad handlers to the possible destinations. We don't
1653       // continue to the unwind destination of the catchswitch for wasm.
1654       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1655         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1656         UnwindDests.back().first->setIsEHScopeEntry();
1657       }
1658       break;
1659     } else {
1660       continue;
1661     }
1662   }
1663 }
1664 
1665 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1666 /// many places it could ultimately go. In the IR, we have a single unwind
1667 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1668 /// This function skips over imaginary basic blocks that hold catchswitch
1669 /// instructions, and finds all the "real" machine
1670 /// basic block destinations. As those destinations may not be successors of
1671 /// EHPadBB, here we also calculate the edge probability to those destinations.
1672 /// The passed-in Prob is the edge probability to EHPadBB.
1673 static void findUnwindDestinations(
1674     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1675     BranchProbability Prob,
1676     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1677         &UnwindDests) {
1678   EHPersonality Personality =
1679     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1680   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1681   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1682   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1683   bool IsSEH = isAsynchronousEHPersonality(Personality);
1684 
1685   if (IsWasmCXX) {
1686     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1687     assert(UnwindDests.size() <= 1 &&
1688            "There should be at most one unwind destination for wasm");
1689     return;
1690   }
1691 
1692   while (EHPadBB) {
1693     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1694     BasicBlock *NewEHPadBB = nullptr;
1695     if (isa<LandingPadInst>(Pad)) {
1696       // Stop on landingpads. They are not funclets.
1697       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1698       break;
1699     } else if (isa<CleanupPadInst>(Pad)) {
1700       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1701       // personalities.
1702       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1703       UnwindDests.back().first->setIsEHScopeEntry();
1704       UnwindDests.back().first->setIsEHFuncletEntry();
1705       break;
1706     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1707       // Add the catchpad handlers to the possible destinations.
1708       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1709         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1710         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1711         if (IsMSVCCXX || IsCoreCLR)
1712           UnwindDests.back().first->setIsEHFuncletEntry();
1713         if (!IsSEH)
1714           UnwindDests.back().first->setIsEHScopeEntry();
1715       }
1716       NewEHPadBB = CatchSwitch->getUnwindDest();
1717     } else {
1718       continue;
1719     }
1720 
1721     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1722     if (BPI && NewEHPadBB)
1723       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1724     EHPadBB = NewEHPadBB;
1725   }
1726 }
1727 
1728 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1729   // Update successor info.
1730   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1731   auto UnwindDest = I.getUnwindDest();
1732   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1733   BranchProbability UnwindDestProb =
1734       (BPI && UnwindDest)
1735           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1736           : BranchProbability::getZero();
1737   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1738   for (auto &UnwindDest : UnwindDests) {
1739     UnwindDest.first->setIsEHPad();
1740     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1741   }
1742   FuncInfo.MBB->normalizeSuccProbs();
1743 
1744   // Create the terminator node.
1745   SDValue Ret =
1746       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1747   DAG.setRoot(Ret);
1748 }
1749 
1750 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1751   report_fatal_error("visitCatchSwitch not yet implemented!");
1752 }
1753 
1754 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1755   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1756   auto &DL = DAG.getDataLayout();
1757   SDValue Chain = getControlRoot();
1758   SmallVector<ISD::OutputArg, 8> Outs;
1759   SmallVector<SDValue, 8> OutVals;
1760 
1761   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1762   // lower
1763   //
1764   //   %val = call <ty> @llvm.experimental.deoptimize()
1765   //   ret <ty> %val
1766   //
1767   // differently.
1768   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1769     LowerDeoptimizingReturn();
1770     return;
1771   }
1772 
1773   if (!FuncInfo.CanLowerReturn) {
1774     unsigned DemoteReg = FuncInfo.DemoteRegister;
1775     const Function *F = I.getParent()->getParent();
1776 
1777     // Emit a store of the return value through the virtual register.
1778     // Leave Outs empty so that LowerReturn won't try to load return
1779     // registers the usual way.
1780     SmallVector<EVT, 1> PtrValueVTs;
1781     ComputeValueVTs(TLI, DL,
1782                     F->getReturnType()->getPointerTo(
1783                         DAG.getDataLayout().getAllocaAddrSpace()),
1784                     PtrValueVTs);
1785 
1786     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1787                                         DemoteReg, PtrValueVTs[0]);
1788     SDValue RetOp = getValue(I.getOperand(0));
1789 
1790     SmallVector<EVT, 4> ValueVTs;
1791     SmallVector<uint64_t, 4> Offsets;
1792     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1793     unsigned NumValues = ValueVTs.size();
1794 
1795     SmallVector<SDValue, 4> Chains(NumValues);
1796     for (unsigned i = 0; i != NumValues; ++i) {
1797       // An aggregate return value cannot wrap around the address space, so
1798       // offsets to its parts don't wrap either.
1799       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1800       Chains[i] = DAG.getStore(
1801           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1802           // FIXME: better loc info would be nice.
1803           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1804     }
1805 
1806     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1807                         MVT::Other, Chains);
1808   } else if (I.getNumOperands() != 0) {
1809     SmallVector<EVT, 4> ValueVTs;
1810     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1811     unsigned NumValues = ValueVTs.size();
1812     if (NumValues) {
1813       SDValue RetOp = getValue(I.getOperand(0));
1814 
1815       const Function *F = I.getParent()->getParent();
1816 
1817       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1818       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1819                                           Attribute::SExt))
1820         ExtendKind = ISD::SIGN_EXTEND;
1821       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1822                                                Attribute::ZExt))
1823         ExtendKind = ISD::ZERO_EXTEND;
1824 
1825       LLVMContext &Context = F->getContext();
1826       bool RetInReg = F->getAttributes().hasAttribute(
1827           AttributeList::ReturnIndex, Attribute::InReg);
1828 
1829       for (unsigned j = 0; j != NumValues; ++j) {
1830         EVT VT = ValueVTs[j];
1831 
1832         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1833           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1834 
1835         CallingConv::ID CC = F->getCallingConv();
1836 
1837         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1838         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1839         SmallVector<SDValue, 4> Parts(NumParts);
1840         getCopyToParts(DAG, getCurSDLoc(),
1841                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1842                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1843 
1844         // 'inreg' on function refers to return value
1845         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1846         if (RetInReg)
1847           Flags.setInReg();
1848 
1849         // Propagate extension type if any
1850         if (ExtendKind == ISD::SIGN_EXTEND)
1851           Flags.setSExt();
1852         else if (ExtendKind == ISD::ZERO_EXTEND)
1853           Flags.setZExt();
1854 
1855         for (unsigned i = 0; i < NumParts; ++i) {
1856           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1857                                         VT, /*isfixed=*/true, 0, 0));
1858           OutVals.push_back(Parts[i]);
1859         }
1860       }
1861     }
1862   }
1863 
1864   // Push in swifterror virtual register as the last element of Outs. This makes
1865   // sure swifterror virtual register will be returned in the swifterror
1866   // physical register.
1867   const Function *F = I.getParent()->getParent();
1868   if (TLI.supportSwiftError() &&
1869       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1870     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1871     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1872     Flags.setSwiftError();
1873     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1874                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1875                                   true /*isfixed*/, 1 /*origidx*/,
1876                                   0 /*partOffs*/));
1877     // Create SDNode for the swifterror virtual register.
1878     OutVals.push_back(
1879         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1880                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1881                         EVT(TLI.getPointerTy(DL))));
1882   }
1883 
1884   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1885   CallingConv::ID CallConv =
1886     DAG.getMachineFunction().getFunction().getCallingConv();
1887   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1888       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1889 
1890   // Verify that the target's LowerReturn behaved as expected.
1891   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1892          "LowerReturn didn't return a valid chain!");
1893 
1894   // Update the DAG with the new chain value resulting from return lowering.
1895   DAG.setRoot(Chain);
1896 }
1897 
1898 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1899 /// created for it, emit nodes to copy the value into the virtual
1900 /// registers.
1901 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1902   // Skip empty types
1903   if (V->getType()->isEmptyTy())
1904     return;
1905 
1906   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1907   if (VMI != FuncInfo.ValueMap.end()) {
1908     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1909     CopyValueToVirtualRegister(V, VMI->second);
1910   }
1911 }
1912 
1913 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1914 /// the current basic block, add it to ValueMap now so that we'll get a
1915 /// CopyTo/FromReg.
1916 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1917   // No need to export constants.
1918   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1919 
1920   // Already exported?
1921   if (FuncInfo.isExportedInst(V)) return;
1922 
1923   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1924   CopyValueToVirtualRegister(V, Reg);
1925 }
1926 
1927 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1928                                                      const BasicBlock *FromBB) {
1929   // The operands of the setcc have to be in this block.  We don't know
1930   // how to export them from some other block.
1931   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1932     // Can export from current BB.
1933     if (VI->getParent() == FromBB)
1934       return true;
1935 
1936     // Is already exported, noop.
1937     return FuncInfo.isExportedInst(V);
1938   }
1939 
1940   // If this is an argument, we can export it if the BB is the entry block or
1941   // if it is already exported.
1942   if (isa<Argument>(V)) {
1943     if (FromBB == &FromBB->getParent()->getEntryBlock())
1944       return true;
1945 
1946     // Otherwise, can only export this if it is already exported.
1947     return FuncInfo.isExportedInst(V);
1948   }
1949 
1950   // Otherwise, constants can always be exported.
1951   return true;
1952 }
1953 
1954 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1955 BranchProbability
1956 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1957                                         const MachineBasicBlock *Dst) const {
1958   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1959   const BasicBlock *SrcBB = Src->getBasicBlock();
1960   const BasicBlock *DstBB = Dst->getBasicBlock();
1961   if (!BPI) {
1962     // If BPI is not available, set the default probability as 1 / N, where N is
1963     // the number of successors.
1964     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1965     return BranchProbability(1, SuccSize);
1966   }
1967   return BPI->getEdgeProbability(SrcBB, DstBB);
1968 }
1969 
1970 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1971                                                MachineBasicBlock *Dst,
1972                                                BranchProbability Prob) {
1973   if (!FuncInfo.BPI)
1974     Src->addSuccessorWithoutProb(Dst);
1975   else {
1976     if (Prob.isUnknown())
1977       Prob = getEdgeProbability(Src, Dst);
1978     Src->addSuccessor(Dst, Prob);
1979   }
1980 }
1981 
1982 static bool InBlock(const Value *V, const BasicBlock *BB) {
1983   if (const Instruction *I = dyn_cast<Instruction>(V))
1984     return I->getParent() == BB;
1985   return true;
1986 }
1987 
1988 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1989 /// This function emits a branch and is used at the leaves of an OR or an
1990 /// AND operator tree.
1991 void
1992 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1993                                                   MachineBasicBlock *TBB,
1994                                                   MachineBasicBlock *FBB,
1995                                                   MachineBasicBlock *CurBB,
1996                                                   MachineBasicBlock *SwitchBB,
1997                                                   BranchProbability TProb,
1998                                                   BranchProbability FProb,
1999                                                   bool InvertCond) {
2000   const BasicBlock *BB = CurBB->getBasicBlock();
2001 
2002   // If the leaf of the tree is a comparison, merge the condition into
2003   // the caseblock.
2004   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2005     // The operands of the cmp have to be in this block.  We don't know
2006     // how to export them from some other block.  If this is the first block
2007     // of the sequence, no exporting is needed.
2008     if (CurBB == SwitchBB ||
2009         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2010          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2011       ISD::CondCode Condition;
2012       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2013         ICmpInst::Predicate Pred =
2014             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2015         Condition = getICmpCondCode(Pred);
2016       } else {
2017         const FCmpInst *FC = cast<FCmpInst>(Cond);
2018         FCmpInst::Predicate Pred =
2019             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2020         Condition = getFCmpCondCode(Pred);
2021         if (TM.Options.NoNaNsFPMath)
2022           Condition = getFCmpCodeWithoutNaN(Condition);
2023       }
2024 
2025       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2026                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2027       SwitchCases.push_back(CB);
2028       return;
2029     }
2030   }
2031 
2032   // Create a CaseBlock record representing this branch.
2033   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2034   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2035                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2036   SwitchCases.push_back(CB);
2037 }
2038 
2039 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2040                                                MachineBasicBlock *TBB,
2041                                                MachineBasicBlock *FBB,
2042                                                MachineBasicBlock *CurBB,
2043                                                MachineBasicBlock *SwitchBB,
2044                                                Instruction::BinaryOps Opc,
2045                                                BranchProbability TProb,
2046                                                BranchProbability FProb,
2047                                                bool InvertCond) {
2048   // Skip over not part of the tree and remember to invert op and operands at
2049   // next level.
2050   Value *NotCond;
2051   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2052       InBlock(NotCond, CurBB->getBasicBlock())) {
2053     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2054                          !InvertCond);
2055     return;
2056   }
2057 
2058   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2059   // Compute the effective opcode for Cond, taking into account whether it needs
2060   // to be inverted, e.g.
2061   //   and (not (or A, B)), C
2062   // gets lowered as
2063   //   and (and (not A, not B), C)
2064   unsigned BOpc = 0;
2065   if (BOp) {
2066     BOpc = BOp->getOpcode();
2067     if (InvertCond) {
2068       if (BOpc == Instruction::And)
2069         BOpc = Instruction::Or;
2070       else if (BOpc == Instruction::Or)
2071         BOpc = Instruction::And;
2072     }
2073   }
2074 
2075   // If this node is not part of the or/and tree, emit it as a branch.
2076   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2077       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2078       BOp->getParent() != CurBB->getBasicBlock() ||
2079       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2080       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2081     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2082                                  TProb, FProb, InvertCond);
2083     return;
2084   }
2085 
2086   //  Create TmpBB after CurBB.
2087   MachineFunction::iterator BBI(CurBB);
2088   MachineFunction &MF = DAG.getMachineFunction();
2089   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2090   CurBB->getParent()->insert(++BBI, TmpBB);
2091 
2092   if (Opc == Instruction::Or) {
2093     // Codegen X | Y as:
2094     // BB1:
2095     //   jmp_if_X TBB
2096     //   jmp TmpBB
2097     // TmpBB:
2098     //   jmp_if_Y TBB
2099     //   jmp FBB
2100     //
2101 
2102     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2103     // The requirement is that
2104     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2105     //     = TrueProb for original BB.
2106     // Assuming the original probabilities are A and B, one choice is to set
2107     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2108     // A/(1+B) and 2B/(1+B). This choice assumes that
2109     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2110     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2111     // TmpBB, but the math is more complicated.
2112 
2113     auto NewTrueProb = TProb / 2;
2114     auto NewFalseProb = TProb / 2 + FProb;
2115     // Emit the LHS condition.
2116     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2117                          NewTrueProb, NewFalseProb, InvertCond);
2118 
2119     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2120     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2121     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2122     // Emit the RHS condition into TmpBB.
2123     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2124                          Probs[0], Probs[1], InvertCond);
2125   } else {
2126     assert(Opc == Instruction::And && "Unknown merge op!");
2127     // Codegen X & Y as:
2128     // BB1:
2129     //   jmp_if_X TmpBB
2130     //   jmp FBB
2131     // TmpBB:
2132     //   jmp_if_Y TBB
2133     //   jmp FBB
2134     //
2135     //  This requires creation of TmpBB after CurBB.
2136 
2137     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2138     // The requirement is that
2139     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2140     //     = FalseProb for original BB.
2141     // Assuming the original probabilities are A and B, one choice is to set
2142     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2143     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2144     // TrueProb for BB1 * FalseProb for TmpBB.
2145 
2146     auto NewTrueProb = TProb + FProb / 2;
2147     auto NewFalseProb = FProb / 2;
2148     // Emit the LHS condition.
2149     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2150                          NewTrueProb, NewFalseProb, InvertCond);
2151 
2152     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2153     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2154     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2155     // Emit the RHS condition into TmpBB.
2156     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2157                          Probs[0], Probs[1], InvertCond);
2158   }
2159 }
2160 
2161 /// If the set of cases should be emitted as a series of branches, return true.
2162 /// If we should emit this as a bunch of and/or'd together conditions, return
2163 /// false.
2164 bool
2165 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2166   if (Cases.size() != 2) return true;
2167 
2168   // If this is two comparisons of the same values or'd or and'd together, they
2169   // will get folded into a single comparison, so don't emit two blocks.
2170   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2171        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2172       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2173        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2174     return false;
2175   }
2176 
2177   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2178   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2179   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2180       Cases[0].CC == Cases[1].CC &&
2181       isa<Constant>(Cases[0].CmpRHS) &&
2182       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2183     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2184       return false;
2185     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2186       return false;
2187   }
2188 
2189   return true;
2190 }
2191 
2192 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2193   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2194 
2195   // Update machine-CFG edges.
2196   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2197 
2198   if (I.isUnconditional()) {
2199     // Update machine-CFG edges.
2200     BrMBB->addSuccessor(Succ0MBB);
2201 
2202     // If this is not a fall-through branch or optimizations are switched off,
2203     // emit the branch.
2204     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2205       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2206                               MVT::Other, getControlRoot(),
2207                               DAG.getBasicBlock(Succ0MBB)));
2208 
2209     return;
2210   }
2211 
2212   // If this condition is one of the special cases we handle, do special stuff
2213   // now.
2214   const Value *CondVal = I.getCondition();
2215   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2216 
2217   // If this is a series of conditions that are or'd or and'd together, emit
2218   // this as a sequence of branches instead of setcc's with and/or operations.
2219   // As long as jumps are not expensive, this should improve performance.
2220   // For example, instead of something like:
2221   //     cmp A, B
2222   //     C = seteq
2223   //     cmp D, E
2224   //     F = setle
2225   //     or C, F
2226   //     jnz foo
2227   // Emit:
2228   //     cmp A, B
2229   //     je foo
2230   //     cmp D, E
2231   //     jle foo
2232   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2233     Instruction::BinaryOps Opcode = BOp->getOpcode();
2234     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2235         !I.getMetadata(LLVMContext::MD_unpredictable) &&
2236         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2237       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2238                            Opcode,
2239                            getEdgeProbability(BrMBB, Succ0MBB),
2240                            getEdgeProbability(BrMBB, Succ1MBB),
2241                            /*InvertCond=*/false);
2242       // If the compares in later blocks need to use values not currently
2243       // exported from this block, export them now.  This block should always
2244       // be the first entry.
2245       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2246 
2247       // Allow some cases to be rejected.
2248       if (ShouldEmitAsBranches(SwitchCases)) {
2249         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
2250           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
2251           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
2252         }
2253 
2254         // Emit the branch for this block.
2255         visitSwitchCase(SwitchCases[0], BrMBB);
2256         SwitchCases.erase(SwitchCases.begin());
2257         return;
2258       }
2259 
2260       // Okay, we decided not to do this, remove any inserted MBB's and clear
2261       // SwitchCases.
2262       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2263         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2264 
2265       SwitchCases.clear();
2266     }
2267   }
2268 
2269   // Create a CaseBlock record representing this branch.
2270   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2271                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2272 
2273   // Use visitSwitchCase to actually insert the fast branch sequence for this
2274   // cond branch.
2275   visitSwitchCase(CB, BrMBB);
2276 }
2277 
2278 /// visitSwitchCase - Emits the necessary code to represent a single node in
2279 /// the binary search tree resulting from lowering a switch instruction.
2280 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2281                                           MachineBasicBlock *SwitchBB) {
2282   SDValue Cond;
2283   SDValue CondLHS = getValue(CB.CmpLHS);
2284   SDLoc dl = CB.DL;
2285 
2286   if (CB.CC == ISD::SETTRUE) {
2287     // Branch or fall through to TrueBB.
2288     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2289     SwitchBB->normalizeSuccProbs();
2290     if (CB.TrueBB != NextBlock(SwitchBB)) {
2291       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2292                               DAG.getBasicBlock(CB.TrueBB)));
2293     }
2294     return;
2295   }
2296 
2297   // Build the setcc now.
2298   if (!CB.CmpMHS) {
2299     // Fold "(X == true)" to X and "(X == false)" to !X to
2300     // handle common cases produced by branch lowering.
2301     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2302         CB.CC == ISD::SETEQ)
2303       Cond = CondLHS;
2304     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2305              CB.CC == ISD::SETEQ) {
2306       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2307       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2308     } else
2309       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2310   } else {
2311     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2312 
2313     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2314     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2315 
2316     SDValue CmpOp = getValue(CB.CmpMHS);
2317     EVT VT = CmpOp.getValueType();
2318 
2319     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2320       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2321                           ISD::SETLE);
2322     } else {
2323       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2324                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2325       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2326                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2327     }
2328   }
2329 
2330   // Update successor info
2331   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2332   // TrueBB and FalseBB are always different unless the incoming IR is
2333   // degenerate. This only happens when running llc on weird IR.
2334   if (CB.TrueBB != CB.FalseBB)
2335     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2336   SwitchBB->normalizeSuccProbs();
2337 
2338   // If the lhs block is the next block, invert the condition so that we can
2339   // fall through to the lhs instead of the rhs block.
2340   if (CB.TrueBB == NextBlock(SwitchBB)) {
2341     std::swap(CB.TrueBB, CB.FalseBB);
2342     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2343     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2344   }
2345 
2346   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2347                                MVT::Other, getControlRoot(), Cond,
2348                                DAG.getBasicBlock(CB.TrueBB));
2349 
2350   // Insert the false branch. Do this even if it's a fall through branch,
2351   // this makes it easier to do DAG optimizations which require inverting
2352   // the branch condition.
2353   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2354                        DAG.getBasicBlock(CB.FalseBB));
2355 
2356   DAG.setRoot(BrCond);
2357 }
2358 
2359 /// visitJumpTable - Emit JumpTable node in the current MBB
2360 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2361   // Emit the code for the jump table
2362   assert(JT.Reg != -1U && "Should lower JT Header first!");
2363   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2364   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2365                                      JT.Reg, PTy);
2366   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2367   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2368                                     MVT::Other, Index.getValue(1),
2369                                     Table, Index);
2370   DAG.setRoot(BrJumpTable);
2371 }
2372 
2373 /// visitJumpTableHeader - This function emits necessary code to produce index
2374 /// in the JumpTable from switch case.
2375 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2376                                                JumpTableHeader &JTH,
2377                                                MachineBasicBlock *SwitchBB) {
2378   SDLoc dl = getCurSDLoc();
2379 
2380   // Subtract the lowest switch case value from the value being switched on.
2381   SDValue SwitchOp = getValue(JTH.SValue);
2382   EVT VT = SwitchOp.getValueType();
2383   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2384                             DAG.getConstant(JTH.First, dl, VT));
2385 
2386   // The SDNode we just created, which holds the value being switched on minus
2387   // the smallest case value, needs to be copied to a virtual register so it
2388   // can be used as an index into the jump table in a subsequent basic block.
2389   // This value may be smaller or larger than the target's pointer type, and
2390   // therefore require extension or truncating.
2391   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2392   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2393 
2394   unsigned JumpTableReg =
2395       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2396   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2397                                     JumpTableReg, SwitchOp);
2398   JT.Reg = JumpTableReg;
2399 
2400   if (!JTH.OmitRangeCheck) {
2401     // Emit the range check for the jump table, and branch to the default block
2402     // for the switch statement if the value being switched on exceeds the
2403     // largest case in the switch.
2404     SDValue CMP = DAG.getSetCC(
2405         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2406                                    Sub.getValueType()),
2407         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2408 
2409     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2410                                  MVT::Other, CopyTo, CMP,
2411                                  DAG.getBasicBlock(JT.Default));
2412 
2413     // Avoid emitting unnecessary branches to the next block.
2414     if (JT.MBB != NextBlock(SwitchBB))
2415       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2416                            DAG.getBasicBlock(JT.MBB));
2417 
2418     DAG.setRoot(BrCond);
2419   } else {
2420     // Avoid emitting unnecessary branches to the next block.
2421     if (JT.MBB != NextBlock(SwitchBB))
2422       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2423                               DAG.getBasicBlock(JT.MBB)));
2424     else
2425       DAG.setRoot(CopyTo);
2426   }
2427 }
2428 
2429 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2430 /// variable if there exists one.
2431 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2432                                  SDValue &Chain) {
2433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2434   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2435   MachineFunction &MF = DAG.getMachineFunction();
2436   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2437   MachineSDNode *Node =
2438       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2439   if (Global) {
2440     MachinePointerInfo MPInfo(Global);
2441     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2442                  MachineMemOperand::MODereferenceable;
2443     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2444         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2445     DAG.setNodeMemRefs(Node, {MemRef});
2446   }
2447   return SDValue(Node, 0);
2448 }
2449 
2450 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2451 /// tail spliced into a stack protector check success bb.
2452 ///
2453 /// For a high level explanation of how this fits into the stack protector
2454 /// generation see the comment on the declaration of class
2455 /// StackProtectorDescriptor.
2456 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2457                                                   MachineBasicBlock *ParentBB) {
2458 
2459   // First create the loads to the guard/stack slot for the comparison.
2460   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2461   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2462 
2463   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2464   int FI = MFI.getStackProtectorIndex();
2465 
2466   SDValue Guard;
2467   SDLoc dl = getCurSDLoc();
2468   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2469   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2470   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2471 
2472   // Generate code to load the content of the guard slot.
2473   SDValue GuardVal = DAG.getLoad(
2474       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2475       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2476       MachineMemOperand::MOVolatile);
2477 
2478   if (TLI.useStackGuardXorFP())
2479     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2480 
2481   // Retrieve guard check function, nullptr if instrumentation is inlined.
2482   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2483     // The target provides a guard check function to validate the guard value.
2484     // Generate a call to that function with the content of the guard slot as
2485     // argument.
2486     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2487     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2488 
2489     TargetLowering::ArgListTy Args;
2490     TargetLowering::ArgListEntry Entry;
2491     Entry.Node = GuardVal;
2492     Entry.Ty = FnTy->getParamType(0);
2493     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2494       Entry.IsInReg = true;
2495     Args.push_back(Entry);
2496 
2497     TargetLowering::CallLoweringInfo CLI(DAG);
2498     CLI.setDebugLoc(getCurSDLoc())
2499         .setChain(DAG.getEntryNode())
2500         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2501                    getValue(GuardCheckFn), std::move(Args));
2502 
2503     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2504     DAG.setRoot(Result.second);
2505     return;
2506   }
2507 
2508   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2509   // Otherwise, emit a volatile load to retrieve the stack guard value.
2510   SDValue Chain = DAG.getEntryNode();
2511   if (TLI.useLoadStackGuardNode()) {
2512     Guard = getLoadStackGuard(DAG, dl, Chain);
2513   } else {
2514     const Value *IRGuard = TLI.getSDagStackGuard(M);
2515     SDValue GuardPtr = getValue(IRGuard);
2516 
2517     Guard =
2518         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2519                     Align, MachineMemOperand::MOVolatile);
2520   }
2521 
2522   // Perform the comparison via a subtract/getsetcc.
2523   EVT VT = Guard.getValueType();
2524   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2525 
2526   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2527                                                         *DAG.getContext(),
2528                                                         Sub.getValueType()),
2529                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2530 
2531   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2532   // branch to failure MBB.
2533   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2534                                MVT::Other, GuardVal.getOperand(0),
2535                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2536   // Otherwise branch to success MBB.
2537   SDValue Br = DAG.getNode(ISD::BR, dl,
2538                            MVT::Other, BrCond,
2539                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2540 
2541   DAG.setRoot(Br);
2542 }
2543 
2544 /// Codegen the failure basic block for a stack protector check.
2545 ///
2546 /// A failure stack protector machine basic block consists simply of a call to
2547 /// __stack_chk_fail().
2548 ///
2549 /// For a high level explanation of how this fits into the stack protector
2550 /// generation see the comment on the declaration of class
2551 /// StackProtectorDescriptor.
2552 void
2553 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2554   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2555   SDValue Chain =
2556       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2557                       None, false, getCurSDLoc(), false, false).second;
2558   // On PS4, the "return address" must still be within the calling function,
2559   // even if it's at the very end, so emit an explicit TRAP here.
2560   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2561   if (TM.getTargetTriple().isPS4CPU())
2562     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2563 
2564   DAG.setRoot(Chain);
2565 }
2566 
2567 /// visitBitTestHeader - This function emits necessary code to produce value
2568 /// suitable for "bit tests"
2569 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2570                                              MachineBasicBlock *SwitchBB) {
2571   SDLoc dl = getCurSDLoc();
2572 
2573   // Subtract the minimum value
2574   SDValue SwitchOp = getValue(B.SValue);
2575   EVT VT = SwitchOp.getValueType();
2576   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2577                             DAG.getConstant(B.First, dl, VT));
2578 
2579   // Check range
2580   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2581   SDValue RangeCmp = DAG.getSetCC(
2582       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2583                                  Sub.getValueType()),
2584       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2585 
2586   // Determine the type of the test operands.
2587   bool UsePtrType = false;
2588   if (!TLI.isTypeLegal(VT))
2589     UsePtrType = true;
2590   else {
2591     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2592       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2593         // Switch table case range are encoded into series of masks.
2594         // Just use pointer type, it's guaranteed to fit.
2595         UsePtrType = true;
2596         break;
2597       }
2598   }
2599   if (UsePtrType) {
2600     VT = TLI.getPointerTy(DAG.getDataLayout());
2601     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2602   }
2603 
2604   B.RegVT = VT.getSimpleVT();
2605   B.Reg = FuncInfo.CreateReg(B.RegVT);
2606   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2607 
2608   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2609 
2610   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2611   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2612   SwitchBB->normalizeSuccProbs();
2613 
2614   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2615                                 MVT::Other, CopyTo, RangeCmp,
2616                                 DAG.getBasicBlock(B.Default));
2617 
2618   // Avoid emitting unnecessary branches to the next block.
2619   if (MBB != NextBlock(SwitchBB))
2620     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2621                           DAG.getBasicBlock(MBB));
2622 
2623   DAG.setRoot(BrRange);
2624 }
2625 
2626 /// visitBitTestCase - this function produces one "bit test"
2627 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2628                                            MachineBasicBlock* NextMBB,
2629                                            BranchProbability BranchProbToNext,
2630                                            unsigned Reg,
2631                                            BitTestCase &B,
2632                                            MachineBasicBlock *SwitchBB) {
2633   SDLoc dl = getCurSDLoc();
2634   MVT VT = BB.RegVT;
2635   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2636   SDValue Cmp;
2637   unsigned PopCount = countPopulation(B.Mask);
2638   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2639   if (PopCount == 1) {
2640     // Testing for a single bit; just compare the shift count with what it
2641     // would need to be to shift a 1 bit in that position.
2642     Cmp = DAG.getSetCC(
2643         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2644         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2645         ISD::SETEQ);
2646   } else if (PopCount == BB.Range) {
2647     // There is only one zero bit in the range, test for it directly.
2648     Cmp = DAG.getSetCC(
2649         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2650         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2651         ISD::SETNE);
2652   } else {
2653     // Make desired shift
2654     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2655                                     DAG.getConstant(1, dl, VT), ShiftOp);
2656 
2657     // Emit bit tests and jumps
2658     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2659                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2660     Cmp = DAG.getSetCC(
2661         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2662         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2663   }
2664 
2665   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2666   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2667   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2668   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2669   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2670   // one as they are relative probabilities (and thus work more like weights),
2671   // and hence we need to normalize them to let the sum of them become one.
2672   SwitchBB->normalizeSuccProbs();
2673 
2674   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2675                               MVT::Other, getControlRoot(),
2676                               Cmp, DAG.getBasicBlock(B.TargetBB));
2677 
2678   // Avoid emitting unnecessary branches to the next block.
2679   if (NextMBB != NextBlock(SwitchBB))
2680     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2681                         DAG.getBasicBlock(NextMBB));
2682 
2683   DAG.setRoot(BrAnd);
2684 }
2685 
2686 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2687   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2688 
2689   // Retrieve successors. Look through artificial IR level blocks like
2690   // catchswitch for successors.
2691   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2692   const BasicBlock *EHPadBB = I.getSuccessor(1);
2693 
2694   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2695   // have to do anything here to lower funclet bundles.
2696   assert(!I.hasOperandBundlesOtherThan(
2697              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2698          "Cannot lower invokes with arbitrary operand bundles yet!");
2699 
2700   const Value *Callee(I.getCalledValue());
2701   const Function *Fn = dyn_cast<Function>(Callee);
2702   if (isa<InlineAsm>(Callee))
2703     visitInlineAsm(&I);
2704   else if (Fn && Fn->isIntrinsic()) {
2705     switch (Fn->getIntrinsicID()) {
2706     default:
2707       llvm_unreachable("Cannot invoke this intrinsic");
2708     case Intrinsic::donothing:
2709       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2710       break;
2711     case Intrinsic::experimental_patchpoint_void:
2712     case Intrinsic::experimental_patchpoint_i64:
2713       visitPatchpoint(&I, EHPadBB);
2714       break;
2715     case Intrinsic::experimental_gc_statepoint:
2716       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2717       break;
2718     case Intrinsic::wasm_rethrow_in_catch: {
2719       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2720       // special because it can be invoked, so we manually lower it to a DAG
2721       // node here.
2722       SmallVector<SDValue, 8> Ops;
2723       Ops.push_back(getRoot()); // inchain
2724       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2725       Ops.push_back(
2726           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2727                                 TLI.getPointerTy(DAG.getDataLayout())));
2728       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2729       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2730       break;
2731     }
2732     }
2733   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2734     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2735     // Eventually we will support lowering the @llvm.experimental.deoptimize
2736     // intrinsic, and right now there are no plans to support other intrinsics
2737     // with deopt state.
2738     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2739   } else {
2740     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2741   }
2742 
2743   // If the value of the invoke is used outside of its defining block, make it
2744   // available as a virtual register.
2745   // We already took care of the exported value for the statepoint instruction
2746   // during call to the LowerStatepoint.
2747   if (!isStatepoint(I)) {
2748     CopyToExportRegsIfNeeded(&I);
2749   }
2750 
2751   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2752   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2753   BranchProbability EHPadBBProb =
2754       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2755           : BranchProbability::getZero();
2756   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2757 
2758   // Update successor info.
2759   addSuccessorWithProb(InvokeMBB, Return);
2760   for (auto &UnwindDest : UnwindDests) {
2761     UnwindDest.first->setIsEHPad();
2762     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2763   }
2764   InvokeMBB->normalizeSuccProbs();
2765 
2766   // Drop into normal successor.
2767   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2768                           DAG.getBasicBlock(Return)));
2769 }
2770 
2771 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2772   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2773 
2774   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2775   // have to do anything here to lower funclet bundles.
2776   assert(!I.hasOperandBundlesOtherThan(
2777              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2778          "Cannot lower callbrs with arbitrary operand bundles yet!");
2779 
2780   assert(isa<InlineAsm>(I.getCalledValue()) &&
2781          "Only know how to handle inlineasm callbr");
2782   visitInlineAsm(&I);
2783 
2784   // Retrieve successors.
2785   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2786 
2787   // Update successor info.
2788   addSuccessorWithProb(CallBrMBB, Return);
2789   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2790     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2791     addSuccessorWithProb(CallBrMBB, Target);
2792   }
2793   CallBrMBB->normalizeSuccProbs();
2794 
2795   // Drop into default successor.
2796   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2797                           MVT::Other, getControlRoot(),
2798                           DAG.getBasicBlock(Return)));
2799 }
2800 
2801 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2802   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2803 }
2804 
2805 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2806   assert(FuncInfo.MBB->isEHPad() &&
2807          "Call to landingpad not in landing pad!");
2808 
2809   // If there aren't registers to copy the values into (e.g., during SjLj
2810   // exceptions), then don't bother to create these DAG nodes.
2811   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2812   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2813   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2814       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2815     return;
2816 
2817   // If landingpad's return type is token type, we don't create DAG nodes
2818   // for its exception pointer and selector value. The extraction of exception
2819   // pointer or selector value from token type landingpads is not currently
2820   // supported.
2821   if (LP.getType()->isTokenTy())
2822     return;
2823 
2824   SmallVector<EVT, 2> ValueVTs;
2825   SDLoc dl = getCurSDLoc();
2826   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2827   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2828 
2829   // Get the two live-in registers as SDValues. The physregs have already been
2830   // copied into virtual registers.
2831   SDValue Ops[2];
2832   if (FuncInfo.ExceptionPointerVirtReg) {
2833     Ops[0] = DAG.getZExtOrTrunc(
2834         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2835                            FuncInfo.ExceptionPointerVirtReg,
2836                            TLI.getPointerTy(DAG.getDataLayout())),
2837         dl, ValueVTs[0]);
2838   } else {
2839     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2840   }
2841   Ops[1] = DAG.getZExtOrTrunc(
2842       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2843                          FuncInfo.ExceptionSelectorVirtReg,
2844                          TLI.getPointerTy(DAG.getDataLayout())),
2845       dl, ValueVTs[1]);
2846 
2847   // Merge into one.
2848   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2849                             DAG.getVTList(ValueVTs), Ops);
2850   setValue(&LP, Res);
2851 }
2852 
2853 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2854 #ifndef NDEBUG
2855   for (const CaseCluster &CC : Clusters)
2856     assert(CC.Low == CC.High && "Input clusters must be single-case");
2857 #endif
2858 
2859   llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
2860     return a.Low->getValue().slt(b.Low->getValue());
2861   });
2862 
2863   // Merge adjacent clusters with the same destination.
2864   const unsigned N = Clusters.size();
2865   unsigned DstIndex = 0;
2866   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2867     CaseCluster &CC = Clusters[SrcIndex];
2868     const ConstantInt *CaseVal = CC.Low;
2869     MachineBasicBlock *Succ = CC.MBB;
2870 
2871     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2872         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2873       // If this case has the same successor and is a neighbour, merge it into
2874       // the previous cluster.
2875       Clusters[DstIndex - 1].High = CaseVal;
2876       Clusters[DstIndex - 1].Prob += CC.Prob;
2877     } else {
2878       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2879                    sizeof(Clusters[SrcIndex]));
2880     }
2881   }
2882   Clusters.resize(DstIndex);
2883 }
2884 
2885 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2886                                            MachineBasicBlock *Last) {
2887   // Update JTCases.
2888   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2889     if (JTCases[i].first.HeaderBB == First)
2890       JTCases[i].first.HeaderBB = Last;
2891 
2892   // Update BitTestCases.
2893   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2894     if (BitTestCases[i].Parent == First)
2895       BitTestCases[i].Parent = Last;
2896 }
2897 
2898 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2899   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2900 
2901   // Update machine-CFG edges with unique successors.
2902   SmallSet<BasicBlock*, 32> Done;
2903   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2904     BasicBlock *BB = I.getSuccessor(i);
2905     bool Inserted = Done.insert(BB).second;
2906     if (!Inserted)
2907         continue;
2908 
2909     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2910     addSuccessorWithProb(IndirectBrMBB, Succ);
2911   }
2912   IndirectBrMBB->normalizeSuccProbs();
2913 
2914   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2915                           MVT::Other, getControlRoot(),
2916                           getValue(I.getAddress())));
2917 }
2918 
2919 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2920   if (!DAG.getTarget().Options.TrapUnreachable)
2921     return;
2922 
2923   // We may be able to ignore unreachable behind a noreturn call.
2924   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2925     const BasicBlock &BB = *I.getParent();
2926     if (&I != &BB.front()) {
2927       BasicBlock::const_iterator PredI =
2928         std::prev(BasicBlock::const_iterator(&I));
2929       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2930         if (Call->doesNotReturn())
2931           return;
2932       }
2933     }
2934   }
2935 
2936   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2937 }
2938 
2939 void SelectionDAGBuilder::visitFSub(const User &I) {
2940   // -0.0 - X --> fneg
2941   Type *Ty = I.getType();
2942   if (isa<Constant>(I.getOperand(0)) &&
2943       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2944     SDValue Op2 = getValue(I.getOperand(1));
2945     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2946                              Op2.getValueType(), Op2));
2947     return;
2948   }
2949 
2950   visitBinary(I, ISD::FSUB);
2951 }
2952 
2953 /// Checks if the given instruction performs a vector reduction, in which case
2954 /// we have the freedom to alter the elements in the result as long as the
2955 /// reduction of them stays unchanged.
2956 static bool isVectorReductionOp(const User *I) {
2957   const Instruction *Inst = dyn_cast<Instruction>(I);
2958   if (!Inst || !Inst->getType()->isVectorTy())
2959     return false;
2960 
2961   auto OpCode = Inst->getOpcode();
2962   switch (OpCode) {
2963   case Instruction::Add:
2964   case Instruction::Mul:
2965   case Instruction::And:
2966   case Instruction::Or:
2967   case Instruction::Xor:
2968     break;
2969   case Instruction::FAdd:
2970   case Instruction::FMul:
2971     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2972       if (FPOp->getFastMathFlags().isFast())
2973         break;
2974     LLVM_FALLTHROUGH;
2975   default:
2976     return false;
2977   }
2978 
2979   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2980   // Ensure the reduction size is a power of 2.
2981   if (!isPowerOf2_32(ElemNum))
2982     return false;
2983 
2984   unsigned ElemNumToReduce = ElemNum;
2985 
2986   // Do DFS search on the def-use chain from the given instruction. We only
2987   // allow four kinds of operations during the search until we reach the
2988   // instruction that extracts the first element from the vector:
2989   //
2990   //   1. The reduction operation of the same opcode as the given instruction.
2991   //
2992   //   2. PHI node.
2993   //
2994   //   3. ShuffleVector instruction together with a reduction operation that
2995   //      does a partial reduction.
2996   //
2997   //   4. ExtractElement that extracts the first element from the vector, and we
2998   //      stop searching the def-use chain here.
2999   //
3000   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3001   // from 1-3 to the stack to continue the DFS. The given instruction is not
3002   // a reduction operation if we meet any other instructions other than those
3003   // listed above.
3004 
3005   SmallVector<const User *, 16> UsersToVisit{Inst};
3006   SmallPtrSet<const User *, 16> Visited;
3007   bool ReduxExtracted = false;
3008 
3009   while (!UsersToVisit.empty()) {
3010     auto User = UsersToVisit.back();
3011     UsersToVisit.pop_back();
3012     if (!Visited.insert(User).second)
3013       continue;
3014 
3015     for (const auto &U : User->users()) {
3016       auto Inst = dyn_cast<Instruction>(U);
3017       if (!Inst)
3018         return false;
3019 
3020       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3021         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3022           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3023             return false;
3024         UsersToVisit.push_back(U);
3025       } else if (const ShuffleVectorInst *ShufInst =
3026                      dyn_cast<ShuffleVectorInst>(U)) {
3027         // Detect the following pattern: A ShuffleVector instruction together
3028         // with a reduction that do partial reduction on the first and second
3029         // ElemNumToReduce / 2 elements, and store the result in
3030         // ElemNumToReduce / 2 elements in another vector.
3031 
3032         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3033         if (ResultElements < ElemNum)
3034           return false;
3035 
3036         if (ElemNumToReduce == 1)
3037           return false;
3038         if (!isa<UndefValue>(U->getOperand(1)))
3039           return false;
3040         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3041           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3042             return false;
3043         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3044           if (ShufInst->getMaskValue(i) != -1)
3045             return false;
3046 
3047         // There is only one user of this ShuffleVector instruction, which
3048         // must be a reduction operation.
3049         if (!U->hasOneUse())
3050           return false;
3051 
3052         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3053         if (!U2 || U2->getOpcode() != OpCode)
3054           return false;
3055 
3056         // Check operands of the reduction operation.
3057         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3058             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3059           UsersToVisit.push_back(U2);
3060           ElemNumToReduce /= 2;
3061         } else
3062           return false;
3063       } else if (isa<ExtractElementInst>(U)) {
3064         // At this moment we should have reduced all elements in the vector.
3065         if (ElemNumToReduce != 1)
3066           return false;
3067 
3068         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3069         if (!Val || !Val->isZero())
3070           return false;
3071 
3072         ReduxExtracted = true;
3073       } else
3074         return false;
3075     }
3076   }
3077   return ReduxExtracted;
3078 }
3079 
3080 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3081   SDNodeFlags Flags;
3082 
3083   SDValue Op = getValue(I.getOperand(0));
3084   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3085                                     Op, Flags);
3086   setValue(&I, UnNodeValue);
3087 }
3088 
3089 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3090   SDNodeFlags Flags;
3091   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3092     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3093     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3094   }
3095   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3096     Flags.setExact(ExactOp->isExact());
3097   }
3098   if (isVectorReductionOp(&I)) {
3099     Flags.setVectorReduction(true);
3100     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3101   }
3102 
3103   SDValue Op1 = getValue(I.getOperand(0));
3104   SDValue Op2 = getValue(I.getOperand(1));
3105   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3106                                      Op1, Op2, Flags);
3107   setValue(&I, BinNodeValue);
3108 }
3109 
3110 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3111   SDValue Op1 = getValue(I.getOperand(0));
3112   SDValue Op2 = getValue(I.getOperand(1));
3113 
3114   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3115       Op1.getValueType(), DAG.getDataLayout());
3116 
3117   // Coerce the shift amount to the right type if we can.
3118   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3119     unsigned ShiftSize = ShiftTy.getSizeInBits();
3120     unsigned Op2Size = Op2.getValueSizeInBits();
3121     SDLoc DL = getCurSDLoc();
3122 
3123     // If the operand is smaller than the shift count type, promote it.
3124     if (ShiftSize > Op2Size)
3125       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3126 
3127     // If the operand is larger than the shift count type but the shift
3128     // count type has enough bits to represent any shift value, truncate
3129     // it now. This is a common case and it exposes the truncate to
3130     // optimization early.
3131     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3132       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3133     // Otherwise we'll need to temporarily settle for some other convenient
3134     // type.  Type legalization will make adjustments once the shiftee is split.
3135     else
3136       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3137   }
3138 
3139   bool nuw = false;
3140   bool nsw = false;
3141   bool exact = false;
3142 
3143   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3144 
3145     if (const OverflowingBinaryOperator *OFBinOp =
3146             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3147       nuw = OFBinOp->hasNoUnsignedWrap();
3148       nsw = OFBinOp->hasNoSignedWrap();
3149     }
3150     if (const PossiblyExactOperator *ExactOp =
3151             dyn_cast<const PossiblyExactOperator>(&I))
3152       exact = ExactOp->isExact();
3153   }
3154   SDNodeFlags Flags;
3155   Flags.setExact(exact);
3156   Flags.setNoSignedWrap(nsw);
3157   Flags.setNoUnsignedWrap(nuw);
3158   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3159                             Flags);
3160   setValue(&I, Res);
3161 }
3162 
3163 void SelectionDAGBuilder::visitSDiv(const User &I) {
3164   SDValue Op1 = getValue(I.getOperand(0));
3165   SDValue Op2 = getValue(I.getOperand(1));
3166 
3167   SDNodeFlags Flags;
3168   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3169                  cast<PossiblyExactOperator>(&I)->isExact());
3170   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3171                            Op2, Flags));
3172 }
3173 
3174 void SelectionDAGBuilder::visitICmp(const User &I) {
3175   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3176   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3177     predicate = IC->getPredicate();
3178   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3179     predicate = ICmpInst::Predicate(IC->getPredicate());
3180   SDValue Op1 = getValue(I.getOperand(0));
3181   SDValue Op2 = getValue(I.getOperand(1));
3182   ISD::CondCode Opcode = getICmpCondCode(predicate);
3183 
3184   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3185                                                         I.getType());
3186   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3187 }
3188 
3189 void SelectionDAGBuilder::visitFCmp(const User &I) {
3190   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3191   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3192     predicate = FC->getPredicate();
3193   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3194     predicate = FCmpInst::Predicate(FC->getPredicate());
3195   SDValue Op1 = getValue(I.getOperand(0));
3196   SDValue Op2 = getValue(I.getOperand(1));
3197 
3198   ISD::CondCode Condition = getFCmpCondCode(predicate);
3199   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3200   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3201     Condition = getFCmpCodeWithoutNaN(Condition);
3202 
3203   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3204                                                         I.getType());
3205   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3206 }
3207 
3208 // Check if the condition of the select has one use or two users that are both
3209 // selects with the same condition.
3210 static bool hasOnlySelectUsers(const Value *Cond) {
3211   return llvm::all_of(Cond->users(), [](const Value *V) {
3212     return isa<SelectInst>(V);
3213   });
3214 }
3215 
3216 void SelectionDAGBuilder::visitSelect(const User &I) {
3217   SmallVector<EVT, 4> ValueVTs;
3218   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3219                   ValueVTs);
3220   unsigned NumValues = ValueVTs.size();
3221   if (NumValues == 0) return;
3222 
3223   SmallVector<SDValue, 4> Values(NumValues);
3224   SDValue Cond     = getValue(I.getOperand(0));
3225   SDValue LHSVal   = getValue(I.getOperand(1));
3226   SDValue RHSVal   = getValue(I.getOperand(2));
3227   auto BaseOps = {Cond};
3228   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3229     ISD::VSELECT : ISD::SELECT;
3230 
3231   bool IsUnaryAbs = false;
3232 
3233   // Min/max matching is only viable if all output VTs are the same.
3234   if (is_splat(ValueVTs)) {
3235     EVT VT = ValueVTs[0];
3236     LLVMContext &Ctx = *DAG.getContext();
3237     auto &TLI = DAG.getTargetLoweringInfo();
3238 
3239     // We care about the legality of the operation after it has been type
3240     // legalized.
3241     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
3242            VT != TLI.getTypeToTransformTo(Ctx, VT))
3243       VT = TLI.getTypeToTransformTo(Ctx, VT);
3244 
3245     // If the vselect is legal, assume we want to leave this as a vector setcc +
3246     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3247     // min/max is legal on the scalar type.
3248     bool UseScalarMinMax = VT.isVector() &&
3249       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3250 
3251     Value *LHS, *RHS;
3252     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3253     ISD::NodeType Opc = ISD::DELETED_NODE;
3254     switch (SPR.Flavor) {
3255     case SPF_UMAX:    Opc = ISD::UMAX; break;
3256     case SPF_UMIN:    Opc = ISD::UMIN; break;
3257     case SPF_SMAX:    Opc = ISD::SMAX; break;
3258     case SPF_SMIN:    Opc = ISD::SMIN; break;
3259     case SPF_FMINNUM:
3260       switch (SPR.NaNBehavior) {
3261       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3262       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3263       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3264       case SPNB_RETURNS_ANY: {
3265         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3266           Opc = ISD::FMINNUM;
3267         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3268           Opc = ISD::FMINIMUM;
3269         else if (UseScalarMinMax)
3270           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3271             ISD::FMINNUM : ISD::FMINIMUM;
3272         break;
3273       }
3274       }
3275       break;
3276     case SPF_FMAXNUM:
3277       switch (SPR.NaNBehavior) {
3278       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3279       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3280       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3281       case SPNB_RETURNS_ANY:
3282 
3283         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3284           Opc = ISD::FMAXNUM;
3285         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3286           Opc = ISD::FMAXIMUM;
3287         else if (UseScalarMinMax)
3288           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3289             ISD::FMAXNUM : ISD::FMAXIMUM;
3290         break;
3291       }
3292       break;
3293     case SPF_ABS:
3294       IsUnaryAbs = true;
3295       Opc = ISD::ABS;
3296       break;
3297     case SPF_NABS:
3298       // TODO: we need to produce sub(0, abs(X)).
3299     default: break;
3300     }
3301 
3302     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3303         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3304          (UseScalarMinMax &&
3305           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3306         // If the underlying comparison instruction is used by any other
3307         // instruction, the consumed instructions won't be destroyed, so it is
3308         // not profitable to convert to a min/max.
3309         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3310       OpCode = Opc;
3311       LHSVal = getValue(LHS);
3312       RHSVal = getValue(RHS);
3313       BaseOps = {};
3314     }
3315 
3316     if (IsUnaryAbs) {
3317       OpCode = Opc;
3318       LHSVal = getValue(LHS);
3319       BaseOps = {};
3320     }
3321   }
3322 
3323   if (IsUnaryAbs) {
3324     for (unsigned i = 0; i != NumValues; ++i) {
3325       Values[i] =
3326           DAG.getNode(OpCode, getCurSDLoc(),
3327                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3328                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3329     }
3330   } else {
3331     for (unsigned i = 0; i != NumValues; ++i) {
3332       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3333       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3334       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3335       Values[i] = DAG.getNode(
3336           OpCode, getCurSDLoc(),
3337           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3338     }
3339   }
3340 
3341   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3342                            DAG.getVTList(ValueVTs), Values));
3343 }
3344 
3345 void SelectionDAGBuilder::visitTrunc(const User &I) {
3346   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3347   SDValue N = getValue(I.getOperand(0));
3348   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3349                                                         I.getType());
3350   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3351 }
3352 
3353 void SelectionDAGBuilder::visitZExt(const User &I) {
3354   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3355   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3356   SDValue N = getValue(I.getOperand(0));
3357   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3358                                                         I.getType());
3359   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3360 }
3361 
3362 void SelectionDAGBuilder::visitSExt(const User &I) {
3363   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3364   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3365   SDValue N = getValue(I.getOperand(0));
3366   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3367                                                         I.getType());
3368   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3369 }
3370 
3371 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3372   // FPTrunc is never a no-op cast, no need to check
3373   SDValue N = getValue(I.getOperand(0));
3374   SDLoc dl = getCurSDLoc();
3375   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3376   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3377   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3378                            DAG.getTargetConstant(
3379                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3380 }
3381 
3382 void SelectionDAGBuilder::visitFPExt(const User &I) {
3383   // FPExt is never a no-op cast, no need to check
3384   SDValue N = getValue(I.getOperand(0));
3385   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3386                                                         I.getType());
3387   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3388 }
3389 
3390 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3391   // FPToUI is never a no-op cast, no need to check
3392   SDValue N = getValue(I.getOperand(0));
3393   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3394                                                         I.getType());
3395   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3396 }
3397 
3398 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3399   // FPToSI is never a no-op cast, no need to check
3400   SDValue N = getValue(I.getOperand(0));
3401   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3402                                                         I.getType());
3403   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3404 }
3405 
3406 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3407   // UIToFP is never a no-op cast, no need to check
3408   SDValue N = getValue(I.getOperand(0));
3409   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3410                                                         I.getType());
3411   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3412 }
3413 
3414 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3415   // SIToFP is never a no-op cast, no need to check
3416   SDValue N = getValue(I.getOperand(0));
3417   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3418                                                         I.getType());
3419   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3420 }
3421 
3422 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3423   // What to do depends on the size of the integer and the size of the pointer.
3424   // We can either truncate, zero extend, or no-op, accordingly.
3425   SDValue N = getValue(I.getOperand(0));
3426   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3427                                                         I.getType());
3428   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3429 }
3430 
3431 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3432   // What to do depends on the size of the integer and the size of the pointer.
3433   // We can either truncate, zero extend, or no-op, accordingly.
3434   SDValue N = getValue(I.getOperand(0));
3435   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3436                                                         I.getType());
3437   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3438 }
3439 
3440 void SelectionDAGBuilder::visitBitCast(const User &I) {
3441   SDValue N = getValue(I.getOperand(0));
3442   SDLoc dl = getCurSDLoc();
3443   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3444                                                         I.getType());
3445 
3446   // BitCast assures us that source and destination are the same size so this is
3447   // either a BITCAST or a no-op.
3448   if (DestVT != N.getValueType())
3449     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3450                              DestVT, N)); // convert types.
3451   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3452   // might fold any kind of constant expression to an integer constant and that
3453   // is not what we are looking for. Only recognize a bitcast of a genuine
3454   // constant integer as an opaque constant.
3455   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3456     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3457                                  /*isOpaque*/true));
3458   else
3459     setValue(&I, N);            // noop cast.
3460 }
3461 
3462 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3463   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3464   const Value *SV = I.getOperand(0);
3465   SDValue N = getValue(SV);
3466   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3467 
3468   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3469   unsigned DestAS = I.getType()->getPointerAddressSpace();
3470 
3471   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3472     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3473 
3474   setValue(&I, N);
3475 }
3476 
3477 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3478   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3479   SDValue InVec = getValue(I.getOperand(0));
3480   SDValue InVal = getValue(I.getOperand(1));
3481   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3482                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3483   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3484                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3485                            InVec, InVal, InIdx));
3486 }
3487 
3488 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3489   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3490   SDValue InVec = getValue(I.getOperand(0));
3491   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3492                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3493   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3494                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3495                            InVec, InIdx));
3496 }
3497 
3498 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3499   SDValue Src1 = getValue(I.getOperand(0));
3500   SDValue Src2 = getValue(I.getOperand(1));
3501   SDLoc DL = getCurSDLoc();
3502 
3503   SmallVector<int, 8> Mask;
3504   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3505   unsigned MaskNumElts = Mask.size();
3506 
3507   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3508   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3509   EVT SrcVT = Src1.getValueType();
3510   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3511 
3512   if (SrcNumElts == MaskNumElts) {
3513     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3514     return;
3515   }
3516 
3517   // Normalize the shuffle vector since mask and vector length don't match.
3518   if (SrcNumElts < MaskNumElts) {
3519     // Mask is longer than the source vectors. We can use concatenate vector to
3520     // make the mask and vectors lengths match.
3521 
3522     if (MaskNumElts % SrcNumElts == 0) {
3523       // Mask length is a multiple of the source vector length.
3524       // Check if the shuffle is some kind of concatenation of the input
3525       // vectors.
3526       unsigned NumConcat = MaskNumElts / SrcNumElts;
3527       bool IsConcat = true;
3528       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3529       for (unsigned i = 0; i != MaskNumElts; ++i) {
3530         int Idx = Mask[i];
3531         if (Idx < 0)
3532           continue;
3533         // Ensure the indices in each SrcVT sized piece are sequential and that
3534         // the same source is used for the whole piece.
3535         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3536             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3537              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3538           IsConcat = false;
3539           break;
3540         }
3541         // Remember which source this index came from.
3542         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3543       }
3544 
3545       // The shuffle is concatenating multiple vectors together. Just emit
3546       // a CONCAT_VECTORS operation.
3547       if (IsConcat) {
3548         SmallVector<SDValue, 8> ConcatOps;
3549         for (auto Src : ConcatSrcs) {
3550           if (Src < 0)
3551             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3552           else if (Src == 0)
3553             ConcatOps.push_back(Src1);
3554           else
3555             ConcatOps.push_back(Src2);
3556         }
3557         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3558         return;
3559       }
3560     }
3561 
3562     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3563     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3564     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3565                                     PaddedMaskNumElts);
3566 
3567     // Pad both vectors with undefs to make them the same length as the mask.
3568     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3569 
3570     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3571     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3572     MOps1[0] = Src1;
3573     MOps2[0] = Src2;
3574 
3575     Src1 = Src1.isUndef()
3576                ? DAG.getUNDEF(PaddedVT)
3577                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3578     Src2 = Src2.isUndef()
3579                ? DAG.getUNDEF(PaddedVT)
3580                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3581 
3582     // Readjust mask for new input vector length.
3583     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3584     for (unsigned i = 0; i != MaskNumElts; ++i) {
3585       int Idx = Mask[i];
3586       if (Idx >= (int)SrcNumElts)
3587         Idx -= SrcNumElts - PaddedMaskNumElts;
3588       MappedOps[i] = Idx;
3589     }
3590 
3591     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3592 
3593     // If the concatenated vector was padded, extract a subvector with the
3594     // correct number of elements.
3595     if (MaskNumElts != PaddedMaskNumElts)
3596       Result = DAG.getNode(
3597           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3598           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3599 
3600     setValue(&I, Result);
3601     return;
3602   }
3603 
3604   if (SrcNumElts > MaskNumElts) {
3605     // Analyze the access pattern of the vector to see if we can extract
3606     // two subvectors and do the shuffle.
3607     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3608     bool CanExtract = true;
3609     for (int Idx : Mask) {
3610       unsigned Input = 0;
3611       if (Idx < 0)
3612         continue;
3613 
3614       if (Idx >= (int)SrcNumElts) {
3615         Input = 1;
3616         Idx -= SrcNumElts;
3617       }
3618 
3619       // If all the indices come from the same MaskNumElts sized portion of
3620       // the sources we can use extract. Also make sure the extract wouldn't
3621       // extract past the end of the source.
3622       int NewStartIdx = alignDown(Idx, MaskNumElts);
3623       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3624           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3625         CanExtract = false;
3626       // Make sure we always update StartIdx as we use it to track if all
3627       // elements are undef.
3628       StartIdx[Input] = NewStartIdx;
3629     }
3630 
3631     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3632       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3633       return;
3634     }
3635     if (CanExtract) {
3636       // Extract appropriate subvector and generate a vector shuffle
3637       for (unsigned Input = 0; Input < 2; ++Input) {
3638         SDValue &Src = Input == 0 ? Src1 : Src2;
3639         if (StartIdx[Input] < 0)
3640           Src = DAG.getUNDEF(VT);
3641         else {
3642           Src = DAG.getNode(
3643               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3644               DAG.getConstant(StartIdx[Input], DL,
3645                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3646         }
3647       }
3648 
3649       // Calculate new mask.
3650       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3651       for (int &Idx : MappedOps) {
3652         if (Idx >= (int)SrcNumElts)
3653           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3654         else if (Idx >= 0)
3655           Idx -= StartIdx[0];
3656       }
3657 
3658       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3659       return;
3660     }
3661   }
3662 
3663   // We can't use either concat vectors or extract subvectors so fall back to
3664   // replacing the shuffle with extract and build vector.
3665   // to insert and build vector.
3666   EVT EltVT = VT.getVectorElementType();
3667   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3668   SmallVector<SDValue,8> Ops;
3669   for (int Idx : Mask) {
3670     SDValue Res;
3671 
3672     if (Idx < 0) {
3673       Res = DAG.getUNDEF(EltVT);
3674     } else {
3675       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3676       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3677 
3678       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3679                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3680     }
3681 
3682     Ops.push_back(Res);
3683   }
3684 
3685   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3686 }
3687 
3688 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3689   ArrayRef<unsigned> Indices;
3690   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3691     Indices = IV->getIndices();
3692   else
3693     Indices = cast<ConstantExpr>(&I)->getIndices();
3694 
3695   const Value *Op0 = I.getOperand(0);
3696   const Value *Op1 = I.getOperand(1);
3697   Type *AggTy = I.getType();
3698   Type *ValTy = Op1->getType();
3699   bool IntoUndef = isa<UndefValue>(Op0);
3700   bool FromUndef = isa<UndefValue>(Op1);
3701 
3702   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3703 
3704   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3705   SmallVector<EVT, 4> AggValueVTs;
3706   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3707   SmallVector<EVT, 4> ValValueVTs;
3708   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3709 
3710   unsigned NumAggValues = AggValueVTs.size();
3711   unsigned NumValValues = ValValueVTs.size();
3712   SmallVector<SDValue, 4> Values(NumAggValues);
3713 
3714   // Ignore an insertvalue that produces an empty object
3715   if (!NumAggValues) {
3716     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3717     return;
3718   }
3719 
3720   SDValue Agg = getValue(Op0);
3721   unsigned i = 0;
3722   // Copy the beginning value(s) from the original aggregate.
3723   for (; i != LinearIndex; ++i)
3724     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3725                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3726   // Copy values from the inserted value(s).
3727   if (NumValValues) {
3728     SDValue Val = getValue(Op1);
3729     for (; i != LinearIndex + NumValValues; ++i)
3730       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3731                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3732   }
3733   // Copy remaining value(s) from the original aggregate.
3734   for (; i != NumAggValues; ++i)
3735     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3736                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3737 
3738   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3739                            DAG.getVTList(AggValueVTs), Values));
3740 }
3741 
3742 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3743   ArrayRef<unsigned> Indices;
3744   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3745     Indices = EV->getIndices();
3746   else
3747     Indices = cast<ConstantExpr>(&I)->getIndices();
3748 
3749   const Value *Op0 = I.getOperand(0);
3750   Type *AggTy = Op0->getType();
3751   Type *ValTy = I.getType();
3752   bool OutOfUndef = isa<UndefValue>(Op0);
3753 
3754   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3755 
3756   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3757   SmallVector<EVT, 4> ValValueVTs;
3758   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3759 
3760   unsigned NumValValues = ValValueVTs.size();
3761 
3762   // Ignore a extractvalue that produces an empty object
3763   if (!NumValValues) {
3764     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3765     return;
3766   }
3767 
3768   SmallVector<SDValue, 4> Values(NumValValues);
3769 
3770   SDValue Agg = getValue(Op0);
3771   // Copy out the selected value(s).
3772   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3773     Values[i - LinearIndex] =
3774       OutOfUndef ?
3775         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3776         SDValue(Agg.getNode(), Agg.getResNo() + i);
3777 
3778   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3779                            DAG.getVTList(ValValueVTs), Values));
3780 }
3781 
3782 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3783   Value *Op0 = I.getOperand(0);
3784   // Note that the pointer operand may be a vector of pointers. Take the scalar
3785   // element which holds a pointer.
3786   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3787   SDValue N = getValue(Op0);
3788   SDLoc dl = getCurSDLoc();
3789 
3790   // Normalize Vector GEP - all scalar operands should be converted to the
3791   // splat vector.
3792   unsigned VectorWidth = I.getType()->isVectorTy() ?
3793     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3794 
3795   if (VectorWidth && !N.getValueType().isVector()) {
3796     LLVMContext &Context = *DAG.getContext();
3797     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3798     N = DAG.getSplatBuildVector(VT, dl, N);
3799   }
3800 
3801   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3802        GTI != E; ++GTI) {
3803     const Value *Idx = GTI.getOperand();
3804     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3805       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3806       if (Field) {
3807         // N = N + Offset
3808         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3809 
3810         // In an inbounds GEP with an offset that is nonnegative even when
3811         // interpreted as signed, assume there is no unsigned overflow.
3812         SDNodeFlags Flags;
3813         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3814           Flags.setNoUnsignedWrap(true);
3815 
3816         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3817                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3818       }
3819     } else {
3820       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3821       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3822       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3823 
3824       // If this is a scalar constant or a splat vector of constants,
3825       // handle it quickly.
3826       const auto *CI = dyn_cast<ConstantInt>(Idx);
3827       if (!CI && isa<ConstantDataVector>(Idx) &&
3828           cast<ConstantDataVector>(Idx)->getSplatValue())
3829         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3830 
3831       if (CI) {
3832         if (CI->isZero())
3833           continue;
3834         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3835         LLVMContext &Context = *DAG.getContext();
3836         SDValue OffsVal = VectorWidth ?
3837           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3838           DAG.getConstant(Offs, dl, IdxTy);
3839 
3840         // In an inbouds GEP with an offset that is nonnegative even when
3841         // interpreted as signed, assume there is no unsigned overflow.
3842         SDNodeFlags Flags;
3843         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3844           Flags.setNoUnsignedWrap(true);
3845 
3846         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3847         continue;
3848       }
3849 
3850       // N = N + Idx * ElementSize;
3851       SDValue IdxN = getValue(Idx);
3852 
3853       if (!IdxN.getValueType().isVector() && VectorWidth) {
3854         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3855         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3856       }
3857 
3858       // If the index is smaller or larger than intptr_t, truncate or extend
3859       // it.
3860       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3861 
3862       // If this is a multiply by a power of two, turn it into a shl
3863       // immediately.  This is a very common case.
3864       if (ElementSize != 1) {
3865         if (ElementSize.isPowerOf2()) {
3866           unsigned Amt = ElementSize.logBase2();
3867           IdxN = DAG.getNode(ISD::SHL, dl,
3868                              N.getValueType(), IdxN,
3869                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3870         } else {
3871           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3872           IdxN = DAG.getNode(ISD::MUL, dl,
3873                              N.getValueType(), IdxN, Scale);
3874         }
3875       }
3876 
3877       N = DAG.getNode(ISD::ADD, dl,
3878                       N.getValueType(), N, IdxN);
3879     }
3880   }
3881 
3882   setValue(&I, N);
3883 }
3884 
3885 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3886   // If this is a fixed sized alloca in the entry block of the function,
3887   // allocate it statically on the stack.
3888   if (FuncInfo.StaticAllocaMap.count(&I))
3889     return;   // getValue will auto-populate this.
3890 
3891   SDLoc dl = getCurSDLoc();
3892   Type *Ty = I.getAllocatedType();
3893   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3894   auto &DL = DAG.getDataLayout();
3895   uint64_t TySize = DL.getTypeAllocSize(Ty);
3896   unsigned Align =
3897       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3898 
3899   SDValue AllocSize = getValue(I.getArraySize());
3900 
3901   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3902   if (AllocSize.getValueType() != IntPtr)
3903     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3904 
3905   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3906                           AllocSize,
3907                           DAG.getConstant(TySize, dl, IntPtr));
3908 
3909   // Handle alignment.  If the requested alignment is less than or equal to
3910   // the stack alignment, ignore it.  If the size is greater than or equal to
3911   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3912   unsigned StackAlign =
3913       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3914   if (Align <= StackAlign)
3915     Align = 0;
3916 
3917   // Round the size of the allocation up to the stack alignment size
3918   // by add SA-1 to the size. This doesn't overflow because we're computing
3919   // an address inside an alloca.
3920   SDNodeFlags Flags;
3921   Flags.setNoUnsignedWrap(true);
3922   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3923                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3924 
3925   // Mask out the low bits for alignment purposes.
3926   AllocSize =
3927       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3928                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3929 
3930   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3931   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3932   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3933   setValue(&I, DSA);
3934   DAG.setRoot(DSA.getValue(1));
3935 
3936   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3937 }
3938 
3939 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3940   if (I.isAtomic())
3941     return visitAtomicLoad(I);
3942 
3943   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3944   const Value *SV = I.getOperand(0);
3945   if (TLI.supportSwiftError()) {
3946     // Swifterror values can come from either a function parameter with
3947     // swifterror attribute or an alloca with swifterror attribute.
3948     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3949       if (Arg->hasSwiftErrorAttr())
3950         return visitLoadFromSwiftError(I);
3951     }
3952 
3953     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3954       if (Alloca->isSwiftError())
3955         return visitLoadFromSwiftError(I);
3956     }
3957   }
3958 
3959   SDValue Ptr = getValue(SV);
3960 
3961   Type *Ty = I.getType();
3962 
3963   bool isVolatile = I.isVolatile();
3964   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3965   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3966   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3967   unsigned Alignment = I.getAlignment();
3968 
3969   AAMDNodes AAInfo;
3970   I.getAAMetadata(AAInfo);
3971   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3972 
3973   SmallVector<EVT, 4> ValueVTs;
3974   SmallVector<uint64_t, 4> Offsets;
3975   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3976   unsigned NumValues = ValueVTs.size();
3977   if (NumValues == 0)
3978     return;
3979 
3980   SDValue Root;
3981   bool ConstantMemory = false;
3982   if (isVolatile || NumValues > MaxParallelChains)
3983     // Serialize volatile loads with other side effects.
3984     Root = getRoot();
3985   else if (AA &&
3986            AA->pointsToConstantMemory(MemoryLocation(
3987                SV,
3988                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3989                AAInfo))) {
3990     // Do not serialize (non-volatile) loads of constant memory with anything.
3991     Root = DAG.getEntryNode();
3992     ConstantMemory = true;
3993   } else {
3994     // Do not serialize non-volatile loads against each other.
3995     Root = DAG.getRoot();
3996   }
3997 
3998   SDLoc dl = getCurSDLoc();
3999 
4000   if (isVolatile)
4001     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4002 
4003   // An aggregate load cannot wrap around the address space, so offsets to its
4004   // parts don't wrap either.
4005   SDNodeFlags Flags;
4006   Flags.setNoUnsignedWrap(true);
4007 
4008   SmallVector<SDValue, 4> Values(NumValues);
4009   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4010   EVT PtrVT = Ptr.getValueType();
4011   unsigned ChainI = 0;
4012   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4013     // Serializing loads here may result in excessive register pressure, and
4014     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4015     // could recover a bit by hoisting nodes upward in the chain by recognizing
4016     // they are side-effect free or do not alias. The optimizer should really
4017     // avoid this case by converting large object/array copies to llvm.memcpy
4018     // (MaxParallelChains should always remain as failsafe).
4019     if (ChainI == MaxParallelChains) {
4020       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4021       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4022                                   makeArrayRef(Chains.data(), ChainI));
4023       Root = Chain;
4024       ChainI = 0;
4025     }
4026     SDValue A = DAG.getNode(ISD::ADD, dl,
4027                             PtrVT, Ptr,
4028                             DAG.getConstant(Offsets[i], dl, PtrVT),
4029                             Flags);
4030     auto MMOFlags = MachineMemOperand::MONone;
4031     if (isVolatile)
4032       MMOFlags |= MachineMemOperand::MOVolatile;
4033     if (isNonTemporal)
4034       MMOFlags |= MachineMemOperand::MONonTemporal;
4035     if (isInvariant)
4036       MMOFlags |= MachineMemOperand::MOInvariant;
4037     if (isDereferenceable)
4038       MMOFlags |= MachineMemOperand::MODereferenceable;
4039     MMOFlags |= TLI.getMMOFlags(I);
4040 
4041     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
4042                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4043                             MMOFlags, AAInfo, Ranges);
4044 
4045     Values[i] = L;
4046     Chains[ChainI] = L.getValue(1);
4047   }
4048 
4049   if (!ConstantMemory) {
4050     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4051                                 makeArrayRef(Chains.data(), ChainI));
4052     if (isVolatile)
4053       DAG.setRoot(Chain);
4054     else
4055       PendingLoads.push_back(Chain);
4056   }
4057 
4058   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4059                            DAG.getVTList(ValueVTs), Values));
4060 }
4061 
4062 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4063   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4064          "call visitStoreToSwiftError when backend supports swifterror");
4065 
4066   SmallVector<EVT, 4> ValueVTs;
4067   SmallVector<uint64_t, 4> Offsets;
4068   const Value *SrcV = I.getOperand(0);
4069   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4070                   SrcV->getType(), ValueVTs, &Offsets);
4071   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4072          "expect a single EVT for swifterror");
4073 
4074   SDValue Src = getValue(SrcV);
4075   // Create a virtual register, then update the virtual register.
4076   unsigned VReg; bool CreatedVReg;
4077   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
4078   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4079   // Chain can be getRoot or getControlRoot.
4080   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4081                                       SDValue(Src.getNode(), Src.getResNo()));
4082   DAG.setRoot(CopyNode);
4083   if (CreatedVReg)
4084     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
4085 }
4086 
4087 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4088   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4089          "call visitLoadFromSwiftError when backend supports swifterror");
4090 
4091   assert(!I.isVolatile() &&
4092          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
4093          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
4094          "Support volatile, non temporal, invariant for load_from_swift_error");
4095 
4096   const Value *SV = I.getOperand(0);
4097   Type *Ty = I.getType();
4098   AAMDNodes AAInfo;
4099   I.getAAMetadata(AAInfo);
4100   assert(
4101       (!AA ||
4102        !AA->pointsToConstantMemory(MemoryLocation(
4103            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4104            AAInfo))) &&
4105       "load_from_swift_error should not be constant memory");
4106 
4107   SmallVector<EVT, 4> ValueVTs;
4108   SmallVector<uint64_t, 4> Offsets;
4109   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4110                   ValueVTs, &Offsets);
4111   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4112          "expect a single EVT for swifterror");
4113 
4114   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4115   SDValue L = DAG.getCopyFromReg(
4116       getRoot(), getCurSDLoc(),
4117       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
4118       ValueVTs[0]);
4119 
4120   setValue(&I, L);
4121 }
4122 
4123 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4124   if (I.isAtomic())
4125     return visitAtomicStore(I);
4126 
4127   const Value *SrcV = I.getOperand(0);
4128   const Value *PtrV = I.getOperand(1);
4129 
4130   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4131   if (TLI.supportSwiftError()) {
4132     // Swifterror values can come from either a function parameter with
4133     // swifterror attribute or an alloca with swifterror attribute.
4134     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4135       if (Arg->hasSwiftErrorAttr())
4136         return visitStoreToSwiftError(I);
4137     }
4138 
4139     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4140       if (Alloca->isSwiftError())
4141         return visitStoreToSwiftError(I);
4142     }
4143   }
4144 
4145   SmallVector<EVT, 4> ValueVTs;
4146   SmallVector<uint64_t, 4> Offsets;
4147   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4148                   SrcV->getType(), ValueVTs, &Offsets);
4149   unsigned NumValues = ValueVTs.size();
4150   if (NumValues == 0)
4151     return;
4152 
4153   // Get the lowered operands. Note that we do this after
4154   // checking if NumResults is zero, because with zero results
4155   // the operands won't have values in the map.
4156   SDValue Src = getValue(SrcV);
4157   SDValue Ptr = getValue(PtrV);
4158 
4159   SDValue Root = getRoot();
4160   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4161   SDLoc dl = getCurSDLoc();
4162   EVT PtrVT = Ptr.getValueType();
4163   unsigned Alignment = I.getAlignment();
4164   AAMDNodes AAInfo;
4165   I.getAAMetadata(AAInfo);
4166 
4167   auto MMOFlags = MachineMemOperand::MONone;
4168   if (I.isVolatile())
4169     MMOFlags |= MachineMemOperand::MOVolatile;
4170   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
4171     MMOFlags |= MachineMemOperand::MONonTemporal;
4172   MMOFlags |= TLI.getMMOFlags(I);
4173 
4174   // An aggregate load cannot wrap around the address space, so offsets to its
4175   // parts don't wrap either.
4176   SDNodeFlags Flags;
4177   Flags.setNoUnsignedWrap(true);
4178 
4179   unsigned ChainI = 0;
4180   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4181     // See visitLoad comments.
4182     if (ChainI == MaxParallelChains) {
4183       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4184                                   makeArrayRef(Chains.data(), ChainI));
4185       Root = Chain;
4186       ChainI = 0;
4187     }
4188     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
4189                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
4190     SDValue St = DAG.getStore(
4191         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
4192         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
4193     Chains[ChainI] = St;
4194   }
4195 
4196   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4197                                   makeArrayRef(Chains.data(), ChainI));
4198   DAG.setRoot(StoreNode);
4199 }
4200 
4201 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4202                                            bool IsCompressing) {
4203   SDLoc sdl = getCurSDLoc();
4204 
4205   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4206                            unsigned& Alignment) {
4207     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4208     Src0 = I.getArgOperand(0);
4209     Ptr = I.getArgOperand(1);
4210     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4211     Mask = I.getArgOperand(3);
4212   };
4213   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4214                            unsigned& Alignment) {
4215     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4216     Src0 = I.getArgOperand(0);
4217     Ptr = I.getArgOperand(1);
4218     Mask = I.getArgOperand(2);
4219     Alignment = 0;
4220   };
4221 
4222   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4223   unsigned Alignment;
4224   if (IsCompressing)
4225     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4226   else
4227     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4228 
4229   SDValue Ptr = getValue(PtrOperand);
4230   SDValue Src0 = getValue(Src0Operand);
4231   SDValue Mask = getValue(MaskOperand);
4232 
4233   EVT VT = Src0.getValueType();
4234   if (!Alignment)
4235     Alignment = DAG.getEVTAlignment(VT);
4236 
4237   AAMDNodes AAInfo;
4238   I.getAAMetadata(AAInfo);
4239 
4240   MachineMemOperand *MMO =
4241     DAG.getMachineFunction().
4242     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4243                           MachineMemOperand::MOStore,  VT.getStoreSize(),
4244                           Alignment, AAInfo);
4245   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
4246                                          MMO, false /* Truncating */,
4247                                          IsCompressing);
4248   DAG.setRoot(StoreNode);
4249   setValue(&I, StoreNode);
4250 }
4251 
4252 // Get a uniform base for the Gather/Scatter intrinsic.
4253 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4254 // We try to represent it as a base pointer + vector of indices.
4255 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4256 // The first operand of the GEP may be a single pointer or a vector of pointers
4257 // Example:
4258 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4259 //  or
4260 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4261 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4262 //
4263 // When the first GEP operand is a single pointer - it is the uniform base we
4264 // are looking for. If first operand of the GEP is a splat vector - we
4265 // extract the splat value and use it as a uniform base.
4266 // In all other cases the function returns 'false'.
4267 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
4268                            SDValue &Scale, SelectionDAGBuilder* SDB) {
4269   SelectionDAG& DAG = SDB->DAG;
4270   LLVMContext &Context = *DAG.getContext();
4271 
4272   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4273   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4274   if (!GEP)
4275     return false;
4276 
4277   const Value *GEPPtr = GEP->getPointerOperand();
4278   if (!GEPPtr->getType()->isVectorTy())
4279     Ptr = GEPPtr;
4280   else if (!(Ptr = getSplatValue(GEPPtr)))
4281     return false;
4282 
4283   unsigned FinalIndex = GEP->getNumOperands() - 1;
4284   Value *IndexVal = GEP->getOperand(FinalIndex);
4285 
4286   // Ensure all the other indices are 0.
4287   for (unsigned i = 1; i < FinalIndex; ++i) {
4288     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
4289     if (!C || !C->isZero())
4290       return false;
4291   }
4292 
4293   // The operands of the GEP may be defined in another basic block.
4294   // In this case we'll not find nodes for the operands.
4295   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
4296     return false;
4297 
4298   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4299   const DataLayout &DL = DAG.getDataLayout();
4300   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4301                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4302   Base = SDB->getValue(Ptr);
4303   Index = SDB->getValue(IndexVal);
4304 
4305   if (!Index.getValueType().isVector()) {
4306     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4307     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4308     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4309   }
4310   return true;
4311 }
4312 
4313 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4314   SDLoc sdl = getCurSDLoc();
4315 
4316   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4317   const Value *Ptr = I.getArgOperand(1);
4318   SDValue Src0 = getValue(I.getArgOperand(0));
4319   SDValue Mask = getValue(I.getArgOperand(3));
4320   EVT VT = Src0.getValueType();
4321   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4322   if (!Alignment)
4323     Alignment = DAG.getEVTAlignment(VT);
4324   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4325 
4326   AAMDNodes AAInfo;
4327   I.getAAMetadata(AAInfo);
4328 
4329   SDValue Base;
4330   SDValue Index;
4331   SDValue Scale;
4332   const Value *BasePtr = Ptr;
4333   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4334 
4335   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4336   MachineMemOperand *MMO = DAG.getMachineFunction().
4337     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4338                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4339                          Alignment, AAInfo);
4340   if (!UniformBase) {
4341     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4342     Index = getValue(Ptr);
4343     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4344   }
4345   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4346   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4347                                          Ops, MMO);
4348   DAG.setRoot(Scatter);
4349   setValue(&I, Scatter);
4350 }
4351 
4352 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4353   SDLoc sdl = getCurSDLoc();
4354 
4355   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4356                            unsigned& Alignment) {
4357     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4358     Ptr = I.getArgOperand(0);
4359     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4360     Mask = I.getArgOperand(2);
4361     Src0 = I.getArgOperand(3);
4362   };
4363   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4364                            unsigned& Alignment) {
4365     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4366     Ptr = I.getArgOperand(0);
4367     Alignment = 0;
4368     Mask = I.getArgOperand(1);
4369     Src0 = I.getArgOperand(2);
4370   };
4371 
4372   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4373   unsigned Alignment;
4374   if (IsExpanding)
4375     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4376   else
4377     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4378 
4379   SDValue Ptr = getValue(PtrOperand);
4380   SDValue Src0 = getValue(Src0Operand);
4381   SDValue Mask = getValue(MaskOperand);
4382 
4383   EVT VT = Src0.getValueType();
4384   if (!Alignment)
4385     Alignment = DAG.getEVTAlignment(VT);
4386 
4387   AAMDNodes AAInfo;
4388   I.getAAMetadata(AAInfo);
4389   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4390 
4391   // Do not serialize masked loads of constant memory with anything.
4392   bool AddToChain =
4393       !AA || !AA->pointsToConstantMemory(MemoryLocation(
4394                  PtrOperand,
4395                  LocationSize::precise(
4396                      DAG.getDataLayout().getTypeStoreSize(I.getType())),
4397                  AAInfo));
4398   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4399 
4400   MachineMemOperand *MMO =
4401     DAG.getMachineFunction().
4402     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4403                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4404                           Alignment, AAInfo, Ranges);
4405 
4406   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4407                                    ISD::NON_EXTLOAD, IsExpanding);
4408   if (AddToChain)
4409     PendingLoads.push_back(Load.getValue(1));
4410   setValue(&I, Load);
4411 }
4412 
4413 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4414   SDLoc sdl = getCurSDLoc();
4415 
4416   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4417   const Value *Ptr = I.getArgOperand(0);
4418   SDValue Src0 = getValue(I.getArgOperand(3));
4419   SDValue Mask = getValue(I.getArgOperand(2));
4420 
4421   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4422   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4423   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4424   if (!Alignment)
4425     Alignment = DAG.getEVTAlignment(VT);
4426 
4427   AAMDNodes AAInfo;
4428   I.getAAMetadata(AAInfo);
4429   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4430 
4431   SDValue Root = DAG.getRoot();
4432   SDValue Base;
4433   SDValue Index;
4434   SDValue Scale;
4435   const Value *BasePtr = Ptr;
4436   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4437   bool ConstantMemory = false;
4438   if (UniformBase && AA &&
4439       AA->pointsToConstantMemory(
4440           MemoryLocation(BasePtr,
4441                          LocationSize::precise(
4442                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4443                          AAInfo))) {
4444     // Do not serialize (non-volatile) loads of constant memory with anything.
4445     Root = DAG.getEntryNode();
4446     ConstantMemory = true;
4447   }
4448 
4449   MachineMemOperand *MMO =
4450     DAG.getMachineFunction().
4451     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4452                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4453                          Alignment, AAInfo, Ranges);
4454 
4455   if (!UniformBase) {
4456     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4457     Index = getValue(Ptr);
4458     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4459   }
4460   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4461   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4462                                        Ops, MMO);
4463 
4464   SDValue OutChain = Gather.getValue(1);
4465   if (!ConstantMemory)
4466     PendingLoads.push_back(OutChain);
4467   setValue(&I, Gather);
4468 }
4469 
4470 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4471   SDLoc dl = getCurSDLoc();
4472   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4473   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4474   SyncScope::ID SSID = I.getSyncScopeID();
4475 
4476   SDValue InChain = getRoot();
4477 
4478   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4479   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4480 
4481   auto Alignment = DAG.getEVTAlignment(MemVT);
4482 
4483   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4484   if (I.isVolatile())
4485     Flags |= MachineMemOperand::MOVolatile;
4486   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4487 
4488   MachineFunction &MF = DAG.getMachineFunction();
4489   MachineMemOperand *MMO =
4490     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4491                             Flags, MemVT.getStoreSize(), Alignment,
4492                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4493                             FailureOrdering);
4494 
4495   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4496                                    dl, MemVT, VTs, InChain,
4497                                    getValue(I.getPointerOperand()),
4498                                    getValue(I.getCompareOperand()),
4499                                    getValue(I.getNewValOperand()), MMO);
4500 
4501   SDValue OutChain = L.getValue(2);
4502 
4503   setValue(&I, L);
4504   DAG.setRoot(OutChain);
4505 }
4506 
4507 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4508   SDLoc dl = getCurSDLoc();
4509   ISD::NodeType NT;
4510   switch (I.getOperation()) {
4511   default: llvm_unreachable("Unknown atomicrmw operation");
4512   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4513   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4514   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4515   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4516   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4517   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4518   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4519   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4520   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4521   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4522   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4523   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4524   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4525   }
4526   AtomicOrdering Ordering = I.getOrdering();
4527   SyncScope::ID SSID = I.getSyncScopeID();
4528 
4529   SDValue InChain = getRoot();
4530 
4531   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4532   auto Alignment = DAG.getEVTAlignment(MemVT);
4533 
4534   auto Flags = MachineMemOperand::MOLoad |  MachineMemOperand::MOStore;
4535   if (I.isVolatile())
4536     Flags |= MachineMemOperand::MOVolatile;
4537   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4538 
4539   MachineFunction &MF = DAG.getMachineFunction();
4540   MachineMemOperand *MMO =
4541     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4542                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4543                             nullptr, SSID, Ordering);
4544 
4545   SDValue L =
4546     DAG.getAtomic(NT, dl, MemVT, InChain,
4547                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4548                   MMO);
4549 
4550   SDValue OutChain = L.getValue(1);
4551 
4552   setValue(&I, L);
4553   DAG.setRoot(OutChain);
4554 }
4555 
4556 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4557   SDLoc dl = getCurSDLoc();
4558   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4559   SDValue Ops[3];
4560   Ops[0] = getRoot();
4561   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4562                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4563   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4564                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4565   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4566 }
4567 
4568 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4569   SDLoc dl = getCurSDLoc();
4570   AtomicOrdering Order = I.getOrdering();
4571   SyncScope::ID SSID = I.getSyncScopeID();
4572 
4573   SDValue InChain = getRoot();
4574 
4575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4576   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4577 
4578   if (!TLI.supportsUnalignedAtomics() &&
4579       I.getAlignment() < VT.getStoreSize())
4580     report_fatal_error("Cannot generate unaligned atomic load");
4581 
4582   auto Flags = MachineMemOperand::MOLoad;
4583   if (I.isVolatile())
4584     Flags |= MachineMemOperand::MOVolatile;
4585   if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr)
4586     Flags |= MachineMemOperand::MOInvariant;
4587   if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout()))
4588     Flags |= MachineMemOperand::MODereferenceable;
4589 
4590   Flags |= TLI.getMMOFlags(I);
4591 
4592   MachineMemOperand *MMO =
4593       DAG.getMachineFunction().
4594       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4595                            Flags, VT.getStoreSize(),
4596                            I.getAlignment() ? I.getAlignment() :
4597                                               DAG.getEVTAlignment(VT),
4598                            AAMDNodes(), nullptr, SSID, Order);
4599 
4600   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4601   SDValue L =
4602       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4603                     getValue(I.getPointerOperand()), MMO);
4604 
4605   SDValue OutChain = L.getValue(1);
4606 
4607   setValue(&I, L);
4608   DAG.setRoot(OutChain);
4609 }
4610 
4611 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4612   SDLoc dl = getCurSDLoc();
4613 
4614   AtomicOrdering Ordering = I.getOrdering();
4615   SyncScope::ID SSID = I.getSyncScopeID();
4616 
4617   SDValue InChain = getRoot();
4618 
4619   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4620   EVT VT =
4621       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4622 
4623   if (I.getAlignment() < VT.getStoreSize())
4624     report_fatal_error("Cannot generate unaligned atomic store");
4625 
4626   auto Flags = MachineMemOperand::MOStore;
4627   if (I.isVolatile())
4628     Flags |= MachineMemOperand::MOVolatile;
4629   Flags |= TLI.getMMOFlags(I);
4630 
4631   MachineFunction &MF = DAG.getMachineFunction();
4632   MachineMemOperand *MMO =
4633     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4634                             VT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4635                             nullptr, SSID, Ordering);
4636   SDValue OutChain =
4637     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, InChain,
4638               getValue(I.getPointerOperand()), getValue(I.getValueOperand()),
4639               MMO);
4640 
4641 
4642   DAG.setRoot(OutChain);
4643 }
4644 
4645 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4646 /// node.
4647 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4648                                                unsigned Intrinsic) {
4649   // Ignore the callsite's attributes. A specific call site may be marked with
4650   // readnone, but the lowering code will expect the chain based on the
4651   // definition.
4652   const Function *F = I.getCalledFunction();
4653   bool HasChain = !F->doesNotAccessMemory();
4654   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4655 
4656   // Build the operand list.
4657   SmallVector<SDValue, 8> Ops;
4658   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4659     if (OnlyLoad) {
4660       // We don't need to serialize loads against other loads.
4661       Ops.push_back(DAG.getRoot());
4662     } else {
4663       Ops.push_back(getRoot());
4664     }
4665   }
4666 
4667   // Info is set by getTgtMemInstrinsic
4668   TargetLowering::IntrinsicInfo Info;
4669   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4670   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4671                                                DAG.getMachineFunction(),
4672                                                Intrinsic);
4673 
4674   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4675   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4676       Info.opc == ISD::INTRINSIC_W_CHAIN)
4677     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4678                                         TLI.getPointerTy(DAG.getDataLayout())));
4679 
4680   // Add all operands of the call to the operand list.
4681   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4682     SDValue Op = getValue(I.getArgOperand(i));
4683     Ops.push_back(Op);
4684   }
4685 
4686   SmallVector<EVT, 4> ValueVTs;
4687   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4688 
4689   if (HasChain)
4690     ValueVTs.push_back(MVT::Other);
4691 
4692   SDVTList VTs = DAG.getVTList(ValueVTs);
4693 
4694   // Create the node.
4695   SDValue Result;
4696   if (IsTgtIntrinsic) {
4697     // This is target intrinsic that touches memory
4698     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4699       Ops, Info.memVT,
4700       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4701       Info.flags, Info.size);
4702   } else if (!HasChain) {
4703     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4704   } else if (!I.getType()->isVoidTy()) {
4705     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4706   } else {
4707     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4708   }
4709 
4710   if (HasChain) {
4711     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4712     if (OnlyLoad)
4713       PendingLoads.push_back(Chain);
4714     else
4715       DAG.setRoot(Chain);
4716   }
4717 
4718   if (!I.getType()->isVoidTy()) {
4719     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4720       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4721       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4722     } else
4723       Result = lowerRangeToAssertZExt(DAG, I, Result);
4724 
4725     setValue(&I, Result);
4726   }
4727 }
4728 
4729 /// GetSignificand - Get the significand and build it into a floating-point
4730 /// number with exponent of 1:
4731 ///
4732 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4733 ///
4734 /// where Op is the hexadecimal representation of floating point value.
4735 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4736   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4737                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4738   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4739                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4740   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4741 }
4742 
4743 /// GetExponent - Get the exponent:
4744 ///
4745 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4746 ///
4747 /// where Op is the hexadecimal representation of floating point value.
4748 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4749                            const TargetLowering &TLI, const SDLoc &dl) {
4750   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4751                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4752   SDValue t1 = DAG.getNode(
4753       ISD::SRL, dl, MVT::i32, t0,
4754       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4755   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4756                            DAG.getConstant(127, dl, MVT::i32));
4757   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4758 }
4759 
4760 /// getF32Constant - Get 32-bit floating point constant.
4761 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4762                               const SDLoc &dl) {
4763   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4764                            MVT::f32);
4765 }
4766 
4767 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4768                                        SelectionDAG &DAG) {
4769   // TODO: What fast-math-flags should be set on the floating-point nodes?
4770 
4771   //   IntegerPartOfX = ((int32_t)(t0);
4772   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4773 
4774   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4775   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4776   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4777 
4778   //   IntegerPartOfX <<= 23;
4779   IntegerPartOfX = DAG.getNode(
4780       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4781       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4782                                   DAG.getDataLayout())));
4783 
4784   SDValue TwoToFractionalPartOfX;
4785   if (LimitFloatPrecision <= 6) {
4786     // For floating-point precision of 6:
4787     //
4788     //   TwoToFractionalPartOfX =
4789     //     0.997535578f +
4790     //       (0.735607626f + 0.252464424f * x) * x;
4791     //
4792     // error 0.0144103317, which is 6 bits
4793     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4794                              getF32Constant(DAG, 0x3e814304, dl));
4795     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4796                              getF32Constant(DAG, 0x3f3c50c8, dl));
4797     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4798     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4799                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4800   } else if (LimitFloatPrecision <= 12) {
4801     // For floating-point precision of 12:
4802     //
4803     //   TwoToFractionalPartOfX =
4804     //     0.999892986f +
4805     //       (0.696457318f +
4806     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4807     //
4808     // error 0.000107046256, which is 13 to 14 bits
4809     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4810                              getF32Constant(DAG, 0x3da235e3, dl));
4811     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4812                              getF32Constant(DAG, 0x3e65b8f3, dl));
4813     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4814     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4815                              getF32Constant(DAG, 0x3f324b07, dl));
4816     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4817     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4818                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4819   } else { // LimitFloatPrecision <= 18
4820     // For floating-point precision of 18:
4821     //
4822     //   TwoToFractionalPartOfX =
4823     //     0.999999982f +
4824     //       (0.693148872f +
4825     //         (0.240227044f +
4826     //           (0.554906021e-1f +
4827     //             (0.961591928e-2f +
4828     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4829     // error 2.47208000*10^(-7), which is better than 18 bits
4830     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4831                              getF32Constant(DAG, 0x3924b03e, dl));
4832     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4833                              getF32Constant(DAG, 0x3ab24b87, dl));
4834     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4835     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4836                              getF32Constant(DAG, 0x3c1d8c17, dl));
4837     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4838     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4839                              getF32Constant(DAG, 0x3d634a1d, dl));
4840     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4841     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4842                              getF32Constant(DAG, 0x3e75fe14, dl));
4843     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4844     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4845                               getF32Constant(DAG, 0x3f317234, dl));
4846     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4847     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4848                                          getF32Constant(DAG, 0x3f800000, dl));
4849   }
4850 
4851   // Add the exponent into the result in integer domain.
4852   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4853   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4854                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4855 }
4856 
4857 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4858 /// limited-precision mode.
4859 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4860                          const TargetLowering &TLI) {
4861   if (Op.getValueType() == MVT::f32 &&
4862       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4863 
4864     // Put the exponent in the right bit position for later addition to the
4865     // final result:
4866     //
4867     //   #define LOG2OFe 1.4426950f
4868     //   t0 = Op * LOG2OFe
4869 
4870     // TODO: What fast-math-flags should be set here?
4871     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4872                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4873     return getLimitedPrecisionExp2(t0, dl, DAG);
4874   }
4875 
4876   // No special expansion.
4877   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4878 }
4879 
4880 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4881 /// limited-precision mode.
4882 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4883                          const TargetLowering &TLI) {
4884   // TODO: What fast-math-flags should be set on the floating-point nodes?
4885 
4886   if (Op.getValueType() == MVT::f32 &&
4887       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4888     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4889 
4890     // Scale the exponent by log(2) [0.69314718f].
4891     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4892     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4893                                         getF32Constant(DAG, 0x3f317218, dl));
4894 
4895     // Get the significand and build it into a floating-point number with
4896     // exponent of 1.
4897     SDValue X = GetSignificand(DAG, Op1, dl);
4898 
4899     SDValue LogOfMantissa;
4900     if (LimitFloatPrecision <= 6) {
4901       // For floating-point precision of 6:
4902       //
4903       //   LogofMantissa =
4904       //     -1.1609546f +
4905       //       (1.4034025f - 0.23903021f * x) * x;
4906       //
4907       // error 0.0034276066, which is better than 8 bits
4908       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4909                                getF32Constant(DAG, 0xbe74c456, dl));
4910       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4911                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4912       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4913       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4914                                   getF32Constant(DAG, 0x3f949a29, dl));
4915     } else if (LimitFloatPrecision <= 12) {
4916       // For floating-point precision of 12:
4917       //
4918       //   LogOfMantissa =
4919       //     -1.7417939f +
4920       //       (2.8212026f +
4921       //         (-1.4699568f +
4922       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4923       //
4924       // error 0.000061011436, which is 14 bits
4925       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4926                                getF32Constant(DAG, 0xbd67b6d6, dl));
4927       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4928                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4929       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4930       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4931                                getF32Constant(DAG, 0x3fbc278b, dl));
4932       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4933       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4934                                getF32Constant(DAG, 0x40348e95, dl));
4935       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4936       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4937                                   getF32Constant(DAG, 0x3fdef31a, dl));
4938     } else { // LimitFloatPrecision <= 18
4939       // For floating-point precision of 18:
4940       //
4941       //   LogOfMantissa =
4942       //     -2.1072184f +
4943       //       (4.2372794f +
4944       //         (-3.7029485f +
4945       //           (2.2781945f +
4946       //             (-0.87823314f +
4947       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4948       //
4949       // error 0.0000023660568, which is better than 18 bits
4950       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4951                                getF32Constant(DAG, 0xbc91e5ac, dl));
4952       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4953                                getF32Constant(DAG, 0x3e4350aa, dl));
4954       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4955       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4956                                getF32Constant(DAG, 0x3f60d3e3, dl));
4957       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4958       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4959                                getF32Constant(DAG, 0x4011cdf0, dl));
4960       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4961       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4962                                getF32Constant(DAG, 0x406cfd1c, dl));
4963       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4964       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4965                                getF32Constant(DAG, 0x408797cb, dl));
4966       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4967       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4968                                   getF32Constant(DAG, 0x4006dcab, dl));
4969     }
4970 
4971     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4972   }
4973 
4974   // No special expansion.
4975   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4976 }
4977 
4978 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4979 /// limited-precision mode.
4980 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4981                           const TargetLowering &TLI) {
4982   // TODO: What fast-math-flags should be set on the floating-point nodes?
4983 
4984   if (Op.getValueType() == MVT::f32 &&
4985       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4986     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4987 
4988     // Get the exponent.
4989     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4990 
4991     // Get the significand and build it into a floating-point number with
4992     // exponent of 1.
4993     SDValue X = GetSignificand(DAG, Op1, dl);
4994 
4995     // Different possible minimax approximations of significand in
4996     // floating-point for various degrees of accuracy over [1,2].
4997     SDValue Log2ofMantissa;
4998     if (LimitFloatPrecision <= 6) {
4999       // For floating-point precision of 6:
5000       //
5001       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5002       //
5003       // error 0.0049451742, which is more than 7 bits
5004       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5005                                getF32Constant(DAG, 0xbeb08fe0, dl));
5006       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5007                                getF32Constant(DAG, 0x40019463, dl));
5008       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5009       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5010                                    getF32Constant(DAG, 0x3fd6633d, dl));
5011     } else if (LimitFloatPrecision <= 12) {
5012       // For floating-point precision of 12:
5013       //
5014       //   Log2ofMantissa =
5015       //     -2.51285454f +
5016       //       (4.07009056f +
5017       //         (-2.12067489f +
5018       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5019       //
5020       // error 0.0000876136000, which is better than 13 bits
5021       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5022                                getF32Constant(DAG, 0xbda7262e, dl));
5023       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5024                                getF32Constant(DAG, 0x3f25280b, dl));
5025       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5026       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5027                                getF32Constant(DAG, 0x4007b923, dl));
5028       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5029       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5030                                getF32Constant(DAG, 0x40823e2f, dl));
5031       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5032       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5033                                    getF32Constant(DAG, 0x4020d29c, dl));
5034     } else { // LimitFloatPrecision <= 18
5035       // For floating-point precision of 18:
5036       //
5037       //   Log2ofMantissa =
5038       //     -3.0400495f +
5039       //       (6.1129976f +
5040       //         (-5.3420409f +
5041       //           (3.2865683f +
5042       //             (-1.2669343f +
5043       //               (0.27515199f -
5044       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5045       //
5046       // error 0.0000018516, which is better than 18 bits
5047       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5048                                getF32Constant(DAG, 0xbcd2769e, dl));
5049       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5050                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5051       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5052       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5053                                getF32Constant(DAG, 0x3fa22ae7, dl));
5054       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5055       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5056                                getF32Constant(DAG, 0x40525723, dl));
5057       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5058       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5059                                getF32Constant(DAG, 0x40aaf200, dl));
5060       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5061       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5062                                getF32Constant(DAG, 0x40c39dad, dl));
5063       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5064       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5065                                    getF32Constant(DAG, 0x4042902c, dl));
5066     }
5067 
5068     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5069   }
5070 
5071   // No special expansion.
5072   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5073 }
5074 
5075 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5076 /// limited-precision mode.
5077 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5078                            const TargetLowering &TLI) {
5079   // TODO: What fast-math-flags should be set on the floating-point nodes?
5080 
5081   if (Op.getValueType() == MVT::f32 &&
5082       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5083     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5084 
5085     // Scale the exponent by log10(2) [0.30102999f].
5086     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5087     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5088                                         getF32Constant(DAG, 0x3e9a209a, dl));
5089 
5090     // Get the significand and build it into a floating-point number with
5091     // exponent of 1.
5092     SDValue X = GetSignificand(DAG, Op1, dl);
5093 
5094     SDValue Log10ofMantissa;
5095     if (LimitFloatPrecision <= 6) {
5096       // For floating-point precision of 6:
5097       //
5098       //   Log10ofMantissa =
5099       //     -0.50419619f +
5100       //       (0.60948995f - 0.10380950f * x) * x;
5101       //
5102       // error 0.0014886165, which is 6 bits
5103       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5104                                getF32Constant(DAG, 0xbdd49a13, dl));
5105       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5106                                getF32Constant(DAG, 0x3f1c0789, dl));
5107       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5108       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5109                                     getF32Constant(DAG, 0x3f011300, dl));
5110     } else if (LimitFloatPrecision <= 12) {
5111       // For floating-point precision of 12:
5112       //
5113       //   Log10ofMantissa =
5114       //     -0.64831180f +
5115       //       (0.91751397f +
5116       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5117       //
5118       // error 0.00019228036, which is better than 12 bits
5119       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5120                                getF32Constant(DAG, 0x3d431f31, dl));
5121       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5122                                getF32Constant(DAG, 0x3ea21fb2, dl));
5123       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5124       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5125                                getF32Constant(DAG, 0x3f6ae232, dl));
5126       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5127       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5128                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5129     } else { // LimitFloatPrecision <= 18
5130       // For floating-point precision of 18:
5131       //
5132       //   Log10ofMantissa =
5133       //     -0.84299375f +
5134       //       (1.5327582f +
5135       //         (-1.0688956f +
5136       //           (0.49102474f +
5137       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5138       //
5139       // error 0.0000037995730, which is better than 18 bits
5140       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5141                                getF32Constant(DAG, 0x3c5d51ce, dl));
5142       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5143                                getF32Constant(DAG, 0x3e00685a, dl));
5144       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5145       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5146                                getF32Constant(DAG, 0x3efb6798, dl));
5147       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5148       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5149                                getF32Constant(DAG, 0x3f88d192, dl));
5150       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5151       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5152                                getF32Constant(DAG, 0x3fc4316c, dl));
5153       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5154       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5155                                     getF32Constant(DAG, 0x3f57ce70, dl));
5156     }
5157 
5158     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5159   }
5160 
5161   // No special expansion.
5162   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5163 }
5164 
5165 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5166 /// limited-precision mode.
5167 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5168                           const TargetLowering &TLI) {
5169   if (Op.getValueType() == MVT::f32 &&
5170       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5171     return getLimitedPrecisionExp2(Op, dl, DAG);
5172 
5173   // No special expansion.
5174   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5175 }
5176 
5177 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5178 /// limited-precision mode with x == 10.0f.
5179 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5180                          SelectionDAG &DAG, const TargetLowering &TLI) {
5181   bool IsExp10 = false;
5182   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5183       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5184     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5185       APFloat Ten(10.0f);
5186       IsExp10 = LHSC->isExactlyValue(Ten);
5187     }
5188   }
5189 
5190   // TODO: What fast-math-flags should be set on the FMUL node?
5191   if (IsExp10) {
5192     // Put the exponent in the right bit position for later addition to the
5193     // final result:
5194     //
5195     //   #define LOG2OF10 3.3219281f
5196     //   t0 = Op * LOG2OF10;
5197     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5198                              getF32Constant(DAG, 0x40549a78, dl));
5199     return getLimitedPrecisionExp2(t0, dl, DAG);
5200   }
5201 
5202   // No special expansion.
5203   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5204 }
5205 
5206 /// ExpandPowI - Expand a llvm.powi intrinsic.
5207 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5208                           SelectionDAG &DAG) {
5209   // If RHS is a constant, we can expand this out to a multiplication tree,
5210   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5211   // optimizing for size, we only want to do this if the expansion would produce
5212   // a small number of multiplies, otherwise we do the full expansion.
5213   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5214     // Get the exponent as a positive value.
5215     unsigned Val = RHSC->getSExtValue();
5216     if ((int)Val < 0) Val = -Val;
5217 
5218     // powi(x, 0) -> 1.0
5219     if (Val == 0)
5220       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5221 
5222     const Function &F = DAG.getMachineFunction().getFunction();
5223     if (!F.hasOptSize() ||
5224         // If optimizing for size, don't insert too many multiplies.
5225         // This inserts up to 5 multiplies.
5226         countPopulation(Val) + Log2_32(Val) < 7) {
5227       // We use the simple binary decomposition method to generate the multiply
5228       // sequence.  There are more optimal ways to do this (for example,
5229       // powi(x,15) generates one more multiply than it should), but this has
5230       // the benefit of being both really simple and much better than a libcall.
5231       SDValue Res;  // Logically starts equal to 1.0
5232       SDValue CurSquare = LHS;
5233       // TODO: Intrinsics should have fast-math-flags that propagate to these
5234       // nodes.
5235       while (Val) {
5236         if (Val & 1) {
5237           if (Res.getNode())
5238             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5239           else
5240             Res = CurSquare;  // 1.0*CurSquare.
5241         }
5242 
5243         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5244                                 CurSquare, CurSquare);
5245         Val >>= 1;
5246       }
5247 
5248       // If the original was negative, invert the result, producing 1/(x*x*x).
5249       if (RHSC->getSExtValue() < 0)
5250         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5251                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5252       return Res;
5253     }
5254   }
5255 
5256   // Otherwise, expand to a libcall.
5257   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5258 }
5259 
5260 // getUnderlyingArgReg - Find underlying register used for a truncated or
5261 // bitcasted argument.
5262 static unsigned getUnderlyingArgReg(const SDValue &N) {
5263   switch (N.getOpcode()) {
5264   case ISD::CopyFromReg:
5265     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
5266   case ISD::BITCAST:
5267   case ISD::AssertZext:
5268   case ISD::AssertSext:
5269   case ISD::TRUNCATE:
5270     return getUnderlyingArgReg(N.getOperand(0));
5271   default:
5272     return 0;
5273   }
5274 }
5275 
5276 /// If the DbgValueInst is a dbg_value of a function argument, create the
5277 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5278 /// instruction selection, they will be inserted to the entry BB.
5279 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5280     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5281     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5282   const Argument *Arg = dyn_cast<Argument>(V);
5283   if (!Arg)
5284     return false;
5285 
5286   if (!IsDbgDeclare) {
5287     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5288     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5289     // the entry block.
5290     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5291     if (!IsInEntryBlock)
5292       return false;
5293 
5294     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5295     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5296     // variable that also is a param.
5297     //
5298     // Although, if we are at the top of the entry block already, we can still
5299     // emit using ArgDbgValue. This might catch some situations when the
5300     // dbg.value refers to an argument that isn't used in the entry block, so
5301     // any CopyToReg node would be optimized out and the only way to express
5302     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5303     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5304     // we should only emit as ArgDbgValue if the Variable is an argument to the
5305     // current function, and the dbg.value intrinsic is found in the entry
5306     // block.
5307     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5308         !DL->getInlinedAt();
5309     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5310     if (!IsInPrologue && !VariableIsFunctionInputArg)
5311       return false;
5312 
5313     // Here we assume that a function argument on IR level only can be used to
5314     // describe one input parameter on source level. If we for example have
5315     // source code like this
5316     //
5317     //    struct A { long x, y; };
5318     //    void foo(struct A a, long b) {
5319     //      ...
5320     //      b = a.x;
5321     //      ...
5322     //    }
5323     //
5324     // and IR like this
5325     //
5326     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5327     //  entry:
5328     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5329     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5330     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5331     //    ...
5332     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5333     //    ...
5334     //
5335     // then the last dbg.value is describing a parameter "b" using a value that
5336     // is an argument. But since we already has used %a1 to describe a parameter
5337     // we should not handle that last dbg.value here (that would result in an
5338     // incorrect hoisting of the DBG_VALUE to the function entry).
5339     // Notice that we allow one dbg.value per IR level argument, to accomodate
5340     // for the situation with fragments above.
5341     if (VariableIsFunctionInputArg) {
5342       unsigned ArgNo = Arg->getArgNo();
5343       if (ArgNo >= FuncInfo.DescribedArgs.size())
5344         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5345       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5346         return false;
5347       FuncInfo.DescribedArgs.set(ArgNo);
5348     }
5349   }
5350 
5351   MachineFunction &MF = DAG.getMachineFunction();
5352   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5353 
5354   bool IsIndirect = false;
5355   Optional<MachineOperand> Op;
5356   // Some arguments' frame index is recorded during argument lowering.
5357   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5358   if (FI != std::numeric_limits<int>::max())
5359     Op = MachineOperand::CreateFI(FI);
5360 
5361   if (!Op && N.getNode()) {
5362     unsigned Reg = getUnderlyingArgReg(N);
5363     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
5364       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5365       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
5366       if (PR)
5367         Reg = PR;
5368     }
5369     if (Reg) {
5370       Op = MachineOperand::CreateReg(Reg, false);
5371       IsIndirect = IsDbgDeclare;
5372     }
5373   }
5374 
5375   if (!Op && N.getNode()) {
5376     // Check if frame index is available.
5377     SDValue LCandidate = peekThroughBitcasts(N);
5378     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5379       if (FrameIndexSDNode *FINode =
5380           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5381         Op = MachineOperand::CreateFI(FINode->getIndex());
5382   }
5383 
5384   if (!Op) {
5385     // Check if ValueMap has reg number.
5386     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
5387     if (VMI != FuncInfo.ValueMap.end()) {
5388       const auto &TLI = DAG.getTargetLoweringInfo();
5389       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5390                        V->getType(), getABIRegCopyCC(V));
5391       if (RFV.occupiesMultipleRegs()) {
5392         unsigned Offset = 0;
5393         for (auto RegAndSize : RFV.getRegsAndSizes()) {
5394           Op = MachineOperand::CreateReg(RegAndSize.first, false);
5395           auto FragmentExpr = DIExpression::createFragmentExpression(
5396               Expr, Offset, RegAndSize.second);
5397           if (!FragmentExpr)
5398             continue;
5399           FuncInfo.ArgDbgValues.push_back(
5400               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5401                       Op->getReg(), Variable, *FragmentExpr));
5402           Offset += RegAndSize.second;
5403         }
5404         return true;
5405       }
5406       Op = MachineOperand::CreateReg(VMI->second, false);
5407       IsIndirect = IsDbgDeclare;
5408     }
5409   }
5410 
5411   if (!Op)
5412     return false;
5413 
5414   assert(Variable->isValidLocationForIntrinsic(DL) &&
5415          "Expected inlined-at fields to agree");
5416   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5417   FuncInfo.ArgDbgValues.push_back(
5418       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5419               *Op, Variable, Expr));
5420 
5421   return true;
5422 }
5423 
5424 /// Return the appropriate SDDbgValue based on N.
5425 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5426                                              DILocalVariable *Variable,
5427                                              DIExpression *Expr,
5428                                              const DebugLoc &dl,
5429                                              unsigned DbgSDNodeOrder) {
5430   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5431     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5432     // stack slot locations.
5433     //
5434     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5435     // debug values here after optimization:
5436     //
5437     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5438     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5439     //
5440     // Both describe the direct values of their associated variables.
5441     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5442                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5443   }
5444   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5445                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5446 }
5447 
5448 // VisualStudio defines setjmp as _setjmp
5449 #if defined(_MSC_VER) && defined(setjmp) && \
5450                          !defined(setjmp_undefined_for_msvc)
5451 #  pragma push_macro("setjmp")
5452 #  undef setjmp
5453 #  define setjmp_undefined_for_msvc
5454 #endif
5455 
5456 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5457   switch (Intrinsic) {
5458   case Intrinsic::smul_fix:
5459     return ISD::SMULFIX;
5460   case Intrinsic::umul_fix:
5461     return ISD::UMULFIX;
5462   default:
5463     llvm_unreachable("Unhandled fixed point intrinsic");
5464   }
5465 }
5466 
5467 /// Lower the call to the specified intrinsic function. If we want to emit this
5468 /// as a call to a named external function, return the name. Otherwise, lower it
5469 /// and return null.
5470 const char *
5471 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
5472   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5473   SDLoc sdl = getCurSDLoc();
5474   DebugLoc dl = getCurDebugLoc();
5475   SDValue Res;
5476 
5477   switch (Intrinsic) {
5478   default:
5479     // By default, turn this into a target intrinsic node.
5480     visitTargetIntrinsic(I, Intrinsic);
5481     return nullptr;
5482   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5483   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5484   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5485   case Intrinsic::returnaddress:
5486     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5487                              TLI.getPointerTy(DAG.getDataLayout()),
5488                              getValue(I.getArgOperand(0))));
5489     return nullptr;
5490   case Intrinsic::addressofreturnaddress:
5491     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5492                              TLI.getPointerTy(DAG.getDataLayout())));
5493     return nullptr;
5494   case Intrinsic::sponentry:
5495     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5496                              TLI.getPointerTy(DAG.getDataLayout())));
5497     return nullptr;
5498   case Intrinsic::frameaddress:
5499     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5500                              TLI.getPointerTy(DAG.getDataLayout()),
5501                              getValue(I.getArgOperand(0))));
5502     return nullptr;
5503   case Intrinsic::read_register: {
5504     Value *Reg = I.getArgOperand(0);
5505     SDValue Chain = getRoot();
5506     SDValue RegName =
5507         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5508     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5509     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5510       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5511     setValue(&I, Res);
5512     DAG.setRoot(Res.getValue(1));
5513     return nullptr;
5514   }
5515   case Intrinsic::write_register: {
5516     Value *Reg = I.getArgOperand(0);
5517     Value *RegValue = I.getArgOperand(1);
5518     SDValue Chain = getRoot();
5519     SDValue RegName =
5520         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5521     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5522                             RegName, getValue(RegValue)));
5523     return nullptr;
5524   }
5525   case Intrinsic::setjmp:
5526     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5527   case Intrinsic::longjmp:
5528     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5529   case Intrinsic::memcpy: {
5530     const auto &MCI = cast<MemCpyInst>(I);
5531     SDValue Op1 = getValue(I.getArgOperand(0));
5532     SDValue Op2 = getValue(I.getArgOperand(1));
5533     SDValue Op3 = getValue(I.getArgOperand(2));
5534     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5535     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5536     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5537     unsigned Align = MinAlign(DstAlign, SrcAlign);
5538     bool isVol = MCI.isVolatile();
5539     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5540     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5541     // node.
5542     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5543                                false, isTC,
5544                                MachinePointerInfo(I.getArgOperand(0)),
5545                                MachinePointerInfo(I.getArgOperand(1)));
5546     updateDAGForMaybeTailCall(MC);
5547     return nullptr;
5548   }
5549   case Intrinsic::memset: {
5550     const auto &MSI = cast<MemSetInst>(I);
5551     SDValue Op1 = getValue(I.getArgOperand(0));
5552     SDValue Op2 = getValue(I.getArgOperand(1));
5553     SDValue Op3 = getValue(I.getArgOperand(2));
5554     // @llvm.memset defines 0 and 1 to both mean no alignment.
5555     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5556     bool isVol = MSI.isVolatile();
5557     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5558     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5559                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5560     updateDAGForMaybeTailCall(MS);
5561     return nullptr;
5562   }
5563   case Intrinsic::memmove: {
5564     const auto &MMI = cast<MemMoveInst>(I);
5565     SDValue Op1 = getValue(I.getArgOperand(0));
5566     SDValue Op2 = getValue(I.getArgOperand(1));
5567     SDValue Op3 = getValue(I.getArgOperand(2));
5568     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5569     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5570     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5571     unsigned Align = MinAlign(DstAlign, SrcAlign);
5572     bool isVol = MMI.isVolatile();
5573     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5574     // FIXME: Support passing different dest/src alignments to the memmove DAG
5575     // node.
5576     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5577                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5578                                 MachinePointerInfo(I.getArgOperand(1)));
5579     updateDAGForMaybeTailCall(MM);
5580     return nullptr;
5581   }
5582   case Intrinsic::memcpy_element_unordered_atomic: {
5583     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5584     SDValue Dst = getValue(MI.getRawDest());
5585     SDValue Src = getValue(MI.getRawSource());
5586     SDValue Length = getValue(MI.getLength());
5587 
5588     unsigned DstAlign = MI.getDestAlignment();
5589     unsigned SrcAlign = MI.getSourceAlignment();
5590     Type *LengthTy = MI.getLength()->getType();
5591     unsigned ElemSz = MI.getElementSizeInBytes();
5592     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5593     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5594                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5595                                      MachinePointerInfo(MI.getRawDest()),
5596                                      MachinePointerInfo(MI.getRawSource()));
5597     updateDAGForMaybeTailCall(MC);
5598     return nullptr;
5599   }
5600   case Intrinsic::memmove_element_unordered_atomic: {
5601     auto &MI = cast<AtomicMemMoveInst>(I);
5602     SDValue Dst = getValue(MI.getRawDest());
5603     SDValue Src = getValue(MI.getRawSource());
5604     SDValue Length = getValue(MI.getLength());
5605 
5606     unsigned DstAlign = MI.getDestAlignment();
5607     unsigned SrcAlign = MI.getSourceAlignment();
5608     Type *LengthTy = MI.getLength()->getType();
5609     unsigned ElemSz = MI.getElementSizeInBytes();
5610     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5611     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5612                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5613                                       MachinePointerInfo(MI.getRawDest()),
5614                                       MachinePointerInfo(MI.getRawSource()));
5615     updateDAGForMaybeTailCall(MC);
5616     return nullptr;
5617   }
5618   case Intrinsic::memset_element_unordered_atomic: {
5619     auto &MI = cast<AtomicMemSetInst>(I);
5620     SDValue Dst = getValue(MI.getRawDest());
5621     SDValue Val = getValue(MI.getValue());
5622     SDValue Length = getValue(MI.getLength());
5623 
5624     unsigned DstAlign = MI.getDestAlignment();
5625     Type *LengthTy = MI.getLength()->getType();
5626     unsigned ElemSz = MI.getElementSizeInBytes();
5627     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5628     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5629                                      LengthTy, ElemSz, isTC,
5630                                      MachinePointerInfo(MI.getRawDest()));
5631     updateDAGForMaybeTailCall(MC);
5632     return nullptr;
5633   }
5634   case Intrinsic::dbg_addr:
5635   case Intrinsic::dbg_declare: {
5636     const auto &DI = cast<DbgVariableIntrinsic>(I);
5637     DILocalVariable *Variable = DI.getVariable();
5638     DIExpression *Expression = DI.getExpression();
5639     dropDanglingDebugInfo(Variable, Expression);
5640     assert(Variable && "Missing variable");
5641 
5642     // Check if address has undef value.
5643     const Value *Address = DI.getVariableLocation();
5644     if (!Address || isa<UndefValue>(Address) ||
5645         (Address->use_empty() && !isa<Argument>(Address))) {
5646       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5647       return nullptr;
5648     }
5649 
5650     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5651 
5652     // Check if this variable can be described by a frame index, typically
5653     // either as a static alloca or a byval parameter.
5654     int FI = std::numeric_limits<int>::max();
5655     if (const auto *AI =
5656             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5657       if (AI->isStaticAlloca()) {
5658         auto I = FuncInfo.StaticAllocaMap.find(AI);
5659         if (I != FuncInfo.StaticAllocaMap.end())
5660           FI = I->second;
5661       }
5662     } else if (const auto *Arg = dyn_cast<Argument>(
5663                    Address->stripInBoundsConstantOffsets())) {
5664       FI = FuncInfo.getArgumentFrameIndex(Arg);
5665     }
5666 
5667     // llvm.dbg.addr is control dependent and always generates indirect
5668     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5669     // the MachineFunction variable table.
5670     if (FI != std::numeric_limits<int>::max()) {
5671       if (Intrinsic == Intrinsic::dbg_addr) {
5672         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5673             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5674         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5675       }
5676       return nullptr;
5677     }
5678 
5679     SDValue &N = NodeMap[Address];
5680     if (!N.getNode() && isa<Argument>(Address))
5681       // Check unused arguments map.
5682       N = UnusedArgNodeMap[Address];
5683     SDDbgValue *SDV;
5684     if (N.getNode()) {
5685       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5686         Address = BCI->getOperand(0);
5687       // Parameters are handled specially.
5688       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5689       if (isParameter && FINode) {
5690         // Byval parameter. We have a frame index at this point.
5691         SDV =
5692             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5693                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5694       } else if (isa<Argument>(Address)) {
5695         // Address is an argument, so try to emit its dbg value using
5696         // virtual register info from the FuncInfo.ValueMap.
5697         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5698         return nullptr;
5699       } else {
5700         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5701                               true, dl, SDNodeOrder);
5702       }
5703       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5704     } else {
5705       // If Address is an argument then try to emit its dbg value using
5706       // virtual register info from the FuncInfo.ValueMap.
5707       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5708                                     N)) {
5709         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5710       }
5711     }
5712     return nullptr;
5713   }
5714   case Intrinsic::dbg_label: {
5715     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5716     DILabel *Label = DI.getLabel();
5717     assert(Label && "Missing label");
5718 
5719     SDDbgLabel *SDV;
5720     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5721     DAG.AddDbgLabel(SDV);
5722     return nullptr;
5723   }
5724   case Intrinsic::dbg_value: {
5725     const DbgValueInst &DI = cast<DbgValueInst>(I);
5726     assert(DI.getVariable() && "Missing variable");
5727 
5728     DILocalVariable *Variable = DI.getVariable();
5729     DIExpression *Expression = DI.getExpression();
5730     dropDanglingDebugInfo(Variable, Expression);
5731     const Value *V = DI.getValue();
5732     if (!V)
5733       return nullptr;
5734 
5735     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5736         SDNodeOrder))
5737       return nullptr;
5738 
5739     // TODO: Dangling debug info will eventually either be resolved or produce
5740     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5741     // between the original dbg.value location and its resolved DBG_VALUE, which
5742     // we should ideally fill with an extra Undef DBG_VALUE.
5743 
5744     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5745     return nullptr;
5746   }
5747 
5748   case Intrinsic::eh_typeid_for: {
5749     // Find the type id for the given typeinfo.
5750     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5751     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5752     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5753     setValue(&I, Res);
5754     return nullptr;
5755   }
5756 
5757   case Intrinsic::eh_return_i32:
5758   case Intrinsic::eh_return_i64:
5759     DAG.getMachineFunction().setCallsEHReturn(true);
5760     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5761                             MVT::Other,
5762                             getControlRoot(),
5763                             getValue(I.getArgOperand(0)),
5764                             getValue(I.getArgOperand(1))));
5765     return nullptr;
5766   case Intrinsic::eh_unwind_init:
5767     DAG.getMachineFunction().setCallsUnwindInit(true);
5768     return nullptr;
5769   case Intrinsic::eh_dwarf_cfa:
5770     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5771                              TLI.getPointerTy(DAG.getDataLayout()),
5772                              getValue(I.getArgOperand(0))));
5773     return nullptr;
5774   case Intrinsic::eh_sjlj_callsite: {
5775     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5776     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5777     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5778     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5779 
5780     MMI.setCurrentCallSite(CI->getZExtValue());
5781     return nullptr;
5782   }
5783   case Intrinsic::eh_sjlj_functioncontext: {
5784     // Get and store the index of the function context.
5785     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5786     AllocaInst *FnCtx =
5787       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5788     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5789     MFI.setFunctionContextIndex(FI);
5790     return nullptr;
5791   }
5792   case Intrinsic::eh_sjlj_setjmp: {
5793     SDValue Ops[2];
5794     Ops[0] = getRoot();
5795     Ops[1] = getValue(I.getArgOperand(0));
5796     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5797                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5798     setValue(&I, Op.getValue(0));
5799     DAG.setRoot(Op.getValue(1));
5800     return nullptr;
5801   }
5802   case Intrinsic::eh_sjlj_longjmp:
5803     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5804                             getRoot(), getValue(I.getArgOperand(0))));
5805     return nullptr;
5806   case Intrinsic::eh_sjlj_setup_dispatch:
5807     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5808                             getRoot()));
5809     return nullptr;
5810   case Intrinsic::masked_gather:
5811     visitMaskedGather(I);
5812     return nullptr;
5813   case Intrinsic::masked_load:
5814     visitMaskedLoad(I);
5815     return nullptr;
5816   case Intrinsic::masked_scatter:
5817     visitMaskedScatter(I);
5818     return nullptr;
5819   case Intrinsic::masked_store:
5820     visitMaskedStore(I);
5821     return nullptr;
5822   case Intrinsic::masked_expandload:
5823     visitMaskedLoad(I, true /* IsExpanding */);
5824     return nullptr;
5825   case Intrinsic::masked_compressstore:
5826     visitMaskedStore(I, true /* IsCompressing */);
5827     return nullptr;
5828   case Intrinsic::x86_mmx_pslli_w:
5829   case Intrinsic::x86_mmx_pslli_d:
5830   case Intrinsic::x86_mmx_pslli_q:
5831   case Intrinsic::x86_mmx_psrli_w:
5832   case Intrinsic::x86_mmx_psrli_d:
5833   case Intrinsic::x86_mmx_psrli_q:
5834   case Intrinsic::x86_mmx_psrai_w:
5835   case Intrinsic::x86_mmx_psrai_d: {
5836     SDValue ShAmt = getValue(I.getArgOperand(1));
5837     if (isa<ConstantSDNode>(ShAmt)) {
5838       visitTargetIntrinsic(I, Intrinsic);
5839       return nullptr;
5840     }
5841     unsigned NewIntrinsic = 0;
5842     EVT ShAmtVT = MVT::v2i32;
5843     switch (Intrinsic) {
5844     case Intrinsic::x86_mmx_pslli_w:
5845       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5846       break;
5847     case Intrinsic::x86_mmx_pslli_d:
5848       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5849       break;
5850     case Intrinsic::x86_mmx_pslli_q:
5851       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5852       break;
5853     case Intrinsic::x86_mmx_psrli_w:
5854       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5855       break;
5856     case Intrinsic::x86_mmx_psrli_d:
5857       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5858       break;
5859     case Intrinsic::x86_mmx_psrli_q:
5860       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5861       break;
5862     case Intrinsic::x86_mmx_psrai_w:
5863       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5864       break;
5865     case Intrinsic::x86_mmx_psrai_d:
5866       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5867       break;
5868     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5869     }
5870 
5871     // The vector shift intrinsics with scalars uses 32b shift amounts but
5872     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5873     // to be zero.
5874     // We must do this early because v2i32 is not a legal type.
5875     SDValue ShOps[2];
5876     ShOps[0] = ShAmt;
5877     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5878     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5879     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5880     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5881     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5882                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5883                        getValue(I.getArgOperand(0)), ShAmt);
5884     setValue(&I, Res);
5885     return nullptr;
5886   }
5887   case Intrinsic::powi:
5888     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5889                             getValue(I.getArgOperand(1)), DAG));
5890     return nullptr;
5891   case Intrinsic::log:
5892     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5893     return nullptr;
5894   case Intrinsic::log2:
5895     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5896     return nullptr;
5897   case Intrinsic::log10:
5898     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5899     return nullptr;
5900   case Intrinsic::exp:
5901     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5902     return nullptr;
5903   case Intrinsic::exp2:
5904     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5905     return nullptr;
5906   case Intrinsic::pow:
5907     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5908                            getValue(I.getArgOperand(1)), DAG, TLI));
5909     return nullptr;
5910   case Intrinsic::sqrt:
5911   case Intrinsic::fabs:
5912   case Intrinsic::sin:
5913   case Intrinsic::cos:
5914   case Intrinsic::floor:
5915   case Intrinsic::ceil:
5916   case Intrinsic::trunc:
5917   case Intrinsic::rint:
5918   case Intrinsic::nearbyint:
5919   case Intrinsic::round:
5920   case Intrinsic::canonicalize: {
5921     unsigned Opcode;
5922     switch (Intrinsic) {
5923     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5924     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5925     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5926     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5927     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5928     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5929     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5930     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5931     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5932     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5933     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5934     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5935     }
5936 
5937     setValue(&I, DAG.getNode(Opcode, sdl,
5938                              getValue(I.getArgOperand(0)).getValueType(),
5939                              getValue(I.getArgOperand(0))));
5940     return nullptr;
5941   }
5942   case Intrinsic::minnum: {
5943     auto VT = getValue(I.getArgOperand(0)).getValueType();
5944     unsigned Opc =
5945         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
5946             ? ISD::FMINIMUM
5947             : ISD::FMINNUM;
5948     setValue(&I, DAG.getNode(Opc, sdl, VT,
5949                              getValue(I.getArgOperand(0)),
5950                              getValue(I.getArgOperand(1))));
5951     return nullptr;
5952   }
5953   case Intrinsic::maxnum: {
5954     auto VT = getValue(I.getArgOperand(0)).getValueType();
5955     unsigned Opc =
5956         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
5957             ? ISD::FMAXIMUM
5958             : ISD::FMAXNUM;
5959     setValue(&I, DAG.getNode(Opc, sdl, VT,
5960                              getValue(I.getArgOperand(0)),
5961                              getValue(I.getArgOperand(1))));
5962     return nullptr;
5963   }
5964   case Intrinsic::minimum:
5965     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
5966                              getValue(I.getArgOperand(0)).getValueType(),
5967                              getValue(I.getArgOperand(0)),
5968                              getValue(I.getArgOperand(1))));
5969     return nullptr;
5970   case Intrinsic::maximum:
5971     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
5972                              getValue(I.getArgOperand(0)).getValueType(),
5973                              getValue(I.getArgOperand(0)),
5974                              getValue(I.getArgOperand(1))));
5975     return nullptr;
5976   case Intrinsic::copysign:
5977     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5978                              getValue(I.getArgOperand(0)).getValueType(),
5979                              getValue(I.getArgOperand(0)),
5980                              getValue(I.getArgOperand(1))));
5981     return nullptr;
5982   case Intrinsic::fma:
5983     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5984                              getValue(I.getArgOperand(0)).getValueType(),
5985                              getValue(I.getArgOperand(0)),
5986                              getValue(I.getArgOperand(1)),
5987                              getValue(I.getArgOperand(2))));
5988     return nullptr;
5989   case Intrinsic::experimental_constrained_fadd:
5990   case Intrinsic::experimental_constrained_fsub:
5991   case Intrinsic::experimental_constrained_fmul:
5992   case Intrinsic::experimental_constrained_fdiv:
5993   case Intrinsic::experimental_constrained_frem:
5994   case Intrinsic::experimental_constrained_fma:
5995   case Intrinsic::experimental_constrained_sqrt:
5996   case Intrinsic::experimental_constrained_pow:
5997   case Intrinsic::experimental_constrained_powi:
5998   case Intrinsic::experimental_constrained_sin:
5999   case Intrinsic::experimental_constrained_cos:
6000   case Intrinsic::experimental_constrained_exp:
6001   case Intrinsic::experimental_constrained_exp2:
6002   case Intrinsic::experimental_constrained_log:
6003   case Intrinsic::experimental_constrained_log10:
6004   case Intrinsic::experimental_constrained_log2:
6005   case Intrinsic::experimental_constrained_rint:
6006   case Intrinsic::experimental_constrained_nearbyint:
6007   case Intrinsic::experimental_constrained_maxnum:
6008   case Intrinsic::experimental_constrained_minnum:
6009   case Intrinsic::experimental_constrained_ceil:
6010   case Intrinsic::experimental_constrained_floor:
6011   case Intrinsic::experimental_constrained_round:
6012   case Intrinsic::experimental_constrained_trunc:
6013     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6014     return nullptr;
6015   case Intrinsic::fmuladd: {
6016     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6017     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6018         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
6019       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6020                                getValue(I.getArgOperand(0)).getValueType(),
6021                                getValue(I.getArgOperand(0)),
6022                                getValue(I.getArgOperand(1)),
6023                                getValue(I.getArgOperand(2))));
6024     } else {
6025       // TODO: Intrinsic calls should have fast-math-flags.
6026       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6027                                 getValue(I.getArgOperand(0)).getValueType(),
6028                                 getValue(I.getArgOperand(0)),
6029                                 getValue(I.getArgOperand(1)));
6030       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6031                                 getValue(I.getArgOperand(0)).getValueType(),
6032                                 Mul,
6033                                 getValue(I.getArgOperand(2)));
6034       setValue(&I, Add);
6035     }
6036     return nullptr;
6037   }
6038   case Intrinsic::convert_to_fp16:
6039     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6040                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6041                                          getValue(I.getArgOperand(0)),
6042                                          DAG.getTargetConstant(0, sdl,
6043                                                                MVT::i32))));
6044     return nullptr;
6045   case Intrinsic::convert_from_fp16:
6046     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6047                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6048                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6049                                          getValue(I.getArgOperand(0)))));
6050     return nullptr;
6051   case Intrinsic::pcmarker: {
6052     SDValue Tmp = getValue(I.getArgOperand(0));
6053     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6054     return nullptr;
6055   }
6056   case Intrinsic::readcyclecounter: {
6057     SDValue Op = getRoot();
6058     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6059                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6060     setValue(&I, Res);
6061     DAG.setRoot(Res.getValue(1));
6062     return nullptr;
6063   }
6064   case Intrinsic::bitreverse:
6065     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6066                              getValue(I.getArgOperand(0)).getValueType(),
6067                              getValue(I.getArgOperand(0))));
6068     return nullptr;
6069   case Intrinsic::bswap:
6070     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6071                              getValue(I.getArgOperand(0)).getValueType(),
6072                              getValue(I.getArgOperand(0))));
6073     return nullptr;
6074   case Intrinsic::cttz: {
6075     SDValue Arg = getValue(I.getArgOperand(0));
6076     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6077     EVT Ty = Arg.getValueType();
6078     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6079                              sdl, Ty, Arg));
6080     return nullptr;
6081   }
6082   case Intrinsic::ctlz: {
6083     SDValue Arg = getValue(I.getArgOperand(0));
6084     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6085     EVT Ty = Arg.getValueType();
6086     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6087                              sdl, Ty, Arg));
6088     return nullptr;
6089   }
6090   case Intrinsic::ctpop: {
6091     SDValue Arg = getValue(I.getArgOperand(0));
6092     EVT Ty = Arg.getValueType();
6093     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6094     return nullptr;
6095   }
6096   case Intrinsic::fshl:
6097   case Intrinsic::fshr: {
6098     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6099     SDValue X = getValue(I.getArgOperand(0));
6100     SDValue Y = getValue(I.getArgOperand(1));
6101     SDValue Z = getValue(I.getArgOperand(2));
6102     EVT VT = X.getValueType();
6103     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6104     SDValue Zero = DAG.getConstant(0, sdl, VT);
6105     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6106 
6107     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6108     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6109       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6110       return nullptr;
6111     }
6112 
6113     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6114     // avoid the select that is necessary in the general case to filter out
6115     // the 0-shift possibility that leads to UB.
6116     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6117       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6118       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6119         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6120         return nullptr;
6121       }
6122 
6123       // Some targets only rotate one way. Try the opposite direction.
6124       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6125       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6126         // Negate the shift amount because it is safe to ignore the high bits.
6127         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6128         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6129         return nullptr;
6130       }
6131 
6132       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6133       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6134       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6135       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6136       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6137       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6138       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6139       return nullptr;
6140     }
6141 
6142     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6143     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6144     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6145     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6146     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6147     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6148 
6149     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6150     // and that is undefined. We must compare and select to avoid UB.
6151     EVT CCVT = MVT::i1;
6152     if (VT.isVector())
6153       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6154 
6155     // For fshl, 0-shift returns the 1st arg (X).
6156     // For fshr, 0-shift returns the 2nd arg (Y).
6157     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6158     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6159     return nullptr;
6160   }
6161   case Intrinsic::sadd_sat: {
6162     SDValue Op1 = getValue(I.getArgOperand(0));
6163     SDValue Op2 = getValue(I.getArgOperand(1));
6164     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6165     return nullptr;
6166   }
6167   case Intrinsic::uadd_sat: {
6168     SDValue Op1 = getValue(I.getArgOperand(0));
6169     SDValue Op2 = getValue(I.getArgOperand(1));
6170     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6171     return nullptr;
6172   }
6173   case Intrinsic::ssub_sat: {
6174     SDValue Op1 = getValue(I.getArgOperand(0));
6175     SDValue Op2 = getValue(I.getArgOperand(1));
6176     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6177     return nullptr;
6178   }
6179   case Intrinsic::usub_sat: {
6180     SDValue Op1 = getValue(I.getArgOperand(0));
6181     SDValue Op2 = getValue(I.getArgOperand(1));
6182     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6183     return nullptr;
6184   }
6185   case Intrinsic::smul_fix:
6186   case Intrinsic::umul_fix: {
6187     SDValue Op1 = getValue(I.getArgOperand(0));
6188     SDValue Op2 = getValue(I.getArgOperand(1));
6189     SDValue Op3 = getValue(I.getArgOperand(2));
6190     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6191                              Op1.getValueType(), Op1, Op2, Op3));
6192     return nullptr;
6193   }
6194   case Intrinsic::stacksave: {
6195     SDValue Op = getRoot();
6196     Res = DAG.getNode(
6197         ISD::STACKSAVE, sdl,
6198         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6199     setValue(&I, Res);
6200     DAG.setRoot(Res.getValue(1));
6201     return nullptr;
6202   }
6203   case Intrinsic::stackrestore:
6204     Res = getValue(I.getArgOperand(0));
6205     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6206     return nullptr;
6207   case Intrinsic::get_dynamic_area_offset: {
6208     SDValue Op = getRoot();
6209     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6210     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6211     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6212     // target.
6213     if (PtrTy != ResTy)
6214       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6215                          " intrinsic!");
6216     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6217                       Op);
6218     DAG.setRoot(Op);
6219     setValue(&I, Res);
6220     return nullptr;
6221   }
6222   case Intrinsic::stackguard: {
6223     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6224     MachineFunction &MF = DAG.getMachineFunction();
6225     const Module &M = *MF.getFunction().getParent();
6226     SDValue Chain = getRoot();
6227     if (TLI.useLoadStackGuardNode()) {
6228       Res = getLoadStackGuard(DAG, sdl, Chain);
6229     } else {
6230       const Value *Global = TLI.getSDagStackGuard(M);
6231       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6232       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6233                         MachinePointerInfo(Global, 0), Align,
6234                         MachineMemOperand::MOVolatile);
6235     }
6236     if (TLI.useStackGuardXorFP())
6237       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6238     DAG.setRoot(Chain);
6239     setValue(&I, Res);
6240     return nullptr;
6241   }
6242   case Intrinsic::stackprotector: {
6243     // Emit code into the DAG to store the stack guard onto the stack.
6244     MachineFunction &MF = DAG.getMachineFunction();
6245     MachineFrameInfo &MFI = MF.getFrameInfo();
6246     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6247     SDValue Src, Chain = getRoot();
6248 
6249     if (TLI.useLoadStackGuardNode())
6250       Src = getLoadStackGuard(DAG, sdl, Chain);
6251     else
6252       Src = getValue(I.getArgOperand(0));   // The guard's value.
6253 
6254     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6255 
6256     int FI = FuncInfo.StaticAllocaMap[Slot];
6257     MFI.setStackProtectorIndex(FI);
6258 
6259     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6260 
6261     // Store the stack protector onto the stack.
6262     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6263                                                  DAG.getMachineFunction(), FI),
6264                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6265     setValue(&I, Res);
6266     DAG.setRoot(Res);
6267     return nullptr;
6268   }
6269   case Intrinsic::objectsize: {
6270     // If we don't know by now, we're never going to know.
6271     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
6272 
6273     assert(CI && "Non-constant type in __builtin_object_size?");
6274 
6275     SDValue Arg = getValue(I.getCalledValue());
6276     EVT Ty = Arg.getValueType();
6277 
6278     if (CI->isZero())
6279       Res = DAG.getConstant(-1ULL, sdl, Ty);
6280     else
6281       Res = DAG.getConstant(0, sdl, Ty);
6282 
6283     setValue(&I, Res);
6284     return nullptr;
6285   }
6286 
6287   case Intrinsic::is_constant:
6288     // If this wasn't constant-folded away by now, then it's not a
6289     // constant.
6290     setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
6291     return nullptr;
6292 
6293   case Intrinsic::annotation:
6294   case Intrinsic::ptr_annotation:
6295   case Intrinsic::launder_invariant_group:
6296   case Intrinsic::strip_invariant_group:
6297     // Drop the intrinsic, but forward the value
6298     setValue(&I, getValue(I.getOperand(0)));
6299     return nullptr;
6300   case Intrinsic::assume:
6301   case Intrinsic::var_annotation:
6302   case Intrinsic::sideeffect:
6303     // Discard annotate attributes, assumptions, and artificial side-effects.
6304     return nullptr;
6305 
6306   case Intrinsic::codeview_annotation: {
6307     // Emit a label associated with this metadata.
6308     MachineFunction &MF = DAG.getMachineFunction();
6309     MCSymbol *Label =
6310         MF.getMMI().getContext().createTempSymbol("annotation", true);
6311     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6312     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6313     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6314     DAG.setRoot(Res);
6315     return nullptr;
6316   }
6317 
6318   case Intrinsic::init_trampoline: {
6319     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6320 
6321     SDValue Ops[6];
6322     Ops[0] = getRoot();
6323     Ops[1] = getValue(I.getArgOperand(0));
6324     Ops[2] = getValue(I.getArgOperand(1));
6325     Ops[3] = getValue(I.getArgOperand(2));
6326     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6327     Ops[5] = DAG.getSrcValue(F);
6328 
6329     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6330 
6331     DAG.setRoot(Res);
6332     return nullptr;
6333   }
6334   case Intrinsic::adjust_trampoline:
6335     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6336                              TLI.getPointerTy(DAG.getDataLayout()),
6337                              getValue(I.getArgOperand(0))));
6338     return nullptr;
6339   case Intrinsic::gcroot: {
6340     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6341            "only valid in functions with gc specified, enforced by Verifier");
6342     assert(GFI && "implied by previous");
6343     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6344     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6345 
6346     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6347     GFI->addStackRoot(FI->getIndex(), TypeMap);
6348     return nullptr;
6349   }
6350   case Intrinsic::gcread:
6351   case Intrinsic::gcwrite:
6352     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6353   case Intrinsic::flt_rounds:
6354     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6355     return nullptr;
6356 
6357   case Intrinsic::expect:
6358     // Just replace __builtin_expect(exp, c) with EXP.
6359     setValue(&I, getValue(I.getArgOperand(0)));
6360     return nullptr;
6361 
6362   case Intrinsic::debugtrap:
6363   case Intrinsic::trap: {
6364     StringRef TrapFuncName =
6365         I.getAttributes()
6366             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6367             .getValueAsString();
6368     if (TrapFuncName.empty()) {
6369       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6370         ISD::TRAP : ISD::DEBUGTRAP;
6371       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6372       return nullptr;
6373     }
6374     TargetLowering::ArgListTy Args;
6375 
6376     TargetLowering::CallLoweringInfo CLI(DAG);
6377     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6378         CallingConv::C, I.getType(),
6379         DAG.getExternalSymbol(TrapFuncName.data(),
6380                               TLI.getPointerTy(DAG.getDataLayout())),
6381         std::move(Args));
6382 
6383     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6384     DAG.setRoot(Result.second);
6385     return nullptr;
6386   }
6387 
6388   case Intrinsic::uadd_with_overflow:
6389   case Intrinsic::sadd_with_overflow:
6390   case Intrinsic::usub_with_overflow:
6391   case Intrinsic::ssub_with_overflow:
6392   case Intrinsic::umul_with_overflow:
6393   case Intrinsic::smul_with_overflow: {
6394     ISD::NodeType Op;
6395     switch (Intrinsic) {
6396     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6397     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6398     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6399     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6400     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6401     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6402     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6403     }
6404     SDValue Op1 = getValue(I.getArgOperand(0));
6405     SDValue Op2 = getValue(I.getArgOperand(1));
6406 
6407     EVT ResultVT = Op1.getValueType();
6408     EVT OverflowVT = MVT::i1;
6409     if (ResultVT.isVector())
6410       OverflowVT = EVT::getVectorVT(
6411           *Context, OverflowVT, ResultVT.getVectorNumElements());
6412 
6413     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6414     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6415     return nullptr;
6416   }
6417   case Intrinsic::prefetch: {
6418     SDValue Ops[5];
6419     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6420     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6421     Ops[0] = DAG.getRoot();
6422     Ops[1] = getValue(I.getArgOperand(0));
6423     Ops[2] = getValue(I.getArgOperand(1));
6424     Ops[3] = getValue(I.getArgOperand(2));
6425     Ops[4] = getValue(I.getArgOperand(3));
6426     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6427                                              DAG.getVTList(MVT::Other), Ops,
6428                                              EVT::getIntegerVT(*Context, 8),
6429                                              MachinePointerInfo(I.getArgOperand(0)),
6430                                              0, /* align */
6431                                              Flags);
6432 
6433     // Chain the prefetch in parallell with any pending loads, to stay out of
6434     // the way of later optimizations.
6435     PendingLoads.push_back(Result);
6436     Result = getRoot();
6437     DAG.setRoot(Result);
6438     return nullptr;
6439   }
6440   case Intrinsic::lifetime_start:
6441   case Intrinsic::lifetime_end: {
6442     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6443     // Stack coloring is not enabled in O0, discard region information.
6444     if (TM.getOptLevel() == CodeGenOpt::None)
6445       return nullptr;
6446 
6447     const int64_t ObjectSize =
6448         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6449     Value *const ObjectPtr = I.getArgOperand(1);
6450     SmallVector<Value *, 4> Allocas;
6451     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6452 
6453     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
6454            E = Allocas.end(); Object != E; ++Object) {
6455       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6456 
6457       // Could not find an Alloca.
6458       if (!LifetimeObject)
6459         continue;
6460 
6461       // First check that the Alloca is static, otherwise it won't have a
6462       // valid frame index.
6463       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6464       if (SI == FuncInfo.StaticAllocaMap.end())
6465         return nullptr;
6466 
6467       const int FrameIndex = SI->second;
6468       int64_t Offset;
6469       if (GetPointerBaseWithConstantOffset(
6470               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6471         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6472       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6473                                 Offset);
6474       DAG.setRoot(Res);
6475     }
6476     return nullptr;
6477   }
6478   case Intrinsic::invariant_start:
6479     // Discard region information.
6480     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6481     return nullptr;
6482   case Intrinsic::invariant_end:
6483     // Discard region information.
6484     return nullptr;
6485   case Intrinsic::clear_cache:
6486     return TLI.getClearCacheBuiltinName();
6487   case Intrinsic::donothing:
6488     // ignore
6489     return nullptr;
6490   case Intrinsic::experimental_stackmap:
6491     visitStackmap(I);
6492     return nullptr;
6493   case Intrinsic::experimental_patchpoint_void:
6494   case Intrinsic::experimental_patchpoint_i64:
6495     visitPatchpoint(&I);
6496     return nullptr;
6497   case Intrinsic::experimental_gc_statepoint:
6498     LowerStatepoint(ImmutableStatepoint(&I));
6499     return nullptr;
6500   case Intrinsic::experimental_gc_result:
6501     visitGCResult(cast<GCResultInst>(I));
6502     return nullptr;
6503   case Intrinsic::experimental_gc_relocate:
6504     visitGCRelocate(cast<GCRelocateInst>(I));
6505     return nullptr;
6506   case Intrinsic::instrprof_increment:
6507     llvm_unreachable("instrprof failed to lower an increment");
6508   case Intrinsic::instrprof_value_profile:
6509     llvm_unreachable("instrprof failed to lower a value profiling call");
6510   case Intrinsic::localescape: {
6511     MachineFunction &MF = DAG.getMachineFunction();
6512     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6513 
6514     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6515     // is the same on all targets.
6516     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6517       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6518       if (isa<ConstantPointerNull>(Arg))
6519         continue; // Skip null pointers. They represent a hole in index space.
6520       AllocaInst *Slot = cast<AllocaInst>(Arg);
6521       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6522              "can only escape static allocas");
6523       int FI = FuncInfo.StaticAllocaMap[Slot];
6524       MCSymbol *FrameAllocSym =
6525           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6526               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6527       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6528               TII->get(TargetOpcode::LOCAL_ESCAPE))
6529           .addSym(FrameAllocSym)
6530           .addFrameIndex(FI);
6531     }
6532 
6533     return nullptr;
6534   }
6535 
6536   case Intrinsic::localrecover: {
6537     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6538     MachineFunction &MF = DAG.getMachineFunction();
6539     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6540 
6541     // Get the symbol that defines the frame offset.
6542     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6543     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6544     unsigned IdxVal =
6545         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6546     MCSymbol *FrameAllocSym =
6547         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6548             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6549 
6550     // Create a MCSymbol for the label to avoid any target lowering
6551     // that would make this PC relative.
6552     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6553     SDValue OffsetVal =
6554         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6555 
6556     // Add the offset to the FP.
6557     Value *FP = I.getArgOperand(1);
6558     SDValue FPVal = getValue(FP);
6559     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6560     setValue(&I, Add);
6561 
6562     return nullptr;
6563   }
6564 
6565   case Intrinsic::eh_exceptionpointer:
6566   case Intrinsic::eh_exceptioncode: {
6567     // Get the exception pointer vreg, copy from it, and resize it to fit.
6568     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6569     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6570     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6571     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6572     SDValue N =
6573         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6574     if (Intrinsic == Intrinsic::eh_exceptioncode)
6575       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6576     setValue(&I, N);
6577     return nullptr;
6578   }
6579   case Intrinsic::xray_customevent: {
6580     // Here we want to make sure that the intrinsic behaves as if it has a
6581     // specific calling convention, and only for x86_64.
6582     // FIXME: Support other platforms later.
6583     const auto &Triple = DAG.getTarget().getTargetTriple();
6584     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6585       return nullptr;
6586 
6587     SDLoc DL = getCurSDLoc();
6588     SmallVector<SDValue, 8> Ops;
6589 
6590     // We want to say that we always want the arguments in registers.
6591     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6592     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6593     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6594     SDValue Chain = getRoot();
6595     Ops.push_back(LogEntryVal);
6596     Ops.push_back(StrSizeVal);
6597     Ops.push_back(Chain);
6598 
6599     // We need to enforce the calling convention for the callsite, so that
6600     // argument ordering is enforced correctly, and that register allocation can
6601     // see that some registers may be assumed clobbered and have to preserve
6602     // them across calls to the intrinsic.
6603     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6604                                            DL, NodeTys, Ops);
6605     SDValue patchableNode = SDValue(MN, 0);
6606     DAG.setRoot(patchableNode);
6607     setValue(&I, patchableNode);
6608     return nullptr;
6609   }
6610   case Intrinsic::xray_typedevent: {
6611     // Here we want to make sure that the intrinsic behaves as if it has a
6612     // specific calling convention, and only for x86_64.
6613     // FIXME: Support other platforms later.
6614     const auto &Triple = DAG.getTarget().getTargetTriple();
6615     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6616       return nullptr;
6617 
6618     SDLoc DL = getCurSDLoc();
6619     SmallVector<SDValue, 8> Ops;
6620 
6621     // We want to say that we always want the arguments in registers.
6622     // It's unclear to me how manipulating the selection DAG here forces callers
6623     // to provide arguments in registers instead of on the stack.
6624     SDValue LogTypeId = getValue(I.getArgOperand(0));
6625     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6626     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6627     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6628     SDValue Chain = getRoot();
6629     Ops.push_back(LogTypeId);
6630     Ops.push_back(LogEntryVal);
6631     Ops.push_back(StrSizeVal);
6632     Ops.push_back(Chain);
6633 
6634     // We need to enforce the calling convention for the callsite, so that
6635     // argument ordering is enforced correctly, and that register allocation can
6636     // see that some registers may be assumed clobbered and have to preserve
6637     // them across calls to the intrinsic.
6638     MachineSDNode *MN = DAG.getMachineNode(
6639         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6640     SDValue patchableNode = SDValue(MN, 0);
6641     DAG.setRoot(patchableNode);
6642     setValue(&I, patchableNode);
6643     return nullptr;
6644   }
6645   case Intrinsic::experimental_deoptimize:
6646     LowerDeoptimizeCall(&I);
6647     return nullptr;
6648 
6649   case Intrinsic::experimental_vector_reduce_fadd:
6650   case Intrinsic::experimental_vector_reduce_fmul:
6651   case Intrinsic::experimental_vector_reduce_add:
6652   case Intrinsic::experimental_vector_reduce_mul:
6653   case Intrinsic::experimental_vector_reduce_and:
6654   case Intrinsic::experimental_vector_reduce_or:
6655   case Intrinsic::experimental_vector_reduce_xor:
6656   case Intrinsic::experimental_vector_reduce_smax:
6657   case Intrinsic::experimental_vector_reduce_smin:
6658   case Intrinsic::experimental_vector_reduce_umax:
6659   case Intrinsic::experimental_vector_reduce_umin:
6660   case Intrinsic::experimental_vector_reduce_fmax:
6661   case Intrinsic::experimental_vector_reduce_fmin:
6662     visitVectorReduce(I, Intrinsic);
6663     return nullptr;
6664 
6665   case Intrinsic::icall_branch_funnel: {
6666     SmallVector<SDValue, 16> Ops;
6667     Ops.push_back(DAG.getRoot());
6668     Ops.push_back(getValue(I.getArgOperand(0)));
6669 
6670     int64_t Offset;
6671     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6672         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6673     if (!Base)
6674       report_fatal_error(
6675           "llvm.icall.branch.funnel operand must be a GlobalValue");
6676     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6677 
6678     struct BranchFunnelTarget {
6679       int64_t Offset;
6680       SDValue Target;
6681     };
6682     SmallVector<BranchFunnelTarget, 8> Targets;
6683 
6684     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6685       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6686           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6687       if (ElemBase != Base)
6688         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6689                            "to the same GlobalValue");
6690 
6691       SDValue Val = getValue(I.getArgOperand(Op + 1));
6692       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6693       if (!GA)
6694         report_fatal_error(
6695             "llvm.icall.branch.funnel operand must be a GlobalValue");
6696       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6697                                      GA->getGlobal(), getCurSDLoc(),
6698                                      Val.getValueType(), GA->getOffset())});
6699     }
6700     llvm::sort(Targets,
6701                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6702                  return T1.Offset < T2.Offset;
6703                });
6704 
6705     for (auto &T : Targets) {
6706       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6707       Ops.push_back(T.Target);
6708     }
6709 
6710     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6711                                  getCurSDLoc(), MVT::Other, Ops),
6712               0);
6713     DAG.setRoot(N);
6714     setValue(&I, N);
6715     HasTailCall = true;
6716     return nullptr;
6717   }
6718 
6719   case Intrinsic::wasm_landingpad_index:
6720     // Information this intrinsic contained has been transferred to
6721     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6722     // delete it now.
6723     return nullptr;
6724   }
6725 }
6726 
6727 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6728     const ConstrainedFPIntrinsic &FPI) {
6729   SDLoc sdl = getCurSDLoc();
6730   unsigned Opcode;
6731   switch (FPI.getIntrinsicID()) {
6732   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6733   case Intrinsic::experimental_constrained_fadd:
6734     Opcode = ISD::STRICT_FADD;
6735     break;
6736   case Intrinsic::experimental_constrained_fsub:
6737     Opcode = ISD::STRICT_FSUB;
6738     break;
6739   case Intrinsic::experimental_constrained_fmul:
6740     Opcode = ISD::STRICT_FMUL;
6741     break;
6742   case Intrinsic::experimental_constrained_fdiv:
6743     Opcode = ISD::STRICT_FDIV;
6744     break;
6745   case Intrinsic::experimental_constrained_frem:
6746     Opcode = ISD::STRICT_FREM;
6747     break;
6748   case Intrinsic::experimental_constrained_fma:
6749     Opcode = ISD::STRICT_FMA;
6750     break;
6751   case Intrinsic::experimental_constrained_sqrt:
6752     Opcode = ISD::STRICT_FSQRT;
6753     break;
6754   case Intrinsic::experimental_constrained_pow:
6755     Opcode = ISD::STRICT_FPOW;
6756     break;
6757   case Intrinsic::experimental_constrained_powi:
6758     Opcode = ISD::STRICT_FPOWI;
6759     break;
6760   case Intrinsic::experimental_constrained_sin:
6761     Opcode = ISD::STRICT_FSIN;
6762     break;
6763   case Intrinsic::experimental_constrained_cos:
6764     Opcode = ISD::STRICT_FCOS;
6765     break;
6766   case Intrinsic::experimental_constrained_exp:
6767     Opcode = ISD::STRICT_FEXP;
6768     break;
6769   case Intrinsic::experimental_constrained_exp2:
6770     Opcode = ISD::STRICT_FEXP2;
6771     break;
6772   case Intrinsic::experimental_constrained_log:
6773     Opcode = ISD::STRICT_FLOG;
6774     break;
6775   case Intrinsic::experimental_constrained_log10:
6776     Opcode = ISD::STRICT_FLOG10;
6777     break;
6778   case Intrinsic::experimental_constrained_log2:
6779     Opcode = ISD::STRICT_FLOG2;
6780     break;
6781   case Intrinsic::experimental_constrained_rint:
6782     Opcode = ISD::STRICT_FRINT;
6783     break;
6784   case Intrinsic::experimental_constrained_nearbyint:
6785     Opcode = ISD::STRICT_FNEARBYINT;
6786     break;
6787   case Intrinsic::experimental_constrained_maxnum:
6788     Opcode = ISD::STRICT_FMAXNUM;
6789     break;
6790   case Intrinsic::experimental_constrained_minnum:
6791     Opcode = ISD::STRICT_FMINNUM;
6792     break;
6793   case Intrinsic::experimental_constrained_ceil:
6794     Opcode = ISD::STRICT_FCEIL;
6795     break;
6796   case Intrinsic::experimental_constrained_floor:
6797     Opcode = ISD::STRICT_FFLOOR;
6798     break;
6799   case Intrinsic::experimental_constrained_round:
6800     Opcode = ISD::STRICT_FROUND;
6801     break;
6802   case Intrinsic::experimental_constrained_trunc:
6803     Opcode = ISD::STRICT_FTRUNC;
6804     break;
6805   }
6806   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6807   SDValue Chain = getRoot();
6808   SmallVector<EVT, 4> ValueVTs;
6809   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6810   ValueVTs.push_back(MVT::Other); // Out chain
6811 
6812   SDVTList VTs = DAG.getVTList(ValueVTs);
6813   SDValue Result;
6814   if (FPI.isUnaryOp())
6815     Result = DAG.getNode(Opcode, sdl, VTs,
6816                          { Chain, getValue(FPI.getArgOperand(0)) });
6817   else if (FPI.isTernaryOp())
6818     Result = DAG.getNode(Opcode, sdl, VTs,
6819                          { Chain, getValue(FPI.getArgOperand(0)),
6820                                   getValue(FPI.getArgOperand(1)),
6821                                   getValue(FPI.getArgOperand(2)) });
6822   else
6823     Result = DAG.getNode(Opcode, sdl, VTs,
6824                          { Chain, getValue(FPI.getArgOperand(0)),
6825                            getValue(FPI.getArgOperand(1))  });
6826 
6827   assert(Result.getNode()->getNumValues() == 2);
6828   SDValue OutChain = Result.getValue(1);
6829   DAG.setRoot(OutChain);
6830   SDValue FPResult = Result.getValue(0);
6831   setValue(&FPI, FPResult);
6832 }
6833 
6834 std::pair<SDValue, SDValue>
6835 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6836                                     const BasicBlock *EHPadBB) {
6837   MachineFunction &MF = DAG.getMachineFunction();
6838   MachineModuleInfo &MMI = MF.getMMI();
6839   MCSymbol *BeginLabel = nullptr;
6840 
6841   if (EHPadBB) {
6842     // Insert a label before the invoke call to mark the try range.  This can be
6843     // used to detect deletion of the invoke via the MachineModuleInfo.
6844     BeginLabel = MMI.getContext().createTempSymbol();
6845 
6846     // For SjLj, keep track of which landing pads go with which invokes
6847     // so as to maintain the ordering of pads in the LSDA.
6848     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6849     if (CallSiteIndex) {
6850       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6851       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6852 
6853       // Now that the call site is handled, stop tracking it.
6854       MMI.setCurrentCallSite(0);
6855     }
6856 
6857     // Both PendingLoads and PendingExports must be flushed here;
6858     // this call might not return.
6859     (void)getRoot();
6860     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6861 
6862     CLI.setChain(getRoot());
6863   }
6864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6865   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6866 
6867   assert((CLI.IsTailCall || Result.second.getNode()) &&
6868          "Non-null chain expected with non-tail call!");
6869   assert((Result.second.getNode() || !Result.first.getNode()) &&
6870          "Null value expected with tail call!");
6871 
6872   if (!Result.second.getNode()) {
6873     // As a special case, a null chain means that a tail call has been emitted
6874     // and the DAG root is already updated.
6875     HasTailCall = true;
6876 
6877     // Since there's no actual continuation from this block, nothing can be
6878     // relying on us setting vregs for them.
6879     PendingExports.clear();
6880   } else {
6881     DAG.setRoot(Result.second);
6882   }
6883 
6884   if (EHPadBB) {
6885     // Insert a label at the end of the invoke call to mark the try range.  This
6886     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6887     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6888     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6889 
6890     // Inform MachineModuleInfo of range.
6891     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6892     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6893     // actually use outlined funclets and their LSDA info style.
6894     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6895       assert(CLI.CS);
6896       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6897       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6898                                 BeginLabel, EndLabel);
6899     } else if (!isScopedEHPersonality(Pers)) {
6900       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6901     }
6902   }
6903 
6904   return Result;
6905 }
6906 
6907 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6908                                       bool isTailCall,
6909                                       const BasicBlock *EHPadBB) {
6910   auto &DL = DAG.getDataLayout();
6911   FunctionType *FTy = CS.getFunctionType();
6912   Type *RetTy = CS.getType();
6913 
6914   TargetLowering::ArgListTy Args;
6915   Args.reserve(CS.arg_size());
6916 
6917   const Value *SwiftErrorVal = nullptr;
6918   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6919 
6920   // We can't tail call inside a function with a swifterror argument. Lowering
6921   // does not support this yet. It would have to move into the swifterror
6922   // register before the call.
6923   auto *Caller = CS.getInstruction()->getParent()->getParent();
6924   if (TLI.supportSwiftError() &&
6925       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6926     isTailCall = false;
6927 
6928   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6929        i != e; ++i) {
6930     TargetLowering::ArgListEntry Entry;
6931     const Value *V = *i;
6932 
6933     // Skip empty types
6934     if (V->getType()->isEmptyTy())
6935       continue;
6936 
6937     SDValue ArgNode = getValue(V);
6938     Entry.Node = ArgNode; Entry.Ty = V->getType();
6939 
6940     Entry.setAttributes(&CS, i - CS.arg_begin());
6941 
6942     // Use swifterror virtual register as input to the call.
6943     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6944       SwiftErrorVal = V;
6945       // We find the virtual register for the actual swifterror argument.
6946       // Instead of using the Value, we use the virtual register instead.
6947       Entry.Node = DAG.getRegister(FuncInfo
6948                                        .getOrCreateSwiftErrorVRegUseAt(
6949                                            CS.getInstruction(), FuncInfo.MBB, V)
6950                                        .first,
6951                                    EVT(TLI.getPointerTy(DL)));
6952     }
6953 
6954     Args.push_back(Entry);
6955 
6956     // If we have an explicit sret argument that is an Instruction, (i.e., it
6957     // might point to function-local memory), we can't meaningfully tail-call.
6958     if (Entry.IsSRet && isa<Instruction>(V))
6959       isTailCall = false;
6960   }
6961 
6962   // Check if target-independent constraints permit a tail call here.
6963   // Target-dependent constraints are checked within TLI->LowerCallTo.
6964   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6965     isTailCall = false;
6966 
6967   // Disable tail calls if there is an swifterror argument. Targets have not
6968   // been updated to support tail calls.
6969   if (TLI.supportSwiftError() && SwiftErrorVal)
6970     isTailCall = false;
6971 
6972   TargetLowering::CallLoweringInfo CLI(DAG);
6973   CLI.setDebugLoc(getCurSDLoc())
6974       .setChain(getRoot())
6975       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6976       .setTailCall(isTailCall)
6977       .setConvergent(CS.isConvergent());
6978   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6979 
6980   if (Result.first.getNode()) {
6981     const Instruction *Inst = CS.getInstruction();
6982     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6983     setValue(Inst, Result.first);
6984   }
6985 
6986   // The last element of CLI.InVals has the SDValue for swifterror return.
6987   // Here we copy it to a virtual register and update SwiftErrorMap for
6988   // book-keeping.
6989   if (SwiftErrorVal && TLI.supportSwiftError()) {
6990     // Get the last element of InVals.
6991     SDValue Src = CLI.InVals.back();
6992     unsigned VReg; bool CreatedVReg;
6993     std::tie(VReg, CreatedVReg) =
6994         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6995     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6996     // We update the virtual register for the actual swifterror argument.
6997     if (CreatedVReg)
6998       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6999     DAG.setRoot(CopyNode);
7000   }
7001 }
7002 
7003 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7004                              SelectionDAGBuilder &Builder) {
7005   // Check to see if this load can be trivially constant folded, e.g. if the
7006   // input is from a string literal.
7007   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7008     // Cast pointer to the type we really want to load.
7009     Type *LoadTy =
7010         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7011     if (LoadVT.isVector())
7012       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7013 
7014     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7015                                          PointerType::getUnqual(LoadTy));
7016 
7017     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7018             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7019       return Builder.getValue(LoadCst);
7020   }
7021 
7022   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7023   // still constant memory, the input chain can be the entry node.
7024   SDValue Root;
7025   bool ConstantMemory = false;
7026 
7027   // Do not serialize (non-volatile) loads of constant memory with anything.
7028   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7029     Root = Builder.DAG.getEntryNode();
7030     ConstantMemory = true;
7031   } else {
7032     // Do not serialize non-volatile loads against each other.
7033     Root = Builder.DAG.getRoot();
7034   }
7035 
7036   SDValue Ptr = Builder.getValue(PtrVal);
7037   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7038                                         Ptr, MachinePointerInfo(PtrVal),
7039                                         /* Alignment = */ 1);
7040 
7041   if (!ConstantMemory)
7042     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7043   return LoadVal;
7044 }
7045 
7046 /// Record the value for an instruction that produces an integer result,
7047 /// converting the type where necessary.
7048 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7049                                                   SDValue Value,
7050                                                   bool IsSigned) {
7051   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7052                                                     I.getType(), true);
7053   if (IsSigned)
7054     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7055   else
7056     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7057   setValue(&I, Value);
7058 }
7059 
7060 /// See if we can lower a memcmp call into an optimized form. If so, return
7061 /// true and lower it. Otherwise return false, and it will be lowered like a
7062 /// normal call.
7063 /// The caller already checked that \p I calls the appropriate LibFunc with a
7064 /// correct prototype.
7065 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7066   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7067   const Value *Size = I.getArgOperand(2);
7068   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7069   if (CSize && CSize->getZExtValue() == 0) {
7070     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7071                                                           I.getType(), true);
7072     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7073     return true;
7074   }
7075 
7076   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7077   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7078       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7079       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7080   if (Res.first.getNode()) {
7081     processIntegerCallValue(I, Res.first, true);
7082     PendingLoads.push_back(Res.second);
7083     return true;
7084   }
7085 
7086   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7087   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7088   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7089     return false;
7090 
7091   // If the target has a fast compare for the given size, it will return a
7092   // preferred load type for that size. Require that the load VT is legal and
7093   // that the target supports unaligned loads of that type. Otherwise, return
7094   // INVALID.
7095   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7096     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7097     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7098     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7099       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7100       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7101       // TODO: Check alignment of src and dest ptrs.
7102       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7103       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7104       if (!TLI.isTypeLegal(LVT) ||
7105           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7106           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7107         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7108     }
7109 
7110     return LVT;
7111   };
7112 
7113   // This turns into unaligned loads. We only do this if the target natively
7114   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7115   // we'll only produce a small number of byte loads.
7116   MVT LoadVT;
7117   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7118   switch (NumBitsToCompare) {
7119   default:
7120     return false;
7121   case 16:
7122     LoadVT = MVT::i16;
7123     break;
7124   case 32:
7125     LoadVT = MVT::i32;
7126     break;
7127   case 64:
7128   case 128:
7129   case 256:
7130     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7131     break;
7132   }
7133 
7134   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7135     return false;
7136 
7137   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7138   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7139 
7140   // Bitcast to a wide integer type if the loads are vectors.
7141   if (LoadVT.isVector()) {
7142     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7143     LoadL = DAG.getBitcast(CmpVT, LoadL);
7144     LoadR = DAG.getBitcast(CmpVT, LoadR);
7145   }
7146 
7147   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7148   processIntegerCallValue(I, Cmp, false);
7149   return true;
7150 }
7151 
7152 /// See if we can lower a memchr call into an optimized form. If so, return
7153 /// true and lower it. Otherwise return false, and it will be lowered like a
7154 /// normal call.
7155 /// The caller already checked that \p I calls the appropriate LibFunc with a
7156 /// correct prototype.
7157 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7158   const Value *Src = I.getArgOperand(0);
7159   const Value *Char = I.getArgOperand(1);
7160   const Value *Length = I.getArgOperand(2);
7161 
7162   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7163   std::pair<SDValue, SDValue> Res =
7164     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7165                                 getValue(Src), getValue(Char), getValue(Length),
7166                                 MachinePointerInfo(Src));
7167   if (Res.first.getNode()) {
7168     setValue(&I, Res.first);
7169     PendingLoads.push_back(Res.second);
7170     return true;
7171   }
7172 
7173   return false;
7174 }
7175 
7176 /// See if we can lower a mempcpy call into an optimized form. If so, return
7177 /// true and lower it. Otherwise return false, and it will be lowered like a
7178 /// normal call.
7179 /// The caller already checked that \p I calls the appropriate LibFunc with a
7180 /// correct prototype.
7181 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7182   SDValue Dst = getValue(I.getArgOperand(0));
7183   SDValue Src = getValue(I.getArgOperand(1));
7184   SDValue Size = getValue(I.getArgOperand(2));
7185 
7186   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7187   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7188   unsigned Align = std::min(DstAlign, SrcAlign);
7189   if (Align == 0) // Alignment of one or both could not be inferred.
7190     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7191 
7192   bool isVol = false;
7193   SDLoc sdl = getCurSDLoc();
7194 
7195   // In the mempcpy context we need to pass in a false value for isTailCall
7196   // because the return pointer needs to be adjusted by the size of
7197   // the copied memory.
7198   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7199                              false, /*isTailCall=*/false,
7200                              MachinePointerInfo(I.getArgOperand(0)),
7201                              MachinePointerInfo(I.getArgOperand(1)));
7202   assert(MC.getNode() != nullptr &&
7203          "** memcpy should not be lowered as TailCall in mempcpy context **");
7204   DAG.setRoot(MC);
7205 
7206   // Check if Size needs to be truncated or extended.
7207   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7208 
7209   // Adjust return pointer to point just past the last dst byte.
7210   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7211                                     Dst, Size);
7212   setValue(&I, DstPlusSize);
7213   return true;
7214 }
7215 
7216 /// See if we can lower a strcpy call into an optimized form.  If so, return
7217 /// true and lower it, otherwise return false and it will be lowered like a
7218 /// normal call.
7219 /// The caller already checked that \p I calls the appropriate LibFunc with a
7220 /// correct prototype.
7221 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7222   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7223 
7224   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7225   std::pair<SDValue, SDValue> Res =
7226     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7227                                 getValue(Arg0), getValue(Arg1),
7228                                 MachinePointerInfo(Arg0),
7229                                 MachinePointerInfo(Arg1), isStpcpy);
7230   if (Res.first.getNode()) {
7231     setValue(&I, Res.first);
7232     DAG.setRoot(Res.second);
7233     return true;
7234   }
7235 
7236   return false;
7237 }
7238 
7239 /// See if we can lower a strcmp call into an optimized form.  If so, return
7240 /// true and lower it, otherwise return false and it will be lowered like a
7241 /// normal call.
7242 /// The caller already checked that \p I calls the appropriate LibFunc with a
7243 /// correct prototype.
7244 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7245   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7246 
7247   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7248   std::pair<SDValue, SDValue> Res =
7249     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7250                                 getValue(Arg0), getValue(Arg1),
7251                                 MachinePointerInfo(Arg0),
7252                                 MachinePointerInfo(Arg1));
7253   if (Res.first.getNode()) {
7254     processIntegerCallValue(I, Res.first, true);
7255     PendingLoads.push_back(Res.second);
7256     return true;
7257   }
7258 
7259   return false;
7260 }
7261 
7262 /// See if we can lower a strlen call into an optimized form.  If so, return
7263 /// true and lower it, otherwise return false and it will be lowered like a
7264 /// normal call.
7265 /// The caller already checked that \p I calls the appropriate LibFunc with a
7266 /// correct prototype.
7267 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7268   const Value *Arg0 = I.getArgOperand(0);
7269 
7270   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7271   std::pair<SDValue, SDValue> Res =
7272     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7273                                 getValue(Arg0), MachinePointerInfo(Arg0));
7274   if (Res.first.getNode()) {
7275     processIntegerCallValue(I, Res.first, false);
7276     PendingLoads.push_back(Res.second);
7277     return true;
7278   }
7279 
7280   return false;
7281 }
7282 
7283 /// See if we can lower a strnlen call into an optimized form.  If so, return
7284 /// true and lower it, otherwise return false and it will be lowered like a
7285 /// normal call.
7286 /// The caller already checked that \p I calls the appropriate LibFunc with a
7287 /// correct prototype.
7288 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7289   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7290 
7291   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7292   std::pair<SDValue, SDValue> Res =
7293     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7294                                  getValue(Arg0), getValue(Arg1),
7295                                  MachinePointerInfo(Arg0));
7296   if (Res.first.getNode()) {
7297     processIntegerCallValue(I, Res.first, false);
7298     PendingLoads.push_back(Res.second);
7299     return true;
7300   }
7301 
7302   return false;
7303 }
7304 
7305 /// See if we can lower a unary floating-point operation into an SDNode with
7306 /// the specified Opcode.  If so, return true and lower it, otherwise return
7307 /// false and it will be lowered like a normal call.
7308 /// The caller already checked that \p I calls the appropriate LibFunc with a
7309 /// correct prototype.
7310 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7311                                               unsigned Opcode) {
7312   // We already checked this call's prototype; verify it doesn't modify errno.
7313   if (!I.onlyReadsMemory())
7314     return false;
7315 
7316   SDValue Tmp = getValue(I.getArgOperand(0));
7317   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7318   return true;
7319 }
7320 
7321 /// See if we can lower a binary floating-point operation into an SDNode with
7322 /// the specified Opcode. If so, return true and lower it. Otherwise return
7323 /// false, and it will be lowered like a normal call.
7324 /// The caller already checked that \p I calls the appropriate LibFunc with a
7325 /// correct prototype.
7326 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7327                                                unsigned Opcode) {
7328   // We already checked this call's prototype; verify it doesn't modify errno.
7329   if (!I.onlyReadsMemory())
7330     return false;
7331 
7332   SDValue Tmp0 = getValue(I.getArgOperand(0));
7333   SDValue Tmp1 = getValue(I.getArgOperand(1));
7334   EVT VT = Tmp0.getValueType();
7335   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7336   return true;
7337 }
7338 
7339 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7340   // Handle inline assembly differently.
7341   if (isa<InlineAsm>(I.getCalledValue())) {
7342     visitInlineAsm(&I);
7343     return;
7344   }
7345 
7346   const char *RenameFn = nullptr;
7347   if (Function *F = I.getCalledFunction()) {
7348     if (F->isDeclaration()) {
7349       // Is this an LLVM intrinsic or a target-specific intrinsic?
7350       unsigned IID = F->getIntrinsicID();
7351       if (!IID)
7352         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7353           IID = II->getIntrinsicID(F);
7354 
7355       if (IID) {
7356         RenameFn = visitIntrinsicCall(I, IID);
7357         if (!RenameFn)
7358           return;
7359       }
7360     }
7361 
7362     // Check for well-known libc/libm calls.  If the function is internal, it
7363     // can't be a library call.  Don't do the check if marked as nobuiltin for
7364     // some reason or the call site requires strict floating point semantics.
7365     LibFunc Func;
7366     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7367         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7368         LibInfo->hasOptimizedCodeGen(Func)) {
7369       switch (Func) {
7370       default: break;
7371       case LibFunc_copysign:
7372       case LibFunc_copysignf:
7373       case LibFunc_copysignl:
7374         // We already checked this call's prototype; verify it doesn't modify
7375         // errno.
7376         if (I.onlyReadsMemory()) {
7377           SDValue LHS = getValue(I.getArgOperand(0));
7378           SDValue RHS = getValue(I.getArgOperand(1));
7379           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7380                                    LHS.getValueType(), LHS, RHS));
7381           return;
7382         }
7383         break;
7384       case LibFunc_fabs:
7385       case LibFunc_fabsf:
7386       case LibFunc_fabsl:
7387         if (visitUnaryFloatCall(I, ISD::FABS))
7388           return;
7389         break;
7390       case LibFunc_fmin:
7391       case LibFunc_fminf:
7392       case LibFunc_fminl:
7393         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7394           return;
7395         break;
7396       case LibFunc_fmax:
7397       case LibFunc_fmaxf:
7398       case LibFunc_fmaxl:
7399         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7400           return;
7401         break;
7402       case LibFunc_sin:
7403       case LibFunc_sinf:
7404       case LibFunc_sinl:
7405         if (visitUnaryFloatCall(I, ISD::FSIN))
7406           return;
7407         break;
7408       case LibFunc_cos:
7409       case LibFunc_cosf:
7410       case LibFunc_cosl:
7411         if (visitUnaryFloatCall(I, ISD::FCOS))
7412           return;
7413         break;
7414       case LibFunc_sqrt:
7415       case LibFunc_sqrtf:
7416       case LibFunc_sqrtl:
7417       case LibFunc_sqrt_finite:
7418       case LibFunc_sqrtf_finite:
7419       case LibFunc_sqrtl_finite:
7420         if (visitUnaryFloatCall(I, ISD::FSQRT))
7421           return;
7422         break;
7423       case LibFunc_floor:
7424       case LibFunc_floorf:
7425       case LibFunc_floorl:
7426         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7427           return;
7428         break;
7429       case LibFunc_nearbyint:
7430       case LibFunc_nearbyintf:
7431       case LibFunc_nearbyintl:
7432         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7433           return;
7434         break;
7435       case LibFunc_ceil:
7436       case LibFunc_ceilf:
7437       case LibFunc_ceill:
7438         if (visitUnaryFloatCall(I, ISD::FCEIL))
7439           return;
7440         break;
7441       case LibFunc_rint:
7442       case LibFunc_rintf:
7443       case LibFunc_rintl:
7444         if (visitUnaryFloatCall(I, ISD::FRINT))
7445           return;
7446         break;
7447       case LibFunc_round:
7448       case LibFunc_roundf:
7449       case LibFunc_roundl:
7450         if (visitUnaryFloatCall(I, ISD::FROUND))
7451           return;
7452         break;
7453       case LibFunc_trunc:
7454       case LibFunc_truncf:
7455       case LibFunc_truncl:
7456         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7457           return;
7458         break;
7459       case LibFunc_log2:
7460       case LibFunc_log2f:
7461       case LibFunc_log2l:
7462         if (visitUnaryFloatCall(I, ISD::FLOG2))
7463           return;
7464         break;
7465       case LibFunc_exp2:
7466       case LibFunc_exp2f:
7467       case LibFunc_exp2l:
7468         if (visitUnaryFloatCall(I, ISD::FEXP2))
7469           return;
7470         break;
7471       case LibFunc_memcmp:
7472         if (visitMemCmpCall(I))
7473           return;
7474         break;
7475       case LibFunc_mempcpy:
7476         if (visitMemPCpyCall(I))
7477           return;
7478         break;
7479       case LibFunc_memchr:
7480         if (visitMemChrCall(I))
7481           return;
7482         break;
7483       case LibFunc_strcpy:
7484         if (visitStrCpyCall(I, false))
7485           return;
7486         break;
7487       case LibFunc_stpcpy:
7488         if (visitStrCpyCall(I, true))
7489           return;
7490         break;
7491       case LibFunc_strcmp:
7492         if (visitStrCmpCall(I))
7493           return;
7494         break;
7495       case LibFunc_strlen:
7496         if (visitStrLenCall(I))
7497           return;
7498         break;
7499       case LibFunc_strnlen:
7500         if (visitStrNLenCall(I))
7501           return;
7502         break;
7503       }
7504     }
7505   }
7506 
7507   SDValue Callee;
7508   if (!RenameFn)
7509     Callee = getValue(I.getCalledValue());
7510   else
7511     Callee = DAG.getExternalSymbol(
7512         RenameFn,
7513         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7514 
7515   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7516   // have to do anything here to lower funclet bundles.
7517   assert(!I.hasOperandBundlesOtherThan(
7518              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7519          "Cannot lower calls with arbitrary operand bundles!");
7520 
7521   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7522     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7523   else
7524     // Check if we can potentially perform a tail call. More detailed checking
7525     // is be done within LowerCallTo, after more information about the call is
7526     // known.
7527     LowerCallTo(&I, Callee, I.isTailCall());
7528 }
7529 
7530 namespace {
7531 
7532 /// AsmOperandInfo - This contains information for each constraint that we are
7533 /// lowering.
7534 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7535 public:
7536   /// CallOperand - If this is the result output operand or a clobber
7537   /// this is null, otherwise it is the incoming operand to the CallInst.
7538   /// This gets modified as the asm is processed.
7539   SDValue CallOperand;
7540 
7541   /// AssignedRegs - If this is a register or register class operand, this
7542   /// contains the set of register corresponding to the operand.
7543   RegsForValue AssignedRegs;
7544 
7545   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7546     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7547   }
7548 
7549   /// Whether or not this operand accesses memory
7550   bool hasMemory(const TargetLowering &TLI) const {
7551     // Indirect operand accesses access memory.
7552     if (isIndirect)
7553       return true;
7554 
7555     for (const auto &Code : Codes)
7556       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7557         return true;
7558 
7559     return false;
7560   }
7561 
7562   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7563   /// corresponds to.  If there is no Value* for this operand, it returns
7564   /// MVT::Other.
7565   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7566                            const DataLayout &DL) const {
7567     if (!CallOperandVal) return MVT::Other;
7568 
7569     if (isa<BasicBlock>(CallOperandVal))
7570       return TLI.getPointerTy(DL);
7571 
7572     llvm::Type *OpTy = CallOperandVal->getType();
7573 
7574     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7575     // If this is an indirect operand, the operand is a pointer to the
7576     // accessed type.
7577     if (isIndirect) {
7578       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7579       if (!PtrTy)
7580         report_fatal_error("Indirect operand for inline asm not a pointer!");
7581       OpTy = PtrTy->getElementType();
7582     }
7583 
7584     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7585     if (StructType *STy = dyn_cast<StructType>(OpTy))
7586       if (STy->getNumElements() == 1)
7587         OpTy = STy->getElementType(0);
7588 
7589     // If OpTy is not a single value, it may be a struct/union that we
7590     // can tile with integers.
7591     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7592       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7593       switch (BitSize) {
7594       default: break;
7595       case 1:
7596       case 8:
7597       case 16:
7598       case 32:
7599       case 64:
7600       case 128:
7601         OpTy = IntegerType::get(Context, BitSize);
7602         break;
7603       }
7604     }
7605 
7606     return TLI.getValueType(DL, OpTy, true);
7607   }
7608 };
7609 
7610 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7611 
7612 } // end anonymous namespace
7613 
7614 /// Make sure that the output operand \p OpInfo and its corresponding input
7615 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7616 /// out).
7617 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7618                                SDISelAsmOperandInfo &MatchingOpInfo,
7619                                SelectionDAG &DAG) {
7620   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7621     return;
7622 
7623   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7624   const auto &TLI = DAG.getTargetLoweringInfo();
7625 
7626   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7627       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7628                                        OpInfo.ConstraintVT);
7629   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7630       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7631                                        MatchingOpInfo.ConstraintVT);
7632   if ((OpInfo.ConstraintVT.isInteger() !=
7633        MatchingOpInfo.ConstraintVT.isInteger()) ||
7634       (MatchRC.second != InputRC.second)) {
7635     // FIXME: error out in a more elegant fashion
7636     report_fatal_error("Unsupported asm: input constraint"
7637                        " with a matching output constraint of"
7638                        " incompatible type!");
7639   }
7640   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7641 }
7642 
7643 /// Get a direct memory input to behave well as an indirect operand.
7644 /// This may introduce stores, hence the need for a \p Chain.
7645 /// \return The (possibly updated) chain.
7646 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7647                                         SDISelAsmOperandInfo &OpInfo,
7648                                         SelectionDAG &DAG) {
7649   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7650 
7651   // If we don't have an indirect input, put it in the constpool if we can,
7652   // otherwise spill it to a stack slot.
7653   // TODO: This isn't quite right. We need to handle these according to
7654   // the addressing mode that the constraint wants. Also, this may take
7655   // an additional register for the computation and we don't want that
7656   // either.
7657 
7658   // If the operand is a float, integer, or vector constant, spill to a
7659   // constant pool entry to get its address.
7660   const Value *OpVal = OpInfo.CallOperandVal;
7661   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7662       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7663     OpInfo.CallOperand = DAG.getConstantPool(
7664         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7665     return Chain;
7666   }
7667 
7668   // Otherwise, create a stack slot and emit a store to it before the asm.
7669   Type *Ty = OpVal->getType();
7670   auto &DL = DAG.getDataLayout();
7671   uint64_t TySize = DL.getTypeAllocSize(Ty);
7672   unsigned Align = DL.getPrefTypeAlignment(Ty);
7673   MachineFunction &MF = DAG.getMachineFunction();
7674   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7675   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7676   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7677                        MachinePointerInfo::getFixedStack(MF, SSFI));
7678   OpInfo.CallOperand = StackSlot;
7679 
7680   return Chain;
7681 }
7682 
7683 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7684 /// specified operand.  We prefer to assign virtual registers, to allow the
7685 /// register allocator to handle the assignment process.  However, if the asm
7686 /// uses features that we can't model on machineinstrs, we have SDISel do the
7687 /// allocation.  This produces generally horrible, but correct, code.
7688 ///
7689 ///   OpInfo describes the operand
7690 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7691 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7692                                  SDISelAsmOperandInfo &OpInfo,
7693                                  SDISelAsmOperandInfo &RefOpInfo) {
7694   LLVMContext &Context = *DAG.getContext();
7695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7696 
7697   MachineFunction &MF = DAG.getMachineFunction();
7698   SmallVector<unsigned, 4> Regs;
7699   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7700 
7701   // No work to do for memory operations.
7702   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7703     return;
7704 
7705   // If this is a constraint for a single physreg, or a constraint for a
7706   // register class, find it.
7707   unsigned AssignedReg;
7708   const TargetRegisterClass *RC;
7709   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7710       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7711   // RC is unset only on failure. Return immediately.
7712   if (!RC)
7713     return;
7714 
7715   // Get the actual register value type.  This is important, because the user
7716   // may have asked for (e.g.) the AX register in i32 type.  We need to
7717   // remember that AX is actually i16 to get the right extension.
7718   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7719 
7720   if (OpInfo.ConstraintVT != MVT::Other) {
7721     // If this is an FP operand in an integer register (or visa versa), or more
7722     // generally if the operand value disagrees with the register class we plan
7723     // to stick it in, fix the operand type.
7724     //
7725     // If this is an input value, the bitcast to the new type is done now.
7726     // Bitcast for output value is done at the end of visitInlineAsm().
7727     if ((OpInfo.Type == InlineAsm::isOutput ||
7728          OpInfo.Type == InlineAsm::isInput) &&
7729         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7730       // Try to convert to the first EVT that the reg class contains.  If the
7731       // types are identical size, use a bitcast to convert (e.g. two differing
7732       // vector types).  Note: output bitcast is done at the end of
7733       // visitInlineAsm().
7734       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7735         // Exclude indirect inputs while they are unsupported because the code
7736         // to perform the load is missing and thus OpInfo.CallOperand still
7737         // refers to the input address rather than the pointed-to value.
7738         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7739           OpInfo.CallOperand =
7740               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7741         OpInfo.ConstraintVT = RegVT;
7742         // If the operand is an FP value and we want it in integer registers,
7743         // use the corresponding integer type. This turns an f64 value into
7744         // i64, which can be passed with two i32 values on a 32-bit machine.
7745       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7746         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7747         if (OpInfo.Type == InlineAsm::isInput)
7748           OpInfo.CallOperand =
7749               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7750         OpInfo.ConstraintVT = VT;
7751       }
7752     }
7753   }
7754 
7755   // No need to allocate a matching input constraint since the constraint it's
7756   // matching to has already been allocated.
7757   if (OpInfo.isMatchingInputConstraint())
7758     return;
7759 
7760   EVT ValueVT = OpInfo.ConstraintVT;
7761   if (OpInfo.ConstraintVT == MVT::Other)
7762     ValueVT = RegVT;
7763 
7764   // Initialize NumRegs.
7765   unsigned NumRegs = 1;
7766   if (OpInfo.ConstraintVT != MVT::Other)
7767     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7768 
7769   // If this is a constraint for a specific physical register, like {r17},
7770   // assign it now.
7771 
7772   // If this associated to a specific register, initialize iterator to correct
7773   // place. If virtual, make sure we have enough registers
7774 
7775   // Initialize iterator if necessary
7776   TargetRegisterClass::iterator I = RC->begin();
7777   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7778 
7779   // Do not check for single registers.
7780   if (AssignedReg) {
7781       for (; *I != AssignedReg; ++I)
7782         assert(I != RC->end() && "AssignedReg should be member of RC");
7783   }
7784 
7785   for (; NumRegs; --NumRegs, ++I) {
7786     assert(I != RC->end() && "Ran out of registers to allocate!");
7787     auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC);
7788     Regs.push_back(R);
7789   }
7790 
7791   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7792 }
7793 
7794 static unsigned
7795 findMatchingInlineAsmOperand(unsigned OperandNo,
7796                              const std::vector<SDValue> &AsmNodeOperands) {
7797   // Scan until we find the definition we already emitted of this operand.
7798   unsigned CurOp = InlineAsm::Op_FirstOperand;
7799   for (; OperandNo; --OperandNo) {
7800     // Advance to the next operand.
7801     unsigned OpFlag =
7802         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7803     assert((InlineAsm::isRegDefKind(OpFlag) ||
7804             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7805             InlineAsm::isMemKind(OpFlag)) &&
7806            "Skipped past definitions?");
7807     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7808   }
7809   return CurOp;
7810 }
7811 
7812 namespace {
7813 
7814 class ExtraFlags {
7815   unsigned Flags = 0;
7816 
7817 public:
7818   explicit ExtraFlags(ImmutableCallSite CS) {
7819     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7820     if (IA->hasSideEffects())
7821       Flags |= InlineAsm::Extra_HasSideEffects;
7822     if (IA->isAlignStack())
7823       Flags |= InlineAsm::Extra_IsAlignStack;
7824     if (CS.isConvergent())
7825       Flags |= InlineAsm::Extra_IsConvergent;
7826     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7827   }
7828 
7829   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7830     // Ideally, we would only check against memory constraints.  However, the
7831     // meaning of an Other constraint can be target-specific and we can't easily
7832     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7833     // for Other constraints as well.
7834     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7835         OpInfo.ConstraintType == TargetLowering::C_Other) {
7836       if (OpInfo.Type == InlineAsm::isInput)
7837         Flags |= InlineAsm::Extra_MayLoad;
7838       else if (OpInfo.Type == InlineAsm::isOutput)
7839         Flags |= InlineAsm::Extra_MayStore;
7840       else if (OpInfo.Type == InlineAsm::isClobber)
7841         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7842     }
7843   }
7844 
7845   unsigned get() const { return Flags; }
7846 };
7847 
7848 } // end anonymous namespace
7849 
7850 /// visitInlineAsm - Handle a call to an InlineAsm object.
7851 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7852   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7853 
7854   /// ConstraintOperands - Information about all of the constraints.
7855   SDISelAsmOperandInfoVector ConstraintOperands;
7856 
7857   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7858   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7859       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7860 
7861   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7862   // AsmDialect, MayLoad, MayStore).
7863   bool HasSideEffect = IA->hasSideEffects();
7864   ExtraFlags ExtraInfo(CS);
7865 
7866   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7867   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7868   for (auto &T : TargetConstraints) {
7869     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7870     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7871 
7872     // Compute the value type for each operand.
7873     if (OpInfo.Type == InlineAsm::isInput ||
7874         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7875       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7876 
7877       // Process the call argument. BasicBlocks are labels, currently appearing
7878       // only in asm's.
7879       const Instruction *I = CS.getInstruction();
7880       if (isa<CallBrInst>(I) &&
7881           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
7882                           cast<CallBrInst>(I)->getNumIndirectDests())) {
7883         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
7884         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
7885         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
7886       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7887         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7888       } else {
7889         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7890       }
7891 
7892       OpInfo.ConstraintVT =
7893           OpInfo
7894               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7895               .getSimpleVT();
7896     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7897       // The return value of the call is this value.  As such, there is no
7898       // corresponding argument.
7899       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7900       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7901         OpInfo.ConstraintVT = TLI.getSimpleValueType(
7902             DAG.getDataLayout(), STy->getElementType(ResNo));
7903       } else {
7904         assert(ResNo == 0 && "Asm only has one result!");
7905         OpInfo.ConstraintVT =
7906             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7907       }
7908       ++ResNo;
7909     } else {
7910       OpInfo.ConstraintVT = MVT::Other;
7911     }
7912 
7913     if (!HasSideEffect)
7914       HasSideEffect = OpInfo.hasMemory(TLI);
7915 
7916     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7917     // FIXME: Could we compute this on OpInfo rather than T?
7918 
7919     // Compute the constraint code and ConstraintType to use.
7920     TLI.ComputeConstraintToUse(T, SDValue());
7921 
7922     ExtraInfo.update(T);
7923   }
7924 
7925   // We won't need to flush pending loads if this asm doesn't touch
7926   // memory and is nonvolatile.
7927   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
7928 
7929   // Second pass over the constraints: compute which constraint option to use.
7930   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7931     // If this is an output operand with a matching input operand, look up the
7932     // matching input. If their types mismatch, e.g. one is an integer, the
7933     // other is floating point, or their sizes are different, flag it as an
7934     // error.
7935     if (OpInfo.hasMatchingInput()) {
7936       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7937       patchMatchingInput(OpInfo, Input, DAG);
7938     }
7939 
7940     // Compute the constraint code and ConstraintType to use.
7941     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7942 
7943     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7944         OpInfo.Type == InlineAsm::isClobber)
7945       continue;
7946 
7947     // If this is a memory input, and if the operand is not indirect, do what we
7948     // need to provide an address for the memory input.
7949     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7950         !OpInfo.isIndirect) {
7951       assert((OpInfo.isMultipleAlternative ||
7952               (OpInfo.Type == InlineAsm::isInput)) &&
7953              "Can only indirectify direct input operands!");
7954 
7955       // Memory operands really want the address of the value.
7956       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7957 
7958       // There is no longer a Value* corresponding to this operand.
7959       OpInfo.CallOperandVal = nullptr;
7960 
7961       // It is now an indirect operand.
7962       OpInfo.isIndirect = true;
7963     }
7964 
7965   }
7966 
7967   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7968   std::vector<SDValue> AsmNodeOperands;
7969   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7970   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7971       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7972 
7973   // If we have a !srcloc metadata node associated with it, we want to attach
7974   // this to the ultimately generated inline asm machineinstr.  To do this, we
7975   // pass in the third operand as this (potentially null) inline asm MDNode.
7976   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7977   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7978 
7979   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7980   // bits as operand 3.
7981   AsmNodeOperands.push_back(DAG.getTargetConstant(
7982       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7983 
7984   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
7985   // this, assign virtual and physical registers for inputs and otput.
7986   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7987     // Assign Registers.
7988     SDISelAsmOperandInfo &RefOpInfo =
7989         OpInfo.isMatchingInputConstraint()
7990             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7991             : OpInfo;
7992     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
7993 
7994     switch (OpInfo.Type) {
7995     case InlineAsm::isOutput:
7996       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7997           (OpInfo.ConstraintType == TargetLowering::C_Other &&
7998            OpInfo.isIndirect)) {
7999         unsigned ConstraintID =
8000             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8001         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8002                "Failed to convert memory constraint code to constraint id.");
8003 
8004         // Add information to the INLINEASM node to know about this output.
8005         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8006         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8007         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8008                                                         MVT::i32));
8009         AsmNodeOperands.push_back(OpInfo.CallOperand);
8010         break;
8011       } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
8012                   !OpInfo.isIndirect) ||
8013                  OpInfo.ConstraintType == TargetLowering::C_Register ||
8014                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
8015         // Otherwise, this outputs to a register (directly for C_Register /
8016         // C_RegisterClass, and a target-defined fashion for C_Other). Find a
8017         // register that we can use.
8018         if (OpInfo.AssignedRegs.Regs.empty()) {
8019           emitInlineAsmError(
8020               CS, "couldn't allocate output register for constraint '" +
8021                       Twine(OpInfo.ConstraintCode) + "'");
8022           return;
8023         }
8024 
8025         // Add information to the INLINEASM node to know that this register is
8026         // set.
8027         OpInfo.AssignedRegs.AddInlineAsmOperands(
8028             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8029                                   : InlineAsm::Kind_RegDef,
8030             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8031       }
8032       break;
8033 
8034     case InlineAsm::isInput: {
8035       SDValue InOperandVal = OpInfo.CallOperand;
8036 
8037       if (OpInfo.isMatchingInputConstraint()) {
8038         // If this is required to match an output register we have already set,
8039         // just use its register.
8040         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8041                                                   AsmNodeOperands);
8042         unsigned OpFlag =
8043           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8044         if (InlineAsm::isRegDefKind(OpFlag) ||
8045             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8046           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8047           if (OpInfo.isIndirect) {
8048             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8049             emitInlineAsmError(CS, "inline asm not supported yet:"
8050                                    " don't know how to handle tied "
8051                                    "indirect register inputs");
8052             return;
8053           }
8054 
8055           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8056           SmallVector<unsigned, 4> Regs;
8057 
8058           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8059             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8060             MachineRegisterInfo &RegInfo =
8061                 DAG.getMachineFunction().getRegInfo();
8062             for (unsigned i = 0; i != NumRegs; ++i)
8063               Regs.push_back(RegInfo.createVirtualRegister(RC));
8064           } else {
8065             emitInlineAsmError(CS, "inline asm error: This value type register "
8066                                    "class is not natively supported!");
8067             return;
8068           }
8069 
8070           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8071 
8072           SDLoc dl = getCurSDLoc();
8073           // Use the produced MatchedRegs object to
8074           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8075                                     CS.getInstruction());
8076           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8077                                            true, OpInfo.getMatchedOperand(), dl,
8078                                            DAG, AsmNodeOperands);
8079           break;
8080         }
8081 
8082         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8083         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8084                "Unexpected number of operands");
8085         // Add information to the INLINEASM node to know about this input.
8086         // See InlineAsm.h isUseOperandTiedToDef.
8087         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8088         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8089                                                     OpInfo.getMatchedOperand());
8090         AsmNodeOperands.push_back(DAG.getTargetConstant(
8091             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8092         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8093         break;
8094       }
8095 
8096       // Treat indirect 'X' constraint as memory.
8097       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8098           OpInfo.isIndirect)
8099         OpInfo.ConstraintType = TargetLowering::C_Memory;
8100 
8101       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
8102         std::vector<SDValue> Ops;
8103         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8104                                           Ops, DAG);
8105         if (Ops.empty()) {
8106           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8107                                      Twine(OpInfo.ConstraintCode) + "'");
8108           return;
8109         }
8110 
8111         // Add information to the INLINEASM node to know about this input.
8112         unsigned ResOpType =
8113           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8114         AsmNodeOperands.push_back(DAG.getTargetConstant(
8115             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8116         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8117         break;
8118       }
8119 
8120       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8121         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8122         assert(InOperandVal.getValueType() ==
8123                    TLI.getPointerTy(DAG.getDataLayout()) &&
8124                "Memory operands expect pointer values");
8125 
8126         unsigned ConstraintID =
8127             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8128         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8129                "Failed to convert memory constraint code to constraint id.");
8130 
8131         // Add information to the INLINEASM node to know about this input.
8132         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8133         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8134         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8135                                                         getCurSDLoc(),
8136                                                         MVT::i32));
8137         AsmNodeOperands.push_back(InOperandVal);
8138         break;
8139       }
8140 
8141       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8142               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8143              "Unknown constraint type!");
8144 
8145       // TODO: Support this.
8146       if (OpInfo.isIndirect) {
8147         emitInlineAsmError(
8148             CS, "Don't know how to handle indirect register inputs yet "
8149                 "for constraint '" +
8150                     Twine(OpInfo.ConstraintCode) + "'");
8151         return;
8152       }
8153 
8154       // Copy the input into the appropriate registers.
8155       if (OpInfo.AssignedRegs.Regs.empty()) {
8156         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8157                                    Twine(OpInfo.ConstraintCode) + "'");
8158         return;
8159       }
8160 
8161       SDLoc dl = getCurSDLoc();
8162 
8163       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8164                                         Chain, &Flag, CS.getInstruction());
8165 
8166       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8167                                                dl, DAG, AsmNodeOperands);
8168       break;
8169     }
8170     case InlineAsm::isClobber:
8171       // Add the clobbered value to the operand list, so that the register
8172       // allocator is aware that the physreg got clobbered.
8173       if (!OpInfo.AssignedRegs.Regs.empty())
8174         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8175                                                  false, 0, getCurSDLoc(), DAG,
8176                                                  AsmNodeOperands);
8177       break;
8178     }
8179   }
8180 
8181   // Finish up input operands.  Set the input chain and add the flag last.
8182   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8183   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8184 
8185   unsigned ISDOpc = isa<CallBrInst>(CS.getInstruction()) ? ISD::INLINEASM_BR
8186                                                          : ISD::INLINEASM;
8187   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8188                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8189   Flag = Chain.getValue(1);
8190 
8191   // Do additional work to generate outputs.
8192 
8193   SmallVector<EVT, 1> ResultVTs;
8194   SmallVector<SDValue, 1> ResultValues;
8195   SmallVector<SDValue, 8> OutChains;
8196 
8197   llvm::Type *CSResultType = CS.getType();
8198   ArrayRef<Type *> ResultTypes;
8199   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8200     ResultTypes = StructResult->elements();
8201   else if (!CSResultType->isVoidTy())
8202     ResultTypes = makeArrayRef(CSResultType);
8203 
8204   auto CurResultType = ResultTypes.begin();
8205   auto handleRegAssign = [&](SDValue V) {
8206     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8207     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8208     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8209     ++CurResultType;
8210     // If the type of the inline asm call site return value is different but has
8211     // same size as the type of the asm output bitcast it.  One example of this
8212     // is for vectors with different width / number of elements.  This can
8213     // happen for register classes that can contain multiple different value
8214     // types.  The preg or vreg allocated may not have the same VT as was
8215     // expected.
8216     //
8217     // This can also happen for a return value that disagrees with the register
8218     // class it is put in, eg. a double in a general-purpose register on a
8219     // 32-bit machine.
8220     if (ResultVT != V.getValueType() &&
8221         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8222       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8223     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8224              V.getValueType().isInteger()) {
8225       // If a result value was tied to an input value, the computed result
8226       // may have a wider width than the expected result.  Extract the
8227       // relevant portion.
8228       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8229     }
8230     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8231     ResultVTs.push_back(ResultVT);
8232     ResultValues.push_back(V);
8233   };
8234 
8235   // Deal with output operands.
8236   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8237     if (OpInfo.Type == InlineAsm::isOutput) {
8238       SDValue Val;
8239       // Skip trivial output operands.
8240       if (OpInfo.AssignedRegs.Regs.empty())
8241         continue;
8242 
8243       switch (OpInfo.ConstraintType) {
8244       case TargetLowering::C_Register:
8245       case TargetLowering::C_RegisterClass:
8246         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8247             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8248         break;
8249       case TargetLowering::C_Other:
8250         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8251                                               OpInfo, DAG);
8252         break;
8253       case TargetLowering::C_Memory:
8254         break; // Already handled.
8255       case TargetLowering::C_Unknown:
8256         assert(false && "Unexpected unknown constraint");
8257       }
8258 
8259       // Indirect output manifest as stores. Record output chains.
8260       if (OpInfo.isIndirect) {
8261         const Value *Ptr = OpInfo.CallOperandVal;
8262         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8263         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8264                                      MachinePointerInfo(Ptr));
8265         OutChains.push_back(Store);
8266       } else {
8267         // generate CopyFromRegs to associated registers.
8268         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8269         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8270           for (const SDValue &V : Val->op_values())
8271             handleRegAssign(V);
8272         } else
8273           handleRegAssign(Val);
8274       }
8275     }
8276   }
8277 
8278   // Set results.
8279   if (!ResultValues.empty()) {
8280     assert(CurResultType == ResultTypes.end() &&
8281            "Mismatch in number of ResultTypes");
8282     assert(ResultValues.size() == ResultTypes.size() &&
8283            "Mismatch in number of output operands in asm result");
8284 
8285     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8286                             DAG.getVTList(ResultVTs), ResultValues);
8287     setValue(CS.getInstruction(), V);
8288   }
8289 
8290   // Collect store chains.
8291   if (!OutChains.empty())
8292     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8293 
8294   // Only Update Root if inline assembly has a memory effect.
8295   if (ResultValues.empty() || HasSideEffect || !OutChains.empty())
8296     DAG.setRoot(Chain);
8297 }
8298 
8299 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8300                                              const Twine &Message) {
8301   LLVMContext &Ctx = *DAG.getContext();
8302   Ctx.emitError(CS.getInstruction(), Message);
8303 
8304   // Make sure we leave the DAG in a valid state
8305   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8306   SmallVector<EVT, 1> ValueVTs;
8307   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8308 
8309   if (ValueVTs.empty())
8310     return;
8311 
8312   SmallVector<SDValue, 1> Ops;
8313   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8314     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8315 
8316   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8317 }
8318 
8319 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8320   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8321                           MVT::Other, getRoot(),
8322                           getValue(I.getArgOperand(0)),
8323                           DAG.getSrcValue(I.getArgOperand(0))));
8324 }
8325 
8326 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8327   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8328   const DataLayout &DL = DAG.getDataLayout();
8329   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
8330                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
8331                            DAG.getSrcValue(I.getOperand(0)),
8332                            DL.getABITypeAlignment(I.getType()));
8333   setValue(&I, V);
8334   DAG.setRoot(V.getValue(1));
8335 }
8336 
8337 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8338   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8339                           MVT::Other, getRoot(),
8340                           getValue(I.getArgOperand(0)),
8341                           DAG.getSrcValue(I.getArgOperand(0))));
8342 }
8343 
8344 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8345   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8346                           MVT::Other, getRoot(),
8347                           getValue(I.getArgOperand(0)),
8348                           getValue(I.getArgOperand(1)),
8349                           DAG.getSrcValue(I.getArgOperand(0)),
8350                           DAG.getSrcValue(I.getArgOperand(1))));
8351 }
8352 
8353 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8354                                                     const Instruction &I,
8355                                                     SDValue Op) {
8356   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8357   if (!Range)
8358     return Op;
8359 
8360   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8361   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8362     return Op;
8363 
8364   APInt Lo = CR.getUnsignedMin();
8365   if (!Lo.isMinValue())
8366     return Op;
8367 
8368   APInt Hi = CR.getUnsignedMax();
8369   unsigned Bits = std::max(Hi.getActiveBits(),
8370                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8371 
8372   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8373 
8374   SDLoc SL = getCurSDLoc();
8375 
8376   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8377                              DAG.getValueType(SmallVT));
8378   unsigned NumVals = Op.getNode()->getNumValues();
8379   if (NumVals == 1)
8380     return ZExt;
8381 
8382   SmallVector<SDValue, 4> Ops;
8383 
8384   Ops.push_back(ZExt);
8385   for (unsigned I = 1; I != NumVals; ++I)
8386     Ops.push_back(Op.getValue(I));
8387 
8388   return DAG.getMergeValues(Ops, SL);
8389 }
8390 
8391 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8392 /// the call being lowered.
8393 ///
8394 /// This is a helper for lowering intrinsics that follow a target calling
8395 /// convention or require stack pointer adjustment. Only a subset of the
8396 /// intrinsic's operands need to participate in the calling convention.
8397 void SelectionDAGBuilder::populateCallLoweringInfo(
8398     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8399     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8400     bool IsPatchPoint) {
8401   TargetLowering::ArgListTy Args;
8402   Args.reserve(NumArgs);
8403 
8404   // Populate the argument list.
8405   // Attributes for args start at offset 1, after the return attribute.
8406   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8407        ArgI != ArgE; ++ArgI) {
8408     const Value *V = Call->getOperand(ArgI);
8409 
8410     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8411 
8412     TargetLowering::ArgListEntry Entry;
8413     Entry.Node = getValue(V);
8414     Entry.Ty = V->getType();
8415     Entry.setAttributes(Call, ArgI);
8416     Args.push_back(Entry);
8417   }
8418 
8419   CLI.setDebugLoc(getCurSDLoc())
8420       .setChain(getRoot())
8421       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8422       .setDiscardResult(Call->use_empty())
8423       .setIsPatchPoint(IsPatchPoint);
8424 }
8425 
8426 /// Add a stack map intrinsic call's live variable operands to a stackmap
8427 /// or patchpoint target node's operand list.
8428 ///
8429 /// Constants are converted to TargetConstants purely as an optimization to
8430 /// avoid constant materialization and register allocation.
8431 ///
8432 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8433 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8434 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8435 /// address materialization and register allocation, but may also be required
8436 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8437 /// alloca in the entry block, then the runtime may assume that the alloca's
8438 /// StackMap location can be read immediately after compilation and that the
8439 /// location is valid at any point during execution (this is similar to the
8440 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8441 /// only available in a register, then the runtime would need to trap when
8442 /// execution reaches the StackMap in order to read the alloca's location.
8443 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8444                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8445                                 SelectionDAGBuilder &Builder) {
8446   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8447     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8448     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8449       Ops.push_back(
8450         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8451       Ops.push_back(
8452         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8453     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8454       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8455       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8456           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8457     } else
8458       Ops.push_back(OpVal);
8459   }
8460 }
8461 
8462 /// Lower llvm.experimental.stackmap directly to its target opcode.
8463 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8464   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8465   //                                  [live variables...])
8466 
8467   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8468 
8469   SDValue Chain, InFlag, Callee, NullPtr;
8470   SmallVector<SDValue, 32> Ops;
8471 
8472   SDLoc DL = getCurSDLoc();
8473   Callee = getValue(CI.getCalledValue());
8474   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8475 
8476   // The stackmap intrinsic only records the live variables (the arguemnts
8477   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8478   // intrinsic, this won't be lowered to a function call. This means we don't
8479   // have to worry about calling conventions and target specific lowering code.
8480   // Instead we perform the call lowering right here.
8481   //
8482   // chain, flag = CALLSEQ_START(chain, 0, 0)
8483   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8484   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8485   //
8486   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8487   InFlag = Chain.getValue(1);
8488 
8489   // Add the <id> and <numBytes> constants.
8490   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8491   Ops.push_back(DAG.getTargetConstant(
8492                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8493   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8494   Ops.push_back(DAG.getTargetConstant(
8495                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8496                   MVT::i32));
8497 
8498   // Push live variables for the stack map.
8499   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8500 
8501   // We are not pushing any register mask info here on the operands list,
8502   // because the stackmap doesn't clobber anything.
8503 
8504   // Push the chain and the glue flag.
8505   Ops.push_back(Chain);
8506   Ops.push_back(InFlag);
8507 
8508   // Create the STACKMAP node.
8509   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8510   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8511   Chain = SDValue(SM, 0);
8512   InFlag = Chain.getValue(1);
8513 
8514   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8515 
8516   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8517 
8518   // Set the root to the target-lowered call chain.
8519   DAG.setRoot(Chain);
8520 
8521   // Inform the Frame Information that we have a stackmap in this function.
8522   FuncInfo.MF->getFrameInfo().setHasStackMap();
8523 }
8524 
8525 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8526 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8527                                           const BasicBlock *EHPadBB) {
8528   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8529   //                                                 i32 <numBytes>,
8530   //                                                 i8* <target>,
8531   //                                                 i32 <numArgs>,
8532   //                                                 [Args...],
8533   //                                                 [live variables...])
8534 
8535   CallingConv::ID CC = CS.getCallingConv();
8536   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8537   bool HasDef = !CS->getType()->isVoidTy();
8538   SDLoc dl = getCurSDLoc();
8539   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8540 
8541   // Handle immediate and symbolic callees.
8542   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8543     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8544                                    /*isTarget=*/true);
8545   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8546     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8547                                          SDLoc(SymbolicCallee),
8548                                          SymbolicCallee->getValueType(0));
8549 
8550   // Get the real number of arguments participating in the call <numArgs>
8551   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8552   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8553 
8554   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8555   // Intrinsics include all meta-operands up to but not including CC.
8556   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8557   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8558          "Not enough arguments provided to the patchpoint intrinsic");
8559 
8560   // For AnyRegCC the arguments are lowered later on manually.
8561   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8562   Type *ReturnTy =
8563     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8564 
8565   TargetLowering::CallLoweringInfo CLI(DAG);
8566   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8567                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8568   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8569 
8570   SDNode *CallEnd = Result.second.getNode();
8571   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8572     CallEnd = CallEnd->getOperand(0).getNode();
8573 
8574   /// Get a call instruction from the call sequence chain.
8575   /// Tail calls are not allowed.
8576   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8577          "Expected a callseq node.");
8578   SDNode *Call = CallEnd->getOperand(0).getNode();
8579   bool HasGlue = Call->getGluedNode();
8580 
8581   // Replace the target specific call node with the patchable intrinsic.
8582   SmallVector<SDValue, 8> Ops;
8583 
8584   // Add the <id> and <numBytes> constants.
8585   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8586   Ops.push_back(DAG.getTargetConstant(
8587                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8588   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8589   Ops.push_back(DAG.getTargetConstant(
8590                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8591                   MVT::i32));
8592 
8593   // Add the callee.
8594   Ops.push_back(Callee);
8595 
8596   // Adjust <numArgs> to account for any arguments that have been passed on the
8597   // stack instead.
8598   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8599   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8600   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8601   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8602 
8603   // Add the calling convention
8604   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8605 
8606   // Add the arguments we omitted previously. The register allocator should
8607   // place these in any free register.
8608   if (IsAnyRegCC)
8609     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8610       Ops.push_back(getValue(CS.getArgument(i)));
8611 
8612   // Push the arguments from the call instruction up to the register mask.
8613   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8614   Ops.append(Call->op_begin() + 2, e);
8615 
8616   // Push live variables for the stack map.
8617   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8618 
8619   // Push the register mask info.
8620   if (HasGlue)
8621     Ops.push_back(*(Call->op_end()-2));
8622   else
8623     Ops.push_back(*(Call->op_end()-1));
8624 
8625   // Push the chain (this is originally the first operand of the call, but
8626   // becomes now the last or second to last operand).
8627   Ops.push_back(*(Call->op_begin()));
8628 
8629   // Push the glue flag (last operand).
8630   if (HasGlue)
8631     Ops.push_back(*(Call->op_end()-1));
8632 
8633   SDVTList NodeTys;
8634   if (IsAnyRegCC && HasDef) {
8635     // Create the return types based on the intrinsic definition
8636     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8637     SmallVector<EVT, 3> ValueVTs;
8638     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8639     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8640 
8641     // There is always a chain and a glue type at the end
8642     ValueVTs.push_back(MVT::Other);
8643     ValueVTs.push_back(MVT::Glue);
8644     NodeTys = DAG.getVTList(ValueVTs);
8645   } else
8646     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8647 
8648   // Replace the target specific call node with a PATCHPOINT node.
8649   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8650                                          dl, NodeTys, Ops);
8651 
8652   // Update the NodeMap.
8653   if (HasDef) {
8654     if (IsAnyRegCC)
8655       setValue(CS.getInstruction(), SDValue(MN, 0));
8656     else
8657       setValue(CS.getInstruction(), Result.first);
8658   }
8659 
8660   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8661   // call sequence. Furthermore the location of the chain and glue can change
8662   // when the AnyReg calling convention is used and the intrinsic returns a
8663   // value.
8664   if (IsAnyRegCC && HasDef) {
8665     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8666     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8667     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8668   } else
8669     DAG.ReplaceAllUsesWith(Call, MN);
8670   DAG.DeleteNode(Call);
8671 
8672   // Inform the Frame Information that we have a patchpoint in this function.
8673   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8674 }
8675 
8676 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8677                                             unsigned Intrinsic) {
8678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8679   SDValue Op1 = getValue(I.getArgOperand(0));
8680   SDValue Op2;
8681   if (I.getNumArgOperands() > 1)
8682     Op2 = getValue(I.getArgOperand(1));
8683   SDLoc dl = getCurSDLoc();
8684   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8685   SDValue Res;
8686   FastMathFlags FMF;
8687   if (isa<FPMathOperator>(I))
8688     FMF = I.getFastMathFlags();
8689 
8690   switch (Intrinsic) {
8691   case Intrinsic::experimental_vector_reduce_fadd:
8692     if (FMF.isFast())
8693       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8694     else
8695       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8696     break;
8697   case Intrinsic::experimental_vector_reduce_fmul:
8698     if (FMF.isFast())
8699       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8700     else
8701       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8702     break;
8703   case Intrinsic::experimental_vector_reduce_add:
8704     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8705     break;
8706   case Intrinsic::experimental_vector_reduce_mul:
8707     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8708     break;
8709   case Intrinsic::experimental_vector_reduce_and:
8710     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8711     break;
8712   case Intrinsic::experimental_vector_reduce_or:
8713     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8714     break;
8715   case Intrinsic::experimental_vector_reduce_xor:
8716     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8717     break;
8718   case Intrinsic::experimental_vector_reduce_smax:
8719     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8720     break;
8721   case Intrinsic::experimental_vector_reduce_smin:
8722     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8723     break;
8724   case Intrinsic::experimental_vector_reduce_umax:
8725     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8726     break;
8727   case Intrinsic::experimental_vector_reduce_umin:
8728     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8729     break;
8730   case Intrinsic::experimental_vector_reduce_fmax:
8731     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8732     break;
8733   case Intrinsic::experimental_vector_reduce_fmin:
8734     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8735     break;
8736   default:
8737     llvm_unreachable("Unhandled vector reduce intrinsic");
8738   }
8739   setValue(&I, Res);
8740 }
8741 
8742 /// Returns an AttributeList representing the attributes applied to the return
8743 /// value of the given call.
8744 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8745   SmallVector<Attribute::AttrKind, 2> Attrs;
8746   if (CLI.RetSExt)
8747     Attrs.push_back(Attribute::SExt);
8748   if (CLI.RetZExt)
8749     Attrs.push_back(Attribute::ZExt);
8750   if (CLI.IsInReg)
8751     Attrs.push_back(Attribute::InReg);
8752 
8753   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8754                             Attrs);
8755 }
8756 
8757 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8758 /// implementation, which just calls LowerCall.
8759 /// FIXME: When all targets are
8760 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8761 std::pair<SDValue, SDValue>
8762 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8763   // Handle the incoming return values from the call.
8764   CLI.Ins.clear();
8765   Type *OrigRetTy = CLI.RetTy;
8766   SmallVector<EVT, 4> RetTys;
8767   SmallVector<uint64_t, 4> Offsets;
8768   auto &DL = CLI.DAG.getDataLayout();
8769   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8770 
8771   if (CLI.IsPostTypeLegalization) {
8772     // If we are lowering a libcall after legalization, split the return type.
8773     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8774     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8775     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8776       EVT RetVT = OldRetTys[i];
8777       uint64_t Offset = OldOffsets[i];
8778       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8779       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8780       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8781       RetTys.append(NumRegs, RegisterVT);
8782       for (unsigned j = 0; j != NumRegs; ++j)
8783         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8784     }
8785   }
8786 
8787   SmallVector<ISD::OutputArg, 4> Outs;
8788   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8789 
8790   bool CanLowerReturn =
8791       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8792                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8793 
8794   SDValue DemoteStackSlot;
8795   int DemoteStackIdx = -100;
8796   if (!CanLowerReturn) {
8797     // FIXME: equivalent assert?
8798     // assert(!CS.hasInAllocaArgument() &&
8799     //        "sret demotion is incompatible with inalloca");
8800     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8801     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8802     MachineFunction &MF = CLI.DAG.getMachineFunction();
8803     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8804     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8805                                               DL.getAllocaAddrSpace());
8806 
8807     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8808     ArgListEntry Entry;
8809     Entry.Node = DemoteStackSlot;
8810     Entry.Ty = StackSlotPtrType;
8811     Entry.IsSExt = false;
8812     Entry.IsZExt = false;
8813     Entry.IsInReg = false;
8814     Entry.IsSRet = true;
8815     Entry.IsNest = false;
8816     Entry.IsByVal = false;
8817     Entry.IsReturned = false;
8818     Entry.IsSwiftSelf = false;
8819     Entry.IsSwiftError = false;
8820     Entry.Alignment = Align;
8821     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8822     CLI.NumFixedArgs += 1;
8823     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8824 
8825     // sret demotion isn't compatible with tail-calls, since the sret argument
8826     // points into the callers stack frame.
8827     CLI.IsTailCall = false;
8828   } else {
8829     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8830       EVT VT = RetTys[I];
8831       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8832                                                      CLI.CallConv, VT);
8833       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8834                                                        CLI.CallConv, VT);
8835       for (unsigned i = 0; i != NumRegs; ++i) {
8836         ISD::InputArg MyFlags;
8837         MyFlags.VT = RegisterVT;
8838         MyFlags.ArgVT = VT;
8839         MyFlags.Used = CLI.IsReturnValueUsed;
8840         if (CLI.RetSExt)
8841           MyFlags.Flags.setSExt();
8842         if (CLI.RetZExt)
8843           MyFlags.Flags.setZExt();
8844         if (CLI.IsInReg)
8845           MyFlags.Flags.setInReg();
8846         CLI.Ins.push_back(MyFlags);
8847       }
8848     }
8849   }
8850 
8851   // We push in swifterror return as the last element of CLI.Ins.
8852   ArgListTy &Args = CLI.getArgs();
8853   if (supportSwiftError()) {
8854     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8855       if (Args[i].IsSwiftError) {
8856         ISD::InputArg MyFlags;
8857         MyFlags.VT = getPointerTy(DL);
8858         MyFlags.ArgVT = EVT(getPointerTy(DL));
8859         MyFlags.Flags.setSwiftError();
8860         CLI.Ins.push_back(MyFlags);
8861       }
8862     }
8863   }
8864 
8865   // Handle all of the outgoing arguments.
8866   CLI.Outs.clear();
8867   CLI.OutVals.clear();
8868   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8869     SmallVector<EVT, 4> ValueVTs;
8870     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8871     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8872     Type *FinalType = Args[i].Ty;
8873     if (Args[i].IsByVal)
8874       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8875     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8876         FinalType, CLI.CallConv, CLI.IsVarArg);
8877     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8878          ++Value) {
8879       EVT VT = ValueVTs[Value];
8880       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8881       SDValue Op = SDValue(Args[i].Node.getNode(),
8882                            Args[i].Node.getResNo() + Value);
8883       ISD::ArgFlagsTy Flags;
8884 
8885       // Certain targets (such as MIPS), may have a different ABI alignment
8886       // for a type depending on the context. Give the target a chance to
8887       // specify the alignment it wants.
8888       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8889 
8890       if (Args[i].IsZExt)
8891         Flags.setZExt();
8892       if (Args[i].IsSExt)
8893         Flags.setSExt();
8894       if (Args[i].IsInReg) {
8895         // If we are using vectorcall calling convention, a structure that is
8896         // passed InReg - is surely an HVA
8897         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8898             isa<StructType>(FinalType)) {
8899           // The first value of a structure is marked
8900           if (0 == Value)
8901             Flags.setHvaStart();
8902           Flags.setHva();
8903         }
8904         // Set InReg Flag
8905         Flags.setInReg();
8906       }
8907       if (Args[i].IsSRet)
8908         Flags.setSRet();
8909       if (Args[i].IsSwiftSelf)
8910         Flags.setSwiftSelf();
8911       if (Args[i].IsSwiftError)
8912         Flags.setSwiftError();
8913       if (Args[i].IsByVal)
8914         Flags.setByVal();
8915       if (Args[i].IsInAlloca) {
8916         Flags.setInAlloca();
8917         // Set the byval flag for CCAssignFn callbacks that don't know about
8918         // inalloca.  This way we can know how many bytes we should've allocated
8919         // and how many bytes a callee cleanup function will pop.  If we port
8920         // inalloca to more targets, we'll have to add custom inalloca handling
8921         // in the various CC lowering callbacks.
8922         Flags.setByVal();
8923       }
8924       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8925         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8926         Type *ElementTy = Ty->getElementType();
8927         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8928         // For ByVal, alignment should come from FE.  BE will guess if this
8929         // info is not there but there are cases it cannot get right.
8930         unsigned FrameAlign;
8931         if (Args[i].Alignment)
8932           FrameAlign = Args[i].Alignment;
8933         else
8934           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8935         Flags.setByValAlign(FrameAlign);
8936       }
8937       if (Args[i].IsNest)
8938         Flags.setNest();
8939       if (NeedsRegBlock)
8940         Flags.setInConsecutiveRegs();
8941       Flags.setOrigAlign(OriginalAlignment);
8942 
8943       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8944                                                  CLI.CallConv, VT);
8945       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8946                                                         CLI.CallConv, VT);
8947       SmallVector<SDValue, 4> Parts(NumParts);
8948       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8949 
8950       if (Args[i].IsSExt)
8951         ExtendKind = ISD::SIGN_EXTEND;
8952       else if (Args[i].IsZExt)
8953         ExtendKind = ISD::ZERO_EXTEND;
8954 
8955       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8956       // for now.
8957       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8958           CanLowerReturn) {
8959         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8960                "unexpected use of 'returned'");
8961         // Before passing 'returned' to the target lowering code, ensure that
8962         // either the register MVT and the actual EVT are the same size or that
8963         // the return value and argument are extended in the same way; in these
8964         // cases it's safe to pass the argument register value unchanged as the
8965         // return register value (although it's at the target's option whether
8966         // to do so)
8967         // TODO: allow code generation to take advantage of partially preserved
8968         // registers rather than clobbering the entire register when the
8969         // parameter extension method is not compatible with the return
8970         // extension method
8971         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8972             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8973              CLI.RetZExt == Args[i].IsZExt))
8974           Flags.setReturned();
8975       }
8976 
8977       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8978                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
8979 
8980       for (unsigned j = 0; j != NumParts; ++j) {
8981         // if it isn't first piece, alignment must be 1
8982         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8983                                i < CLI.NumFixedArgs,
8984                                i, j*Parts[j].getValueType().getStoreSize());
8985         if (NumParts > 1 && j == 0)
8986           MyFlags.Flags.setSplit();
8987         else if (j != 0) {
8988           MyFlags.Flags.setOrigAlign(1);
8989           if (j == NumParts - 1)
8990             MyFlags.Flags.setSplitEnd();
8991         }
8992 
8993         CLI.Outs.push_back(MyFlags);
8994         CLI.OutVals.push_back(Parts[j]);
8995       }
8996 
8997       if (NeedsRegBlock && Value == NumValues - 1)
8998         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8999     }
9000   }
9001 
9002   SmallVector<SDValue, 4> InVals;
9003   CLI.Chain = LowerCall(CLI, InVals);
9004 
9005   // Update CLI.InVals to use outside of this function.
9006   CLI.InVals = InVals;
9007 
9008   // Verify that the target's LowerCall behaved as expected.
9009   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9010          "LowerCall didn't return a valid chain!");
9011   assert((!CLI.IsTailCall || InVals.empty()) &&
9012          "LowerCall emitted a return value for a tail call!");
9013   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9014          "LowerCall didn't emit the correct number of values!");
9015 
9016   // For a tail call, the return value is merely live-out and there aren't
9017   // any nodes in the DAG representing it. Return a special value to
9018   // indicate that a tail call has been emitted and no more Instructions
9019   // should be processed in the current block.
9020   if (CLI.IsTailCall) {
9021     CLI.DAG.setRoot(CLI.Chain);
9022     return std::make_pair(SDValue(), SDValue());
9023   }
9024 
9025 #ifndef NDEBUG
9026   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9027     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9028     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9029            "LowerCall emitted a value with the wrong type!");
9030   }
9031 #endif
9032 
9033   SmallVector<SDValue, 4> ReturnValues;
9034   if (!CanLowerReturn) {
9035     // The instruction result is the result of loading from the
9036     // hidden sret parameter.
9037     SmallVector<EVT, 1> PVTs;
9038     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9039 
9040     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9041     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9042     EVT PtrVT = PVTs[0];
9043 
9044     unsigned NumValues = RetTys.size();
9045     ReturnValues.resize(NumValues);
9046     SmallVector<SDValue, 4> Chains(NumValues);
9047 
9048     // An aggregate return value cannot wrap around the address space, so
9049     // offsets to its parts don't wrap either.
9050     SDNodeFlags Flags;
9051     Flags.setNoUnsignedWrap(true);
9052 
9053     for (unsigned i = 0; i < NumValues; ++i) {
9054       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9055                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9056                                                         PtrVT), Flags);
9057       SDValue L = CLI.DAG.getLoad(
9058           RetTys[i], CLI.DL, CLI.Chain, Add,
9059           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9060                                             DemoteStackIdx, Offsets[i]),
9061           /* Alignment = */ 1);
9062       ReturnValues[i] = L;
9063       Chains[i] = L.getValue(1);
9064     }
9065 
9066     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9067   } else {
9068     // Collect the legal value parts into potentially illegal values
9069     // that correspond to the original function's return values.
9070     Optional<ISD::NodeType> AssertOp;
9071     if (CLI.RetSExt)
9072       AssertOp = ISD::AssertSext;
9073     else if (CLI.RetZExt)
9074       AssertOp = ISD::AssertZext;
9075     unsigned CurReg = 0;
9076     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9077       EVT VT = RetTys[I];
9078       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9079                                                      CLI.CallConv, VT);
9080       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9081                                                        CLI.CallConv, VT);
9082 
9083       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9084                                               NumRegs, RegisterVT, VT, nullptr,
9085                                               CLI.CallConv, AssertOp));
9086       CurReg += NumRegs;
9087     }
9088 
9089     // For a function returning void, there is no return value. We can't create
9090     // such a node, so we just return a null return value in that case. In
9091     // that case, nothing will actually look at the value.
9092     if (ReturnValues.empty())
9093       return std::make_pair(SDValue(), CLI.Chain);
9094   }
9095 
9096   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9097                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9098   return std::make_pair(Res, CLI.Chain);
9099 }
9100 
9101 void TargetLowering::LowerOperationWrapper(SDNode *N,
9102                                            SmallVectorImpl<SDValue> &Results,
9103                                            SelectionDAG &DAG) const {
9104   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9105     Results.push_back(Res);
9106 }
9107 
9108 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9109   llvm_unreachable("LowerOperation not implemented for this target!");
9110 }
9111 
9112 void
9113 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9114   SDValue Op = getNonRegisterValue(V);
9115   assert((Op.getOpcode() != ISD::CopyFromReg ||
9116           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9117          "Copy from a reg to the same reg!");
9118   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
9119 
9120   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9121   // If this is an InlineAsm we have to match the registers required, not the
9122   // notional registers required by the type.
9123 
9124   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9125                    None); // This is not an ABI copy.
9126   SDValue Chain = DAG.getEntryNode();
9127 
9128   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9129                               FuncInfo.PreferredExtendType.end())
9130                                  ? ISD::ANY_EXTEND
9131                                  : FuncInfo.PreferredExtendType[V];
9132   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9133   PendingExports.push_back(Chain);
9134 }
9135 
9136 #include "llvm/CodeGen/SelectionDAGISel.h"
9137 
9138 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9139 /// entry block, return true.  This includes arguments used by switches, since
9140 /// the switch may expand into multiple basic blocks.
9141 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9142   // With FastISel active, we may be splitting blocks, so force creation
9143   // of virtual registers for all non-dead arguments.
9144   if (FastISel)
9145     return A->use_empty();
9146 
9147   const BasicBlock &Entry = A->getParent()->front();
9148   for (const User *U : A->users())
9149     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9150       return false;  // Use not in entry block.
9151 
9152   return true;
9153 }
9154 
9155 using ArgCopyElisionMapTy =
9156     DenseMap<const Argument *,
9157              std::pair<const AllocaInst *, const StoreInst *>>;
9158 
9159 /// Scan the entry block of the function in FuncInfo for arguments that look
9160 /// like copies into a local alloca. Record any copied arguments in
9161 /// ArgCopyElisionCandidates.
9162 static void
9163 findArgumentCopyElisionCandidates(const DataLayout &DL,
9164                                   FunctionLoweringInfo *FuncInfo,
9165                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9166   // Record the state of every static alloca used in the entry block. Argument
9167   // allocas are all used in the entry block, so we need approximately as many
9168   // entries as we have arguments.
9169   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9170   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9171   unsigned NumArgs = FuncInfo->Fn->arg_size();
9172   StaticAllocas.reserve(NumArgs * 2);
9173 
9174   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9175     if (!V)
9176       return nullptr;
9177     V = V->stripPointerCasts();
9178     const auto *AI = dyn_cast<AllocaInst>(V);
9179     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9180       return nullptr;
9181     auto Iter = StaticAllocas.insert({AI, Unknown});
9182     return &Iter.first->second;
9183   };
9184 
9185   // Look for stores of arguments to static allocas. Look through bitcasts and
9186   // GEPs to handle type coercions, as long as the alloca is fully initialized
9187   // by the store. Any non-store use of an alloca escapes it and any subsequent
9188   // unanalyzed store might write it.
9189   // FIXME: Handle structs initialized with multiple stores.
9190   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9191     // Look for stores, and handle non-store uses conservatively.
9192     const auto *SI = dyn_cast<StoreInst>(&I);
9193     if (!SI) {
9194       // We will look through cast uses, so ignore them completely.
9195       if (I.isCast())
9196         continue;
9197       // Ignore debug info intrinsics, they don't escape or store to allocas.
9198       if (isa<DbgInfoIntrinsic>(I))
9199         continue;
9200       // This is an unknown instruction. Assume it escapes or writes to all
9201       // static alloca operands.
9202       for (const Use &U : I.operands()) {
9203         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9204           *Info = StaticAllocaInfo::Clobbered;
9205       }
9206       continue;
9207     }
9208 
9209     // If the stored value is a static alloca, mark it as escaped.
9210     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9211       *Info = StaticAllocaInfo::Clobbered;
9212 
9213     // Check if the destination is a static alloca.
9214     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9215     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9216     if (!Info)
9217       continue;
9218     const AllocaInst *AI = cast<AllocaInst>(Dst);
9219 
9220     // Skip allocas that have been initialized or clobbered.
9221     if (*Info != StaticAllocaInfo::Unknown)
9222       continue;
9223 
9224     // Check if the stored value is an argument, and that this store fully
9225     // initializes the alloca. Don't elide copies from the same argument twice.
9226     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9227     const auto *Arg = dyn_cast<Argument>(Val);
9228     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9229         Arg->getType()->isEmptyTy() ||
9230         DL.getTypeStoreSize(Arg->getType()) !=
9231             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9232         ArgCopyElisionCandidates.count(Arg)) {
9233       *Info = StaticAllocaInfo::Clobbered;
9234       continue;
9235     }
9236 
9237     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9238                       << '\n');
9239 
9240     // Mark this alloca and store for argument copy elision.
9241     *Info = StaticAllocaInfo::Elidable;
9242     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9243 
9244     // Stop scanning if we've seen all arguments. This will happen early in -O0
9245     // builds, which is useful, because -O0 builds have large entry blocks and
9246     // many allocas.
9247     if (ArgCopyElisionCandidates.size() == NumArgs)
9248       break;
9249   }
9250 }
9251 
9252 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9253 /// ArgVal is a load from a suitable fixed stack object.
9254 static void tryToElideArgumentCopy(
9255     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9256     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9257     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9258     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9259     SDValue ArgVal, bool &ArgHasUses) {
9260   // Check if this is a load from a fixed stack object.
9261   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9262   if (!LNode)
9263     return;
9264   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9265   if (!FINode)
9266     return;
9267 
9268   // Check that the fixed stack object is the right size and alignment.
9269   // Look at the alignment that the user wrote on the alloca instead of looking
9270   // at the stack object.
9271   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9272   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9273   const AllocaInst *AI = ArgCopyIter->second.first;
9274   int FixedIndex = FINode->getIndex();
9275   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9276   int OldIndex = AllocaIndex;
9277   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9278   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9279     LLVM_DEBUG(
9280         dbgs() << "  argument copy elision failed due to bad fixed stack "
9281                   "object size\n");
9282     return;
9283   }
9284   unsigned RequiredAlignment = AI->getAlignment();
9285   if (!RequiredAlignment) {
9286     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9287         AI->getAllocatedType());
9288   }
9289   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9290     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9291                          "greater than stack argument alignment ("
9292                       << RequiredAlignment << " vs "
9293                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9294     return;
9295   }
9296 
9297   // Perform the elision. Delete the old stack object and replace its only use
9298   // in the variable info map. Mark the stack object as mutable.
9299   LLVM_DEBUG({
9300     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9301            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9302            << '\n';
9303   });
9304   MFI.RemoveStackObject(OldIndex);
9305   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9306   AllocaIndex = FixedIndex;
9307   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9308   Chains.push_back(ArgVal.getValue(1));
9309 
9310   // Avoid emitting code for the store implementing the copy.
9311   const StoreInst *SI = ArgCopyIter->second.second;
9312   ElidedArgCopyInstrs.insert(SI);
9313 
9314   // Check for uses of the argument again so that we can avoid exporting ArgVal
9315   // if it is't used by anything other than the store.
9316   for (const Value *U : Arg.users()) {
9317     if (U != SI) {
9318       ArgHasUses = true;
9319       break;
9320     }
9321   }
9322 }
9323 
9324 void SelectionDAGISel::LowerArguments(const Function &F) {
9325   SelectionDAG &DAG = SDB->DAG;
9326   SDLoc dl = SDB->getCurSDLoc();
9327   const DataLayout &DL = DAG.getDataLayout();
9328   SmallVector<ISD::InputArg, 16> Ins;
9329 
9330   if (!FuncInfo->CanLowerReturn) {
9331     // Put in an sret pointer parameter before all the other parameters.
9332     SmallVector<EVT, 1> ValueVTs;
9333     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9334                     F.getReturnType()->getPointerTo(
9335                         DAG.getDataLayout().getAllocaAddrSpace()),
9336                     ValueVTs);
9337 
9338     // NOTE: Assuming that a pointer will never break down to more than one VT
9339     // or one register.
9340     ISD::ArgFlagsTy Flags;
9341     Flags.setSRet();
9342     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9343     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9344                          ISD::InputArg::NoArgIndex, 0);
9345     Ins.push_back(RetArg);
9346   }
9347 
9348   // Look for stores of arguments to static allocas. Mark such arguments with a
9349   // flag to ask the target to give us the memory location of that argument if
9350   // available.
9351   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9352   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9353 
9354   // Set up the incoming argument description vector.
9355   for (const Argument &Arg : F.args()) {
9356     unsigned ArgNo = Arg.getArgNo();
9357     SmallVector<EVT, 4> ValueVTs;
9358     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9359     bool isArgValueUsed = !Arg.use_empty();
9360     unsigned PartBase = 0;
9361     Type *FinalType = Arg.getType();
9362     if (Arg.hasAttribute(Attribute::ByVal))
9363       FinalType = cast<PointerType>(FinalType)->getElementType();
9364     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9365         FinalType, F.getCallingConv(), F.isVarArg());
9366     for (unsigned Value = 0, NumValues = ValueVTs.size();
9367          Value != NumValues; ++Value) {
9368       EVT VT = ValueVTs[Value];
9369       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9370       ISD::ArgFlagsTy Flags;
9371 
9372       // Certain targets (such as MIPS), may have a different ABI alignment
9373       // for a type depending on the context. Give the target a chance to
9374       // specify the alignment it wants.
9375       unsigned OriginalAlignment =
9376           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9377 
9378       if (Arg.hasAttribute(Attribute::ZExt))
9379         Flags.setZExt();
9380       if (Arg.hasAttribute(Attribute::SExt))
9381         Flags.setSExt();
9382       if (Arg.hasAttribute(Attribute::InReg)) {
9383         // If we are using vectorcall calling convention, a structure that is
9384         // passed InReg - is surely an HVA
9385         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9386             isa<StructType>(Arg.getType())) {
9387           // The first value of a structure is marked
9388           if (0 == Value)
9389             Flags.setHvaStart();
9390           Flags.setHva();
9391         }
9392         // Set InReg Flag
9393         Flags.setInReg();
9394       }
9395       if (Arg.hasAttribute(Attribute::StructRet))
9396         Flags.setSRet();
9397       if (Arg.hasAttribute(Attribute::SwiftSelf))
9398         Flags.setSwiftSelf();
9399       if (Arg.hasAttribute(Attribute::SwiftError))
9400         Flags.setSwiftError();
9401       if (Arg.hasAttribute(Attribute::ByVal))
9402         Flags.setByVal();
9403       if (Arg.hasAttribute(Attribute::InAlloca)) {
9404         Flags.setInAlloca();
9405         // Set the byval flag for CCAssignFn callbacks that don't know about
9406         // inalloca.  This way we can know how many bytes we should've allocated
9407         // and how many bytes a callee cleanup function will pop.  If we port
9408         // inalloca to more targets, we'll have to add custom inalloca handling
9409         // in the various CC lowering callbacks.
9410         Flags.setByVal();
9411       }
9412       if (F.getCallingConv() == CallingConv::X86_INTR) {
9413         // IA Interrupt passes frame (1st parameter) by value in the stack.
9414         if (ArgNo == 0)
9415           Flags.setByVal();
9416       }
9417       if (Flags.isByVal() || Flags.isInAlloca()) {
9418         PointerType *Ty = cast<PointerType>(Arg.getType());
9419         Type *ElementTy = Ty->getElementType();
9420         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
9421         // For ByVal, alignment should be passed from FE.  BE will guess if
9422         // this info is not there but there are cases it cannot get right.
9423         unsigned FrameAlign;
9424         if (Arg.getParamAlignment())
9425           FrameAlign = Arg.getParamAlignment();
9426         else
9427           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9428         Flags.setByValAlign(FrameAlign);
9429       }
9430       if (Arg.hasAttribute(Attribute::Nest))
9431         Flags.setNest();
9432       if (NeedsRegBlock)
9433         Flags.setInConsecutiveRegs();
9434       Flags.setOrigAlign(OriginalAlignment);
9435       if (ArgCopyElisionCandidates.count(&Arg))
9436         Flags.setCopyElisionCandidate();
9437 
9438       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9439           *CurDAG->getContext(), F.getCallingConv(), VT);
9440       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9441           *CurDAG->getContext(), F.getCallingConv(), VT);
9442       for (unsigned i = 0; i != NumRegs; ++i) {
9443         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9444                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9445         if (NumRegs > 1 && i == 0)
9446           MyFlags.Flags.setSplit();
9447         // if it isn't first piece, alignment must be 1
9448         else if (i > 0) {
9449           MyFlags.Flags.setOrigAlign(1);
9450           if (i == NumRegs - 1)
9451             MyFlags.Flags.setSplitEnd();
9452         }
9453         Ins.push_back(MyFlags);
9454       }
9455       if (NeedsRegBlock && Value == NumValues - 1)
9456         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9457       PartBase += VT.getStoreSize();
9458     }
9459   }
9460 
9461   // Call the target to set up the argument values.
9462   SmallVector<SDValue, 8> InVals;
9463   SDValue NewRoot = TLI->LowerFormalArguments(
9464       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9465 
9466   // Verify that the target's LowerFormalArguments behaved as expected.
9467   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9468          "LowerFormalArguments didn't return a valid chain!");
9469   assert(InVals.size() == Ins.size() &&
9470          "LowerFormalArguments didn't emit the correct number of values!");
9471   LLVM_DEBUG({
9472     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9473       assert(InVals[i].getNode() &&
9474              "LowerFormalArguments emitted a null value!");
9475       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9476              "LowerFormalArguments emitted a value with the wrong type!");
9477     }
9478   });
9479 
9480   // Update the DAG with the new chain value resulting from argument lowering.
9481   DAG.setRoot(NewRoot);
9482 
9483   // Set up the argument values.
9484   unsigned i = 0;
9485   if (!FuncInfo->CanLowerReturn) {
9486     // Create a virtual register for the sret pointer, and put in a copy
9487     // from the sret argument into it.
9488     SmallVector<EVT, 1> ValueVTs;
9489     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9490                     F.getReturnType()->getPointerTo(
9491                         DAG.getDataLayout().getAllocaAddrSpace()),
9492                     ValueVTs);
9493     MVT VT = ValueVTs[0].getSimpleVT();
9494     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9495     Optional<ISD::NodeType> AssertOp = None;
9496     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9497                                         nullptr, F.getCallingConv(), AssertOp);
9498 
9499     MachineFunction& MF = SDB->DAG.getMachineFunction();
9500     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9501     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9502     FuncInfo->DemoteRegister = SRetReg;
9503     NewRoot =
9504         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9505     DAG.setRoot(NewRoot);
9506 
9507     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9508     ++i;
9509   }
9510 
9511   SmallVector<SDValue, 4> Chains;
9512   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9513   for (const Argument &Arg : F.args()) {
9514     SmallVector<SDValue, 4> ArgValues;
9515     SmallVector<EVT, 4> ValueVTs;
9516     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9517     unsigned NumValues = ValueVTs.size();
9518     if (NumValues == 0)
9519       continue;
9520 
9521     bool ArgHasUses = !Arg.use_empty();
9522 
9523     // Elide the copying store if the target loaded this argument from a
9524     // suitable fixed stack object.
9525     if (Ins[i].Flags.isCopyElisionCandidate()) {
9526       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9527                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9528                              InVals[i], ArgHasUses);
9529     }
9530 
9531     // If this argument is unused then remember its value. It is used to generate
9532     // debugging information.
9533     bool isSwiftErrorArg =
9534         TLI->supportSwiftError() &&
9535         Arg.hasAttribute(Attribute::SwiftError);
9536     if (!ArgHasUses && !isSwiftErrorArg) {
9537       SDB->setUnusedArgValue(&Arg, InVals[i]);
9538 
9539       // Also remember any frame index for use in FastISel.
9540       if (FrameIndexSDNode *FI =
9541           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9542         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9543     }
9544 
9545     for (unsigned Val = 0; Val != NumValues; ++Val) {
9546       EVT VT = ValueVTs[Val];
9547       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9548                                                       F.getCallingConv(), VT);
9549       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9550           *CurDAG->getContext(), F.getCallingConv(), VT);
9551 
9552       // Even an apparant 'unused' swifterror argument needs to be returned. So
9553       // we do generate a copy for it that can be used on return from the
9554       // function.
9555       if (ArgHasUses || isSwiftErrorArg) {
9556         Optional<ISD::NodeType> AssertOp;
9557         if (Arg.hasAttribute(Attribute::SExt))
9558           AssertOp = ISD::AssertSext;
9559         else if (Arg.hasAttribute(Attribute::ZExt))
9560           AssertOp = ISD::AssertZext;
9561 
9562         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9563                                              PartVT, VT, nullptr,
9564                                              F.getCallingConv(), AssertOp));
9565       }
9566 
9567       i += NumParts;
9568     }
9569 
9570     // We don't need to do anything else for unused arguments.
9571     if (ArgValues.empty())
9572       continue;
9573 
9574     // Note down frame index.
9575     if (FrameIndexSDNode *FI =
9576         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9577       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9578 
9579     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9580                                      SDB->getCurSDLoc());
9581 
9582     SDB->setValue(&Arg, Res);
9583     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9584       // We want to associate the argument with the frame index, among
9585       // involved operands, that correspond to the lowest address. The
9586       // getCopyFromParts function, called earlier, is swapping the order of
9587       // the operands to BUILD_PAIR depending on endianness. The result of
9588       // that swapping is that the least significant bits of the argument will
9589       // be in the first operand of the BUILD_PAIR node, and the most
9590       // significant bits will be in the second operand.
9591       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9592       if (LoadSDNode *LNode =
9593           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9594         if (FrameIndexSDNode *FI =
9595             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9596           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9597     }
9598 
9599     // Update the SwiftErrorVRegDefMap.
9600     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9601       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9602       if (TargetRegisterInfo::isVirtualRegister(Reg))
9603         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9604                                            FuncInfo->SwiftErrorArg, Reg);
9605     }
9606 
9607     // If this argument is live outside of the entry block, insert a copy from
9608     // wherever we got it to the vreg that other BB's will reference it as.
9609     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9610       // If we can, though, try to skip creating an unnecessary vreg.
9611       // FIXME: This isn't very clean... it would be nice to make this more
9612       // general.  It's also subtly incompatible with the hacks FastISel
9613       // uses with vregs.
9614       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9615       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9616         FuncInfo->ValueMap[&Arg] = Reg;
9617         continue;
9618       }
9619     }
9620     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9621       FuncInfo->InitializeRegForValue(&Arg);
9622       SDB->CopyToExportRegsIfNeeded(&Arg);
9623     }
9624   }
9625 
9626   if (!Chains.empty()) {
9627     Chains.push_back(NewRoot);
9628     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9629   }
9630 
9631   DAG.setRoot(NewRoot);
9632 
9633   assert(i == InVals.size() && "Argument register count mismatch!");
9634 
9635   // If any argument copy elisions occurred and we have debug info, update the
9636   // stale frame indices used in the dbg.declare variable info table.
9637   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9638   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9639     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9640       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9641       if (I != ArgCopyElisionFrameIndexMap.end())
9642         VI.Slot = I->second;
9643     }
9644   }
9645 
9646   // Finally, if the target has anything special to do, allow it to do so.
9647   EmitFunctionEntryCode();
9648 }
9649 
9650 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9651 /// ensure constants are generated when needed.  Remember the virtual registers
9652 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9653 /// directly add them, because expansion might result in multiple MBB's for one
9654 /// BB.  As such, the start of the BB might correspond to a different MBB than
9655 /// the end.
9656 void
9657 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9658   const Instruction *TI = LLVMBB->getTerminator();
9659 
9660   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9661 
9662   // Check PHI nodes in successors that expect a value to be available from this
9663   // block.
9664   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9665     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9666     if (!isa<PHINode>(SuccBB->begin())) continue;
9667     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9668 
9669     // If this terminator has multiple identical successors (common for
9670     // switches), only handle each succ once.
9671     if (!SuccsHandled.insert(SuccMBB).second)
9672       continue;
9673 
9674     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9675 
9676     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9677     // nodes and Machine PHI nodes, but the incoming operands have not been
9678     // emitted yet.
9679     for (const PHINode &PN : SuccBB->phis()) {
9680       // Ignore dead phi's.
9681       if (PN.use_empty())
9682         continue;
9683 
9684       // Skip empty types
9685       if (PN.getType()->isEmptyTy())
9686         continue;
9687 
9688       unsigned Reg;
9689       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9690 
9691       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9692         unsigned &RegOut = ConstantsOut[C];
9693         if (RegOut == 0) {
9694           RegOut = FuncInfo.CreateRegs(C->getType());
9695           CopyValueToVirtualRegister(C, RegOut);
9696         }
9697         Reg = RegOut;
9698       } else {
9699         DenseMap<const Value *, unsigned>::iterator I =
9700           FuncInfo.ValueMap.find(PHIOp);
9701         if (I != FuncInfo.ValueMap.end())
9702           Reg = I->second;
9703         else {
9704           assert(isa<AllocaInst>(PHIOp) &&
9705                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9706                  "Didn't codegen value into a register!??");
9707           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9708           CopyValueToVirtualRegister(PHIOp, Reg);
9709         }
9710       }
9711 
9712       // Remember that this register needs to added to the machine PHI node as
9713       // the input for this MBB.
9714       SmallVector<EVT, 4> ValueVTs;
9715       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9716       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9717       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9718         EVT VT = ValueVTs[vti];
9719         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9720         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9721           FuncInfo.PHINodesToUpdate.push_back(
9722               std::make_pair(&*MBBI++, Reg + i));
9723         Reg += NumRegisters;
9724       }
9725     }
9726   }
9727 
9728   ConstantsOut.clear();
9729 }
9730 
9731 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9732 /// is 0.
9733 MachineBasicBlock *
9734 SelectionDAGBuilder::StackProtectorDescriptor::
9735 AddSuccessorMBB(const BasicBlock *BB,
9736                 MachineBasicBlock *ParentMBB,
9737                 bool IsLikely,
9738                 MachineBasicBlock *SuccMBB) {
9739   // If SuccBB has not been created yet, create it.
9740   if (!SuccMBB) {
9741     MachineFunction *MF = ParentMBB->getParent();
9742     MachineFunction::iterator BBI(ParentMBB);
9743     SuccMBB = MF->CreateMachineBasicBlock(BB);
9744     MF->insert(++BBI, SuccMBB);
9745   }
9746   // Add it as a successor of ParentMBB.
9747   ParentMBB->addSuccessor(
9748       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9749   return SuccMBB;
9750 }
9751 
9752 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9753   MachineFunction::iterator I(MBB);
9754   if (++I == FuncInfo.MF->end())
9755     return nullptr;
9756   return &*I;
9757 }
9758 
9759 /// During lowering new call nodes can be created (such as memset, etc.).
9760 /// Those will become new roots of the current DAG, but complications arise
9761 /// when they are tail calls. In such cases, the call lowering will update
9762 /// the root, but the builder still needs to know that a tail call has been
9763 /// lowered in order to avoid generating an additional return.
9764 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9765   // If the node is null, we do have a tail call.
9766   if (MaybeTC.getNode() != nullptr)
9767     DAG.setRoot(MaybeTC);
9768   else
9769     HasTailCall = true;
9770 }
9771 
9772 uint64_t
9773 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9774                                        unsigned First, unsigned Last) const {
9775   assert(Last >= First);
9776   const APInt &LowCase = Clusters[First].Low->getValue();
9777   const APInt &HighCase = Clusters[Last].High->getValue();
9778   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9779 
9780   // FIXME: A range of consecutive cases has 100% density, but only requires one
9781   // comparison to lower. We should discriminate against such consecutive ranges
9782   // in jump tables.
9783 
9784   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9785 }
9786 
9787 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9788     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9789     unsigned Last) const {
9790   assert(Last >= First);
9791   assert(TotalCases[Last] >= TotalCases[First]);
9792   uint64_t NumCases =
9793       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9794   return NumCases;
9795 }
9796 
9797 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9798                                          unsigned First, unsigned Last,
9799                                          const SwitchInst *SI,
9800                                          MachineBasicBlock *DefaultMBB,
9801                                          CaseCluster &JTCluster) {
9802   assert(First <= Last);
9803 
9804   auto Prob = BranchProbability::getZero();
9805   unsigned NumCmps = 0;
9806   std::vector<MachineBasicBlock*> Table;
9807   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9808 
9809   // Initialize probabilities in JTProbs.
9810   for (unsigned I = First; I <= Last; ++I)
9811     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9812 
9813   for (unsigned I = First; I <= Last; ++I) {
9814     assert(Clusters[I].Kind == CC_Range);
9815     Prob += Clusters[I].Prob;
9816     const APInt &Low = Clusters[I].Low->getValue();
9817     const APInt &High = Clusters[I].High->getValue();
9818     NumCmps += (Low == High) ? 1 : 2;
9819     if (I != First) {
9820       // Fill the gap between this and the previous cluster.
9821       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9822       assert(PreviousHigh.slt(Low));
9823       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9824       for (uint64_t J = 0; J < Gap; J++)
9825         Table.push_back(DefaultMBB);
9826     }
9827     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9828     for (uint64_t J = 0; J < ClusterSize; ++J)
9829       Table.push_back(Clusters[I].MBB);
9830     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9831   }
9832 
9833   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9834   unsigned NumDests = JTProbs.size();
9835   if (TLI.isSuitableForBitTests(
9836           NumDests, NumCmps, Clusters[First].Low->getValue(),
9837           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9838     // Clusters[First..Last] should be lowered as bit tests instead.
9839     return false;
9840   }
9841 
9842   // Create the MBB that will load from and jump through the table.
9843   // Note: We create it here, but it's not inserted into the function yet.
9844   MachineFunction *CurMF = FuncInfo.MF;
9845   MachineBasicBlock *JumpTableMBB =
9846       CurMF->CreateMachineBasicBlock(SI->getParent());
9847 
9848   // Add successors. Note: use table order for determinism.
9849   SmallPtrSet<MachineBasicBlock *, 8> Done;
9850   for (MachineBasicBlock *Succ : Table) {
9851     if (Done.count(Succ))
9852       continue;
9853     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9854     Done.insert(Succ);
9855   }
9856   JumpTableMBB->normalizeSuccProbs();
9857 
9858   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9859                      ->createJumpTableIndex(Table);
9860 
9861   // Set up the jump table info.
9862   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9863   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9864                       Clusters[Last].High->getValue(), SI->getCondition(),
9865                       nullptr, false);
9866   JTCases.emplace_back(std::move(JTH), std::move(JT));
9867 
9868   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9869                                      JTCases.size() - 1, Prob);
9870   return true;
9871 }
9872 
9873 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9874                                          const SwitchInst *SI,
9875                                          MachineBasicBlock *DefaultMBB) {
9876 #ifndef NDEBUG
9877   // Clusters must be non-empty, sorted, and only contain Range clusters.
9878   assert(!Clusters.empty());
9879   for (CaseCluster &C : Clusters)
9880     assert(C.Kind == CC_Range);
9881   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9882     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9883 #endif
9884 
9885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9886   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9887     return;
9888 
9889   const int64_t N = Clusters.size();
9890   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9891   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9892 
9893   if (N < 2 || N < MinJumpTableEntries)
9894     return;
9895 
9896   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9897   SmallVector<unsigned, 8> TotalCases(N);
9898   for (unsigned i = 0; i < N; ++i) {
9899     const APInt &Hi = Clusters[i].High->getValue();
9900     const APInt &Lo = Clusters[i].Low->getValue();
9901     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9902     if (i != 0)
9903       TotalCases[i] += TotalCases[i - 1];
9904   }
9905 
9906   // Cheap case: the whole range may be suitable for jump table.
9907   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9908   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9909   assert(NumCases < UINT64_MAX / 100);
9910   assert(Range >= NumCases);
9911   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9912     CaseCluster JTCluster;
9913     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9914       Clusters[0] = JTCluster;
9915       Clusters.resize(1);
9916       return;
9917     }
9918   }
9919 
9920   // The algorithm below is not suitable for -O0.
9921   if (TM.getOptLevel() == CodeGenOpt::None)
9922     return;
9923 
9924   // Split Clusters into minimum number of dense partitions. The algorithm uses
9925   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9926   // for the Case Statement'" (1994), but builds the MinPartitions array in
9927   // reverse order to make it easier to reconstruct the partitions in ascending
9928   // order. In the choice between two optimal partitionings, it picks the one
9929   // which yields more jump tables.
9930 
9931   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9932   SmallVector<unsigned, 8> MinPartitions(N);
9933   // LastElement[i] is the last element of the partition starting at i.
9934   SmallVector<unsigned, 8> LastElement(N);
9935   // PartitionsScore[i] is used to break ties when choosing between two
9936   // partitionings resulting in the same number of partitions.
9937   SmallVector<unsigned, 8> PartitionsScore(N);
9938   // For PartitionsScore, a small number of comparisons is considered as good as
9939   // a jump table and a single comparison is considered better than a jump
9940   // table.
9941   enum PartitionScores : unsigned {
9942     NoTable = 0,
9943     Table = 1,
9944     FewCases = 1,
9945     SingleCase = 2
9946   };
9947 
9948   // Base case: There is only one way to partition Clusters[N-1].
9949   MinPartitions[N - 1] = 1;
9950   LastElement[N - 1] = N - 1;
9951   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9952 
9953   // Note: loop indexes are signed to avoid underflow.
9954   for (int64_t i = N - 2; i >= 0; i--) {
9955     // Find optimal partitioning of Clusters[i..N-1].
9956     // Baseline: Put Clusters[i] into a partition on its own.
9957     MinPartitions[i] = MinPartitions[i + 1] + 1;
9958     LastElement[i] = i;
9959     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9960 
9961     // Search for a solution that results in fewer partitions.
9962     for (int64_t j = N - 1; j > i; j--) {
9963       // Try building a partition from Clusters[i..j].
9964       uint64_t Range = getJumpTableRange(Clusters, i, j);
9965       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9966       assert(NumCases < UINT64_MAX / 100);
9967       assert(Range >= NumCases);
9968       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9969         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9970         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9971         int64_t NumEntries = j - i + 1;
9972 
9973         if (NumEntries == 1)
9974           Score += PartitionScores::SingleCase;
9975         else if (NumEntries <= SmallNumberOfEntries)
9976           Score += PartitionScores::FewCases;
9977         else if (NumEntries >= MinJumpTableEntries)
9978           Score += PartitionScores::Table;
9979 
9980         // If this leads to fewer partitions, or to the same number of
9981         // partitions with better score, it is a better partitioning.
9982         if (NumPartitions < MinPartitions[i] ||
9983             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9984           MinPartitions[i] = NumPartitions;
9985           LastElement[i] = j;
9986           PartitionsScore[i] = Score;
9987         }
9988       }
9989     }
9990   }
9991 
9992   // Iterate over the partitions, replacing some with jump tables in-place.
9993   unsigned DstIndex = 0;
9994   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9995     Last = LastElement[First];
9996     assert(Last >= First);
9997     assert(DstIndex <= First);
9998     unsigned NumClusters = Last - First + 1;
9999 
10000     CaseCluster JTCluster;
10001     if (NumClusters >= MinJumpTableEntries &&
10002         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
10003       Clusters[DstIndex++] = JTCluster;
10004     } else {
10005       for (unsigned I = First; I <= Last; ++I)
10006         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
10007     }
10008   }
10009   Clusters.resize(DstIndex);
10010 }
10011 
10012 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
10013                                         unsigned First, unsigned Last,
10014                                         const SwitchInst *SI,
10015                                         CaseCluster &BTCluster) {
10016   assert(First <= Last);
10017   if (First == Last)
10018     return false;
10019 
10020   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
10021   unsigned NumCmps = 0;
10022   for (int64_t I = First; I <= Last; ++I) {
10023     assert(Clusters[I].Kind == CC_Range);
10024     Dests.set(Clusters[I].MBB->getNumber());
10025     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
10026   }
10027   unsigned NumDests = Dests.count();
10028 
10029   APInt Low = Clusters[First].Low->getValue();
10030   APInt High = Clusters[Last].High->getValue();
10031   assert(Low.slt(High));
10032 
10033   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10034   const DataLayout &DL = DAG.getDataLayout();
10035   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
10036     return false;
10037 
10038   APInt LowBound;
10039   APInt CmpRange;
10040 
10041   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
10042   assert(TLI.rangeFitsInWord(Low, High, DL) &&
10043          "Case range must fit in bit mask!");
10044 
10045   // Check if the clusters cover a contiguous range such that no value in the
10046   // range will jump to the default statement.
10047   bool ContiguousRange = true;
10048   for (int64_t I = First + 1; I <= Last; ++I) {
10049     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
10050       ContiguousRange = false;
10051       break;
10052     }
10053   }
10054 
10055   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
10056     // Optimize the case where all the case values fit in a word without having
10057     // to subtract minValue. In this case, we can optimize away the subtraction.
10058     LowBound = APInt::getNullValue(Low.getBitWidth());
10059     CmpRange = High;
10060     ContiguousRange = false;
10061   } else {
10062     LowBound = Low;
10063     CmpRange = High - Low;
10064   }
10065 
10066   CaseBitsVector CBV;
10067   auto TotalProb = BranchProbability::getZero();
10068   for (unsigned i = First; i <= Last; ++i) {
10069     // Find the CaseBits for this destination.
10070     unsigned j;
10071     for (j = 0; j < CBV.size(); ++j)
10072       if (CBV[j].BB == Clusters[i].MBB)
10073         break;
10074     if (j == CBV.size())
10075       CBV.push_back(
10076           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
10077     CaseBits *CB = &CBV[j];
10078 
10079     // Update Mask, Bits and ExtraProb.
10080     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
10081     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
10082     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
10083     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
10084     CB->Bits += Hi - Lo + 1;
10085     CB->ExtraProb += Clusters[i].Prob;
10086     TotalProb += Clusters[i].Prob;
10087   }
10088 
10089   BitTestInfo BTI;
10090   llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
10091     // Sort by probability first, number of bits second, bit mask third.
10092     if (a.ExtraProb != b.ExtraProb)
10093       return a.ExtraProb > b.ExtraProb;
10094     if (a.Bits != b.Bits)
10095       return a.Bits > b.Bits;
10096     return a.Mask < b.Mask;
10097   });
10098 
10099   for (auto &CB : CBV) {
10100     MachineBasicBlock *BitTestBB =
10101         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
10102     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
10103   }
10104   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
10105                             SI->getCondition(), -1U, MVT::Other, false,
10106                             ContiguousRange, nullptr, nullptr, std::move(BTI),
10107                             TotalProb);
10108 
10109   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
10110                                     BitTestCases.size() - 1, TotalProb);
10111   return true;
10112 }
10113 
10114 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
10115                                               const SwitchInst *SI) {
10116 // Partition Clusters into as few subsets as possible, where each subset has a
10117 // range that fits in a machine word and has <= 3 unique destinations.
10118 
10119 #ifndef NDEBUG
10120   // Clusters must be sorted and contain Range or JumpTable clusters.
10121   assert(!Clusters.empty());
10122   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
10123   for (const CaseCluster &C : Clusters)
10124     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
10125   for (unsigned i = 1; i < Clusters.size(); ++i)
10126     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
10127 #endif
10128 
10129   // The algorithm below is not suitable for -O0.
10130   if (TM.getOptLevel() == CodeGenOpt::None)
10131     return;
10132 
10133   // If target does not have legal shift left, do not emit bit tests at all.
10134   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10135   const DataLayout &DL = DAG.getDataLayout();
10136 
10137   EVT PTy = TLI.getPointerTy(DL);
10138   if (!TLI.isOperationLegal(ISD::SHL, PTy))
10139     return;
10140 
10141   int BitWidth = PTy.getSizeInBits();
10142   const int64_t N = Clusters.size();
10143 
10144   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
10145   SmallVector<unsigned, 8> MinPartitions(N);
10146   // LastElement[i] is the last element of the partition starting at i.
10147   SmallVector<unsigned, 8> LastElement(N);
10148 
10149   // FIXME: This might not be the best algorithm for finding bit test clusters.
10150 
10151   // Base case: There is only one way to partition Clusters[N-1].
10152   MinPartitions[N - 1] = 1;
10153   LastElement[N - 1] = N - 1;
10154 
10155   // Note: loop indexes are signed to avoid underflow.
10156   for (int64_t i = N - 2; i >= 0; --i) {
10157     // Find optimal partitioning of Clusters[i..N-1].
10158     // Baseline: Put Clusters[i] into a partition on its own.
10159     MinPartitions[i] = MinPartitions[i + 1] + 1;
10160     LastElement[i] = i;
10161 
10162     // Search for a solution that results in fewer partitions.
10163     // Note: the search is limited by BitWidth, reducing time complexity.
10164     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
10165       // Try building a partition from Clusters[i..j].
10166 
10167       // Check the range.
10168       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
10169                                Clusters[j].High->getValue(), DL))
10170         continue;
10171 
10172       // Check nbr of destinations and cluster types.
10173       // FIXME: This works, but doesn't seem very efficient.
10174       bool RangesOnly = true;
10175       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
10176       for (int64_t k = i; k <= j; k++) {
10177         if (Clusters[k].Kind != CC_Range) {
10178           RangesOnly = false;
10179           break;
10180         }
10181         Dests.set(Clusters[k].MBB->getNumber());
10182       }
10183       if (!RangesOnly || Dests.count() > 3)
10184         break;
10185 
10186       // Check if it's a better partition.
10187       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
10188       if (NumPartitions < MinPartitions[i]) {
10189         // Found a better partition.
10190         MinPartitions[i] = NumPartitions;
10191         LastElement[i] = j;
10192       }
10193     }
10194   }
10195 
10196   // Iterate over the partitions, replacing with bit-test clusters in-place.
10197   unsigned DstIndex = 0;
10198   for (unsigned First = 0, Last; First < N; First = Last + 1) {
10199     Last = LastElement[First];
10200     assert(First <= Last);
10201     assert(DstIndex <= First);
10202 
10203     CaseCluster BitTestCluster;
10204     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
10205       Clusters[DstIndex++] = BitTestCluster;
10206     } else {
10207       size_t NumClusters = Last - First + 1;
10208       std::memmove(&Clusters[DstIndex], &Clusters[First],
10209                    sizeof(Clusters[0]) * NumClusters);
10210       DstIndex += NumClusters;
10211     }
10212   }
10213   Clusters.resize(DstIndex);
10214 }
10215 
10216 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10217                                         MachineBasicBlock *SwitchMBB,
10218                                         MachineBasicBlock *DefaultMBB) {
10219   MachineFunction *CurMF = FuncInfo.MF;
10220   MachineBasicBlock *NextMBB = nullptr;
10221   MachineFunction::iterator BBI(W.MBB);
10222   if (++BBI != FuncInfo.MF->end())
10223     NextMBB = &*BBI;
10224 
10225   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10226 
10227   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10228 
10229   if (Size == 2 && W.MBB == SwitchMBB) {
10230     // If any two of the cases has the same destination, and if one value
10231     // is the same as the other, but has one bit unset that the other has set,
10232     // use bit manipulation to do two compares at once.  For example:
10233     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10234     // TODO: This could be extended to merge any 2 cases in switches with 3
10235     // cases.
10236     // TODO: Handle cases where W.CaseBB != SwitchBB.
10237     CaseCluster &Small = *W.FirstCluster;
10238     CaseCluster &Big = *W.LastCluster;
10239 
10240     if (Small.Low == Small.High && Big.Low == Big.High &&
10241         Small.MBB == Big.MBB) {
10242       const APInt &SmallValue = Small.Low->getValue();
10243       const APInt &BigValue = Big.Low->getValue();
10244 
10245       // Check that there is only one bit different.
10246       APInt CommonBit = BigValue ^ SmallValue;
10247       if (CommonBit.isPowerOf2()) {
10248         SDValue CondLHS = getValue(Cond);
10249         EVT VT = CondLHS.getValueType();
10250         SDLoc DL = getCurSDLoc();
10251 
10252         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10253                                  DAG.getConstant(CommonBit, DL, VT));
10254         SDValue Cond = DAG.getSetCC(
10255             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10256             ISD::SETEQ);
10257 
10258         // Update successor info.
10259         // Both Small and Big will jump to Small.BB, so we sum up the
10260         // probabilities.
10261         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10262         if (BPI)
10263           addSuccessorWithProb(
10264               SwitchMBB, DefaultMBB,
10265               // The default destination is the first successor in IR.
10266               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10267         else
10268           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10269 
10270         // Insert the true branch.
10271         SDValue BrCond =
10272             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10273                         DAG.getBasicBlock(Small.MBB));
10274         // Insert the false branch.
10275         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10276                              DAG.getBasicBlock(DefaultMBB));
10277 
10278         DAG.setRoot(BrCond);
10279         return;
10280       }
10281     }
10282   }
10283 
10284   if (TM.getOptLevel() != CodeGenOpt::None) {
10285     // Here, we order cases by probability so the most likely case will be
10286     // checked first. However, two clusters can have the same probability in
10287     // which case their relative ordering is non-deterministic. So we use Low
10288     // as a tie-breaker as clusters are guaranteed to never overlap.
10289     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10290                [](const CaseCluster &a, const CaseCluster &b) {
10291       return a.Prob != b.Prob ?
10292              a.Prob > b.Prob :
10293              a.Low->getValue().slt(b.Low->getValue());
10294     });
10295 
10296     // Rearrange the case blocks so that the last one falls through if possible
10297     // without changing the order of probabilities.
10298     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10299       --I;
10300       if (I->Prob > W.LastCluster->Prob)
10301         break;
10302       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10303         std::swap(*I, *W.LastCluster);
10304         break;
10305       }
10306     }
10307   }
10308 
10309   // Compute total probability.
10310   BranchProbability DefaultProb = W.DefaultProb;
10311   BranchProbability UnhandledProbs = DefaultProb;
10312   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10313     UnhandledProbs += I->Prob;
10314 
10315   MachineBasicBlock *CurMBB = W.MBB;
10316   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10317     bool FallthroughUnreachable = false;
10318     MachineBasicBlock *Fallthrough;
10319     if (I == W.LastCluster) {
10320       // For the last cluster, fall through to the default destination.
10321       Fallthrough = DefaultMBB;
10322       FallthroughUnreachable = isa<UnreachableInst>(
10323           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10324     } else {
10325       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10326       CurMF->insert(BBI, Fallthrough);
10327       // Put Cond in a virtual register to make it available from the new blocks.
10328       ExportFromCurrentBlock(Cond);
10329     }
10330     UnhandledProbs -= I->Prob;
10331 
10332     switch (I->Kind) {
10333       case CC_JumpTable: {
10334         // FIXME: Optimize away range check based on pivot comparisons.
10335         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
10336         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
10337 
10338         // The jump block hasn't been inserted yet; insert it here.
10339         MachineBasicBlock *JumpMBB = JT->MBB;
10340         CurMF->insert(BBI, JumpMBB);
10341 
10342         auto JumpProb = I->Prob;
10343         auto FallthroughProb = UnhandledProbs;
10344 
10345         // If the default statement is a target of the jump table, we evenly
10346         // distribute the default probability to successors of CurMBB. Also
10347         // update the probability on the edge from JumpMBB to Fallthrough.
10348         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10349                                               SE = JumpMBB->succ_end();
10350              SI != SE; ++SI) {
10351           if (*SI == DefaultMBB) {
10352             JumpProb += DefaultProb / 2;
10353             FallthroughProb -= DefaultProb / 2;
10354             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10355             JumpMBB->normalizeSuccProbs();
10356             break;
10357           }
10358         }
10359 
10360         if (FallthroughUnreachable) {
10361           // Skip the range check if the fallthrough block is unreachable.
10362           JTH->OmitRangeCheck = true;
10363         }
10364 
10365         if (!JTH->OmitRangeCheck)
10366           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10367         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10368         CurMBB->normalizeSuccProbs();
10369 
10370         // The jump table header will be inserted in our current block, do the
10371         // range check, and fall through to our fallthrough block.
10372         JTH->HeaderBB = CurMBB;
10373         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10374 
10375         // If we're in the right place, emit the jump table header right now.
10376         if (CurMBB == SwitchMBB) {
10377           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10378           JTH->Emitted = true;
10379         }
10380         break;
10381       }
10382       case CC_BitTests: {
10383         // FIXME: If Fallthrough is unreachable, skip the range check.
10384 
10385         // FIXME: Optimize away range check based on pivot comparisons.
10386         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
10387 
10388         // The bit test blocks haven't been inserted yet; insert them here.
10389         for (BitTestCase &BTC : BTB->Cases)
10390           CurMF->insert(BBI, BTC.ThisBB);
10391 
10392         // Fill in fields of the BitTestBlock.
10393         BTB->Parent = CurMBB;
10394         BTB->Default = Fallthrough;
10395 
10396         BTB->DefaultProb = UnhandledProbs;
10397         // If the cases in bit test don't form a contiguous range, we evenly
10398         // distribute the probability on the edge to Fallthrough to two
10399         // successors of CurMBB.
10400         if (!BTB->ContiguousRange) {
10401           BTB->Prob += DefaultProb / 2;
10402           BTB->DefaultProb -= DefaultProb / 2;
10403         }
10404 
10405         // If we're in the right place, emit the bit test header right now.
10406         if (CurMBB == SwitchMBB) {
10407           visitBitTestHeader(*BTB, SwitchMBB);
10408           BTB->Emitted = true;
10409         }
10410         break;
10411       }
10412       case CC_Range: {
10413         const Value *RHS, *LHS, *MHS;
10414         ISD::CondCode CC;
10415         if (I->Low == I->High) {
10416           // Check Cond == I->Low.
10417           CC = ISD::SETEQ;
10418           LHS = Cond;
10419           RHS=I->Low;
10420           MHS = nullptr;
10421         } else {
10422           // Check I->Low <= Cond <= I->High.
10423           CC = ISD::SETLE;
10424           LHS = I->Low;
10425           MHS = Cond;
10426           RHS = I->High;
10427         }
10428 
10429         // If Fallthrough is unreachable, fold away the comparison.
10430         if (FallthroughUnreachable)
10431           CC = ISD::SETTRUE;
10432 
10433         // The false probability is the sum of all unhandled cases.
10434         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10435                      getCurSDLoc(), I->Prob, UnhandledProbs);
10436 
10437         if (CurMBB == SwitchMBB)
10438           visitSwitchCase(CB, SwitchMBB);
10439         else
10440           SwitchCases.push_back(CB);
10441 
10442         break;
10443       }
10444     }
10445     CurMBB = Fallthrough;
10446   }
10447 }
10448 
10449 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10450                                               CaseClusterIt First,
10451                                               CaseClusterIt Last) {
10452   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10453     if (X.Prob != CC.Prob)
10454       return X.Prob > CC.Prob;
10455 
10456     // Ties are broken by comparing the case value.
10457     return X.Low->getValue().slt(CC.Low->getValue());
10458   });
10459 }
10460 
10461 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10462                                         const SwitchWorkListItem &W,
10463                                         Value *Cond,
10464                                         MachineBasicBlock *SwitchMBB) {
10465   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10466          "Clusters not sorted?");
10467 
10468   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10469 
10470   // Balance the tree based on branch probabilities to create a near-optimal (in
10471   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10472   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10473   CaseClusterIt LastLeft = W.FirstCluster;
10474   CaseClusterIt FirstRight = W.LastCluster;
10475   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10476   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10477 
10478   // Move LastLeft and FirstRight towards each other from opposite directions to
10479   // find a partitioning of the clusters which balances the probability on both
10480   // sides. If LeftProb and RightProb are equal, alternate which side is
10481   // taken to ensure 0-probability nodes are distributed evenly.
10482   unsigned I = 0;
10483   while (LastLeft + 1 < FirstRight) {
10484     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10485       LeftProb += (++LastLeft)->Prob;
10486     else
10487       RightProb += (--FirstRight)->Prob;
10488     I++;
10489   }
10490 
10491   while (true) {
10492     // Our binary search tree differs from a typical BST in that ours can have up
10493     // to three values in each leaf. The pivot selection above doesn't take that
10494     // into account, which means the tree might require more nodes and be less
10495     // efficient. We compensate for this here.
10496 
10497     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10498     unsigned NumRight = W.LastCluster - FirstRight + 1;
10499 
10500     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10501       // If one side has less than 3 clusters, and the other has more than 3,
10502       // consider taking a cluster from the other side.
10503 
10504       if (NumLeft < NumRight) {
10505         // Consider moving the first cluster on the right to the left side.
10506         CaseCluster &CC = *FirstRight;
10507         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10508         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10509         if (LeftSideRank <= RightSideRank) {
10510           // Moving the cluster to the left does not demote it.
10511           ++LastLeft;
10512           ++FirstRight;
10513           continue;
10514         }
10515       } else {
10516         assert(NumRight < NumLeft);
10517         // Consider moving the last element on the left to the right side.
10518         CaseCluster &CC = *LastLeft;
10519         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10520         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10521         if (RightSideRank <= LeftSideRank) {
10522           // Moving the cluster to the right does not demot it.
10523           --LastLeft;
10524           --FirstRight;
10525           continue;
10526         }
10527       }
10528     }
10529     break;
10530   }
10531 
10532   assert(LastLeft + 1 == FirstRight);
10533   assert(LastLeft >= W.FirstCluster);
10534   assert(FirstRight <= W.LastCluster);
10535 
10536   // Use the first element on the right as pivot since we will make less-than
10537   // comparisons against it.
10538   CaseClusterIt PivotCluster = FirstRight;
10539   assert(PivotCluster > W.FirstCluster);
10540   assert(PivotCluster <= W.LastCluster);
10541 
10542   CaseClusterIt FirstLeft = W.FirstCluster;
10543   CaseClusterIt LastRight = W.LastCluster;
10544 
10545   const ConstantInt *Pivot = PivotCluster->Low;
10546 
10547   // New blocks will be inserted immediately after the current one.
10548   MachineFunction::iterator BBI(W.MBB);
10549   ++BBI;
10550 
10551   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10552   // we can branch to its destination directly if it's squeezed exactly in
10553   // between the known lower bound and Pivot - 1.
10554   MachineBasicBlock *LeftMBB;
10555   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10556       FirstLeft->Low == W.GE &&
10557       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10558     LeftMBB = FirstLeft->MBB;
10559   } else {
10560     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10561     FuncInfo.MF->insert(BBI, LeftMBB);
10562     WorkList.push_back(
10563         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10564     // Put Cond in a virtual register to make it available from the new blocks.
10565     ExportFromCurrentBlock(Cond);
10566   }
10567 
10568   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10569   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10570   // directly if RHS.High equals the current upper bound.
10571   MachineBasicBlock *RightMBB;
10572   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10573       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10574     RightMBB = FirstRight->MBB;
10575   } else {
10576     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10577     FuncInfo.MF->insert(BBI, RightMBB);
10578     WorkList.push_back(
10579         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10580     // Put Cond in a virtual register to make it available from the new blocks.
10581     ExportFromCurrentBlock(Cond);
10582   }
10583 
10584   // Create the CaseBlock record that will be used to lower the branch.
10585   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10586                getCurSDLoc(), LeftProb, RightProb);
10587 
10588   if (W.MBB == SwitchMBB)
10589     visitSwitchCase(CB, SwitchMBB);
10590   else
10591     SwitchCases.push_back(CB);
10592 }
10593 
10594 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10595 // from the swith statement.
10596 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10597                                             BranchProbability PeeledCaseProb) {
10598   if (PeeledCaseProb == BranchProbability::getOne())
10599     return BranchProbability::getZero();
10600   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10601 
10602   uint32_t Numerator = CaseProb.getNumerator();
10603   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10604   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10605 }
10606 
10607 // Try to peel the top probability case if it exceeds the threshold.
10608 // Return current MachineBasicBlock for the switch statement if the peeling
10609 // does not occur.
10610 // If the peeling is performed, return the newly created MachineBasicBlock
10611 // for the peeled switch statement. Also update Clusters to remove the peeled
10612 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10613 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10614     const SwitchInst &SI, CaseClusterVector &Clusters,
10615     BranchProbability &PeeledCaseProb) {
10616   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10617   // Don't perform if there is only one cluster or optimizing for size.
10618   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10619       TM.getOptLevel() == CodeGenOpt::None ||
10620       SwitchMBB->getParent()->getFunction().hasMinSize())
10621     return SwitchMBB;
10622 
10623   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10624   unsigned PeeledCaseIndex = 0;
10625   bool SwitchPeeled = false;
10626   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10627     CaseCluster &CC = Clusters[Index];
10628     if (CC.Prob < TopCaseProb)
10629       continue;
10630     TopCaseProb = CC.Prob;
10631     PeeledCaseIndex = Index;
10632     SwitchPeeled = true;
10633   }
10634   if (!SwitchPeeled)
10635     return SwitchMBB;
10636 
10637   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10638                     << TopCaseProb << "\n");
10639 
10640   // Record the MBB for the peeled switch statement.
10641   MachineFunction::iterator BBI(SwitchMBB);
10642   ++BBI;
10643   MachineBasicBlock *PeeledSwitchMBB =
10644       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10645   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10646 
10647   ExportFromCurrentBlock(SI.getCondition());
10648   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10649   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10650                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10651   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10652 
10653   Clusters.erase(PeeledCaseIt);
10654   for (CaseCluster &CC : Clusters) {
10655     LLVM_DEBUG(
10656         dbgs() << "Scale the probablity for one cluster, before scaling: "
10657                << CC.Prob << "\n");
10658     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10659     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10660   }
10661   PeeledCaseProb = TopCaseProb;
10662   return PeeledSwitchMBB;
10663 }
10664 
10665 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10666   // Extract cases from the switch.
10667   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10668   CaseClusterVector Clusters;
10669   Clusters.reserve(SI.getNumCases());
10670   for (auto I : SI.cases()) {
10671     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10672     const ConstantInt *CaseVal = I.getCaseValue();
10673     BranchProbability Prob =
10674         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10675             : BranchProbability(1, SI.getNumCases() + 1);
10676     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10677   }
10678 
10679   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10680 
10681   // Cluster adjacent cases with the same destination. We do this at all
10682   // optimization levels because it's cheap to do and will make codegen faster
10683   // if there are many clusters.
10684   sortAndRangeify(Clusters);
10685 
10686   // The branch probablity of the peeled case.
10687   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10688   MachineBasicBlock *PeeledSwitchMBB =
10689       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10690 
10691   // If there is only the default destination, jump there directly.
10692   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10693   if (Clusters.empty()) {
10694     assert(PeeledSwitchMBB == SwitchMBB);
10695     SwitchMBB->addSuccessor(DefaultMBB);
10696     if (DefaultMBB != NextBlock(SwitchMBB)) {
10697       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10698                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10699     }
10700     return;
10701   }
10702 
10703   findJumpTables(Clusters, &SI, DefaultMBB);
10704   findBitTestClusters(Clusters, &SI);
10705 
10706   LLVM_DEBUG({
10707     dbgs() << "Case clusters: ";
10708     for (const CaseCluster &C : Clusters) {
10709       if (C.Kind == CC_JumpTable)
10710         dbgs() << "JT:";
10711       if (C.Kind == CC_BitTests)
10712         dbgs() << "BT:";
10713 
10714       C.Low->getValue().print(dbgs(), true);
10715       if (C.Low != C.High) {
10716         dbgs() << '-';
10717         C.High->getValue().print(dbgs(), true);
10718       }
10719       dbgs() << ' ';
10720     }
10721     dbgs() << '\n';
10722   });
10723 
10724   assert(!Clusters.empty());
10725   SwitchWorkList WorkList;
10726   CaseClusterIt First = Clusters.begin();
10727   CaseClusterIt Last = Clusters.end() - 1;
10728   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10729   // Scale the branchprobability for DefaultMBB if the peel occurs and
10730   // DefaultMBB is not replaced.
10731   if (PeeledCaseProb != BranchProbability::getZero() &&
10732       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10733     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10734   WorkList.push_back(
10735       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10736 
10737   while (!WorkList.empty()) {
10738     SwitchWorkListItem W = WorkList.back();
10739     WorkList.pop_back();
10740     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10741 
10742     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10743         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10744       // For optimized builds, lower large range as a balanced binary tree.
10745       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10746       continue;
10747     }
10748 
10749     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10750   }
10751 }
10752