xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 38bfc22161d94b4b6fb6fed5bf498afe936ab874)
1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SelectionDAGBuilder.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/Loads.h"
24 #include "llvm/Analysis/TargetLibraryInfo.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/Analysis/VectorUtils.h"
27 #include "llvm/CodeGen/FastISel.h"
28 #include "llvm/CodeGen/FunctionLoweringInfo.h"
29 #include "llvm/CodeGen/GCMetadata.h"
30 #include "llvm/CodeGen/GCStrategy.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
39 #include "llvm/CodeGen/StackMaps.h"
40 #include "llvm/CodeGen/WinEHFuncInfo.h"
41 #include "llvm/IR/CallingConv.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/DebugInfo.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/Function.h"
47 #include "llvm/IR/GetElementPtrTypeIterator.h"
48 #include "llvm/IR/GlobalVariable.h"
49 #include "llvm/IR/InlineAsm.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/IntrinsicInst.h"
52 #include "llvm/IR/Intrinsics.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/IR/Statepoint.h"
56 #include "llvm/MC/MCSymbol.h"
57 #include "llvm/Support/CommandLine.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/MathExtras.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include "llvm/Target/TargetFrameLowering.h"
63 #include "llvm/Target/TargetInstrInfo.h"
64 #include "llvm/Target/TargetIntrinsicInfo.h"
65 #include "llvm/Target/TargetLowering.h"
66 #include "llvm/Target/TargetOptions.h"
67 #include "llvm/Target/TargetSubtargetInfo.h"
68 #include <algorithm>
69 #include <utility>
70 using namespace llvm;
71 
72 #define DEBUG_TYPE "isel"
73 
74 /// LimitFloatPrecision - Generate low-precision inline sequences for
75 /// some float libcalls (6, 8 or 12 bits).
76 static unsigned LimitFloatPrecision;
77 
78 static cl::opt<unsigned, true>
79 LimitFPPrecision("limit-float-precision",
80                  cl::desc("Generate low-precision inline sequences "
81                           "for some float libcalls"),
82                  cl::location(LimitFloatPrecision),
83                  cl::init(0));
84 
85 static cl::opt<bool>
86 EnableFMFInDAG("enable-fmf-dag", cl::init(true), cl::Hidden,
87                 cl::desc("Enable fast-math-flags for DAG nodes"));
88 
89 // Limit the width of DAG chains. This is important in general to prevent
90 // DAG-based analysis from blowing up. For example, alias analysis and
91 // load clustering may not complete in reasonable time. It is difficult to
92 // recognize and avoid this situation within each individual analysis, and
93 // future analyses are likely to have the same behavior. Limiting DAG width is
94 // the safe approach and will be especially important with global DAGs.
95 //
96 // MaxParallelChains default is arbitrarily high to avoid affecting
97 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
98 // sequence over this should have been converted to llvm.memcpy by the
99 // frontend. It easy to induce this behavior with .ll code such as:
100 // %buffer = alloca [4096 x i8]
101 // %data = load [4096 x i8]* %argPtr
102 // store [4096 x i8] %data, [4096 x i8]* %buffer
103 static const unsigned MaxParallelChains = 64;
104 
105 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
106                                       const SDValue *Parts, unsigned NumParts,
107                                       MVT PartVT, EVT ValueVT, const Value *V);
108 
109 /// getCopyFromParts - Create a value that contains the specified legal parts
110 /// combined into the value they represent.  If the parts combine to a type
111 /// larger then ValueVT then AssertOp can be used to specify whether the extra
112 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
113 /// (ISD::AssertSext).
114 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
115                                 const SDValue *Parts,
116                                 unsigned NumParts, MVT PartVT, EVT ValueVT,
117                                 const Value *V,
118                                 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
119   if (ValueVT.isVector())
120     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
121                                   PartVT, ValueVT, V);
122 
123   assert(NumParts > 0 && "No parts to assemble!");
124   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
125   SDValue Val = Parts[0];
126 
127   if (NumParts > 1) {
128     // Assemble the value from multiple parts.
129     if (ValueVT.isInteger()) {
130       unsigned PartBits = PartVT.getSizeInBits();
131       unsigned ValueBits = ValueVT.getSizeInBits();
132 
133       // Assemble the power of 2 part.
134       unsigned RoundParts = NumParts & (NumParts - 1) ?
135         1 << Log2_32(NumParts) : NumParts;
136       unsigned RoundBits = PartBits * RoundParts;
137       EVT RoundVT = RoundBits == ValueBits ?
138         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
139       SDValue Lo, Hi;
140 
141       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
142 
143       if (RoundParts > 2) {
144         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
145                               PartVT, HalfVT, V);
146         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
147                               RoundParts / 2, PartVT, HalfVT, V);
148       } else {
149         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
150         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
151       }
152 
153       if (DAG.getDataLayout().isBigEndian())
154         std::swap(Lo, Hi);
155 
156       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
157 
158       if (RoundParts < NumParts) {
159         // Assemble the trailing non-power-of-2 part.
160         unsigned OddParts = NumParts - RoundParts;
161         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
162         Hi = getCopyFromParts(DAG, DL,
163                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
164 
165         // Combine the round and odd parts.
166         Lo = Val;
167         if (DAG.getDataLayout().isBigEndian())
168           std::swap(Lo, Hi);
169         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
170         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
171         Hi =
172             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
173                         DAG.getConstant(Lo.getValueType().getSizeInBits(), DL,
174                                         TLI.getPointerTy(DAG.getDataLayout())));
175         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
176         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
177       }
178     } else if (PartVT.isFloatingPoint()) {
179       // FP split into multiple FP parts (for ppcf128)
180       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
181              "Unexpected split");
182       SDValue Lo, Hi;
183       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
184       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
185       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
186         std::swap(Lo, Hi);
187       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
188     } else {
189       // FP split into integer parts (soft fp)
190       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
191              !PartVT.isVector() && "Unexpected split");
192       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
193       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
194     }
195   }
196 
197   // There is now one part, held in Val.  Correct it to match ValueVT.
198   // PartEVT is the type of the register class that holds the value.
199   // ValueVT is the type of the inline asm operation.
200   EVT PartEVT = Val.getValueType();
201 
202   if (PartEVT == ValueVT)
203     return Val;
204 
205   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
206       ValueVT.bitsLT(PartEVT)) {
207     // For an FP value in an integer part, we need to truncate to the right
208     // width first.
209     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
210     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
211   }
212 
213   // Handle types that have the same size.
214   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
215     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
216 
217   // Handle types with different sizes.
218   if (PartEVT.isInteger() && ValueVT.isInteger()) {
219     if (ValueVT.bitsLT(PartEVT)) {
220       // For a truncate, see if we have any information to
221       // indicate whether the truncated bits will always be
222       // zero or sign-extension.
223       if (AssertOp != ISD::DELETED_NODE)
224         Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
225                           DAG.getValueType(ValueVT));
226       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
227     }
228     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
229   }
230 
231   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
232     // FP_ROUND's are always exact here.
233     if (ValueVT.bitsLT(Val.getValueType()))
234       return DAG.getNode(
235           ISD::FP_ROUND, DL, ValueVT, Val,
236           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
237 
238     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
239   }
240 
241   llvm_unreachable("Unknown mismatch!");
242 }
243 
244 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
245                                               const Twine &ErrMsg) {
246   const Instruction *I = dyn_cast_or_null<Instruction>(V);
247   if (!V)
248     return Ctx.emitError(ErrMsg);
249 
250   const char *AsmError = ", possible invalid constraint for vector type";
251   if (const CallInst *CI = dyn_cast<CallInst>(I))
252     if (isa<InlineAsm>(CI->getCalledValue()))
253       return Ctx.emitError(I, ErrMsg + AsmError);
254 
255   return Ctx.emitError(I, ErrMsg);
256 }
257 
258 /// getCopyFromPartsVector - Create a value that contains the specified legal
259 /// parts combined into the value they represent.  If the parts combine to a
260 /// type larger then ValueVT then AssertOp can be used to specify whether the
261 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
262 /// ValueVT (ISD::AssertSext).
263 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
264                                       const SDValue *Parts, unsigned NumParts,
265                                       MVT PartVT, EVT ValueVT, const Value *V) {
266   assert(ValueVT.isVector() && "Not a vector value");
267   assert(NumParts > 0 && "No parts to assemble!");
268   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
269   SDValue Val = Parts[0];
270 
271   // Handle a multi-element vector.
272   if (NumParts > 1) {
273     EVT IntermediateVT;
274     MVT RegisterVT;
275     unsigned NumIntermediates;
276     unsigned NumRegs =
277     TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
278                                NumIntermediates, RegisterVT);
279     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
280     NumParts = NumRegs; // Silence a compiler warning.
281     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
282     assert(RegisterVT.getSizeInBits() ==
283            Parts[0].getSimpleValueType().getSizeInBits() &&
284            "Part type sizes don't match!");
285 
286     // Assemble the parts into intermediate operands.
287     SmallVector<SDValue, 8> Ops(NumIntermediates);
288     if (NumIntermediates == NumParts) {
289       // If the register was not expanded, truncate or copy the value,
290       // as appropriate.
291       for (unsigned i = 0; i != NumParts; ++i)
292         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
293                                   PartVT, IntermediateVT, V);
294     } else if (NumParts > 0) {
295       // If the intermediate type was expanded, build the intermediate
296       // operands from the parts.
297       assert(NumParts % NumIntermediates == 0 &&
298              "Must expand into a divisible number of parts!");
299       unsigned Factor = NumParts / NumIntermediates;
300       for (unsigned i = 0; i != NumIntermediates; ++i)
301         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
302                                   PartVT, IntermediateVT, V);
303     }
304 
305     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
306     // intermediate operands.
307     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
308                                                 : ISD::BUILD_VECTOR,
309                       DL, ValueVT, Ops);
310   }
311 
312   // There is now one part, held in Val.  Correct it to match ValueVT.
313   EVT PartEVT = Val.getValueType();
314 
315   if (PartEVT == ValueVT)
316     return Val;
317 
318   if (PartEVT.isVector()) {
319     // If the element type of the source/dest vectors are the same, but the
320     // parts vector has more elements than the value vector, then we have a
321     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
322     // elements we want.
323     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
324       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
325              "Cannot narrow, it would be a lossy transformation");
326       return DAG.getNode(
327           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
328           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
329     }
330 
331     // Vector/Vector bitcast.
332     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
333       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
334 
335     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
336       "Cannot handle this kind of promotion");
337     // Promoted vector extract
338     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
339 
340   }
341 
342   // Trivial bitcast if the types are the same size and the destination
343   // vector type is legal.
344   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
345       TLI.isTypeLegal(ValueVT))
346     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
347 
348   // Handle cases such as i8 -> <1 x i1>
349   if (ValueVT.getVectorNumElements() != 1) {
350     diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
351                                       "non-trivial scalar-to-vector conversion");
352     return DAG.getUNDEF(ValueVT);
353   }
354 
355   if (ValueVT.getVectorNumElements() == 1 &&
356       ValueVT.getVectorElementType() != PartEVT)
357     Val = DAG.getAnyExtOrTrunc(Val, DL, ValueVT.getScalarType());
358 
359   return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
360 }
361 
362 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
363                                  SDValue Val, SDValue *Parts, unsigned NumParts,
364                                  MVT PartVT, const Value *V);
365 
366 /// getCopyToParts - Create a series of nodes that contain the specified value
367 /// split into legal parts.  If the parts contain more bits than Val, then, for
368 /// integers, ExtendKind can be used to specify how to generate the extra bits.
369 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
370                            SDValue Val, SDValue *Parts, unsigned NumParts,
371                            MVT PartVT, const Value *V,
372                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
373   EVT ValueVT = Val.getValueType();
374 
375   // Handle the vector case separately.
376   if (ValueVT.isVector())
377     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
378 
379   unsigned PartBits = PartVT.getSizeInBits();
380   unsigned OrigNumParts = NumParts;
381   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
382          "Copying to an illegal type!");
383 
384   if (NumParts == 0)
385     return;
386 
387   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
388   EVT PartEVT = PartVT;
389   if (PartEVT == ValueVT) {
390     assert(NumParts == 1 && "No-op copy with multiple parts!");
391     Parts[0] = Val;
392     return;
393   }
394 
395   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
396     // If the parts cover more bits than the value has, promote the value.
397     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
398       assert(NumParts == 1 && "Do not know what to promote to!");
399       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
400     } else {
401       if (ValueVT.isFloatingPoint()) {
402         // FP values need to be bitcast, then extended if they are being put
403         // into a larger container.
404         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
405         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
406       }
407       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
408              ValueVT.isInteger() &&
409              "Unknown mismatch!");
410       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
411       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
412       if (PartVT == MVT::x86mmx)
413         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
414     }
415   } else if (PartBits == ValueVT.getSizeInBits()) {
416     // Different types of the same size.
417     assert(NumParts == 1 && PartEVT != ValueVT);
418     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
419   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
420     // If the parts cover less bits than value has, truncate the value.
421     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
422            ValueVT.isInteger() &&
423            "Unknown mismatch!");
424     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
425     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
426     if (PartVT == MVT::x86mmx)
427       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
428   }
429 
430   // The value may have changed - recompute ValueVT.
431   ValueVT = Val.getValueType();
432   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
433          "Failed to tile the value with PartVT!");
434 
435   if (NumParts == 1) {
436     if (PartEVT != ValueVT)
437       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
438                                         "scalar-to-vector conversion failed");
439 
440     Parts[0] = Val;
441     return;
442   }
443 
444   // Expand the value into multiple parts.
445   if (NumParts & (NumParts - 1)) {
446     // The number of parts is not a power of 2.  Split off and copy the tail.
447     assert(PartVT.isInteger() && ValueVT.isInteger() &&
448            "Do not know what to expand to!");
449     unsigned RoundParts = 1 << Log2_32(NumParts);
450     unsigned RoundBits = RoundParts * PartBits;
451     unsigned OddParts = NumParts - RoundParts;
452     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
453                                  DAG.getIntPtrConstant(RoundBits, DL));
454     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
455 
456     if (DAG.getDataLayout().isBigEndian())
457       // The odd parts were reversed by getCopyToParts - unreverse them.
458       std::reverse(Parts + RoundParts, Parts + NumParts);
459 
460     NumParts = RoundParts;
461     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
462     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
463   }
464 
465   // The number of parts is a power of 2.  Repeatedly bisect the value using
466   // EXTRACT_ELEMENT.
467   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
468                          EVT::getIntegerVT(*DAG.getContext(),
469                                            ValueVT.getSizeInBits()),
470                          Val);
471 
472   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
473     for (unsigned i = 0; i < NumParts; i += StepSize) {
474       unsigned ThisBits = StepSize * PartBits / 2;
475       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
476       SDValue &Part0 = Parts[i];
477       SDValue &Part1 = Parts[i+StepSize/2];
478 
479       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
480                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
481       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
482                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
483 
484       if (ThisBits == PartBits && ThisVT != PartVT) {
485         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
486         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
487       }
488     }
489   }
490 
491   if (DAG.getDataLayout().isBigEndian())
492     std::reverse(Parts, Parts + OrigNumParts);
493 }
494 
495 
496 /// getCopyToPartsVector - Create a series of nodes that contain the specified
497 /// value split into legal parts.
498 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
499                                  SDValue Val, SDValue *Parts, unsigned NumParts,
500                                  MVT PartVT, const Value *V) {
501   EVT ValueVT = Val.getValueType();
502   assert(ValueVT.isVector() && "Not a vector");
503   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
504 
505   if (NumParts == 1) {
506     EVT PartEVT = PartVT;
507     if (PartEVT == ValueVT) {
508       // Nothing to do.
509     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
510       // Bitconvert vector->vector case.
511       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
512     } else if (PartVT.isVector() &&
513                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
514                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
515       EVT ElementVT = PartVT.getVectorElementType();
516       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
517       // undef elements.
518       SmallVector<SDValue, 16> Ops;
519       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
520         Ops.push_back(DAG.getNode(
521             ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
522             DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
523 
524       for (unsigned i = ValueVT.getVectorNumElements(),
525            e = PartVT.getVectorNumElements(); i != e; ++i)
526         Ops.push_back(DAG.getUNDEF(ElementVT));
527 
528       Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
529 
530       // FIXME: Use CONCAT for 2x -> 4x.
531 
532       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
533       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
534     } else if (PartVT.isVector() &&
535                PartEVT.getVectorElementType().bitsGE(
536                  ValueVT.getVectorElementType()) &&
537                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
538 
539       // Promoted vector extract
540       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
541     } else{
542       // Vector -> scalar conversion.
543       assert(ValueVT.getVectorNumElements() == 1 &&
544              "Only trivial vector-to-scalar conversions should get here!");
545       Val = DAG.getNode(
546           ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
547           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
548 
549       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
550     }
551 
552     Parts[0] = Val;
553     return;
554   }
555 
556   // Handle a multi-element vector.
557   EVT IntermediateVT;
558   MVT RegisterVT;
559   unsigned NumIntermediates;
560   unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
561                                                 IntermediateVT,
562                                                 NumIntermediates, RegisterVT);
563   unsigned NumElements = ValueVT.getVectorNumElements();
564 
565   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
566   NumParts = NumRegs; // Silence a compiler warning.
567   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
568 
569   // Split the vector into intermediate operands.
570   SmallVector<SDValue, 8> Ops(NumIntermediates);
571   for (unsigned i = 0; i != NumIntermediates; ++i) {
572     if (IntermediateVT.isVector())
573       Ops[i] =
574           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
575                       DAG.getConstant(i * (NumElements / NumIntermediates), DL,
576                                       TLI.getVectorIdxTy(DAG.getDataLayout())));
577     else
578       Ops[i] = DAG.getNode(
579           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
580           DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
581   }
582 
583   // Split the intermediate operands into legal parts.
584   if (NumParts == NumIntermediates) {
585     // If the register was not expanded, promote or copy the value,
586     // as appropriate.
587     for (unsigned i = 0; i != NumParts; ++i)
588       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
589   } else if (NumParts > 0) {
590     // If the intermediate type was expanded, split each the value into
591     // legal parts.
592     assert(NumIntermediates != 0 && "division by zero");
593     assert(NumParts % NumIntermediates == 0 &&
594            "Must expand into a divisible number of parts!");
595     unsigned Factor = NumParts / NumIntermediates;
596     for (unsigned i = 0; i != NumIntermediates; ++i)
597       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
598   }
599 }
600 
601 RegsForValue::RegsForValue() {}
602 
603 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
604                            EVT valuevt)
605     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
606 
607 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
608                            const DataLayout &DL, unsigned Reg, Type *Ty) {
609   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
610 
611   for (EVT ValueVT : ValueVTs) {
612     unsigned NumRegs = TLI.getNumRegisters(Context, ValueVT);
613     MVT RegisterVT = TLI.getRegisterType(Context, ValueVT);
614     for (unsigned i = 0; i != NumRegs; ++i)
615       Regs.push_back(Reg + i);
616     RegVTs.push_back(RegisterVT);
617     Reg += NumRegs;
618   }
619 }
620 
621 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
622 /// this value and returns the result as a ValueVT value.  This uses
623 /// Chain/Flag as the input and updates them for the output Chain/Flag.
624 /// If the Flag pointer is NULL, no flag is used.
625 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
626                                       FunctionLoweringInfo &FuncInfo,
627                                       SDLoc dl,
628                                       SDValue &Chain, SDValue *Flag,
629                                       const Value *V) const {
630   // A Value with type {} or [0 x %t] needs no registers.
631   if (ValueVTs.empty())
632     return SDValue();
633 
634   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
635 
636   // Assemble the legal parts into the final values.
637   SmallVector<SDValue, 4> Values(ValueVTs.size());
638   SmallVector<SDValue, 8> Parts;
639   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
640     // Copy the legal parts from the registers.
641     EVT ValueVT = ValueVTs[Value];
642     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
643     MVT RegisterVT = RegVTs[Value];
644 
645     Parts.resize(NumRegs);
646     for (unsigned i = 0; i != NumRegs; ++i) {
647       SDValue P;
648       if (!Flag) {
649         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
650       } else {
651         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
652         *Flag = P.getValue(2);
653       }
654 
655       Chain = P.getValue(1);
656       Parts[i] = P;
657 
658       // If the source register was virtual and if we know something about it,
659       // add an assert node.
660       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
661           !RegisterVT.isInteger() || RegisterVT.isVector())
662         continue;
663 
664       const FunctionLoweringInfo::LiveOutInfo *LOI =
665         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
666       if (!LOI)
667         continue;
668 
669       unsigned RegSize = RegisterVT.getSizeInBits();
670       unsigned NumSignBits = LOI->NumSignBits;
671       unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
672 
673       if (NumZeroBits == RegSize) {
674         // The current value is a zero.
675         // Explicitly express that as it would be easier for
676         // optimizations to kick in.
677         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
678         continue;
679       }
680 
681       // FIXME: We capture more information than the dag can represent.  For
682       // now, just use the tightest assertzext/assertsext possible.
683       bool isSExt = true;
684       EVT FromVT(MVT::Other);
685       if (NumSignBits == RegSize) {
686         isSExt = true;   // ASSERT SEXT 1
687         FromVT = MVT::i1;
688       } else if (NumZeroBits >= RegSize - 1) {
689         isSExt = false;  // ASSERT ZEXT 1
690         FromVT = MVT::i1;
691       } else if (NumSignBits > RegSize - 8) {
692         isSExt = true;   // ASSERT SEXT 8
693         FromVT = MVT::i8;
694       } else if (NumZeroBits >= RegSize - 8) {
695         isSExt = false;  // ASSERT ZEXT 8
696         FromVT = MVT::i8;
697       } else if (NumSignBits > RegSize - 16) {
698         isSExt = true;   // ASSERT SEXT 16
699         FromVT = MVT::i16;
700       } else if (NumZeroBits >= RegSize - 16) {
701         isSExt = false;  // ASSERT ZEXT 16
702         FromVT = MVT::i16;
703       } else if (NumSignBits > RegSize - 32) {
704         isSExt = true;   // ASSERT SEXT 32
705         FromVT = MVT::i32;
706       } else if (NumZeroBits >= RegSize - 32) {
707         isSExt = false;  // ASSERT ZEXT 32
708         FromVT = MVT::i32;
709       } else {
710         continue;
711       }
712       // Add an assertion node.
713       assert(FromVT != MVT::Other);
714       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
715                              RegisterVT, P, DAG.getValueType(FromVT));
716     }
717 
718     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
719                                      NumRegs, RegisterVT, ValueVT, V);
720     Part += NumRegs;
721     Parts.clear();
722   }
723 
724   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
725 }
726 
727 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
728 /// specified value into the registers specified by this object.  This uses
729 /// Chain/Flag as the input and updates them for the output Chain/Flag.
730 /// If the Flag pointer is NULL, no flag is used.
731 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
732                                  SDValue &Chain, SDValue *Flag, const Value *V,
733                                  ISD::NodeType PreferredExtendType) const {
734   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
735   ISD::NodeType ExtendKind = PreferredExtendType;
736 
737   // Get the list of the values's legal parts.
738   unsigned NumRegs = Regs.size();
739   SmallVector<SDValue, 8> Parts(NumRegs);
740   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
741     EVT ValueVT = ValueVTs[Value];
742     unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
743     MVT RegisterVT = RegVTs[Value];
744 
745     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
746       ExtendKind = ISD::ZERO_EXTEND;
747 
748     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
749                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
750     Part += NumParts;
751   }
752 
753   // Copy the parts into the registers.
754   SmallVector<SDValue, 8> Chains(NumRegs);
755   for (unsigned i = 0; i != NumRegs; ++i) {
756     SDValue Part;
757     if (!Flag) {
758       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
759     } else {
760       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
761       *Flag = Part.getValue(1);
762     }
763 
764     Chains[i] = Part.getValue(0);
765   }
766 
767   if (NumRegs == 1 || Flag)
768     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
769     // flagged to it. That is the CopyToReg nodes and the user are considered
770     // a single scheduling unit. If we create a TokenFactor and return it as
771     // chain, then the TokenFactor is both a predecessor (operand) of the
772     // user as well as a successor (the TF operands are flagged to the user).
773     // c1, f1 = CopyToReg
774     // c2, f2 = CopyToReg
775     // c3     = TokenFactor c1, c2
776     // ...
777     //        = op c3, ..., f2
778     Chain = Chains[NumRegs-1];
779   else
780     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
781 }
782 
783 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
784 /// operand list.  This adds the code marker and includes the number of
785 /// values added into it.
786 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
787                                         unsigned MatchingIdx, SDLoc dl,
788                                         SelectionDAG &DAG,
789                                         std::vector<SDValue> &Ops) const {
790   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
791 
792   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
793   if (HasMatching)
794     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
795   else if (!Regs.empty() &&
796            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
797     // Put the register class of the virtual registers in the flag word.  That
798     // way, later passes can recompute register class constraints for inline
799     // assembly as well as normal instructions.
800     // Don't do this for tied operands that can use the regclass information
801     // from the def.
802     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
803     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
804     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
805   }
806 
807   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
808   Ops.push_back(Res);
809 
810   unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
811   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
812     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
813     MVT RegisterVT = RegVTs[Value];
814     for (unsigned i = 0; i != NumRegs; ++i) {
815       assert(Reg < Regs.size() && "Mismatch in # registers expected");
816       unsigned TheReg = Regs[Reg++];
817       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
818 
819       if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
820         // If we clobbered the stack pointer, MFI should know about it.
821         assert(DAG.getMachineFunction().getFrameInfo()->
822             hasOpaqueSPAdjustment());
823       }
824     }
825   }
826 }
827 
828 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
829                                const TargetLibraryInfo *li) {
830   AA = &aa;
831   GFI = gfi;
832   LibInfo = li;
833   DL = &DAG.getDataLayout();
834   Context = DAG.getContext();
835   LPadToCallSiteMap.clear();
836 }
837 
838 /// clear - Clear out the current SelectionDAG and the associated
839 /// state and prepare this SelectionDAGBuilder object to be used
840 /// for a new block. This doesn't clear out information about
841 /// additional blocks that are needed to complete switch lowering
842 /// or PHI node updating; that information is cleared out as it is
843 /// consumed.
844 void SelectionDAGBuilder::clear() {
845   NodeMap.clear();
846   UnusedArgNodeMap.clear();
847   PendingLoads.clear();
848   PendingExports.clear();
849   CurInst = nullptr;
850   HasTailCall = false;
851   SDNodeOrder = LowestSDNodeOrder;
852   StatepointLowering.clear();
853 }
854 
855 /// clearDanglingDebugInfo - Clear the dangling debug information
856 /// map. This function is separated from the clear so that debug
857 /// information that is dangling in a basic block can be properly
858 /// resolved in a different basic block. This allows the
859 /// SelectionDAG to resolve dangling debug information attached
860 /// to PHI nodes.
861 void SelectionDAGBuilder::clearDanglingDebugInfo() {
862   DanglingDebugInfoMap.clear();
863 }
864 
865 /// getRoot - Return the current virtual root of the Selection DAG,
866 /// flushing any PendingLoad items. This must be done before emitting
867 /// a store or any other node that may need to be ordered after any
868 /// prior load instructions.
869 ///
870 SDValue SelectionDAGBuilder::getRoot() {
871   if (PendingLoads.empty())
872     return DAG.getRoot();
873 
874   if (PendingLoads.size() == 1) {
875     SDValue Root = PendingLoads[0];
876     DAG.setRoot(Root);
877     PendingLoads.clear();
878     return Root;
879   }
880 
881   // Otherwise, we have to make a token factor node.
882   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
883                              PendingLoads);
884   PendingLoads.clear();
885   DAG.setRoot(Root);
886   return Root;
887 }
888 
889 /// getControlRoot - Similar to getRoot, but instead of flushing all the
890 /// PendingLoad items, flush all the PendingExports items. It is necessary
891 /// to do this before emitting a terminator instruction.
892 ///
893 SDValue SelectionDAGBuilder::getControlRoot() {
894   SDValue Root = DAG.getRoot();
895 
896   if (PendingExports.empty())
897     return Root;
898 
899   // Turn all of the CopyToReg chains into one factored node.
900   if (Root.getOpcode() != ISD::EntryToken) {
901     unsigned i = 0, e = PendingExports.size();
902     for (; i != e; ++i) {
903       assert(PendingExports[i].getNode()->getNumOperands() > 1);
904       if (PendingExports[i].getNode()->getOperand(0) == Root)
905         break;  // Don't add the root if we already indirectly depend on it.
906     }
907 
908     if (i == e)
909       PendingExports.push_back(Root);
910   }
911 
912   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
913                      PendingExports);
914   PendingExports.clear();
915   DAG.setRoot(Root);
916   return Root;
917 }
918 
919 void SelectionDAGBuilder::visit(const Instruction &I) {
920   // Set up outgoing PHI node register values before emitting the terminator.
921   if (isa<TerminatorInst>(&I))
922     HandlePHINodesInSuccessorBlocks(I.getParent());
923 
924   ++SDNodeOrder;
925 
926   CurInst = &I;
927 
928   visit(I.getOpcode(), I);
929 
930   if (!isa<TerminatorInst>(&I) && !HasTailCall &&
931       !isStatepoint(&I)) // statepoints handle their exports internally
932     CopyToExportRegsIfNeeded(&I);
933 
934   CurInst = nullptr;
935 }
936 
937 void SelectionDAGBuilder::visitPHI(const PHINode &) {
938   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
939 }
940 
941 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
942   // Note: this doesn't use InstVisitor, because it has to work with
943   // ConstantExpr's in addition to instructions.
944   switch (Opcode) {
945   default: llvm_unreachable("Unknown instruction type encountered!");
946     // Build the switch statement using the Instruction.def file.
947 #define HANDLE_INST(NUM, OPCODE, CLASS) \
948     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
949 #include "llvm/IR/Instruction.def"
950   }
951 }
952 
953 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
954 // generate the debug data structures now that we've seen its definition.
955 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
956                                                    SDValue Val) {
957   DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
958   if (DDI.getDI()) {
959     const DbgValueInst *DI = DDI.getDI();
960     DebugLoc dl = DDI.getdl();
961     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
962     DILocalVariable *Variable = DI->getVariable();
963     DIExpression *Expr = DI->getExpression();
964     assert(Variable->isValidLocationForIntrinsic(dl) &&
965            "Expected inlined-at fields to agree");
966     uint64_t Offset = DI->getOffset();
967     SDDbgValue *SDV;
968     if (Val.getNode()) {
969       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, false,
970                                     Val)) {
971         SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
972                               false, Offset, dl, DbgSDNodeOrder);
973         DAG.AddDbgValue(SDV, Val.getNode(), false);
974       }
975     } else
976       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
977     DanglingDebugInfoMap[V] = DanglingDebugInfo();
978   }
979 }
980 
981 /// getCopyFromRegs - If there was virtual register allocated for the value V
982 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
983 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
984   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
985   SDValue Result;
986 
987   if (It != FuncInfo.ValueMap.end()) {
988     unsigned InReg = It->second;
989     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
990                      DAG.getDataLayout(), InReg, Ty);
991     SDValue Chain = DAG.getEntryNode();
992     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
993     resolveDanglingDebugInfo(V, Result);
994   }
995 
996   return Result;
997 }
998 
999 /// getValue - Return an SDValue for the given Value.
1000 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1001   // If we already have an SDValue for this value, use it. It's important
1002   // to do this first, so that we don't create a CopyFromReg if we already
1003   // have a regular SDValue.
1004   SDValue &N = NodeMap[V];
1005   if (N.getNode()) return N;
1006 
1007   // If there's a virtual register allocated and initialized for this
1008   // value, use it.
1009   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1010     return copyFromReg;
1011 
1012   // Otherwise create a new SDValue and remember it.
1013   SDValue Val = getValueImpl(V);
1014   NodeMap[V] = Val;
1015   resolveDanglingDebugInfo(V, Val);
1016   return Val;
1017 }
1018 
1019 // Return true if SDValue exists for the given Value
1020 bool SelectionDAGBuilder::findValue(const Value *V) const {
1021   return (NodeMap.find(V) != NodeMap.end()) ||
1022     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1023 }
1024 
1025 /// getNonRegisterValue - Return an SDValue for the given Value, but
1026 /// don't look in FuncInfo.ValueMap for a virtual register.
1027 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1028   // If we already have an SDValue for this value, use it.
1029   SDValue &N = NodeMap[V];
1030   if (N.getNode()) {
1031     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1032       // Remove the debug location from the node as the node is about to be used
1033       // in a location which may differ from the original debug location.  This
1034       // is relevant to Constant and ConstantFP nodes because they can appear
1035       // as constant expressions inside PHI nodes.
1036       N->setDebugLoc(DebugLoc());
1037     }
1038     return N;
1039   }
1040 
1041   // Otherwise create a new SDValue and remember it.
1042   SDValue Val = getValueImpl(V);
1043   NodeMap[V] = Val;
1044   resolveDanglingDebugInfo(V, Val);
1045   return Val;
1046 }
1047 
1048 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1049 /// Create an SDValue for the given value.
1050 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1051   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1052 
1053   if (const Constant *C = dyn_cast<Constant>(V)) {
1054     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1055 
1056     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1057       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1058 
1059     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1060       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1061 
1062     if (isa<ConstantPointerNull>(C)) {
1063       unsigned AS = V->getType()->getPointerAddressSpace();
1064       return DAG.getConstant(0, getCurSDLoc(),
1065                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1066     }
1067 
1068     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1069       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1070 
1071     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1072       return DAG.getUNDEF(VT);
1073 
1074     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1075       visit(CE->getOpcode(), *CE);
1076       SDValue N1 = NodeMap[V];
1077       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1078       return N1;
1079     }
1080 
1081     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1082       SmallVector<SDValue, 4> Constants;
1083       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1084            OI != OE; ++OI) {
1085         SDNode *Val = getValue(*OI).getNode();
1086         // If the operand is an empty aggregate, there are no values.
1087         if (!Val) continue;
1088         // Add each leaf value from the operand to the Constants list
1089         // to form a flattened list of all the values.
1090         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1091           Constants.push_back(SDValue(Val, i));
1092       }
1093 
1094       return DAG.getMergeValues(Constants, getCurSDLoc());
1095     }
1096 
1097     if (const ConstantDataSequential *CDS =
1098           dyn_cast<ConstantDataSequential>(C)) {
1099       SmallVector<SDValue, 4> Ops;
1100       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1101         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1102         // Add each leaf value from the operand to the Constants list
1103         // to form a flattened list of all the values.
1104         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1105           Ops.push_back(SDValue(Val, i));
1106       }
1107 
1108       if (isa<ArrayType>(CDS->getType()))
1109         return DAG.getMergeValues(Ops, getCurSDLoc());
1110       return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1111                                       VT, Ops);
1112     }
1113 
1114     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1115       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1116              "Unknown struct or array constant!");
1117 
1118       SmallVector<EVT, 4> ValueVTs;
1119       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1120       unsigned NumElts = ValueVTs.size();
1121       if (NumElts == 0)
1122         return SDValue(); // empty struct
1123       SmallVector<SDValue, 4> Constants(NumElts);
1124       for (unsigned i = 0; i != NumElts; ++i) {
1125         EVT EltVT = ValueVTs[i];
1126         if (isa<UndefValue>(C))
1127           Constants[i] = DAG.getUNDEF(EltVT);
1128         else if (EltVT.isFloatingPoint())
1129           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1130         else
1131           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1132       }
1133 
1134       return DAG.getMergeValues(Constants, getCurSDLoc());
1135     }
1136 
1137     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1138       return DAG.getBlockAddress(BA, VT);
1139 
1140     VectorType *VecTy = cast<VectorType>(V->getType());
1141     unsigned NumElements = VecTy->getNumElements();
1142 
1143     // Now that we know the number and type of the elements, get that number of
1144     // elements into the Ops array based on what kind of constant it is.
1145     SmallVector<SDValue, 16> Ops;
1146     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1147       for (unsigned i = 0; i != NumElements; ++i)
1148         Ops.push_back(getValue(CV->getOperand(i)));
1149     } else {
1150       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1151       EVT EltVT =
1152           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1153 
1154       SDValue Op;
1155       if (EltVT.isFloatingPoint())
1156         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1157       else
1158         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1159       Ops.assign(NumElements, Op);
1160     }
1161 
1162     // Create a BUILD_VECTOR node.
1163     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
1164   }
1165 
1166   // If this is a static alloca, generate it as the frameindex instead of
1167   // computation.
1168   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1169     DenseMap<const AllocaInst*, int>::iterator SI =
1170       FuncInfo.StaticAllocaMap.find(AI);
1171     if (SI != FuncInfo.StaticAllocaMap.end())
1172       return DAG.getFrameIndex(SI->second,
1173                                TLI.getPointerTy(DAG.getDataLayout()));
1174   }
1175 
1176   // If this is an instruction which fast-isel has deferred, select it now.
1177   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1178     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1179     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1180                      Inst->getType());
1181     SDValue Chain = DAG.getEntryNode();
1182     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1183   }
1184 
1185   llvm_unreachable("Can't get register for value!");
1186 }
1187 
1188 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1189   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1190   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1191   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1192   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1193   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1194   if (IsMSVCCXX || IsCoreCLR)
1195     CatchPadMBB->setIsEHFuncletEntry();
1196 
1197   DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot()));
1198 }
1199 
1200 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1201   // Update machine-CFG edge.
1202   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1203   FuncInfo.MBB->addSuccessor(TargetMBB);
1204 
1205   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1206   bool IsSEH = isAsynchronousEHPersonality(Pers);
1207   if (IsSEH) {
1208     // If this is not a fall-through branch or optimizations are switched off,
1209     // emit the branch.
1210     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1211         TM.getOptLevel() == CodeGenOpt::None)
1212       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1213                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1214     return;
1215   }
1216 
1217   // Figure out the funclet membership for the catchret's successor.
1218   // This will be used by the FuncletLayout pass to determine how to order the
1219   // BB's.
1220   // A 'catchret' returns to the outer scope's color.
1221   Value *ParentPad = I.getCatchSwitchParentPad();
1222   const BasicBlock *SuccessorColor;
1223   if (isa<ConstantTokenNone>(ParentPad))
1224     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1225   else
1226     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1227   assert(SuccessorColor && "No parent funclet for catchret!");
1228   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1229   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1230 
1231   // Create the terminator node.
1232   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1233                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1234                             DAG.getBasicBlock(SuccessorColorMBB));
1235   DAG.setRoot(Ret);
1236 }
1237 
1238 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1239   // Don't emit any special code for the cleanuppad instruction. It just marks
1240   // the start of a funclet.
1241   FuncInfo.MBB->setIsEHFuncletEntry();
1242   FuncInfo.MBB->setIsCleanupFuncletEntry();
1243 }
1244 
1245 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1246 /// many places it could ultimately go. In the IR, we have a single unwind
1247 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1248 /// This function skips over imaginary basic blocks that hold catchswitch
1249 /// instructions, and finds all the "real" machine
1250 /// basic block destinations. As those destinations may not be successors of
1251 /// EHPadBB, here we also calculate the edge probability to those destinations.
1252 /// The passed-in Prob is the edge probability to EHPadBB.
1253 static void findUnwindDestinations(
1254     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1255     BranchProbability Prob,
1256     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1257         &UnwindDests) {
1258   EHPersonality Personality =
1259     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1260   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1261   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1262 
1263   while (EHPadBB) {
1264     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1265     BasicBlock *NewEHPadBB = nullptr;
1266     if (isa<LandingPadInst>(Pad)) {
1267       // Stop on landingpads. They are not funclets.
1268       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1269       break;
1270     } else if (isa<CleanupPadInst>(Pad)) {
1271       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1272       // personalities.
1273       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1274       UnwindDests.back().first->setIsEHFuncletEntry();
1275       break;
1276     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1277       // Add the catchpad handlers to the possible destinations.
1278       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1279         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1280         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1281         if (IsMSVCCXX || IsCoreCLR)
1282           UnwindDests.back().first->setIsEHFuncletEntry();
1283       }
1284       NewEHPadBB = CatchSwitch->getUnwindDest();
1285     } else {
1286       continue;
1287     }
1288 
1289     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1290     if (BPI && NewEHPadBB)
1291       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1292     EHPadBB = NewEHPadBB;
1293   }
1294 }
1295 
1296 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1297   // Update successor info.
1298   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1299   auto UnwindDest = I.getUnwindDest();
1300   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1301   BranchProbability UnwindDestProb =
1302       (BPI && UnwindDest)
1303           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1304           : BranchProbability::getZero();
1305   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1306   for (auto &UnwindDest : UnwindDests) {
1307     UnwindDest.first->setIsEHPad();
1308     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1309   }
1310   FuncInfo.MBB->normalizeSuccProbs();
1311 
1312   // Create the terminator node.
1313   SDValue Ret =
1314       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1315   DAG.setRoot(Ret);
1316 }
1317 
1318 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1319   report_fatal_error("visitCatchSwitch not yet implemented!");
1320 }
1321 
1322 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1323   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1324   auto &DL = DAG.getDataLayout();
1325   SDValue Chain = getControlRoot();
1326   SmallVector<ISD::OutputArg, 8> Outs;
1327   SmallVector<SDValue, 8> OutVals;
1328 
1329   if (!FuncInfo.CanLowerReturn) {
1330     unsigned DemoteReg = FuncInfo.DemoteRegister;
1331     const Function *F = I.getParent()->getParent();
1332 
1333     // Emit a store of the return value through the virtual register.
1334     // Leave Outs empty so that LowerReturn won't try to load return
1335     // registers the usual way.
1336     SmallVector<EVT, 1> PtrValueVTs;
1337     ComputeValueVTs(TLI, DL, PointerType::getUnqual(F->getReturnType()),
1338                     PtrValueVTs);
1339 
1340     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1341                                         DemoteReg, PtrValueVTs[0]);
1342     SDValue RetOp = getValue(I.getOperand(0));
1343 
1344     SmallVector<EVT, 4> ValueVTs;
1345     SmallVector<uint64_t, 4> Offsets;
1346     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1347     unsigned NumValues = ValueVTs.size();
1348 
1349     // An aggregate return value cannot wrap around the address space, so
1350     // offsets to its parts don't wrap either.
1351     SDNodeFlags Flags;
1352     Flags.setNoUnsignedWrap(true);
1353 
1354     SmallVector<SDValue, 4> Chains(NumValues);
1355     for (unsigned i = 0; i != NumValues; ++i) {
1356       SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1357                                 RetPtr.getValueType(), RetPtr,
1358                                 DAG.getIntPtrConstant(Offsets[i],
1359                                                       getCurSDLoc()),
1360                                 &Flags);
1361       Chains[i] =
1362         DAG.getStore(Chain, getCurSDLoc(),
1363                      SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1364                      // FIXME: better loc info would be nice.
1365                      Add, MachinePointerInfo(), false, false, 0);
1366     }
1367 
1368     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1369                         MVT::Other, Chains);
1370   } else if (I.getNumOperands() != 0) {
1371     SmallVector<EVT, 4> ValueVTs;
1372     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1373     unsigned NumValues = ValueVTs.size();
1374     if (NumValues) {
1375       SDValue RetOp = getValue(I.getOperand(0));
1376 
1377       const Function *F = I.getParent()->getParent();
1378 
1379       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1380       if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1381                                           Attribute::SExt))
1382         ExtendKind = ISD::SIGN_EXTEND;
1383       else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1384                                                Attribute::ZExt))
1385         ExtendKind = ISD::ZERO_EXTEND;
1386 
1387       LLVMContext &Context = F->getContext();
1388       bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1389                                                       Attribute::InReg);
1390 
1391       for (unsigned j = 0; j != NumValues; ++j) {
1392         EVT VT = ValueVTs[j];
1393 
1394         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1395           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1396 
1397         unsigned NumParts = TLI.getNumRegisters(Context, VT);
1398         MVT PartVT = TLI.getRegisterType(Context, VT);
1399         SmallVector<SDValue, 4> Parts(NumParts);
1400         getCopyToParts(DAG, getCurSDLoc(),
1401                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1402                        &Parts[0], NumParts, PartVT, &I, ExtendKind);
1403 
1404         // 'inreg' on function refers to return value
1405         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1406         if (RetInReg)
1407           Flags.setInReg();
1408 
1409         // Propagate extension type if any
1410         if (ExtendKind == ISD::SIGN_EXTEND)
1411           Flags.setSExt();
1412         else if (ExtendKind == ISD::ZERO_EXTEND)
1413           Flags.setZExt();
1414 
1415         for (unsigned i = 0; i < NumParts; ++i) {
1416           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1417                                         VT, /*isfixed=*/true, 0, 0));
1418           OutVals.push_back(Parts[i]);
1419         }
1420       }
1421     }
1422   }
1423 
1424   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1425   CallingConv::ID CallConv =
1426     DAG.getMachineFunction().getFunction()->getCallingConv();
1427   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1428       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1429 
1430   // Verify that the target's LowerReturn behaved as expected.
1431   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1432          "LowerReturn didn't return a valid chain!");
1433 
1434   // Update the DAG with the new chain value resulting from return lowering.
1435   DAG.setRoot(Chain);
1436 }
1437 
1438 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1439 /// created for it, emit nodes to copy the value into the virtual
1440 /// registers.
1441 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1442   // Skip empty types
1443   if (V->getType()->isEmptyTy())
1444     return;
1445 
1446   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1447   if (VMI != FuncInfo.ValueMap.end()) {
1448     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1449     CopyValueToVirtualRegister(V, VMI->second);
1450   }
1451 }
1452 
1453 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1454 /// the current basic block, add it to ValueMap now so that we'll get a
1455 /// CopyTo/FromReg.
1456 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1457   // No need to export constants.
1458   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1459 
1460   // Already exported?
1461   if (FuncInfo.isExportedInst(V)) return;
1462 
1463   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1464   CopyValueToVirtualRegister(V, Reg);
1465 }
1466 
1467 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1468                                                      const BasicBlock *FromBB) {
1469   // The operands of the setcc have to be in this block.  We don't know
1470   // how to export them from some other block.
1471   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1472     // Can export from current BB.
1473     if (VI->getParent() == FromBB)
1474       return true;
1475 
1476     // Is already exported, noop.
1477     return FuncInfo.isExportedInst(V);
1478   }
1479 
1480   // If this is an argument, we can export it if the BB is the entry block or
1481   // if it is already exported.
1482   if (isa<Argument>(V)) {
1483     if (FromBB == &FromBB->getParent()->getEntryBlock())
1484       return true;
1485 
1486     // Otherwise, can only export this if it is already exported.
1487     return FuncInfo.isExportedInst(V);
1488   }
1489 
1490   // Otherwise, constants can always be exported.
1491   return true;
1492 }
1493 
1494 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1495 BranchProbability
1496 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1497                                         const MachineBasicBlock *Dst) const {
1498   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1499   const BasicBlock *SrcBB = Src->getBasicBlock();
1500   const BasicBlock *DstBB = Dst->getBasicBlock();
1501   if (!BPI) {
1502     // If BPI is not available, set the default probability as 1 / N, where N is
1503     // the number of successors.
1504     auto SuccSize = std::max<uint32_t>(
1505         std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1);
1506     return BranchProbability(1, SuccSize);
1507   }
1508   return BPI->getEdgeProbability(SrcBB, DstBB);
1509 }
1510 
1511 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1512                                                MachineBasicBlock *Dst,
1513                                                BranchProbability Prob) {
1514   if (!FuncInfo.BPI)
1515     Src->addSuccessorWithoutProb(Dst);
1516   else {
1517     if (Prob.isUnknown())
1518       Prob = getEdgeProbability(Src, Dst);
1519     Src->addSuccessor(Dst, Prob);
1520   }
1521 }
1522 
1523 static bool InBlock(const Value *V, const BasicBlock *BB) {
1524   if (const Instruction *I = dyn_cast<Instruction>(V))
1525     return I->getParent() == BB;
1526   return true;
1527 }
1528 
1529 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1530 /// This function emits a branch and is used at the leaves of an OR or an
1531 /// AND operator tree.
1532 ///
1533 void
1534 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1535                                                   MachineBasicBlock *TBB,
1536                                                   MachineBasicBlock *FBB,
1537                                                   MachineBasicBlock *CurBB,
1538                                                   MachineBasicBlock *SwitchBB,
1539                                                   BranchProbability TProb,
1540                                                   BranchProbability FProb) {
1541   const BasicBlock *BB = CurBB->getBasicBlock();
1542 
1543   // If the leaf of the tree is a comparison, merge the condition into
1544   // the caseblock.
1545   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1546     // The operands of the cmp have to be in this block.  We don't know
1547     // how to export them from some other block.  If this is the first block
1548     // of the sequence, no exporting is needed.
1549     if (CurBB == SwitchBB ||
1550         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1551          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1552       ISD::CondCode Condition;
1553       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1554         Condition = getICmpCondCode(IC->getPredicate());
1555       } else {
1556         const FCmpInst *FC = cast<FCmpInst>(Cond);
1557         Condition = getFCmpCondCode(FC->getPredicate());
1558         if (TM.Options.NoNaNsFPMath)
1559           Condition = getFCmpCodeWithoutNaN(Condition);
1560       }
1561 
1562       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1563                    TBB, FBB, CurBB, TProb, FProb);
1564       SwitchCases.push_back(CB);
1565       return;
1566     }
1567   }
1568 
1569   // Create a CaseBlock record representing this branch.
1570   CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1571                nullptr, TBB, FBB, CurBB, TProb, FProb);
1572   SwitchCases.push_back(CB);
1573 }
1574 
1575 /// FindMergedConditions - If Cond is an expression like
1576 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1577                                                MachineBasicBlock *TBB,
1578                                                MachineBasicBlock *FBB,
1579                                                MachineBasicBlock *CurBB,
1580                                                MachineBasicBlock *SwitchBB,
1581                                                Instruction::BinaryOps Opc,
1582                                                BranchProbability TProb,
1583                                                BranchProbability FProb) {
1584   // If this node is not part of the or/and tree, emit it as a branch.
1585   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1586   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1587       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1588       BOp->getParent() != CurBB->getBasicBlock() ||
1589       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1590       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1591     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1592                                  TProb, FProb);
1593     return;
1594   }
1595 
1596   //  Create TmpBB after CurBB.
1597   MachineFunction::iterator BBI(CurBB);
1598   MachineFunction &MF = DAG.getMachineFunction();
1599   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1600   CurBB->getParent()->insert(++BBI, TmpBB);
1601 
1602   if (Opc == Instruction::Or) {
1603     // Codegen X | Y as:
1604     // BB1:
1605     //   jmp_if_X TBB
1606     //   jmp TmpBB
1607     // TmpBB:
1608     //   jmp_if_Y TBB
1609     //   jmp FBB
1610     //
1611 
1612     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1613     // The requirement is that
1614     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1615     //     = TrueProb for original BB.
1616     // Assuming the original probabilities are A and B, one choice is to set
1617     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1618     // A/(1+B) and 2B/(1+B). This choice assumes that
1619     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1620     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1621     // TmpBB, but the math is more complicated.
1622 
1623     auto NewTrueProb = TProb / 2;
1624     auto NewFalseProb = TProb / 2 + FProb;
1625     // Emit the LHS condition.
1626     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1627                          NewTrueProb, NewFalseProb);
1628 
1629     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1630     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1631     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1632     // Emit the RHS condition into TmpBB.
1633     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1634                          Probs[0], Probs[1]);
1635   } else {
1636     assert(Opc == Instruction::And && "Unknown merge op!");
1637     // Codegen X & Y as:
1638     // BB1:
1639     //   jmp_if_X TmpBB
1640     //   jmp FBB
1641     // TmpBB:
1642     //   jmp_if_Y TBB
1643     //   jmp FBB
1644     //
1645     //  This requires creation of TmpBB after CurBB.
1646 
1647     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1648     // The requirement is that
1649     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1650     //     = FalseProb for original BB.
1651     // Assuming the original probabilities are A and B, one choice is to set
1652     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1653     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1654     // TrueProb for BB1 * FalseProb for TmpBB.
1655 
1656     auto NewTrueProb = TProb + FProb / 2;
1657     auto NewFalseProb = FProb / 2;
1658     // Emit the LHS condition.
1659     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1660                          NewTrueProb, NewFalseProb);
1661 
1662     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1663     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1664     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1665     // Emit the RHS condition into TmpBB.
1666     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1667                          Probs[0], Probs[1]);
1668   }
1669 }
1670 
1671 /// If the set of cases should be emitted as a series of branches, return true.
1672 /// If we should emit this as a bunch of and/or'd together conditions, return
1673 /// false.
1674 bool
1675 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1676   if (Cases.size() != 2) return true;
1677 
1678   // If this is two comparisons of the same values or'd or and'd together, they
1679   // will get folded into a single comparison, so don't emit two blocks.
1680   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1681        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1682       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1683        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1684     return false;
1685   }
1686 
1687   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1688   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1689   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1690       Cases[0].CC == Cases[1].CC &&
1691       isa<Constant>(Cases[0].CmpRHS) &&
1692       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1693     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1694       return false;
1695     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1696       return false;
1697   }
1698 
1699   return true;
1700 }
1701 
1702 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1703   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1704 
1705   // Update machine-CFG edges.
1706   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1707 
1708   if (I.isUnconditional()) {
1709     // Update machine-CFG edges.
1710     BrMBB->addSuccessor(Succ0MBB);
1711 
1712     // If this is not a fall-through branch or optimizations are switched off,
1713     // emit the branch.
1714     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1715       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1716                               MVT::Other, getControlRoot(),
1717                               DAG.getBasicBlock(Succ0MBB)));
1718 
1719     return;
1720   }
1721 
1722   // If this condition is one of the special cases we handle, do special stuff
1723   // now.
1724   const Value *CondVal = I.getCondition();
1725   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1726 
1727   // If this is a series of conditions that are or'd or and'd together, emit
1728   // this as a sequence of branches instead of setcc's with and/or operations.
1729   // As long as jumps are not expensive, this should improve performance.
1730   // For example, instead of something like:
1731   //     cmp A, B
1732   //     C = seteq
1733   //     cmp D, E
1734   //     F = setle
1735   //     or C, F
1736   //     jnz foo
1737   // Emit:
1738   //     cmp A, B
1739   //     je foo
1740   //     cmp D, E
1741   //     jle foo
1742   //
1743   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1744     Instruction::BinaryOps Opcode = BOp->getOpcode();
1745     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
1746         !I.getMetadata(LLVMContext::MD_unpredictable) &&
1747         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
1748       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1749                            Opcode,
1750                            getEdgeProbability(BrMBB, Succ0MBB),
1751                            getEdgeProbability(BrMBB, Succ1MBB));
1752       // If the compares in later blocks need to use values not currently
1753       // exported from this block, export them now.  This block should always
1754       // be the first entry.
1755       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1756 
1757       // Allow some cases to be rejected.
1758       if (ShouldEmitAsBranches(SwitchCases)) {
1759         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1760           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1761           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1762         }
1763 
1764         // Emit the branch for this block.
1765         visitSwitchCase(SwitchCases[0], BrMBB);
1766         SwitchCases.erase(SwitchCases.begin());
1767         return;
1768       }
1769 
1770       // Okay, we decided not to do this, remove any inserted MBB's and clear
1771       // SwitchCases.
1772       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1773         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1774 
1775       SwitchCases.clear();
1776     }
1777   }
1778 
1779   // Create a CaseBlock record representing this branch.
1780   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1781                nullptr, Succ0MBB, Succ1MBB, BrMBB);
1782 
1783   // Use visitSwitchCase to actually insert the fast branch sequence for this
1784   // cond branch.
1785   visitSwitchCase(CB, BrMBB);
1786 }
1787 
1788 /// visitSwitchCase - Emits the necessary code to represent a single node in
1789 /// the binary search tree resulting from lowering a switch instruction.
1790 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1791                                           MachineBasicBlock *SwitchBB) {
1792   SDValue Cond;
1793   SDValue CondLHS = getValue(CB.CmpLHS);
1794   SDLoc dl = getCurSDLoc();
1795 
1796   // Build the setcc now.
1797   if (!CB.CmpMHS) {
1798     // Fold "(X == true)" to X and "(X == false)" to !X to
1799     // handle common cases produced by branch lowering.
1800     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1801         CB.CC == ISD::SETEQ)
1802       Cond = CondLHS;
1803     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1804              CB.CC == ISD::SETEQ) {
1805       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
1806       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1807     } else
1808       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1809   } else {
1810     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1811 
1812     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1813     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1814 
1815     SDValue CmpOp = getValue(CB.CmpMHS);
1816     EVT VT = CmpOp.getValueType();
1817 
1818     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1819       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
1820                           ISD::SETLE);
1821     } else {
1822       SDValue SUB = DAG.getNode(ISD::SUB, dl,
1823                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
1824       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1825                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
1826     }
1827   }
1828 
1829   // Update successor info
1830   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
1831   // TrueBB and FalseBB are always different unless the incoming IR is
1832   // degenerate. This only happens when running llc on weird IR.
1833   if (CB.TrueBB != CB.FalseBB)
1834     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
1835   SwitchBB->normalizeSuccProbs();
1836 
1837   // If the lhs block is the next block, invert the condition so that we can
1838   // fall through to the lhs instead of the rhs block.
1839   if (CB.TrueBB == NextBlock(SwitchBB)) {
1840     std::swap(CB.TrueBB, CB.FalseBB);
1841     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
1842     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1843   }
1844 
1845   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1846                                MVT::Other, getControlRoot(), Cond,
1847                                DAG.getBasicBlock(CB.TrueBB));
1848 
1849   // Insert the false branch. Do this even if it's a fall through branch,
1850   // this makes it easier to do DAG optimizations which require inverting
1851   // the branch condition.
1852   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1853                        DAG.getBasicBlock(CB.FalseBB));
1854 
1855   DAG.setRoot(BrCond);
1856 }
1857 
1858 /// visitJumpTable - Emit JumpTable node in the current MBB
1859 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1860   // Emit the code for the jump table
1861   assert(JT.Reg != -1U && "Should lower JT Header first!");
1862   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1863   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1864                                      JT.Reg, PTy);
1865   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1866   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1867                                     MVT::Other, Index.getValue(1),
1868                                     Table, Index);
1869   DAG.setRoot(BrJumpTable);
1870 }
1871 
1872 /// visitJumpTableHeader - This function emits necessary code to produce index
1873 /// in the JumpTable from switch case.
1874 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1875                                                JumpTableHeader &JTH,
1876                                                MachineBasicBlock *SwitchBB) {
1877   SDLoc dl = getCurSDLoc();
1878 
1879   // Subtract the lowest switch case value from the value being switched on and
1880   // conditional branch to default mbb if the result is greater than the
1881   // difference between smallest and largest cases.
1882   SDValue SwitchOp = getValue(JTH.SValue);
1883   EVT VT = SwitchOp.getValueType();
1884   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
1885                             DAG.getConstant(JTH.First, dl, VT));
1886 
1887   // The SDNode we just created, which holds the value being switched on minus
1888   // the smallest case value, needs to be copied to a virtual register so it
1889   // can be used as an index into the jump table in a subsequent basic block.
1890   // This value may be smaller or larger than the target's pointer type, and
1891   // therefore require extension or truncating.
1892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1893   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
1894 
1895   unsigned JumpTableReg =
1896       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
1897   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
1898                                     JumpTableReg, SwitchOp);
1899   JT.Reg = JumpTableReg;
1900 
1901   // Emit the range check for the jump table, and branch to the default block
1902   // for the switch statement if the value being switched on exceeds the largest
1903   // case in the switch.
1904   SDValue CMP = DAG.getSetCC(
1905       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
1906                                  Sub.getValueType()),
1907       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
1908 
1909   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1910                                MVT::Other, CopyTo, CMP,
1911                                DAG.getBasicBlock(JT.Default));
1912 
1913   // Avoid emitting unnecessary branches to the next block.
1914   if (JT.MBB != NextBlock(SwitchBB))
1915     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1916                          DAG.getBasicBlock(JT.MBB));
1917 
1918   DAG.setRoot(BrCond);
1919 }
1920 
1921 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1922 /// tail spliced into a stack protector check success bb.
1923 ///
1924 /// For a high level explanation of how this fits into the stack protector
1925 /// generation see the comment on the declaration of class
1926 /// StackProtectorDescriptor.
1927 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1928                                                   MachineBasicBlock *ParentBB) {
1929 
1930   // First create the loads to the guard/stack slot for the comparison.
1931   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1932   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
1933 
1934   MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1935   int FI = MFI->getStackProtectorIndex();
1936 
1937   const Value *IRGuard = SPD.getGuard();
1938   SDValue GuardPtr = getValue(IRGuard);
1939   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1940 
1941   unsigned Align = DL->getPrefTypeAlignment(IRGuard->getType());
1942 
1943   SDValue Guard;
1944   SDLoc dl = getCurSDLoc();
1945 
1946   // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1947   // guard value from the virtual register holding the value. Otherwise, emit a
1948   // volatile load to retrieve the stack guard value.
1949   unsigned GuardReg = SPD.getGuardReg();
1950 
1951   if (GuardReg && TLI.useLoadStackGuardNode())
1952     Guard = DAG.getCopyFromReg(DAG.getEntryNode(), dl, GuardReg,
1953                                PtrTy);
1954   else
1955     Guard = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(),
1956                         GuardPtr, MachinePointerInfo(IRGuard, 0),
1957                         true, false, false, Align);
1958 
1959   SDValue StackSlot = DAG.getLoad(
1960       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
1961       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), true,
1962       false, false, Align);
1963 
1964   // Perform the comparison via a subtract/getsetcc.
1965   EVT VT = Guard.getValueType();
1966   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot);
1967 
1968   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
1969                                                         *DAG.getContext(),
1970                                                         Sub.getValueType()),
1971                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
1972 
1973   // If the sub is not 0, then we know the guard/stackslot do not equal, so
1974   // branch to failure MBB.
1975   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1976                                MVT::Other, StackSlot.getOperand(0),
1977                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1978   // Otherwise branch to success MBB.
1979   SDValue Br = DAG.getNode(ISD::BR, dl,
1980                            MVT::Other, BrCond,
1981                            DAG.getBasicBlock(SPD.getSuccessMBB()));
1982 
1983   DAG.setRoot(Br);
1984 }
1985 
1986 /// Codegen the failure basic block for a stack protector check.
1987 ///
1988 /// A failure stack protector machine basic block consists simply of a call to
1989 /// __stack_chk_fail().
1990 ///
1991 /// For a high level explanation of how this fits into the stack protector
1992 /// generation see the comment on the declaration of class
1993 /// StackProtectorDescriptor.
1994 void
1995 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1996   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1997   SDValue Chain =
1998       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
1999                       None, false, getCurSDLoc(), false, false).second;
2000   DAG.setRoot(Chain);
2001 }
2002 
2003 /// visitBitTestHeader - This function emits necessary code to produce value
2004 /// suitable for "bit tests"
2005 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2006                                              MachineBasicBlock *SwitchBB) {
2007   SDLoc dl = getCurSDLoc();
2008 
2009   // Subtract the minimum value
2010   SDValue SwitchOp = getValue(B.SValue);
2011   EVT VT = SwitchOp.getValueType();
2012   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2013                             DAG.getConstant(B.First, dl, VT));
2014 
2015   // Check range
2016   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2017   SDValue RangeCmp = DAG.getSetCC(
2018       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2019                                  Sub.getValueType()),
2020       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2021 
2022   // Determine the type of the test operands.
2023   bool UsePtrType = false;
2024   if (!TLI.isTypeLegal(VT))
2025     UsePtrType = true;
2026   else {
2027     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2028       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2029         // Switch table case range are encoded into series of masks.
2030         // Just use pointer type, it's guaranteed to fit.
2031         UsePtrType = true;
2032         break;
2033       }
2034   }
2035   if (UsePtrType) {
2036     VT = TLI.getPointerTy(DAG.getDataLayout());
2037     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2038   }
2039 
2040   B.RegVT = VT.getSimpleVT();
2041   B.Reg = FuncInfo.CreateReg(B.RegVT);
2042   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2043 
2044   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2045 
2046   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2047   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2048   SwitchBB->normalizeSuccProbs();
2049 
2050   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2051                                 MVT::Other, CopyTo, RangeCmp,
2052                                 DAG.getBasicBlock(B.Default));
2053 
2054   // Avoid emitting unnecessary branches to the next block.
2055   if (MBB != NextBlock(SwitchBB))
2056     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2057                           DAG.getBasicBlock(MBB));
2058 
2059   DAG.setRoot(BrRange);
2060 }
2061 
2062 /// visitBitTestCase - this function produces one "bit test"
2063 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2064                                            MachineBasicBlock* NextMBB,
2065                                            BranchProbability BranchProbToNext,
2066                                            unsigned Reg,
2067                                            BitTestCase &B,
2068                                            MachineBasicBlock *SwitchBB) {
2069   SDLoc dl = getCurSDLoc();
2070   MVT VT = BB.RegVT;
2071   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2072   SDValue Cmp;
2073   unsigned PopCount = countPopulation(B.Mask);
2074   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2075   if (PopCount == 1) {
2076     // Testing for a single bit; just compare the shift count with what it
2077     // would need to be to shift a 1 bit in that position.
2078     Cmp = DAG.getSetCC(
2079         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2080         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2081         ISD::SETEQ);
2082   } else if (PopCount == BB.Range) {
2083     // There is only one zero bit in the range, test for it directly.
2084     Cmp = DAG.getSetCC(
2085         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2086         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2087         ISD::SETNE);
2088   } else {
2089     // Make desired shift
2090     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2091                                     DAG.getConstant(1, dl, VT), ShiftOp);
2092 
2093     // Emit bit tests and jumps
2094     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2095                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2096     Cmp = DAG.getSetCC(
2097         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2098         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2099   }
2100 
2101   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2102   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2103   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2104   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2105   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2106   // one as they are relative probabilities (and thus work more like weights),
2107   // and hence we need to normalize them to let the sum of them become one.
2108   SwitchBB->normalizeSuccProbs();
2109 
2110   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2111                               MVT::Other, getControlRoot(),
2112                               Cmp, DAG.getBasicBlock(B.TargetBB));
2113 
2114   // Avoid emitting unnecessary branches to the next block.
2115   if (NextMBB != NextBlock(SwitchBB))
2116     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2117                         DAG.getBasicBlock(NextMBB));
2118 
2119   DAG.setRoot(BrAnd);
2120 }
2121 
2122 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2123   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2124 
2125   // Retrieve successors. Look through artificial IR level blocks like
2126   // catchswitch for successors.
2127   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2128   const BasicBlock *EHPadBB = I.getSuccessor(1);
2129 
2130 #ifndef NDEBUG
2131   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2132   // have to do anything here to lower funclet bundles.
2133   for (unsigned i = 0, e = I.getNumOperandBundles(); i != e; ++i)
2134     assert((I.getOperandBundleAt(i).isDeoptOperandBundle() ||
2135             I.getOperandBundleAt(i).isFuncletOperandBundle()) &&
2136            "Cannot lower invokes with arbitrary operand bundles yet!");
2137 #endif
2138 
2139   const Value *Callee(I.getCalledValue());
2140   const Function *Fn = dyn_cast<Function>(Callee);
2141   if (isa<InlineAsm>(Callee))
2142     visitInlineAsm(&I);
2143   else if (Fn && Fn->isIntrinsic()) {
2144     switch (Fn->getIntrinsicID()) {
2145     default:
2146       llvm_unreachable("Cannot invoke this intrinsic");
2147     case Intrinsic::donothing:
2148       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2149       break;
2150     case Intrinsic::experimental_patchpoint_void:
2151     case Intrinsic::experimental_patchpoint_i64:
2152       visitPatchpoint(&I, EHPadBB);
2153       break;
2154     case Intrinsic::experimental_gc_statepoint:
2155       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2156       break;
2157     }
2158   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2159     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2160     // Eventually we will support lowering the @llvm.experimental.deoptimize
2161     // intrinsic, and right now there are no plans to support other intrinsics
2162     // with deopt state.
2163     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2164   } else {
2165     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2166   }
2167 
2168   // If the value of the invoke is used outside of its defining block, make it
2169   // available as a virtual register.
2170   // We already took care of the exported value for the statepoint instruction
2171   // during call to the LowerStatepoint.
2172   if (!isStatepoint(I)) {
2173     CopyToExportRegsIfNeeded(&I);
2174   }
2175 
2176   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2177   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2178   BranchProbability EHPadBBProb =
2179       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2180           : BranchProbability::getZero();
2181   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2182 
2183   // Update successor info.
2184   addSuccessorWithProb(InvokeMBB, Return);
2185   for (auto &UnwindDest : UnwindDests) {
2186     UnwindDest.first->setIsEHPad();
2187     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2188   }
2189   InvokeMBB->normalizeSuccProbs();
2190 
2191   // Drop into normal successor.
2192   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2193                           MVT::Other, getControlRoot(),
2194                           DAG.getBasicBlock(Return)));
2195 }
2196 
2197 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2198   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2199 }
2200 
2201 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2202   assert(FuncInfo.MBB->isEHPad() &&
2203          "Call to landingpad not in landing pad!");
2204 
2205   MachineBasicBlock *MBB = FuncInfo.MBB;
2206   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2207   AddLandingPadInfo(LP, MMI, MBB);
2208 
2209   // If there aren't registers to copy the values into (e.g., during SjLj
2210   // exceptions), then don't bother to create these DAG nodes.
2211   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2212   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2213   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2214       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2215     return;
2216 
2217   // If landingpad's return type is token type, we don't create DAG nodes
2218   // for its exception pointer and selector value. The extraction of exception
2219   // pointer or selector value from token type landingpads is not currently
2220   // supported.
2221   if (LP.getType()->isTokenTy())
2222     return;
2223 
2224   SmallVector<EVT, 2> ValueVTs;
2225   SDLoc dl = getCurSDLoc();
2226   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2227   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2228 
2229   // Get the two live-in registers as SDValues. The physregs have already been
2230   // copied into virtual registers.
2231   SDValue Ops[2];
2232   if (FuncInfo.ExceptionPointerVirtReg) {
2233     Ops[0] = DAG.getZExtOrTrunc(
2234         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2235                            FuncInfo.ExceptionPointerVirtReg,
2236                            TLI.getPointerTy(DAG.getDataLayout())),
2237         dl, ValueVTs[0]);
2238   } else {
2239     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2240   }
2241   Ops[1] = DAG.getZExtOrTrunc(
2242       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2243                          FuncInfo.ExceptionSelectorVirtReg,
2244                          TLI.getPointerTy(DAG.getDataLayout())),
2245       dl, ValueVTs[1]);
2246 
2247   // Merge into one.
2248   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2249                             DAG.getVTList(ValueVTs), Ops);
2250   setValue(&LP, Res);
2251 }
2252 
2253 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2254 #ifndef NDEBUG
2255   for (const CaseCluster &CC : Clusters)
2256     assert(CC.Low == CC.High && "Input clusters must be single-case");
2257 #endif
2258 
2259   std::sort(Clusters.begin(), Clusters.end(),
2260             [](const CaseCluster &a, const CaseCluster &b) {
2261     return a.Low->getValue().slt(b.Low->getValue());
2262   });
2263 
2264   // Merge adjacent clusters with the same destination.
2265   const unsigned N = Clusters.size();
2266   unsigned DstIndex = 0;
2267   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2268     CaseCluster &CC = Clusters[SrcIndex];
2269     const ConstantInt *CaseVal = CC.Low;
2270     MachineBasicBlock *Succ = CC.MBB;
2271 
2272     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2273         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2274       // If this case has the same successor and is a neighbour, merge it into
2275       // the previous cluster.
2276       Clusters[DstIndex - 1].High = CaseVal;
2277       Clusters[DstIndex - 1].Prob += CC.Prob;
2278     } else {
2279       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2280                    sizeof(Clusters[SrcIndex]));
2281     }
2282   }
2283   Clusters.resize(DstIndex);
2284 }
2285 
2286 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2287                                            MachineBasicBlock *Last) {
2288   // Update JTCases.
2289   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2290     if (JTCases[i].first.HeaderBB == First)
2291       JTCases[i].first.HeaderBB = Last;
2292 
2293   // Update BitTestCases.
2294   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2295     if (BitTestCases[i].Parent == First)
2296       BitTestCases[i].Parent = Last;
2297 }
2298 
2299 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2300   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2301 
2302   // Update machine-CFG edges with unique successors.
2303   SmallSet<BasicBlock*, 32> Done;
2304   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2305     BasicBlock *BB = I.getSuccessor(i);
2306     bool Inserted = Done.insert(BB).second;
2307     if (!Inserted)
2308         continue;
2309 
2310     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2311     addSuccessorWithProb(IndirectBrMBB, Succ);
2312   }
2313   IndirectBrMBB->normalizeSuccProbs();
2314 
2315   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2316                           MVT::Other, getControlRoot(),
2317                           getValue(I.getAddress())));
2318 }
2319 
2320 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2321   if (DAG.getTarget().Options.TrapUnreachable)
2322     DAG.setRoot(
2323         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2324 }
2325 
2326 void SelectionDAGBuilder::visitFSub(const User &I) {
2327   // -0.0 - X --> fneg
2328   Type *Ty = I.getType();
2329   if (isa<Constant>(I.getOperand(0)) &&
2330       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2331     SDValue Op2 = getValue(I.getOperand(1));
2332     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2333                              Op2.getValueType(), Op2));
2334     return;
2335   }
2336 
2337   visitBinary(I, ISD::FSUB);
2338 }
2339 
2340 /// Checks if the given instruction performs a vector reduction, in which case
2341 /// we have the freedom to alter the elements in the result as long as the
2342 /// reduction of them stays unchanged.
2343 static bool isVectorReductionOp(const User *I) {
2344   const Instruction *Inst = dyn_cast<Instruction>(I);
2345   if (!Inst || !Inst->getType()->isVectorTy())
2346     return false;
2347 
2348   auto OpCode = Inst->getOpcode();
2349   switch (OpCode) {
2350   case Instruction::Add:
2351   case Instruction::Mul:
2352   case Instruction::And:
2353   case Instruction::Or:
2354   case Instruction::Xor:
2355     break;
2356   case Instruction::FAdd:
2357   case Instruction::FMul:
2358     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2359       if (FPOp->getFastMathFlags().unsafeAlgebra())
2360         break;
2361     // Fall through.
2362   default:
2363     return false;
2364   }
2365 
2366   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2367   unsigned ElemNumToReduce = ElemNum;
2368 
2369   // Do DFS search on the def-use chain from the given instruction. We only
2370   // allow four kinds of operations during the search until we reach the
2371   // instruction that extracts the first element from the vector:
2372   //
2373   //   1. The reduction operation of the same opcode as the given instruction.
2374   //
2375   //   2. PHI node.
2376   //
2377   //   3. ShuffleVector instruction together with a reduction operation that
2378   //      does a partial reduction.
2379   //
2380   //   4. ExtractElement that extracts the first element from the vector, and we
2381   //      stop searching the def-use chain here.
2382   //
2383   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2384   // from 1-3 to the stack to continue the DFS. The given instruction is not
2385   // a reduction operation if we meet any other instructions other than those
2386   // listed above.
2387 
2388   SmallVector<const User *, 16> UsersToVisit{Inst};
2389   SmallPtrSet<const User *, 16> Visited;
2390   bool ReduxExtracted = false;
2391 
2392   while (!UsersToVisit.empty()) {
2393     auto User = UsersToVisit.back();
2394     UsersToVisit.pop_back();
2395     if (!Visited.insert(User).second)
2396       continue;
2397 
2398     for (const auto &U : User->users()) {
2399       auto Inst = dyn_cast<Instruction>(U);
2400       if (!Inst)
2401         return false;
2402 
2403       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2404         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2405           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().unsafeAlgebra())
2406             return false;
2407         UsersToVisit.push_back(U);
2408       } else if (const ShuffleVectorInst *ShufInst =
2409                      dyn_cast<ShuffleVectorInst>(U)) {
2410         // Detect the following pattern: A ShuffleVector instruction together
2411         // with a reduction that do partial reduction on the first and second
2412         // ElemNumToReduce / 2 elements, and store the result in
2413         // ElemNumToReduce / 2 elements in another vector.
2414 
2415         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2416         if (ResultElements < ElemNum)
2417           return false;
2418 
2419         if (ElemNumToReduce == 1)
2420           return false;
2421         if (!isa<UndefValue>(U->getOperand(1)))
2422           return false;
2423         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2424           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2425             return false;
2426         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2427           if (ShufInst->getMaskValue(i) != -1)
2428             return false;
2429 
2430         // There is only one user of this ShuffleVector instruction, which
2431         // must be a reduction operation.
2432         if (!U->hasOneUse())
2433           return false;
2434 
2435         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2436         if (!U2 || U2->getOpcode() != OpCode)
2437           return false;
2438 
2439         // Check operands of the reduction operation.
2440         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2441             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2442           UsersToVisit.push_back(U2);
2443           ElemNumToReduce /= 2;
2444         } else
2445           return false;
2446       } else if (isa<ExtractElementInst>(U)) {
2447         // At this moment we should have reduced all elements in the vector.
2448         if (ElemNumToReduce != 1)
2449           return false;
2450 
2451         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2452         if (!Val || Val->getZExtValue() != 0)
2453           return false;
2454 
2455         ReduxExtracted = true;
2456       } else
2457         return false;
2458     }
2459   }
2460   return ReduxExtracted;
2461 }
2462 
2463 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2464   SDValue Op1 = getValue(I.getOperand(0));
2465   SDValue Op2 = getValue(I.getOperand(1));
2466 
2467   bool nuw = false;
2468   bool nsw = false;
2469   bool exact = false;
2470   bool vec_redux = false;
2471   FastMathFlags FMF;
2472 
2473   if (const OverflowingBinaryOperator *OFBinOp =
2474           dyn_cast<const OverflowingBinaryOperator>(&I)) {
2475     nuw = OFBinOp->hasNoUnsignedWrap();
2476     nsw = OFBinOp->hasNoSignedWrap();
2477   }
2478   if (const PossiblyExactOperator *ExactOp =
2479           dyn_cast<const PossiblyExactOperator>(&I))
2480     exact = ExactOp->isExact();
2481   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
2482     FMF = FPOp->getFastMathFlags();
2483 
2484   if (isVectorReductionOp(&I)) {
2485     vec_redux = true;
2486     DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2487   }
2488 
2489   SDNodeFlags Flags;
2490   Flags.setExact(exact);
2491   Flags.setNoSignedWrap(nsw);
2492   Flags.setNoUnsignedWrap(nuw);
2493   Flags.setVectorReduction(vec_redux);
2494   if (EnableFMFInDAG) {
2495     Flags.setAllowReciprocal(FMF.allowReciprocal());
2496     Flags.setNoInfs(FMF.noInfs());
2497     Flags.setNoNaNs(FMF.noNaNs());
2498     Flags.setNoSignedZeros(FMF.noSignedZeros());
2499     Flags.setUnsafeAlgebra(FMF.unsafeAlgebra());
2500   }
2501   SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2502                                      Op1, Op2, &Flags);
2503   setValue(&I, BinNodeValue);
2504 }
2505 
2506 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2507   SDValue Op1 = getValue(I.getOperand(0));
2508   SDValue Op2 = getValue(I.getOperand(1));
2509 
2510   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2511       Op2.getValueType(), DAG.getDataLayout());
2512 
2513   // Coerce the shift amount to the right type if we can.
2514   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2515     unsigned ShiftSize = ShiftTy.getSizeInBits();
2516     unsigned Op2Size = Op2.getValueType().getSizeInBits();
2517     SDLoc DL = getCurSDLoc();
2518 
2519     // If the operand is smaller than the shift count type, promote it.
2520     if (ShiftSize > Op2Size)
2521       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2522 
2523     // If the operand is larger than the shift count type but the shift
2524     // count type has enough bits to represent any shift value, truncate
2525     // it now. This is a common case and it exposes the truncate to
2526     // optimization early.
2527     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2528       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2529     // Otherwise we'll need to temporarily settle for some other convenient
2530     // type.  Type legalization will make adjustments once the shiftee is split.
2531     else
2532       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2533   }
2534 
2535   bool nuw = false;
2536   bool nsw = false;
2537   bool exact = false;
2538 
2539   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2540 
2541     if (const OverflowingBinaryOperator *OFBinOp =
2542             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2543       nuw = OFBinOp->hasNoUnsignedWrap();
2544       nsw = OFBinOp->hasNoSignedWrap();
2545     }
2546     if (const PossiblyExactOperator *ExactOp =
2547             dyn_cast<const PossiblyExactOperator>(&I))
2548       exact = ExactOp->isExact();
2549   }
2550   SDNodeFlags Flags;
2551   Flags.setExact(exact);
2552   Flags.setNoSignedWrap(nsw);
2553   Flags.setNoUnsignedWrap(nuw);
2554   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2555                             &Flags);
2556   setValue(&I, Res);
2557 }
2558 
2559 void SelectionDAGBuilder::visitSDiv(const User &I) {
2560   SDValue Op1 = getValue(I.getOperand(0));
2561   SDValue Op2 = getValue(I.getOperand(1));
2562 
2563   SDNodeFlags Flags;
2564   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2565                  cast<PossiblyExactOperator>(&I)->isExact());
2566   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2567                            Op2, &Flags));
2568 }
2569 
2570 void SelectionDAGBuilder::visitICmp(const User &I) {
2571   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2572   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2573     predicate = IC->getPredicate();
2574   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2575     predicate = ICmpInst::Predicate(IC->getPredicate());
2576   SDValue Op1 = getValue(I.getOperand(0));
2577   SDValue Op2 = getValue(I.getOperand(1));
2578   ISD::CondCode Opcode = getICmpCondCode(predicate);
2579 
2580   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2581                                                         I.getType());
2582   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2583 }
2584 
2585 void SelectionDAGBuilder::visitFCmp(const User &I) {
2586   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2587   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2588     predicate = FC->getPredicate();
2589   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2590     predicate = FCmpInst::Predicate(FC->getPredicate());
2591   SDValue Op1 = getValue(I.getOperand(0));
2592   SDValue Op2 = getValue(I.getOperand(1));
2593   ISD::CondCode Condition = getFCmpCondCode(predicate);
2594 
2595   // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
2596   // FIXME: We should propagate the fast-math-flags to the DAG node itself for
2597   // further optimization, but currently FMF is only applicable to binary nodes.
2598   if (TM.Options.NoNaNsFPMath)
2599     Condition = getFCmpCodeWithoutNaN(Condition);
2600   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2601                                                         I.getType());
2602   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2603 }
2604 
2605 void SelectionDAGBuilder::visitSelect(const User &I) {
2606   SmallVector<EVT, 4> ValueVTs;
2607   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2608                   ValueVTs);
2609   unsigned NumValues = ValueVTs.size();
2610   if (NumValues == 0) return;
2611 
2612   SmallVector<SDValue, 4> Values(NumValues);
2613   SDValue Cond     = getValue(I.getOperand(0));
2614   SDValue LHSVal   = getValue(I.getOperand(1));
2615   SDValue RHSVal   = getValue(I.getOperand(2));
2616   auto BaseOps = {Cond};
2617   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2618     ISD::VSELECT : ISD::SELECT;
2619 
2620   // Min/max matching is only viable if all output VTs are the same.
2621   if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
2622     EVT VT = ValueVTs[0];
2623     LLVMContext &Ctx = *DAG.getContext();
2624     auto &TLI = DAG.getTargetLoweringInfo();
2625 
2626     // We care about the legality of the operation after it has been type
2627     // legalized.
2628     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2629            VT != TLI.getTypeToTransformTo(Ctx, VT))
2630       VT = TLI.getTypeToTransformTo(Ctx, VT);
2631 
2632     // If the vselect is legal, assume we want to leave this as a vector setcc +
2633     // vselect. Otherwise, if this is going to be scalarized, we want to see if
2634     // min/max is legal on the scalar type.
2635     bool UseScalarMinMax = VT.isVector() &&
2636       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2637 
2638     Value *LHS, *RHS;
2639     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2640     ISD::NodeType Opc = ISD::DELETED_NODE;
2641     switch (SPR.Flavor) {
2642     case SPF_UMAX:    Opc = ISD::UMAX; break;
2643     case SPF_UMIN:    Opc = ISD::UMIN; break;
2644     case SPF_SMAX:    Opc = ISD::SMAX; break;
2645     case SPF_SMIN:    Opc = ISD::SMIN; break;
2646     case SPF_FMINNUM:
2647       switch (SPR.NaNBehavior) {
2648       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2649       case SPNB_RETURNS_NAN:   Opc = ISD::FMINNAN; break;
2650       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2651       case SPNB_RETURNS_ANY: {
2652         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2653           Opc = ISD::FMINNUM;
2654         else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
2655           Opc = ISD::FMINNAN;
2656         else if (UseScalarMinMax)
2657           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2658             ISD::FMINNUM : ISD::FMINNAN;
2659         break;
2660       }
2661       }
2662       break;
2663     case SPF_FMAXNUM:
2664       switch (SPR.NaNBehavior) {
2665       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2666       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXNAN; break;
2667       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
2668       case SPNB_RETURNS_ANY:
2669 
2670         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
2671           Opc = ISD::FMAXNUM;
2672         else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
2673           Opc = ISD::FMAXNAN;
2674         else if (UseScalarMinMax)
2675           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
2676             ISD::FMAXNUM : ISD::FMAXNAN;
2677         break;
2678       }
2679       break;
2680     default: break;
2681     }
2682 
2683     if (Opc != ISD::DELETED_NODE &&
2684         (TLI.isOperationLegalOrCustom(Opc, VT) ||
2685          (UseScalarMinMax &&
2686           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
2687         // If the underlying comparison instruction is used by any other
2688         // instruction, the consumed instructions won't be destroyed, so it is
2689         // not profitable to convert to a min/max.
2690         cast<SelectInst>(&I)->getCondition()->hasOneUse()) {
2691       OpCode = Opc;
2692       LHSVal = getValue(LHS);
2693       RHSVal = getValue(RHS);
2694       BaseOps = {};
2695     }
2696   }
2697 
2698   for (unsigned i = 0; i != NumValues; ++i) {
2699     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
2700     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
2701     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
2702     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2703                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
2704                             Ops);
2705   }
2706 
2707   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2708                            DAG.getVTList(ValueVTs), Values));
2709 }
2710 
2711 void SelectionDAGBuilder::visitTrunc(const User &I) {
2712   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2713   SDValue N = getValue(I.getOperand(0));
2714   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2715                                                         I.getType());
2716   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2717 }
2718 
2719 void SelectionDAGBuilder::visitZExt(const User &I) {
2720   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2721   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2722   SDValue N = getValue(I.getOperand(0));
2723   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2724                                                         I.getType());
2725   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2726 }
2727 
2728 void SelectionDAGBuilder::visitSExt(const User &I) {
2729   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2730   // SExt also can't be a cast to bool for same reason. So, nothing much to do
2731   SDValue N = getValue(I.getOperand(0));
2732   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2733                                                         I.getType());
2734   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2735 }
2736 
2737 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2738   // FPTrunc is never a no-op cast, no need to check
2739   SDValue N = getValue(I.getOperand(0));
2740   SDLoc dl = getCurSDLoc();
2741   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2742   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2743   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
2744                            DAG.getTargetConstant(
2745                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
2746 }
2747 
2748 void SelectionDAGBuilder::visitFPExt(const User &I) {
2749   // FPExt is never a no-op cast, no need to check
2750   SDValue N = getValue(I.getOperand(0));
2751   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2752                                                         I.getType());
2753   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2754 }
2755 
2756 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2757   // FPToUI is never a no-op cast, no need to check
2758   SDValue N = getValue(I.getOperand(0));
2759   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2760                                                         I.getType());
2761   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2762 }
2763 
2764 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2765   // FPToSI is never a no-op cast, no need to check
2766   SDValue N = getValue(I.getOperand(0));
2767   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2768                                                         I.getType());
2769   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2770 }
2771 
2772 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2773   // UIToFP is never a no-op cast, no need to check
2774   SDValue N = getValue(I.getOperand(0));
2775   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2776                                                         I.getType());
2777   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
2778 }
2779 
2780 void SelectionDAGBuilder::visitSIToFP(const User &I) {
2781   // SIToFP is never a no-op cast, no need to check
2782   SDValue N = getValue(I.getOperand(0));
2783   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2784                                                         I.getType());
2785   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
2786 }
2787 
2788 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2789   // What to do depends on the size of the integer and the size of the pointer.
2790   // We can either truncate, zero extend, or no-op, accordingly.
2791   SDValue N = getValue(I.getOperand(0));
2792   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2793                                                         I.getType());
2794   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2795 }
2796 
2797 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2798   // What to do depends on the size of the integer and the size of the pointer.
2799   // We can either truncate, zero extend, or no-op, accordingly.
2800   SDValue N = getValue(I.getOperand(0));
2801   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2802                                                         I.getType());
2803   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2804 }
2805 
2806 void SelectionDAGBuilder::visitBitCast(const User &I) {
2807   SDValue N = getValue(I.getOperand(0));
2808   SDLoc dl = getCurSDLoc();
2809   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2810                                                         I.getType());
2811 
2812   // BitCast assures us that source and destination are the same size so this is
2813   // either a BITCAST or a no-op.
2814   if (DestVT != N.getValueType())
2815     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
2816                              DestVT, N)); // convert types.
2817   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
2818   // might fold any kind of constant expression to an integer constant and that
2819   // is not what we are looking for. Only regcognize a bitcast of a genuine
2820   // constant integer as an opaque constant.
2821   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
2822     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
2823                                  /*isOpaque*/true));
2824   else
2825     setValue(&I, N);            // noop cast.
2826 }
2827 
2828 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
2829   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2830   const Value *SV = I.getOperand(0);
2831   SDValue N = getValue(SV);
2832   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2833 
2834   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
2835   unsigned DestAS = I.getType()->getPointerAddressSpace();
2836 
2837   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2838     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
2839 
2840   setValue(&I, N);
2841 }
2842 
2843 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2844   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2845   SDValue InVec = getValue(I.getOperand(0));
2846   SDValue InVal = getValue(I.getOperand(1));
2847   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
2848                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
2849   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
2850                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
2851                            InVec, InVal, InIdx));
2852 }
2853 
2854 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2855   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2856   SDValue InVec = getValue(I.getOperand(0));
2857   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
2858                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
2859   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
2860                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
2861                            InVec, InIdx));
2862 }
2863 
2864 // Utility for visitShuffleVector - Return true if every element in Mask,
2865 // beginning from position Pos and ending in Pos+Size, falls within the
2866 // specified sequential range [L, L+Pos). or is undef.
2867 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
2868                                 unsigned Pos, unsigned Size, int Low) {
2869   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
2870     if (Mask[i] >= 0 && Mask[i] != Low)
2871       return false;
2872   return true;
2873 }
2874 
2875 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2876   SDValue Src1 = getValue(I.getOperand(0));
2877   SDValue Src2 = getValue(I.getOperand(1));
2878 
2879   SmallVector<int, 8> Mask;
2880   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
2881   unsigned MaskNumElts = Mask.size();
2882 
2883   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2884   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2885   EVT SrcVT = Src1.getValueType();
2886   unsigned SrcNumElts = SrcVT.getVectorNumElements();
2887 
2888   if (SrcNumElts == MaskNumElts) {
2889     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
2890                                       &Mask[0]));
2891     return;
2892   }
2893 
2894   // Normalize the shuffle vector since mask and vector length don't match.
2895   if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2896     // Mask is longer than the source vectors and is a multiple of the source
2897     // vectors.  We can use concatenate vector to make the mask and vectors
2898     // lengths match.
2899     if (SrcNumElts*2 == MaskNumElts) {
2900       // First check for Src1 in low and Src2 in high
2901       if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
2902           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
2903         // The shuffle is concatenating two vectors together.
2904         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
2905                                  VT, Src1, Src2));
2906         return;
2907       }
2908       // Then check for Src2 in low and Src1 in high
2909       if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
2910           isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
2911         // The shuffle is concatenating two vectors together.
2912         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
2913                                  VT, Src2, Src1));
2914         return;
2915       }
2916     }
2917 
2918     // Pad both vectors with undefs to make them the same length as the mask.
2919     unsigned NumConcat = MaskNumElts / SrcNumElts;
2920     bool Src1U = Src1.isUndef();
2921     bool Src2U = Src2.isUndef();
2922     SDValue UndefVal = DAG.getUNDEF(SrcVT);
2923 
2924     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2925     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2926     MOps1[0] = Src1;
2927     MOps2[0] = Src2;
2928 
2929     Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2930                                                   getCurSDLoc(), VT, MOps1);
2931     Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2932                                                   getCurSDLoc(), VT, MOps2);
2933 
2934     // Readjust mask for new input vector length.
2935     SmallVector<int, 8> MappedOps;
2936     for (unsigned i = 0; i != MaskNumElts; ++i) {
2937       int Idx = Mask[i];
2938       if (Idx >= (int)SrcNumElts)
2939         Idx -= SrcNumElts - MaskNumElts;
2940       MappedOps.push_back(Idx);
2941     }
2942 
2943     setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
2944                                       &MappedOps[0]));
2945     return;
2946   }
2947 
2948   if (SrcNumElts > MaskNumElts) {
2949     // Analyze the access pattern of the vector to see if we can extract
2950     // two subvectors and do the shuffle. The analysis is done by calculating
2951     // the range of elements the mask access on both vectors.
2952     int MinRange[2] = { static_cast<int>(SrcNumElts),
2953                         static_cast<int>(SrcNumElts)};
2954     int MaxRange[2] = {-1, -1};
2955 
2956     for (unsigned i = 0; i != MaskNumElts; ++i) {
2957       int Idx = Mask[i];
2958       unsigned Input = 0;
2959       if (Idx < 0)
2960         continue;
2961 
2962       if (Idx >= (int)SrcNumElts) {
2963         Input = 1;
2964         Idx -= SrcNumElts;
2965       }
2966       if (Idx > MaxRange[Input])
2967         MaxRange[Input] = Idx;
2968       if (Idx < MinRange[Input])
2969         MinRange[Input] = Idx;
2970     }
2971 
2972     // Check if the access is smaller than the vector size and can we find
2973     // a reasonable extract index.
2974     int RangeUse[2] = { -1, -1 };  // 0 = Unused, 1 = Extract, -1 = Can not
2975                                    // Extract.
2976     int StartIdx[2];  // StartIdx to extract from
2977     for (unsigned Input = 0; Input < 2; ++Input) {
2978       if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
2979         RangeUse[Input] = 0; // Unused
2980         StartIdx[Input] = 0;
2981         continue;
2982       }
2983 
2984       // Find a good start index that is a multiple of the mask length. Then
2985       // see if the rest of the elements are in range.
2986       StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2987       if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2988           StartIdx[Input] + MaskNumElts <= SrcNumElts)
2989         RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2990     }
2991 
2992     if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2993       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2994       return;
2995     }
2996     if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
2997       // Extract appropriate subvector and generate a vector shuffle
2998       for (unsigned Input = 0; Input < 2; ++Input) {
2999         SDValue &Src = Input == 0 ? Src1 : Src2;
3000         if (RangeUse[Input] == 0)
3001           Src = DAG.getUNDEF(VT);
3002         else {
3003           SDLoc dl = getCurSDLoc();
3004           Src = DAG.getNode(
3005               ISD::EXTRACT_SUBVECTOR, dl, VT, Src,
3006               DAG.getConstant(StartIdx[Input], dl,
3007                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3008         }
3009       }
3010 
3011       // Calculate new mask.
3012       SmallVector<int, 8> MappedOps;
3013       for (unsigned i = 0; i != MaskNumElts; ++i) {
3014         int Idx = Mask[i];
3015         if (Idx >= 0) {
3016           if (Idx < (int)SrcNumElts)
3017             Idx -= StartIdx[0];
3018           else
3019             Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3020         }
3021         MappedOps.push_back(Idx);
3022       }
3023 
3024       setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3025                                         &MappedOps[0]));
3026       return;
3027     }
3028   }
3029 
3030   // We can't use either concat vectors or extract subvectors so fall back to
3031   // replacing the shuffle with extract and build vector.
3032   // to insert and build vector.
3033   EVT EltVT = VT.getVectorElementType();
3034   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3035   SDLoc dl = getCurSDLoc();
3036   SmallVector<SDValue,8> Ops;
3037   for (unsigned i = 0; i != MaskNumElts; ++i) {
3038     int Idx = Mask[i];
3039     SDValue Res;
3040 
3041     if (Idx < 0) {
3042       Res = DAG.getUNDEF(EltVT);
3043     } else {
3044       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3045       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3046 
3047       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
3048                         EltVT, Src, DAG.getConstant(Idx, dl, IdxVT));
3049     }
3050 
3051     Ops.push_back(Res);
3052   }
3053 
3054   setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops));
3055 }
3056 
3057 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3058   const Value *Op0 = I.getOperand(0);
3059   const Value *Op1 = I.getOperand(1);
3060   Type *AggTy = I.getType();
3061   Type *ValTy = Op1->getType();
3062   bool IntoUndef = isa<UndefValue>(Op0);
3063   bool FromUndef = isa<UndefValue>(Op1);
3064 
3065   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3066 
3067   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3068   SmallVector<EVT, 4> AggValueVTs;
3069   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3070   SmallVector<EVT, 4> ValValueVTs;
3071   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3072 
3073   unsigned NumAggValues = AggValueVTs.size();
3074   unsigned NumValValues = ValValueVTs.size();
3075   SmallVector<SDValue, 4> Values(NumAggValues);
3076 
3077   // Ignore an insertvalue that produces an empty object
3078   if (!NumAggValues) {
3079     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3080     return;
3081   }
3082 
3083   SDValue Agg = getValue(Op0);
3084   unsigned i = 0;
3085   // Copy the beginning value(s) from the original aggregate.
3086   for (; i != LinearIndex; ++i)
3087     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3088                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3089   // Copy values from the inserted value(s).
3090   if (NumValValues) {
3091     SDValue Val = getValue(Op1);
3092     for (; i != LinearIndex + NumValValues; ++i)
3093       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3094                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3095   }
3096   // Copy remaining value(s) from the original aggregate.
3097   for (; i != NumAggValues; ++i)
3098     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3099                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3100 
3101   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3102                            DAG.getVTList(AggValueVTs), Values));
3103 }
3104 
3105 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3106   const Value *Op0 = I.getOperand(0);
3107   Type *AggTy = Op0->getType();
3108   Type *ValTy = I.getType();
3109   bool OutOfUndef = isa<UndefValue>(Op0);
3110 
3111   unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3112 
3113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3114   SmallVector<EVT, 4> ValValueVTs;
3115   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3116 
3117   unsigned NumValValues = ValValueVTs.size();
3118 
3119   // Ignore a extractvalue that produces an empty object
3120   if (!NumValValues) {
3121     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3122     return;
3123   }
3124 
3125   SmallVector<SDValue, 4> Values(NumValValues);
3126 
3127   SDValue Agg = getValue(Op0);
3128   // Copy out the selected value(s).
3129   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3130     Values[i - LinearIndex] =
3131       OutOfUndef ?
3132         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3133         SDValue(Agg.getNode(), Agg.getResNo() + i);
3134 
3135   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3136                            DAG.getVTList(ValValueVTs), Values));
3137 }
3138 
3139 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3140   Value *Op0 = I.getOperand(0);
3141   // Note that the pointer operand may be a vector of pointers. Take the scalar
3142   // element which holds a pointer.
3143   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3144   SDValue N = getValue(Op0);
3145   SDLoc dl = getCurSDLoc();
3146 
3147   // Normalize Vector GEP - all scalar operands should be converted to the
3148   // splat vector.
3149   unsigned VectorWidth = I.getType()->isVectorTy() ?
3150     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3151 
3152   if (VectorWidth && !N.getValueType().isVector()) {
3153     MVT VT = MVT::getVectorVT(N.getValueType().getSimpleVT(), VectorWidth);
3154     SmallVector<SDValue, 16> Ops(VectorWidth, N);
3155     N = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3156   }
3157   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3158        GTI != E; ++GTI) {
3159     const Value *Idx = GTI.getOperand();
3160     if (StructType *StTy = dyn_cast<StructType>(*GTI)) {
3161       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3162       if (Field) {
3163         // N = N + Offset
3164         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3165 
3166         // In an inbouds GEP with an offset that is nonnegative even when
3167         // interpreted as signed, assume there is no unsigned overflow.
3168         SDNodeFlags Flags;
3169         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3170           Flags.setNoUnsignedWrap(true);
3171 
3172         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3173                         DAG.getConstant(Offset, dl, N.getValueType()), &Flags);
3174       }
3175     } else {
3176       MVT PtrTy =
3177           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS);
3178       unsigned PtrSize = PtrTy.getSizeInBits();
3179       APInt ElementSize(PtrSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3180 
3181       // If this is a scalar constant or a splat vector of constants,
3182       // handle it quickly.
3183       const auto *CI = dyn_cast<ConstantInt>(Idx);
3184       if (!CI && isa<ConstantDataVector>(Idx) &&
3185           cast<ConstantDataVector>(Idx)->getSplatValue())
3186         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3187 
3188       if (CI) {
3189         if (CI->isZero())
3190           continue;
3191         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
3192         SDValue OffsVal = VectorWidth ?
3193           DAG.getConstant(Offs, dl, MVT::getVectorVT(PtrTy, VectorWidth)) :
3194           DAG.getConstant(Offs, dl, PtrTy);
3195 
3196         // In an inbouds GEP with an offset that is nonnegative even when
3197         // interpreted as signed, assume there is no unsigned overflow.
3198         SDNodeFlags Flags;
3199         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3200           Flags.setNoUnsignedWrap(true);
3201 
3202         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, &Flags);
3203         continue;
3204       }
3205 
3206       // N = N + Idx * ElementSize;
3207       SDValue IdxN = getValue(Idx);
3208 
3209       if (!IdxN.getValueType().isVector() && VectorWidth) {
3210         MVT VT = MVT::getVectorVT(IdxN.getValueType().getSimpleVT(), VectorWidth);
3211         SmallVector<SDValue, 16> Ops(VectorWidth, IdxN);
3212         IdxN = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3213       }
3214       // If the index is smaller or larger than intptr_t, truncate or extend
3215       // it.
3216       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3217 
3218       // If this is a multiply by a power of two, turn it into a shl
3219       // immediately.  This is a very common case.
3220       if (ElementSize != 1) {
3221         if (ElementSize.isPowerOf2()) {
3222           unsigned Amt = ElementSize.logBase2();
3223           IdxN = DAG.getNode(ISD::SHL, dl,
3224                              N.getValueType(), IdxN,
3225                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3226         } else {
3227           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3228           IdxN = DAG.getNode(ISD::MUL, dl,
3229                              N.getValueType(), IdxN, Scale);
3230         }
3231       }
3232 
3233       N = DAG.getNode(ISD::ADD, dl,
3234                       N.getValueType(), N, IdxN);
3235     }
3236   }
3237 
3238   setValue(&I, N);
3239 }
3240 
3241 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3242   // If this is a fixed sized alloca in the entry block of the function,
3243   // allocate it statically on the stack.
3244   if (FuncInfo.StaticAllocaMap.count(&I))
3245     return;   // getValue will auto-populate this.
3246 
3247   SDLoc dl = getCurSDLoc();
3248   Type *Ty = I.getAllocatedType();
3249   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3250   auto &DL = DAG.getDataLayout();
3251   uint64_t TySize = DL.getTypeAllocSize(Ty);
3252   unsigned Align =
3253       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3254 
3255   SDValue AllocSize = getValue(I.getArraySize());
3256 
3257   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout());
3258   if (AllocSize.getValueType() != IntPtr)
3259     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3260 
3261   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3262                           AllocSize,
3263                           DAG.getConstant(TySize, dl, IntPtr));
3264 
3265   // Handle alignment.  If the requested alignment is less than or equal to
3266   // the stack alignment, ignore it.  If the size is greater than or equal to
3267   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3268   unsigned StackAlign =
3269       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3270   if (Align <= StackAlign)
3271     Align = 0;
3272 
3273   // Round the size of the allocation up to the stack alignment size
3274   // by add SA-1 to the size. This doesn't overflow because we're computing
3275   // an address inside an alloca.
3276   SDNodeFlags Flags;
3277   Flags.setNoUnsignedWrap(true);
3278   AllocSize = DAG.getNode(ISD::ADD, dl,
3279                           AllocSize.getValueType(), AllocSize,
3280                           DAG.getIntPtrConstant(StackAlign - 1, dl), &Flags);
3281 
3282   // Mask out the low bits for alignment purposes.
3283   AllocSize = DAG.getNode(ISD::AND, dl,
3284                           AllocSize.getValueType(), AllocSize,
3285                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1),
3286                                                 dl));
3287 
3288   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) };
3289   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3290   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3291   setValue(&I, DSA);
3292   DAG.setRoot(DSA.getValue(1));
3293 
3294   assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
3295 }
3296 
3297 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3298   if (I.isAtomic())
3299     return visitAtomicLoad(I);
3300 
3301   const Value *SV = I.getOperand(0);
3302   SDValue Ptr = getValue(SV);
3303 
3304   Type *Ty = I.getType();
3305 
3306   bool isVolatile = I.isVolatile();
3307   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3308 
3309   // The IR notion of invariant_load only guarantees that all *non-faulting*
3310   // invariant loads result in the same value.  The MI notion of invariant load
3311   // guarantees that the load can be legally moved to any location within its
3312   // containing function.  The MI notion of invariant_load is stronger than the
3313   // IR notion of invariant_load -- an MI invariant_load is an IR invariant_load
3314   // with a guarantee that the location being loaded from is dereferenceable
3315   // throughout the function's lifetime.
3316 
3317   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr &&
3318                      isDereferenceablePointer(SV, DAG.getDataLayout());
3319   unsigned Alignment = I.getAlignment();
3320 
3321   AAMDNodes AAInfo;
3322   I.getAAMetadata(AAInfo);
3323   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3324 
3325   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3326   SmallVector<EVT, 4> ValueVTs;
3327   SmallVector<uint64_t, 4> Offsets;
3328   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3329   unsigned NumValues = ValueVTs.size();
3330   if (NumValues == 0)
3331     return;
3332 
3333   SDValue Root;
3334   bool ConstantMemory = false;
3335   if (isVolatile || NumValues > MaxParallelChains)
3336     // Serialize volatile loads with other side effects.
3337     Root = getRoot();
3338   else if (AA->pointsToConstantMemory(MemoryLocation(
3339                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3340     // Do not serialize (non-volatile) loads of constant memory with anything.
3341     Root = DAG.getEntryNode();
3342     ConstantMemory = true;
3343   } else {
3344     // Do not serialize non-volatile loads against each other.
3345     Root = DAG.getRoot();
3346   }
3347 
3348   SDLoc dl = getCurSDLoc();
3349 
3350   if (isVolatile)
3351     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3352 
3353   // An aggregate load cannot wrap around the address space, so offsets to its
3354   // parts don't wrap either.
3355   SDNodeFlags Flags;
3356   Flags.setNoUnsignedWrap(true);
3357 
3358   SmallVector<SDValue, 4> Values(NumValues);
3359   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3360   EVT PtrVT = Ptr.getValueType();
3361   unsigned ChainI = 0;
3362   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3363     // Serializing loads here may result in excessive register pressure, and
3364     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3365     // could recover a bit by hoisting nodes upward in the chain by recognizing
3366     // they are side-effect free or do not alias. The optimizer should really
3367     // avoid this case by converting large object/array copies to llvm.memcpy
3368     // (MaxParallelChains should always remain as failsafe).
3369     if (ChainI == MaxParallelChains) {
3370       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3371       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3372                                   makeArrayRef(Chains.data(), ChainI));
3373       Root = Chain;
3374       ChainI = 0;
3375     }
3376     SDValue A = DAG.getNode(ISD::ADD, dl,
3377                             PtrVT, Ptr,
3378                             DAG.getConstant(Offsets[i], dl, PtrVT),
3379                             &Flags);
3380     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root,
3381                             A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3382                             isNonTemporal, isInvariant, Alignment, AAInfo,
3383                             Ranges);
3384 
3385     Values[i] = L;
3386     Chains[ChainI] = L.getValue(1);
3387   }
3388 
3389   if (!ConstantMemory) {
3390     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3391                                 makeArrayRef(Chains.data(), ChainI));
3392     if (isVolatile)
3393       DAG.setRoot(Chain);
3394     else
3395       PendingLoads.push_back(Chain);
3396   }
3397 
3398   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3399                            DAG.getVTList(ValueVTs), Values));
3400 }
3401 
3402 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3403   if (I.isAtomic())
3404     return visitAtomicStore(I);
3405 
3406   const Value *SrcV = I.getOperand(0);
3407   const Value *PtrV = I.getOperand(1);
3408 
3409   SmallVector<EVT, 4> ValueVTs;
3410   SmallVector<uint64_t, 4> Offsets;
3411   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3412                   SrcV->getType(), ValueVTs, &Offsets);
3413   unsigned NumValues = ValueVTs.size();
3414   if (NumValues == 0)
3415     return;
3416 
3417   // Get the lowered operands. Note that we do this after
3418   // checking if NumResults is zero, because with zero results
3419   // the operands won't have values in the map.
3420   SDValue Src = getValue(SrcV);
3421   SDValue Ptr = getValue(PtrV);
3422 
3423   SDValue Root = getRoot();
3424   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3425   EVT PtrVT = Ptr.getValueType();
3426   bool isVolatile = I.isVolatile();
3427   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3428   unsigned Alignment = I.getAlignment();
3429   SDLoc dl = getCurSDLoc();
3430 
3431   AAMDNodes AAInfo;
3432   I.getAAMetadata(AAInfo);
3433 
3434   // An aggregate load cannot wrap around the address space, so offsets to its
3435   // parts don't wrap either.
3436   SDNodeFlags Flags;
3437   Flags.setNoUnsignedWrap(true);
3438 
3439   unsigned ChainI = 0;
3440   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3441     // See visitLoad comments.
3442     if (ChainI == MaxParallelChains) {
3443       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3444                                   makeArrayRef(Chains.data(), ChainI));
3445       Root = Chain;
3446       ChainI = 0;
3447     }
3448     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3449                               DAG.getConstant(Offsets[i], dl, PtrVT), &Flags);
3450     SDValue St = DAG.getStore(Root, dl,
3451                               SDValue(Src.getNode(), Src.getResNo() + i),
3452                               Add, MachinePointerInfo(PtrV, Offsets[i]),
3453                               isVolatile, isNonTemporal, Alignment, AAInfo);
3454     Chains[ChainI] = St;
3455   }
3456 
3457   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3458                                   makeArrayRef(Chains.data(), ChainI));
3459   DAG.setRoot(StoreNode);
3460 }
3461 
3462 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) {
3463   SDLoc sdl = getCurSDLoc();
3464 
3465   // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3466   Value  *PtrOperand = I.getArgOperand(1);
3467   SDValue Ptr = getValue(PtrOperand);
3468   SDValue Src0 = getValue(I.getArgOperand(0));
3469   SDValue Mask = getValue(I.getArgOperand(3));
3470   EVT VT = Src0.getValueType();
3471   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3472   if (!Alignment)
3473     Alignment = DAG.getEVTAlignment(VT);
3474 
3475   AAMDNodes AAInfo;
3476   I.getAAMetadata(AAInfo);
3477 
3478   MachineMemOperand *MMO =
3479     DAG.getMachineFunction().
3480     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3481                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3482                           Alignment, AAInfo);
3483   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3484                                          MMO, false);
3485   DAG.setRoot(StoreNode);
3486   setValue(&I, StoreNode);
3487 }
3488 
3489 // Get a uniform base for the Gather/Scatter intrinsic.
3490 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3491 // We try to represent it as a base pointer + vector of indices.
3492 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3493 // The first operand of the GEP may be a single pointer or a vector of pointers
3494 // Example:
3495 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3496 //  or
3497 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
3498 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3499 //
3500 // When the first GEP operand is a single pointer - it is the uniform base we
3501 // are looking for. If first operand of the GEP is a splat vector - we
3502 // extract the spalt value and use it as a uniform base.
3503 // In all other cases the function returns 'false'.
3504 //
3505 static bool getUniformBase(const Value *& Ptr, SDValue& Base, SDValue& Index,
3506                            SelectionDAGBuilder* SDB) {
3507 
3508   SelectionDAG& DAG = SDB->DAG;
3509   LLVMContext &Context = *DAG.getContext();
3510 
3511   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3512   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3513   if (!GEP || GEP->getNumOperands() > 2)
3514     return false;
3515 
3516   const Value *GEPPtr = GEP->getPointerOperand();
3517   if (!GEPPtr->getType()->isVectorTy())
3518     Ptr = GEPPtr;
3519   else if (!(Ptr = getSplatValue(GEPPtr)))
3520     return false;
3521 
3522   Value *IndexVal = GEP->getOperand(1);
3523 
3524   // The operands of the GEP may be defined in another basic block.
3525   // In this case we'll not find nodes for the operands.
3526   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3527     return false;
3528 
3529   Base = SDB->getValue(Ptr);
3530   Index = SDB->getValue(IndexVal);
3531 
3532   // Suppress sign extension.
3533   if (SExtInst* Sext = dyn_cast<SExtInst>(IndexVal)) {
3534     if (SDB->findValue(Sext->getOperand(0))) {
3535       IndexVal = Sext->getOperand(0);
3536       Index = SDB->getValue(IndexVal);
3537     }
3538   }
3539   if (!Index.getValueType().isVector()) {
3540     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
3541     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
3542     SmallVector<SDValue, 16> Ops(GEPWidth, Index);
3543     Index = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Index), VT, Ops);
3544   }
3545   return true;
3546 }
3547 
3548 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
3549   SDLoc sdl = getCurSDLoc();
3550 
3551   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
3552   const Value *Ptr = I.getArgOperand(1);
3553   SDValue Src0 = getValue(I.getArgOperand(0));
3554   SDValue Mask = getValue(I.getArgOperand(3));
3555   EVT VT = Src0.getValueType();
3556   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3557   if (!Alignment)
3558     Alignment = DAG.getEVTAlignment(VT);
3559   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3560 
3561   AAMDNodes AAInfo;
3562   I.getAAMetadata(AAInfo);
3563 
3564   SDValue Base;
3565   SDValue Index;
3566   const Value *BasePtr = Ptr;
3567   bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
3568 
3569   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
3570   MachineMemOperand *MMO = DAG.getMachineFunction().
3571     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
3572                          MachineMemOperand::MOStore,  VT.getStoreSize(),
3573                          Alignment, AAInfo);
3574   if (!UniformBase) {
3575     Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3576     Index = getValue(Ptr);
3577   }
3578   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index };
3579   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
3580                                          Ops, MMO);
3581   DAG.setRoot(Scatter);
3582   setValue(&I, Scatter);
3583 }
3584 
3585 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) {
3586   SDLoc sdl = getCurSDLoc();
3587 
3588   // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
3589   Value  *PtrOperand = I.getArgOperand(0);
3590   SDValue Ptr = getValue(PtrOperand);
3591   SDValue Src0 = getValue(I.getArgOperand(3));
3592   SDValue Mask = getValue(I.getArgOperand(2));
3593 
3594   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3595   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3596   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
3597   if (!Alignment)
3598     Alignment = DAG.getEVTAlignment(VT);
3599 
3600   AAMDNodes AAInfo;
3601   I.getAAMetadata(AAInfo);
3602   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3603 
3604   SDValue InChain = DAG.getRoot();
3605   if (AA->pointsToConstantMemory(MemoryLocation(
3606           PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()),
3607           AAInfo))) {
3608     // Do not serialize (non-volatile) loads of constant memory with anything.
3609     InChain = DAG.getEntryNode();
3610   }
3611 
3612   MachineMemOperand *MMO =
3613     DAG.getMachineFunction().
3614     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3615                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
3616                           Alignment, AAInfo, Ranges);
3617 
3618   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
3619                                    ISD::NON_EXTLOAD);
3620   SDValue OutChain = Load.getValue(1);
3621   DAG.setRoot(OutChain);
3622   setValue(&I, Load);
3623 }
3624 
3625 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
3626   SDLoc sdl = getCurSDLoc();
3627 
3628   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
3629   const Value *Ptr = I.getArgOperand(0);
3630   SDValue Src0 = getValue(I.getArgOperand(3));
3631   SDValue Mask = getValue(I.getArgOperand(2));
3632 
3633   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3634   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3635   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
3636   if (!Alignment)
3637     Alignment = DAG.getEVTAlignment(VT);
3638 
3639   AAMDNodes AAInfo;
3640   I.getAAMetadata(AAInfo);
3641   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3642 
3643   SDValue Root = DAG.getRoot();
3644   SDValue Base;
3645   SDValue Index;
3646   const Value *BasePtr = Ptr;
3647   bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
3648   bool ConstantMemory = false;
3649   if (UniformBase &&
3650       AA->pointsToConstantMemory(MemoryLocation(
3651           BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
3652           AAInfo))) {
3653     // Do not serialize (non-volatile) loads of constant memory with anything.
3654     Root = DAG.getEntryNode();
3655     ConstantMemory = true;
3656   }
3657 
3658   MachineMemOperand *MMO =
3659     DAG.getMachineFunction().
3660     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
3661                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
3662                          Alignment, AAInfo, Ranges);
3663 
3664   if (!UniformBase) {
3665     Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3666     Index = getValue(Ptr);
3667   }
3668   SDValue Ops[] = { Root, Src0, Mask, Base, Index };
3669   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
3670                                        Ops, MMO);
3671 
3672   SDValue OutChain = Gather.getValue(1);
3673   if (!ConstantMemory)
3674     PendingLoads.push_back(OutChain);
3675   setValue(&I, Gather);
3676 }
3677 
3678 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3679   SDLoc dl = getCurSDLoc();
3680   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3681   AtomicOrdering FailureOrder = I.getFailureOrdering();
3682   SynchronizationScope Scope = I.getSynchScope();
3683 
3684   SDValue InChain = getRoot();
3685 
3686   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3687   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3688   SDValue L = DAG.getAtomicCmpSwap(
3689       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3690       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3691       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
3692       /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
3693 
3694   SDValue OutChain = L.getValue(2);
3695 
3696   setValue(&I, L);
3697   DAG.setRoot(OutChain);
3698 }
3699 
3700 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3701   SDLoc dl = getCurSDLoc();
3702   ISD::NodeType NT;
3703   switch (I.getOperation()) {
3704   default: llvm_unreachable("Unknown atomicrmw operation");
3705   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3706   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
3707   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
3708   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
3709   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3710   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
3711   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
3712   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
3713   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
3714   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3715   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3716   }
3717   AtomicOrdering Order = I.getOrdering();
3718   SynchronizationScope Scope = I.getSynchScope();
3719 
3720   SDValue InChain = getRoot();
3721 
3722   SDValue L =
3723     DAG.getAtomic(NT, dl,
3724                   getValue(I.getValOperand()).getSimpleValueType(),
3725                   InChain,
3726                   getValue(I.getPointerOperand()),
3727                   getValue(I.getValOperand()),
3728                   I.getPointerOperand(),
3729                   /* Alignment=*/ 0, Order, Scope);
3730 
3731   SDValue OutChain = L.getValue(1);
3732 
3733   setValue(&I, L);
3734   DAG.setRoot(OutChain);
3735 }
3736 
3737 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3738   SDLoc dl = getCurSDLoc();
3739   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3740   SDValue Ops[3];
3741   Ops[0] = getRoot();
3742   Ops[1] = DAG.getConstant(I.getOrdering(), dl,
3743                            TLI.getPointerTy(DAG.getDataLayout()));
3744   Ops[2] = DAG.getConstant(I.getSynchScope(), dl,
3745                            TLI.getPointerTy(DAG.getDataLayout()));
3746   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
3747 }
3748 
3749 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3750   SDLoc dl = getCurSDLoc();
3751   AtomicOrdering Order = I.getOrdering();
3752   SynchronizationScope Scope = I.getSynchScope();
3753 
3754   SDValue InChain = getRoot();
3755 
3756   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3757   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3758 
3759   if (I.getAlignment() < VT.getSizeInBits() / 8)
3760     report_fatal_error("Cannot generate unaligned atomic load");
3761 
3762   MachineMemOperand *MMO =
3763       DAG.getMachineFunction().
3764       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3765                            MachineMemOperand::MOVolatile |
3766                            MachineMemOperand::MOLoad,
3767                            VT.getStoreSize(),
3768                            I.getAlignment() ? I.getAlignment() :
3769                                               DAG.getEVTAlignment(VT));
3770 
3771   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
3772   SDValue L =
3773       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3774                     getValue(I.getPointerOperand()), MMO,
3775                     Order, Scope);
3776 
3777   SDValue OutChain = L.getValue(1);
3778 
3779   setValue(&I, L);
3780   DAG.setRoot(OutChain);
3781 }
3782 
3783 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3784   SDLoc dl = getCurSDLoc();
3785 
3786   AtomicOrdering Order = I.getOrdering();
3787   SynchronizationScope Scope = I.getSynchScope();
3788 
3789   SDValue InChain = getRoot();
3790 
3791   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3792   EVT VT =
3793       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
3794 
3795   if (I.getAlignment() < VT.getSizeInBits() / 8)
3796     report_fatal_error("Cannot generate unaligned atomic store");
3797 
3798   SDValue OutChain =
3799     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3800                   InChain,
3801                   getValue(I.getPointerOperand()),
3802                   getValue(I.getValueOperand()),
3803                   I.getPointerOperand(), I.getAlignment(),
3804                   Order, Scope);
3805 
3806   DAG.setRoot(OutChain);
3807 }
3808 
3809 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3810 /// node.
3811 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3812                                                unsigned Intrinsic) {
3813   bool HasChain = !I.doesNotAccessMemory();
3814   bool OnlyLoad = HasChain && I.onlyReadsMemory();
3815 
3816   // Build the operand list.
3817   SmallVector<SDValue, 8> Ops;
3818   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
3819     if (OnlyLoad) {
3820       // We don't need to serialize loads against other loads.
3821       Ops.push_back(DAG.getRoot());
3822     } else {
3823       Ops.push_back(getRoot());
3824     }
3825   }
3826 
3827   // Info is set by getTgtMemInstrinsic
3828   TargetLowering::IntrinsicInfo Info;
3829   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3830   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3831 
3832   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3833   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3834       Info.opc == ISD::INTRINSIC_W_CHAIN)
3835     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
3836                                         TLI.getPointerTy(DAG.getDataLayout())));
3837 
3838   // Add all operands of the call to the operand list.
3839   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3840     SDValue Op = getValue(I.getArgOperand(i));
3841     Ops.push_back(Op);
3842   }
3843 
3844   SmallVector<EVT, 4> ValueVTs;
3845   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
3846 
3847   if (HasChain)
3848     ValueVTs.push_back(MVT::Other);
3849 
3850   SDVTList VTs = DAG.getVTList(ValueVTs);
3851 
3852   // Create the node.
3853   SDValue Result;
3854   if (IsTgtIntrinsic) {
3855     // This is target intrinsic that touches memory
3856     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
3857                                      VTs, Ops, Info.memVT,
3858                                    MachinePointerInfo(Info.ptrVal, Info.offset),
3859                                      Info.align, Info.vol,
3860                                      Info.readMem, Info.writeMem, Info.size);
3861   } else if (!HasChain) {
3862     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
3863   } else if (!I.getType()->isVoidTy()) {
3864     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
3865   } else {
3866     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
3867   }
3868 
3869   if (HasChain) {
3870     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3871     if (OnlyLoad)
3872       PendingLoads.push_back(Chain);
3873     else
3874       DAG.setRoot(Chain);
3875   }
3876 
3877   if (!I.getType()->isVoidTy()) {
3878     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3879       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
3880       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
3881     } else
3882       Result = lowerRangeToAssertZExt(DAG, I, Result);
3883 
3884     setValue(&I, Result);
3885   }
3886 }
3887 
3888 /// GetSignificand - Get the significand and build it into a floating-point
3889 /// number with exponent of 1:
3890 ///
3891 ///   Op = (Op & 0x007fffff) | 0x3f800000;
3892 ///
3893 /// where Op is the hexadecimal representation of floating point value.
3894 static SDValue
3895 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
3896   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3897                            DAG.getConstant(0x007fffff, dl, MVT::i32));
3898   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3899                            DAG.getConstant(0x3f800000, dl, MVT::i32));
3900   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3901 }
3902 
3903 /// GetExponent - Get the exponent:
3904 ///
3905 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3906 ///
3907 /// where Op is the hexadecimal representation of floating point value.
3908 static SDValue
3909 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3910             SDLoc dl) {
3911   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3912                            DAG.getConstant(0x7f800000, dl, MVT::i32));
3913   SDValue t1 = DAG.getNode(
3914       ISD::SRL, dl, MVT::i32, t0,
3915       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
3916   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3917                            DAG.getConstant(127, dl, MVT::i32));
3918   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3919 }
3920 
3921 /// getF32Constant - Get 32-bit floating point constant.
3922 static SDValue
3923 getF32Constant(SelectionDAG &DAG, unsigned Flt, SDLoc dl) {
3924   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), dl,
3925                            MVT::f32);
3926 }
3927 
3928 static SDValue getLimitedPrecisionExp2(SDValue t0, SDLoc dl,
3929                                        SelectionDAG &DAG) {
3930   // TODO: What fast-math-flags should be set on the floating-point nodes?
3931 
3932   //   IntegerPartOfX = ((int32_t)(t0);
3933   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3934 
3935   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
3936   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3937   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3938 
3939   //   IntegerPartOfX <<= 23;
3940   IntegerPartOfX = DAG.getNode(
3941       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3942       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
3943                                   DAG.getDataLayout())));
3944 
3945   SDValue TwoToFractionalPartOfX;
3946   if (LimitFloatPrecision <= 6) {
3947     // For floating-point precision of 6:
3948     //
3949     //   TwoToFractionalPartOfX =
3950     //     0.997535578f +
3951     //       (0.735607626f + 0.252464424f * x) * x;
3952     //
3953     // error 0.0144103317, which is 6 bits
3954     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3955                              getF32Constant(DAG, 0x3e814304, dl));
3956     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3957                              getF32Constant(DAG, 0x3f3c50c8, dl));
3958     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3959     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3960                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
3961   } else if (LimitFloatPrecision <= 12) {
3962     // For floating-point precision of 12:
3963     //
3964     //   TwoToFractionalPartOfX =
3965     //     0.999892986f +
3966     //       (0.696457318f +
3967     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3968     //
3969     // error 0.000107046256, which is 13 to 14 bits
3970     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3971                              getF32Constant(DAG, 0x3da235e3, dl));
3972     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3973                              getF32Constant(DAG, 0x3e65b8f3, dl));
3974     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3975     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3976                              getF32Constant(DAG, 0x3f324b07, dl));
3977     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3978     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3979                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
3980   } else { // LimitFloatPrecision <= 18
3981     // For floating-point precision of 18:
3982     //
3983     //   TwoToFractionalPartOfX =
3984     //     0.999999982f +
3985     //       (0.693148872f +
3986     //         (0.240227044f +
3987     //           (0.554906021e-1f +
3988     //             (0.961591928e-2f +
3989     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3990     // error 2.47208000*10^(-7), which is better than 18 bits
3991     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3992                              getF32Constant(DAG, 0x3924b03e, dl));
3993     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3994                              getF32Constant(DAG, 0x3ab24b87, dl));
3995     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3996     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3997                              getF32Constant(DAG, 0x3c1d8c17, dl));
3998     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3999     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4000                              getF32Constant(DAG, 0x3d634a1d, dl));
4001     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4002     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4003                              getF32Constant(DAG, 0x3e75fe14, dl));
4004     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4005     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4006                               getF32Constant(DAG, 0x3f317234, dl));
4007     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4008     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4009                                          getF32Constant(DAG, 0x3f800000, dl));
4010   }
4011 
4012   // Add the exponent into the result in integer domain.
4013   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4014   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4015                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4016 }
4017 
4018 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4019 /// limited-precision mode.
4020 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4021                          const TargetLowering &TLI) {
4022   if (Op.getValueType() == MVT::f32 &&
4023       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4024 
4025     // Put the exponent in the right bit position for later addition to the
4026     // final result:
4027     //
4028     //   #define LOG2OFe 1.4426950f
4029     //   t0 = Op * LOG2OFe
4030 
4031     // TODO: What fast-math-flags should be set here?
4032     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4033                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4034     return getLimitedPrecisionExp2(t0, dl, DAG);
4035   }
4036 
4037   // No special expansion.
4038   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4039 }
4040 
4041 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4042 /// limited-precision mode.
4043 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4044                          const TargetLowering &TLI) {
4045 
4046   // TODO: What fast-math-flags should be set on the floating-point nodes?
4047 
4048   if (Op.getValueType() == MVT::f32 &&
4049       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4050     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4051 
4052     // Scale the exponent by log(2) [0.69314718f].
4053     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4054     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4055                                         getF32Constant(DAG, 0x3f317218, dl));
4056 
4057     // Get the significand and build it into a floating-point number with
4058     // exponent of 1.
4059     SDValue X = GetSignificand(DAG, Op1, dl);
4060 
4061     SDValue LogOfMantissa;
4062     if (LimitFloatPrecision <= 6) {
4063       // For floating-point precision of 6:
4064       //
4065       //   LogofMantissa =
4066       //     -1.1609546f +
4067       //       (1.4034025f - 0.23903021f * x) * x;
4068       //
4069       // error 0.0034276066, which is better than 8 bits
4070       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4071                                getF32Constant(DAG, 0xbe74c456, dl));
4072       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4073                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4074       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4075       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4076                                   getF32Constant(DAG, 0x3f949a29, dl));
4077     } else if (LimitFloatPrecision <= 12) {
4078       // For floating-point precision of 12:
4079       //
4080       //   LogOfMantissa =
4081       //     -1.7417939f +
4082       //       (2.8212026f +
4083       //         (-1.4699568f +
4084       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4085       //
4086       // error 0.000061011436, which is 14 bits
4087       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4088                                getF32Constant(DAG, 0xbd67b6d6, dl));
4089       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4090                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4091       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4092       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4093                                getF32Constant(DAG, 0x3fbc278b, dl));
4094       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4095       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4096                                getF32Constant(DAG, 0x40348e95, dl));
4097       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4098       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4099                                   getF32Constant(DAG, 0x3fdef31a, dl));
4100     } else { // LimitFloatPrecision <= 18
4101       // For floating-point precision of 18:
4102       //
4103       //   LogOfMantissa =
4104       //     -2.1072184f +
4105       //       (4.2372794f +
4106       //         (-3.7029485f +
4107       //           (2.2781945f +
4108       //             (-0.87823314f +
4109       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4110       //
4111       // error 0.0000023660568, which is better than 18 bits
4112       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4113                                getF32Constant(DAG, 0xbc91e5ac, dl));
4114       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4115                                getF32Constant(DAG, 0x3e4350aa, dl));
4116       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4117       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4118                                getF32Constant(DAG, 0x3f60d3e3, dl));
4119       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4120       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4121                                getF32Constant(DAG, 0x4011cdf0, dl));
4122       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4123       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4124                                getF32Constant(DAG, 0x406cfd1c, dl));
4125       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4126       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4127                                getF32Constant(DAG, 0x408797cb, dl));
4128       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4129       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4130                                   getF32Constant(DAG, 0x4006dcab, dl));
4131     }
4132 
4133     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4134   }
4135 
4136   // No special expansion.
4137   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4138 }
4139 
4140 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4141 /// limited-precision mode.
4142 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4143                           const TargetLowering &TLI) {
4144 
4145   // TODO: What fast-math-flags should be set on the floating-point nodes?
4146 
4147   if (Op.getValueType() == MVT::f32 &&
4148       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4149     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4150 
4151     // Get the exponent.
4152     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4153 
4154     // Get the significand and build it into a floating-point number with
4155     // exponent of 1.
4156     SDValue X = GetSignificand(DAG, Op1, dl);
4157 
4158     // Different possible minimax approximations of significand in
4159     // floating-point for various degrees of accuracy over [1,2].
4160     SDValue Log2ofMantissa;
4161     if (LimitFloatPrecision <= 6) {
4162       // For floating-point precision of 6:
4163       //
4164       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4165       //
4166       // error 0.0049451742, which is more than 7 bits
4167       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4168                                getF32Constant(DAG, 0xbeb08fe0, dl));
4169       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4170                                getF32Constant(DAG, 0x40019463, dl));
4171       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4172       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4173                                    getF32Constant(DAG, 0x3fd6633d, dl));
4174     } else if (LimitFloatPrecision <= 12) {
4175       // For floating-point precision of 12:
4176       //
4177       //   Log2ofMantissa =
4178       //     -2.51285454f +
4179       //       (4.07009056f +
4180       //         (-2.12067489f +
4181       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4182       //
4183       // error 0.0000876136000, which is better than 13 bits
4184       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4185                                getF32Constant(DAG, 0xbda7262e, dl));
4186       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4187                                getF32Constant(DAG, 0x3f25280b, dl));
4188       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4189       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4190                                getF32Constant(DAG, 0x4007b923, dl));
4191       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4192       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4193                                getF32Constant(DAG, 0x40823e2f, dl));
4194       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4195       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4196                                    getF32Constant(DAG, 0x4020d29c, dl));
4197     } else { // LimitFloatPrecision <= 18
4198       // For floating-point precision of 18:
4199       //
4200       //   Log2ofMantissa =
4201       //     -3.0400495f +
4202       //       (6.1129976f +
4203       //         (-5.3420409f +
4204       //           (3.2865683f +
4205       //             (-1.2669343f +
4206       //               (0.27515199f -
4207       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4208       //
4209       // error 0.0000018516, which is better than 18 bits
4210       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4211                                getF32Constant(DAG, 0xbcd2769e, dl));
4212       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4213                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4214       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4215       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4216                                getF32Constant(DAG, 0x3fa22ae7, dl));
4217       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4218       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4219                                getF32Constant(DAG, 0x40525723, dl));
4220       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4221       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4222                                getF32Constant(DAG, 0x40aaf200, dl));
4223       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4224       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4225                                getF32Constant(DAG, 0x40c39dad, dl));
4226       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4227       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4228                                    getF32Constant(DAG, 0x4042902c, dl));
4229     }
4230 
4231     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4232   }
4233 
4234   // No special expansion.
4235   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4236 }
4237 
4238 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4239 /// limited-precision mode.
4240 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4241                            const TargetLowering &TLI) {
4242 
4243   // TODO: What fast-math-flags should be set on the floating-point nodes?
4244 
4245   if (Op.getValueType() == MVT::f32 &&
4246       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4247     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4248 
4249     // Scale the exponent by log10(2) [0.30102999f].
4250     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4251     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4252                                         getF32Constant(DAG, 0x3e9a209a, dl));
4253 
4254     // Get the significand and build it into a floating-point number with
4255     // exponent of 1.
4256     SDValue X = GetSignificand(DAG, Op1, dl);
4257 
4258     SDValue Log10ofMantissa;
4259     if (LimitFloatPrecision <= 6) {
4260       // For floating-point precision of 6:
4261       //
4262       //   Log10ofMantissa =
4263       //     -0.50419619f +
4264       //       (0.60948995f - 0.10380950f * x) * x;
4265       //
4266       // error 0.0014886165, which is 6 bits
4267       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4268                                getF32Constant(DAG, 0xbdd49a13, dl));
4269       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4270                                getF32Constant(DAG, 0x3f1c0789, dl));
4271       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4272       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4273                                     getF32Constant(DAG, 0x3f011300, dl));
4274     } else if (LimitFloatPrecision <= 12) {
4275       // For floating-point precision of 12:
4276       //
4277       //   Log10ofMantissa =
4278       //     -0.64831180f +
4279       //       (0.91751397f +
4280       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4281       //
4282       // error 0.00019228036, which is better than 12 bits
4283       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4284                                getF32Constant(DAG, 0x3d431f31, dl));
4285       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4286                                getF32Constant(DAG, 0x3ea21fb2, dl));
4287       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4288       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4289                                getF32Constant(DAG, 0x3f6ae232, dl));
4290       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4291       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4292                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4293     } else { // LimitFloatPrecision <= 18
4294       // For floating-point precision of 18:
4295       //
4296       //   Log10ofMantissa =
4297       //     -0.84299375f +
4298       //       (1.5327582f +
4299       //         (-1.0688956f +
4300       //           (0.49102474f +
4301       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4302       //
4303       // error 0.0000037995730, which is better than 18 bits
4304       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4305                                getF32Constant(DAG, 0x3c5d51ce, dl));
4306       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4307                                getF32Constant(DAG, 0x3e00685a, dl));
4308       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4309       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4310                                getF32Constant(DAG, 0x3efb6798, dl));
4311       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4312       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4313                                getF32Constant(DAG, 0x3f88d192, dl));
4314       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4315       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4316                                getF32Constant(DAG, 0x3fc4316c, dl));
4317       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4318       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4319                                     getF32Constant(DAG, 0x3f57ce70, dl));
4320     }
4321 
4322     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4323   }
4324 
4325   // No special expansion.
4326   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4327 }
4328 
4329 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4330 /// limited-precision mode.
4331 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4332                           const TargetLowering &TLI) {
4333   if (Op.getValueType() == MVT::f32 &&
4334       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4335     return getLimitedPrecisionExp2(Op, dl, DAG);
4336 
4337   // No special expansion.
4338   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4339 }
4340 
4341 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4342 /// limited-precision mode with x == 10.0f.
4343 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
4344                          SelectionDAG &DAG, const TargetLowering &TLI) {
4345   bool IsExp10 = false;
4346   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4347       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4348     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4349       APFloat Ten(10.0f);
4350       IsExp10 = LHSC->isExactlyValue(Ten);
4351     }
4352   }
4353 
4354   // TODO: What fast-math-flags should be set on the FMUL node?
4355   if (IsExp10) {
4356     // Put the exponent in the right bit position for later addition to the
4357     // final result:
4358     //
4359     //   #define LOG2OF10 3.3219281f
4360     //   t0 = Op * LOG2OF10;
4361     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4362                              getF32Constant(DAG, 0x40549a78, dl));
4363     return getLimitedPrecisionExp2(t0, dl, DAG);
4364   }
4365 
4366   // No special expansion.
4367   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4368 }
4369 
4370 
4371 /// ExpandPowI - Expand a llvm.powi intrinsic.
4372 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
4373                           SelectionDAG &DAG) {
4374   // If RHS is a constant, we can expand this out to a multiplication tree,
4375   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4376   // optimizing for size, we only want to do this if the expansion would produce
4377   // a small number of multiplies, otherwise we do the full expansion.
4378   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4379     // Get the exponent as a positive value.
4380     unsigned Val = RHSC->getSExtValue();
4381     if ((int)Val < 0) Val = -Val;
4382 
4383     // powi(x, 0) -> 1.0
4384     if (Val == 0)
4385       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4386 
4387     const Function *F = DAG.getMachineFunction().getFunction();
4388     if (!F->optForSize() ||
4389         // If optimizing for size, don't insert too many multiplies.
4390         // This inserts up to 5 multiplies.
4391         countPopulation(Val) + Log2_32(Val) < 7) {
4392       // We use the simple binary decomposition method to generate the multiply
4393       // sequence.  There are more optimal ways to do this (for example,
4394       // powi(x,15) generates one more multiply than it should), but this has
4395       // the benefit of being both really simple and much better than a libcall.
4396       SDValue Res;  // Logically starts equal to 1.0
4397       SDValue CurSquare = LHS;
4398       // TODO: Intrinsics should have fast-math-flags that propagate to these
4399       // nodes.
4400       while (Val) {
4401         if (Val & 1) {
4402           if (Res.getNode())
4403             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4404           else
4405             Res = CurSquare;  // 1.0*CurSquare.
4406         }
4407 
4408         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4409                                 CurSquare, CurSquare);
4410         Val >>= 1;
4411       }
4412 
4413       // If the original was negative, invert the result, producing 1/(x*x*x).
4414       if (RHSC->getSExtValue() < 0)
4415         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4416                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4417       return Res;
4418     }
4419   }
4420 
4421   // Otherwise, expand to a libcall.
4422   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4423 }
4424 
4425 // getUnderlyingArgReg - Find underlying register used for a truncated or
4426 // bitcasted argument.
4427 static unsigned getUnderlyingArgReg(const SDValue &N) {
4428   switch (N.getOpcode()) {
4429   case ISD::CopyFromReg:
4430     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4431   case ISD::BITCAST:
4432   case ISD::AssertZext:
4433   case ISD::AssertSext:
4434   case ISD::TRUNCATE:
4435     return getUnderlyingArgReg(N.getOperand(0));
4436   default:
4437     return 0;
4438   }
4439 }
4440 
4441 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4442 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4443 /// At the end of instruction selection, they will be inserted to the entry BB.
4444 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4445     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4446     DILocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) {
4447   const Argument *Arg = dyn_cast<Argument>(V);
4448   if (!Arg)
4449     return false;
4450 
4451   MachineFunction &MF = DAG.getMachineFunction();
4452   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4453 
4454   // Ignore inlined function arguments here.
4455   //
4456   // FIXME: Should we be checking DL->inlinedAt() to determine this?
4457   if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction()))
4458     return false;
4459 
4460   Optional<MachineOperand> Op;
4461   // Some arguments' frame index is recorded during argument lowering.
4462   if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4463     Op = MachineOperand::CreateFI(FI);
4464 
4465   if (!Op && N.getNode()) {
4466     unsigned Reg = getUnderlyingArgReg(N);
4467     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4468       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4469       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4470       if (PR)
4471         Reg = PR;
4472     }
4473     if (Reg)
4474       Op = MachineOperand::CreateReg(Reg, false);
4475   }
4476 
4477   if (!Op) {
4478     // Check if ValueMap has reg number.
4479     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4480     if (VMI != FuncInfo.ValueMap.end())
4481       Op = MachineOperand::CreateReg(VMI->second, false);
4482   }
4483 
4484   if (!Op && N.getNode())
4485     // Check if frame index is available.
4486     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4487       if (FrameIndexSDNode *FINode =
4488           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4489         Op = MachineOperand::CreateFI(FINode->getIndex());
4490 
4491   if (!Op)
4492     return false;
4493 
4494   assert(Variable->isValidLocationForIntrinsic(DL) &&
4495          "Expected inlined-at fields to agree");
4496   if (Op->isReg())
4497     FuncInfo.ArgDbgValues.push_back(
4498         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4499                 Op->getReg(), Offset, Variable, Expr));
4500   else
4501     FuncInfo.ArgDbgValues.push_back(
4502         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
4503             .addOperand(*Op)
4504             .addImm(Offset)
4505             .addMetadata(Variable)
4506             .addMetadata(Expr));
4507 
4508   return true;
4509 }
4510 
4511 // VisualStudio defines setjmp as _setjmp
4512 #if defined(_MSC_VER) && defined(setjmp) && \
4513                          !defined(setjmp_undefined_for_msvc)
4514 #  pragma push_macro("setjmp")
4515 #  undef setjmp
4516 #  define setjmp_undefined_for_msvc
4517 #endif
4518 
4519 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
4520 /// we want to emit this as a call to a named external function, return the name
4521 /// otherwise lower it and return null.
4522 const char *
4523 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4525   SDLoc sdl = getCurSDLoc();
4526   DebugLoc dl = getCurDebugLoc();
4527   SDValue Res;
4528 
4529   switch (Intrinsic) {
4530   default:
4531     // By default, turn this into a target intrinsic node.
4532     visitTargetIntrinsic(I, Intrinsic);
4533     return nullptr;
4534   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
4535   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
4536   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
4537   case Intrinsic::returnaddress:
4538     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
4539                              TLI.getPointerTy(DAG.getDataLayout()),
4540                              getValue(I.getArgOperand(0))));
4541     return nullptr;
4542   case Intrinsic::frameaddress:
4543     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
4544                              TLI.getPointerTy(DAG.getDataLayout()),
4545                              getValue(I.getArgOperand(0))));
4546     return nullptr;
4547   case Intrinsic::read_register: {
4548     Value *Reg = I.getArgOperand(0);
4549     SDValue Chain = getRoot();
4550     SDValue RegName =
4551         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4552     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4553     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
4554       DAG.getVTList(VT, MVT::Other), Chain, RegName);
4555     setValue(&I, Res);
4556     DAG.setRoot(Res.getValue(1));
4557     return nullptr;
4558   }
4559   case Intrinsic::write_register: {
4560     Value *Reg = I.getArgOperand(0);
4561     Value *RegValue = I.getArgOperand(1);
4562     SDValue Chain = getRoot();
4563     SDValue RegName =
4564         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4565     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
4566                             RegName, getValue(RegValue)));
4567     return nullptr;
4568   }
4569   case Intrinsic::setjmp:
4570     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
4571   case Intrinsic::longjmp:
4572     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
4573   case Intrinsic::memcpy: {
4574     SDValue Op1 = getValue(I.getArgOperand(0));
4575     SDValue Op2 = getValue(I.getArgOperand(1));
4576     SDValue Op3 = getValue(I.getArgOperand(2));
4577     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4578     if (!Align)
4579       Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4580     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4581     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4582     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4583                                false, isTC,
4584                                MachinePointerInfo(I.getArgOperand(0)),
4585                                MachinePointerInfo(I.getArgOperand(1)));
4586     updateDAGForMaybeTailCall(MC);
4587     return nullptr;
4588   }
4589   case Intrinsic::memset: {
4590     SDValue Op1 = getValue(I.getArgOperand(0));
4591     SDValue Op2 = getValue(I.getArgOperand(1));
4592     SDValue Op3 = getValue(I.getArgOperand(2));
4593     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4594     if (!Align)
4595       Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4596     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4597     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4598     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4599                                isTC, MachinePointerInfo(I.getArgOperand(0)));
4600     updateDAGForMaybeTailCall(MS);
4601     return nullptr;
4602   }
4603   case Intrinsic::memmove: {
4604     SDValue Op1 = getValue(I.getArgOperand(0));
4605     SDValue Op2 = getValue(I.getArgOperand(1));
4606     SDValue Op3 = getValue(I.getArgOperand(2));
4607     unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4608     if (!Align)
4609       Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4610     bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4611     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4612     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4613                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
4614                                 MachinePointerInfo(I.getArgOperand(1)));
4615     updateDAGForMaybeTailCall(MM);
4616     return nullptr;
4617   }
4618   case Intrinsic::dbg_declare: {
4619     const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4620     DILocalVariable *Variable = DI.getVariable();
4621     DIExpression *Expression = DI.getExpression();
4622     const Value *Address = DI.getAddress();
4623     assert(Variable && "Missing variable");
4624     if (!Address) {
4625       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4626       return nullptr;
4627     }
4628 
4629     // Check if address has undef value.
4630     if (isa<UndefValue>(Address) ||
4631         (Address->use_empty() && !isa<Argument>(Address))) {
4632       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4633       return nullptr;
4634     }
4635 
4636     SDValue &N = NodeMap[Address];
4637     if (!N.getNode() && isa<Argument>(Address))
4638       // Check unused arguments map.
4639       N = UnusedArgNodeMap[Address];
4640     SDDbgValue *SDV;
4641     if (N.getNode()) {
4642       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4643         Address = BCI->getOperand(0);
4644       // Parameters are handled specially.
4645       bool isParameter = Variable->isParameter() || isa<Argument>(Address);
4646       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4647       if (isParameter && FINode) {
4648         // Byval parameter. We have a frame index at this point.
4649         SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
4650                                         FINode->getIndex(), 0, dl, SDNodeOrder);
4651       } else if (isa<Argument>(Address)) {
4652         // Address is an argument, so try to emit its dbg value using
4653         // virtual register info from the FuncInfo.ValueMap.
4654         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4655                                  N);
4656         return nullptr;
4657       } else {
4658         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4659                               true, 0, dl, SDNodeOrder);
4660       }
4661       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4662     } else {
4663       // If Address is an argument then try to emit its dbg value using
4664       // virtual register info from the FuncInfo.ValueMap.
4665       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4666                                     N)) {
4667         // If variable is pinned by a alloca in dominating bb then
4668         // use StaticAllocaMap.
4669         if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4670           if (AI->getParent() != DI.getParent()) {
4671             DenseMap<const AllocaInst*, int>::iterator SI =
4672               FuncInfo.StaticAllocaMap.find(AI);
4673             if (SI != FuncInfo.StaticAllocaMap.end()) {
4674               SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
4675                                               0, dl, SDNodeOrder);
4676               DAG.AddDbgValue(SDV, nullptr, false);
4677               return nullptr;
4678             }
4679           }
4680         }
4681         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4682       }
4683     }
4684     return nullptr;
4685   }
4686   case Intrinsic::dbg_value: {
4687     const DbgValueInst &DI = cast<DbgValueInst>(I);
4688     assert(DI.getVariable() && "Missing variable");
4689 
4690     DILocalVariable *Variable = DI.getVariable();
4691     DIExpression *Expression = DI.getExpression();
4692     uint64_t Offset = DI.getOffset();
4693     const Value *V = DI.getValue();
4694     if (!V)
4695       return nullptr;
4696 
4697     SDDbgValue *SDV;
4698     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4699       SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
4700                                     SDNodeOrder);
4701       DAG.AddDbgValue(SDV, nullptr, false);
4702     } else {
4703       // Do not use getValue() in here; we don't want to generate code at
4704       // this point if it hasn't been done yet.
4705       SDValue N = NodeMap[V];
4706       if (!N.getNode() && isa<Argument>(V))
4707         // Check unused arguments map.
4708         N = UnusedArgNodeMap[V];
4709       if (N.getNode()) {
4710         if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset,
4711                                       false, N)) {
4712           SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4713                                 false, Offset, dl, SDNodeOrder);
4714           DAG.AddDbgValue(SDV, N.getNode(), false);
4715         }
4716       } else if (!V->use_empty() ) {
4717         // Do not call getValue(V) yet, as we don't want to generate code.
4718         // Remember it for later.
4719         DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4720         DanglingDebugInfoMap[V] = DDI;
4721       } else {
4722         // We may expand this to cover more cases.  One case where we have no
4723         // data available is an unreferenced parameter.
4724         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4725       }
4726     }
4727 
4728     // Build a debug info table entry.
4729     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4730       V = BCI->getOperand(0);
4731     const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4732     // Don't handle byval struct arguments or VLAs, for example.
4733     if (!AI) {
4734       DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
4735       DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
4736       return nullptr;
4737     }
4738     DenseMap<const AllocaInst*, int>::iterator SI =
4739       FuncInfo.StaticAllocaMap.find(AI);
4740     if (SI == FuncInfo.StaticAllocaMap.end())
4741       return nullptr; // VLAs.
4742     return nullptr;
4743   }
4744 
4745   case Intrinsic::eh_typeid_for: {
4746     // Find the type id for the given typeinfo.
4747     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
4748     unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4749     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
4750     setValue(&I, Res);
4751     return nullptr;
4752   }
4753 
4754   case Intrinsic::eh_return_i32:
4755   case Intrinsic::eh_return_i64:
4756     DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4757     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
4758                             MVT::Other,
4759                             getControlRoot(),
4760                             getValue(I.getArgOperand(0)),
4761                             getValue(I.getArgOperand(1))));
4762     return nullptr;
4763   case Intrinsic::eh_unwind_init:
4764     DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4765     return nullptr;
4766   case Intrinsic::eh_dwarf_cfa: {
4767     SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
4768                                         TLI.getPointerTy(DAG.getDataLayout()));
4769     SDValue Offset = DAG.getNode(ISD::ADD, sdl,
4770                                  CfaArg.getValueType(),
4771                                  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
4772                                              CfaArg.getValueType()),
4773                                  CfaArg);
4774     SDValue FA = DAG.getNode(
4775         ISD::FRAMEADDR, sdl, TLI.getPointerTy(DAG.getDataLayout()),
4776         DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
4777     setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
4778                              FA, Offset));
4779     return nullptr;
4780   }
4781   case Intrinsic::eh_sjlj_callsite: {
4782     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4783     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4784     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4785     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4786 
4787     MMI.setCurrentCallSite(CI->getZExtValue());
4788     return nullptr;
4789   }
4790   case Intrinsic::eh_sjlj_functioncontext: {
4791     // Get and store the index of the function context.
4792     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4793     AllocaInst *FnCtx =
4794       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4795     int FI = FuncInfo.StaticAllocaMap[FnCtx];
4796     MFI->setFunctionContextIndex(FI);
4797     return nullptr;
4798   }
4799   case Intrinsic::eh_sjlj_setjmp: {
4800     SDValue Ops[2];
4801     Ops[0] = getRoot();
4802     Ops[1] = getValue(I.getArgOperand(0));
4803     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
4804                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
4805     setValue(&I, Op.getValue(0));
4806     DAG.setRoot(Op.getValue(1));
4807     return nullptr;
4808   }
4809   case Intrinsic::eh_sjlj_longjmp: {
4810     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
4811                             getRoot(), getValue(I.getArgOperand(0))));
4812     return nullptr;
4813   }
4814   case Intrinsic::eh_sjlj_setup_dispatch: {
4815     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
4816                             getRoot()));
4817     return nullptr;
4818   }
4819 
4820   case Intrinsic::masked_gather:
4821     visitMaskedGather(I);
4822     return nullptr;
4823   case Intrinsic::masked_load:
4824     visitMaskedLoad(I);
4825     return nullptr;
4826   case Intrinsic::masked_scatter:
4827     visitMaskedScatter(I);
4828     return nullptr;
4829   case Intrinsic::masked_store:
4830     visitMaskedStore(I);
4831     return nullptr;
4832   case Intrinsic::x86_mmx_pslli_w:
4833   case Intrinsic::x86_mmx_pslli_d:
4834   case Intrinsic::x86_mmx_pslli_q:
4835   case Intrinsic::x86_mmx_psrli_w:
4836   case Intrinsic::x86_mmx_psrli_d:
4837   case Intrinsic::x86_mmx_psrli_q:
4838   case Intrinsic::x86_mmx_psrai_w:
4839   case Intrinsic::x86_mmx_psrai_d: {
4840     SDValue ShAmt = getValue(I.getArgOperand(1));
4841     if (isa<ConstantSDNode>(ShAmt)) {
4842       visitTargetIntrinsic(I, Intrinsic);
4843       return nullptr;
4844     }
4845     unsigned NewIntrinsic = 0;
4846     EVT ShAmtVT = MVT::v2i32;
4847     switch (Intrinsic) {
4848     case Intrinsic::x86_mmx_pslli_w:
4849       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4850       break;
4851     case Intrinsic::x86_mmx_pslli_d:
4852       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4853       break;
4854     case Intrinsic::x86_mmx_pslli_q:
4855       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4856       break;
4857     case Intrinsic::x86_mmx_psrli_w:
4858       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4859       break;
4860     case Intrinsic::x86_mmx_psrli_d:
4861       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4862       break;
4863     case Intrinsic::x86_mmx_psrli_q:
4864       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4865       break;
4866     case Intrinsic::x86_mmx_psrai_w:
4867       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4868       break;
4869     case Intrinsic::x86_mmx_psrai_d:
4870       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4871       break;
4872     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
4873     }
4874 
4875     // The vector shift intrinsics with scalars uses 32b shift amounts but
4876     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4877     // to be zero.
4878     // We must do this early because v2i32 is not a legal type.
4879     SDValue ShOps[2];
4880     ShOps[0] = ShAmt;
4881     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
4882     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
4883     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4884     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4885     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
4886                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
4887                        getValue(I.getArgOperand(0)), ShAmt);
4888     setValue(&I, Res);
4889     return nullptr;
4890   }
4891   case Intrinsic::convertff:
4892   case Intrinsic::convertfsi:
4893   case Intrinsic::convertfui:
4894   case Intrinsic::convertsif:
4895   case Intrinsic::convertuif:
4896   case Intrinsic::convertss:
4897   case Intrinsic::convertsu:
4898   case Intrinsic::convertus:
4899   case Intrinsic::convertuu: {
4900     ISD::CvtCode Code = ISD::CVT_INVALID;
4901     switch (Intrinsic) {
4902     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
4903     case Intrinsic::convertff:  Code = ISD::CVT_FF; break;
4904     case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4905     case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4906     case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4907     case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4908     case Intrinsic::convertss:  Code = ISD::CVT_SS; break;
4909     case Intrinsic::convertsu:  Code = ISD::CVT_SU; break;
4910     case Intrinsic::convertus:  Code = ISD::CVT_US; break;
4911     case Intrinsic::convertuu:  Code = ISD::CVT_UU; break;
4912     }
4913     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4914     const Value *Op1 = I.getArgOperand(0);
4915     Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
4916                                DAG.getValueType(DestVT),
4917                                DAG.getValueType(getValue(Op1).getValueType()),
4918                                getValue(I.getArgOperand(1)),
4919                                getValue(I.getArgOperand(2)),
4920                                Code);
4921     setValue(&I, Res);
4922     return nullptr;
4923   }
4924   case Intrinsic::powi:
4925     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
4926                             getValue(I.getArgOperand(1)), DAG));
4927     return nullptr;
4928   case Intrinsic::log:
4929     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4930     return nullptr;
4931   case Intrinsic::log2:
4932     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4933     return nullptr;
4934   case Intrinsic::log10:
4935     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4936     return nullptr;
4937   case Intrinsic::exp:
4938     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4939     return nullptr;
4940   case Intrinsic::exp2:
4941     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4942     return nullptr;
4943   case Intrinsic::pow:
4944     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
4945                            getValue(I.getArgOperand(1)), DAG, TLI));
4946     return nullptr;
4947   case Intrinsic::sqrt:
4948   case Intrinsic::fabs:
4949   case Intrinsic::sin:
4950   case Intrinsic::cos:
4951   case Intrinsic::floor:
4952   case Intrinsic::ceil:
4953   case Intrinsic::trunc:
4954   case Intrinsic::rint:
4955   case Intrinsic::nearbyint:
4956   case Intrinsic::round: {
4957     unsigned Opcode;
4958     switch (Intrinsic) {
4959     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
4960     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
4961     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
4962     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
4963     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
4964     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
4965     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
4966     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
4967     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
4968     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
4969     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
4970     }
4971 
4972     setValue(&I, DAG.getNode(Opcode, sdl,
4973                              getValue(I.getArgOperand(0)).getValueType(),
4974                              getValue(I.getArgOperand(0))));
4975     return nullptr;
4976   }
4977   case Intrinsic::minnum:
4978     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
4979                              getValue(I.getArgOperand(0)).getValueType(),
4980                              getValue(I.getArgOperand(0)),
4981                              getValue(I.getArgOperand(1))));
4982     return nullptr;
4983   case Intrinsic::maxnum:
4984     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
4985                              getValue(I.getArgOperand(0)).getValueType(),
4986                              getValue(I.getArgOperand(0)),
4987                              getValue(I.getArgOperand(1))));
4988     return nullptr;
4989   case Intrinsic::copysign:
4990     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
4991                              getValue(I.getArgOperand(0)).getValueType(),
4992                              getValue(I.getArgOperand(0)),
4993                              getValue(I.getArgOperand(1))));
4994     return nullptr;
4995   case Intrinsic::fma:
4996     setValue(&I, DAG.getNode(ISD::FMA, sdl,
4997                              getValue(I.getArgOperand(0)).getValueType(),
4998                              getValue(I.getArgOperand(0)),
4999                              getValue(I.getArgOperand(1)),
5000                              getValue(I.getArgOperand(2))));
5001     return nullptr;
5002   case Intrinsic::fmuladd: {
5003     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5004     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5005         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5006       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5007                                getValue(I.getArgOperand(0)).getValueType(),
5008                                getValue(I.getArgOperand(0)),
5009                                getValue(I.getArgOperand(1)),
5010                                getValue(I.getArgOperand(2))));
5011     } else {
5012       // TODO: Intrinsic calls should have fast-math-flags.
5013       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5014                                 getValue(I.getArgOperand(0)).getValueType(),
5015                                 getValue(I.getArgOperand(0)),
5016                                 getValue(I.getArgOperand(1)));
5017       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5018                                 getValue(I.getArgOperand(0)).getValueType(),
5019                                 Mul,
5020                                 getValue(I.getArgOperand(2)));
5021       setValue(&I, Add);
5022     }
5023     return nullptr;
5024   }
5025   case Intrinsic::convert_to_fp16:
5026     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5027                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5028                                          getValue(I.getArgOperand(0)),
5029                                          DAG.getTargetConstant(0, sdl,
5030                                                                MVT::i32))));
5031     return nullptr;
5032   case Intrinsic::convert_from_fp16:
5033     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5034                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5035                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5036                                          getValue(I.getArgOperand(0)))));
5037     return nullptr;
5038   case Intrinsic::pcmarker: {
5039     SDValue Tmp = getValue(I.getArgOperand(0));
5040     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5041     return nullptr;
5042   }
5043   case Intrinsic::readcyclecounter: {
5044     SDValue Op = getRoot();
5045     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5046                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5047     setValue(&I, Res);
5048     DAG.setRoot(Res.getValue(1));
5049     return nullptr;
5050   }
5051   case Intrinsic::bitreverse:
5052     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5053                              getValue(I.getArgOperand(0)).getValueType(),
5054                              getValue(I.getArgOperand(0))));
5055     return nullptr;
5056   case Intrinsic::bswap:
5057     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5058                              getValue(I.getArgOperand(0)).getValueType(),
5059                              getValue(I.getArgOperand(0))));
5060     return nullptr;
5061   case Intrinsic::cttz: {
5062     SDValue Arg = getValue(I.getArgOperand(0));
5063     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5064     EVT Ty = Arg.getValueType();
5065     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5066                              sdl, Ty, Arg));
5067     return nullptr;
5068   }
5069   case Intrinsic::ctlz: {
5070     SDValue Arg = getValue(I.getArgOperand(0));
5071     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5072     EVT Ty = Arg.getValueType();
5073     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5074                              sdl, Ty, Arg));
5075     return nullptr;
5076   }
5077   case Intrinsic::ctpop: {
5078     SDValue Arg = getValue(I.getArgOperand(0));
5079     EVT Ty = Arg.getValueType();
5080     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5081     return nullptr;
5082   }
5083   case Intrinsic::stacksave: {
5084     SDValue Op = getRoot();
5085     Res = DAG.getNode(
5086         ISD::STACKSAVE, sdl,
5087         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5088     setValue(&I, Res);
5089     DAG.setRoot(Res.getValue(1));
5090     return nullptr;
5091   }
5092   case Intrinsic::stackrestore: {
5093     Res = getValue(I.getArgOperand(0));
5094     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5095     return nullptr;
5096   }
5097   case Intrinsic::get_dynamic_area_offset: {
5098     SDValue Op = getRoot();
5099     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5100     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5101     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5102     // target.
5103     if (PtrTy != ResTy)
5104       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5105                          " intrinsic!");
5106     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5107                       Op);
5108     DAG.setRoot(Op);
5109     setValue(&I, Res);
5110     return nullptr;
5111   }
5112   case Intrinsic::stackprotector: {
5113     // Emit code into the DAG to store the stack guard onto the stack.
5114     MachineFunction &MF = DAG.getMachineFunction();
5115     MachineFrameInfo *MFI = MF.getFrameInfo();
5116     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5117     SDValue Src, Chain = getRoot();
5118     const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
5119     const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
5120 
5121     // See if Ptr is a bitcast. If it is, look through it and see if we can get
5122     // global variable __stack_chk_guard.
5123     if (!GV)
5124       if (const Operator *BC = dyn_cast<Operator>(Ptr))
5125         if (BC->getOpcode() == Instruction::BitCast)
5126           GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
5127 
5128     if (GV && TLI.useLoadStackGuardNode()) {
5129       // Emit a LOAD_STACK_GUARD node.
5130       MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
5131                                                sdl, PtrTy, Chain);
5132       MachinePointerInfo MPInfo(GV);
5133       MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
5134       unsigned Flags = MachineMemOperand::MOLoad |
5135                        MachineMemOperand::MOInvariant;
5136       *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
5137                                          PtrTy.getSizeInBits() / 8,
5138                                          DAG.getEVTAlignment(PtrTy));
5139       Node->setMemRefs(MemRefs, MemRefs + 1);
5140 
5141       // Copy the guard value to a virtual register so that it can be
5142       // retrieved in the epilogue.
5143       Src = SDValue(Node, 0);
5144       const TargetRegisterClass *RC =
5145           TLI.getRegClassFor(Src.getSimpleValueType());
5146       unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
5147 
5148       SPDescriptor.setGuardReg(Reg);
5149       Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
5150     } else {
5151       Src = getValue(I.getArgOperand(0));   // The guard's value.
5152     }
5153 
5154     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5155 
5156     int FI = FuncInfo.StaticAllocaMap[Slot];
5157     MFI->setStackProtectorIndex(FI);
5158 
5159     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5160 
5161     // Store the stack protector onto the stack.
5162     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5163                                                  DAG.getMachineFunction(), FI),
5164                        true, false, 0);
5165     setValue(&I, Res);
5166     DAG.setRoot(Res);
5167     return nullptr;
5168   }
5169   case Intrinsic::objectsize: {
5170     // If we don't know by now, we're never going to know.
5171     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5172 
5173     assert(CI && "Non-constant type in __builtin_object_size?");
5174 
5175     SDValue Arg = getValue(I.getCalledValue());
5176     EVT Ty = Arg.getValueType();
5177 
5178     if (CI->isZero())
5179       Res = DAG.getConstant(-1ULL, sdl, Ty);
5180     else
5181       Res = DAG.getConstant(0, sdl, Ty);
5182 
5183     setValue(&I, Res);
5184     return nullptr;
5185   }
5186   case Intrinsic::annotation:
5187   case Intrinsic::ptr_annotation:
5188     // Drop the intrinsic, but forward the value
5189     setValue(&I, getValue(I.getOperand(0)));
5190     return nullptr;
5191   case Intrinsic::assume:
5192   case Intrinsic::var_annotation:
5193     // Discard annotate attributes and assumptions
5194     return nullptr;
5195 
5196   case Intrinsic::init_trampoline: {
5197     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5198 
5199     SDValue Ops[6];
5200     Ops[0] = getRoot();
5201     Ops[1] = getValue(I.getArgOperand(0));
5202     Ops[2] = getValue(I.getArgOperand(1));
5203     Ops[3] = getValue(I.getArgOperand(2));
5204     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5205     Ops[5] = DAG.getSrcValue(F);
5206 
5207     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5208 
5209     DAG.setRoot(Res);
5210     return nullptr;
5211   }
5212   case Intrinsic::adjust_trampoline: {
5213     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5214                              TLI.getPointerTy(DAG.getDataLayout()),
5215                              getValue(I.getArgOperand(0))));
5216     return nullptr;
5217   }
5218   case Intrinsic::gcroot: {
5219     MachineFunction &MF = DAG.getMachineFunction();
5220     const Function *F = MF.getFunction();
5221     (void)F;
5222     assert(F->hasGC() &&
5223            "only valid in functions with gc specified, enforced by Verifier");
5224     assert(GFI && "implied by previous");
5225     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5226     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5227 
5228     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5229     GFI->addStackRoot(FI->getIndex(), TypeMap);
5230     return nullptr;
5231   }
5232   case Intrinsic::gcread:
5233   case Intrinsic::gcwrite:
5234     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5235   case Intrinsic::flt_rounds:
5236     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5237     return nullptr;
5238 
5239   case Intrinsic::expect: {
5240     // Just replace __builtin_expect(exp, c) with EXP.
5241     setValue(&I, getValue(I.getArgOperand(0)));
5242     return nullptr;
5243   }
5244 
5245   case Intrinsic::debugtrap:
5246   case Intrinsic::trap: {
5247     StringRef TrapFuncName =
5248         I.getAttributes()
5249             .getAttribute(AttributeSet::FunctionIndex, "trap-func-name")
5250             .getValueAsString();
5251     if (TrapFuncName.empty()) {
5252       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5253         ISD::TRAP : ISD::DEBUGTRAP;
5254       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5255       return nullptr;
5256     }
5257     TargetLowering::ArgListTy Args;
5258 
5259     TargetLowering::CallLoweringInfo CLI(DAG);
5260     CLI.setDebugLoc(sdl).setChain(getRoot()).setCallee(
5261         CallingConv::C, I.getType(),
5262         DAG.getExternalSymbol(TrapFuncName.data(),
5263                               TLI.getPointerTy(DAG.getDataLayout())),
5264         std::move(Args), 0);
5265 
5266     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5267     DAG.setRoot(Result.second);
5268     return nullptr;
5269   }
5270 
5271   case Intrinsic::uadd_with_overflow:
5272   case Intrinsic::sadd_with_overflow:
5273   case Intrinsic::usub_with_overflow:
5274   case Intrinsic::ssub_with_overflow:
5275   case Intrinsic::umul_with_overflow:
5276   case Intrinsic::smul_with_overflow: {
5277     ISD::NodeType Op;
5278     switch (Intrinsic) {
5279     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5280     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5281     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5282     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5283     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5284     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5285     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5286     }
5287     SDValue Op1 = getValue(I.getArgOperand(0));
5288     SDValue Op2 = getValue(I.getArgOperand(1));
5289 
5290     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5291     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5292     return nullptr;
5293   }
5294   case Intrinsic::prefetch: {
5295     SDValue Ops[5];
5296     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5297     Ops[0] = getRoot();
5298     Ops[1] = getValue(I.getArgOperand(0));
5299     Ops[2] = getValue(I.getArgOperand(1));
5300     Ops[3] = getValue(I.getArgOperand(2));
5301     Ops[4] = getValue(I.getArgOperand(3));
5302     DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5303                                         DAG.getVTList(MVT::Other), Ops,
5304                                         EVT::getIntegerVT(*Context, 8),
5305                                         MachinePointerInfo(I.getArgOperand(0)),
5306                                         0, /* align */
5307                                         false, /* volatile */
5308                                         rw==0, /* read */
5309                                         rw==1)); /* write */
5310     return nullptr;
5311   }
5312   case Intrinsic::lifetime_start:
5313   case Intrinsic::lifetime_end: {
5314     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5315     // Stack coloring is not enabled in O0, discard region information.
5316     if (TM.getOptLevel() == CodeGenOpt::None)
5317       return nullptr;
5318 
5319     SmallVector<Value *, 4> Allocas;
5320     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
5321 
5322     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5323            E = Allocas.end(); Object != E; ++Object) {
5324       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5325 
5326       // Could not find an Alloca.
5327       if (!LifetimeObject)
5328         continue;
5329 
5330       // First check that the Alloca is static, otherwise it won't have a
5331       // valid frame index.
5332       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5333       if (SI == FuncInfo.StaticAllocaMap.end())
5334         return nullptr;
5335 
5336       int FI = SI->second;
5337 
5338       SDValue Ops[2];
5339       Ops[0] = getRoot();
5340       Ops[1] =
5341           DAG.getFrameIndex(FI, TLI.getPointerTy(DAG.getDataLayout()), true);
5342       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5343 
5344       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5345       DAG.setRoot(Res);
5346     }
5347     return nullptr;
5348   }
5349   case Intrinsic::invariant_start:
5350     // Discard region information.
5351     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
5352     return nullptr;
5353   case Intrinsic::invariant_end:
5354     // Discard region information.
5355     return nullptr;
5356   case Intrinsic::stackprotectorcheck: {
5357     // Do not actually emit anything for this basic block. Instead we initialize
5358     // the stack protector descriptor and export the guard variable so we can
5359     // access it in FinishBasicBlock.
5360     const BasicBlock *BB = I.getParent();
5361     SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5362     ExportFromCurrentBlock(SPDescriptor.getGuard());
5363 
5364     // Flush our exports since we are going to process a terminator.
5365     (void)getControlRoot();
5366     return nullptr;
5367   }
5368   case Intrinsic::clear_cache:
5369     return TLI.getClearCacheBuiltinName();
5370   case Intrinsic::donothing:
5371     // ignore
5372     return nullptr;
5373   case Intrinsic::experimental_stackmap: {
5374     visitStackmap(I);
5375     return nullptr;
5376   }
5377   case Intrinsic::experimental_patchpoint_void:
5378   case Intrinsic::experimental_patchpoint_i64: {
5379     visitPatchpoint(&I);
5380     return nullptr;
5381   }
5382   case Intrinsic::experimental_gc_statepoint: {
5383     LowerStatepoint(ImmutableStatepoint(&I));
5384     return nullptr;
5385   }
5386   case Intrinsic::experimental_gc_result: {
5387     visitGCResult(I);
5388     return nullptr;
5389   }
5390   case Intrinsic::experimental_gc_relocate: {
5391     visitGCRelocate(cast<GCRelocateInst>(I));
5392     return nullptr;
5393   }
5394   case Intrinsic::instrprof_increment:
5395     llvm_unreachable("instrprof failed to lower an increment");
5396   case Intrinsic::instrprof_value_profile:
5397     llvm_unreachable("instrprof failed to lower a value profiling call");
5398   case Intrinsic::localescape: {
5399     MachineFunction &MF = DAG.getMachineFunction();
5400     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5401 
5402     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
5403     // is the same on all targets.
5404     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
5405       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
5406       if (isa<ConstantPointerNull>(Arg))
5407         continue; // Skip null pointers. They represent a hole in index space.
5408       AllocaInst *Slot = cast<AllocaInst>(Arg);
5409       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
5410              "can only escape static allocas");
5411       int FI = FuncInfo.StaticAllocaMap[Slot];
5412       MCSymbol *FrameAllocSym =
5413           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5414               GlobalValue::getRealLinkageName(MF.getName()), Idx);
5415       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
5416               TII->get(TargetOpcode::LOCAL_ESCAPE))
5417           .addSym(FrameAllocSym)
5418           .addFrameIndex(FI);
5419     }
5420 
5421     return nullptr;
5422   }
5423 
5424   case Intrinsic::localrecover: {
5425     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
5426     MachineFunction &MF = DAG.getMachineFunction();
5427     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
5428 
5429     // Get the symbol that defines the frame offset.
5430     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
5431     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
5432     unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX));
5433     MCSymbol *FrameAllocSym =
5434         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5435             GlobalValue::getRealLinkageName(Fn->getName()), IdxVal);
5436 
5437     // Create a MCSymbol for the label to avoid any target lowering
5438     // that would make this PC relative.
5439     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
5440     SDValue OffsetVal =
5441         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
5442 
5443     // Add the offset to the FP.
5444     Value *FP = I.getArgOperand(1);
5445     SDValue FPVal = getValue(FP);
5446     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
5447     setValue(&I, Add);
5448 
5449     return nullptr;
5450   }
5451 
5452   case Intrinsic::eh_exceptionpointer:
5453   case Intrinsic::eh_exceptioncode: {
5454     // Get the exception pointer vreg, copy from it, and resize it to fit.
5455     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
5456     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
5457     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
5458     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
5459     SDValue N =
5460         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
5461     if (Intrinsic == Intrinsic::eh_exceptioncode)
5462       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
5463     setValue(&I, N);
5464     return nullptr;
5465   }
5466   }
5467 }
5468 
5469 std::pair<SDValue, SDValue>
5470 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
5471                                     const BasicBlock *EHPadBB) {
5472   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5473   MCSymbol *BeginLabel = nullptr;
5474 
5475   if (EHPadBB) {
5476     // Insert a label before the invoke call to mark the try range.  This can be
5477     // used to detect deletion of the invoke via the MachineModuleInfo.
5478     BeginLabel = MMI.getContext().createTempSymbol();
5479 
5480     // For SjLj, keep track of which landing pads go with which invokes
5481     // so as to maintain the ordering of pads in the LSDA.
5482     unsigned CallSiteIndex = MMI.getCurrentCallSite();
5483     if (CallSiteIndex) {
5484       MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5485       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
5486 
5487       // Now that the call site is handled, stop tracking it.
5488       MMI.setCurrentCallSite(0);
5489     }
5490 
5491     // Both PendingLoads and PendingExports must be flushed here;
5492     // this call might not return.
5493     (void)getRoot();
5494     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5495 
5496     CLI.setChain(getRoot());
5497   }
5498   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5499   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5500 
5501   assert((CLI.IsTailCall || Result.second.getNode()) &&
5502          "Non-null chain expected with non-tail call!");
5503   assert((Result.second.getNode() || !Result.first.getNode()) &&
5504          "Null value expected with tail call!");
5505 
5506   if (!Result.second.getNode()) {
5507     // As a special case, a null chain means that a tail call has been emitted
5508     // and the DAG root is already updated.
5509     HasTailCall = true;
5510 
5511     // Since there's no actual continuation from this block, nothing can be
5512     // relying on us setting vregs for them.
5513     PendingExports.clear();
5514   } else {
5515     DAG.setRoot(Result.second);
5516   }
5517 
5518   if (EHPadBB) {
5519     // Insert a label at the end of the invoke call to mark the try range.  This
5520     // can be used to detect deletion of the invoke via the MachineModuleInfo.
5521     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
5522     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5523 
5524     // Inform MachineModuleInfo of range.
5525     if (MMI.hasEHFunclets()) {
5526       assert(CLI.CS);
5527       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
5528       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS->getInstruction()),
5529                                 BeginLabel, EndLabel);
5530     } else {
5531       MMI.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
5532     }
5533   }
5534 
5535   return Result;
5536 }
5537 
5538 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5539                                       bool isTailCall,
5540                                       const BasicBlock *EHPadBB) {
5541   FunctionType *FTy = CS.getFunctionType();
5542   Type *RetTy = CS.getType();
5543 
5544   TargetLowering::ArgListTy Args;
5545   TargetLowering::ArgListEntry Entry;
5546   Args.reserve(CS.arg_size());
5547 
5548   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5549        i != e; ++i) {
5550     const Value *V = *i;
5551 
5552     // Skip empty types
5553     if (V->getType()->isEmptyTy())
5554       continue;
5555 
5556     SDValue ArgNode = getValue(V);
5557     Entry.Node = ArgNode; Entry.Ty = V->getType();
5558 
5559     // Skip the first return-type Attribute to get to params.
5560     Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5561     Args.push_back(Entry);
5562 
5563     // If we have an explicit sret argument that is an Instruction, (i.e., it
5564     // might point to function-local memory), we can't meaningfully tail-call.
5565     if (Entry.isSRet && isa<Instruction>(V))
5566       isTailCall = false;
5567   }
5568 
5569   // Check if target-independent constraints permit a tail call here.
5570   // Target-dependent constraints are checked within TLI->LowerCallTo.
5571   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
5572     isTailCall = false;
5573 
5574   TargetLowering::CallLoweringInfo CLI(DAG);
5575   CLI.setDebugLoc(getCurSDLoc())
5576       .setChain(getRoot())
5577       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
5578       .setTailCall(isTailCall)
5579       .setConvergent(CS.isConvergent());
5580   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
5581 
5582   if (Result.first.getNode()) {
5583     const Instruction *Inst = CS.getInstruction();
5584     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
5585     setValue(Inst, Result.first);
5586   }
5587 }
5588 
5589 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5590 /// value is equal or not-equal to zero.
5591 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5592   for (const User *U : V->users()) {
5593     if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
5594       if (IC->isEquality())
5595         if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5596           if (C->isNullValue())
5597             continue;
5598     // Unknown instruction.
5599     return false;
5600   }
5601   return true;
5602 }
5603 
5604 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5605                              Type *LoadTy,
5606                              SelectionDAGBuilder &Builder) {
5607 
5608   // Check to see if this load can be trivially constant folded, e.g. if the
5609   // input is from a string literal.
5610   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5611     // Cast pointer to the type we really want to load.
5612     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5613                                          PointerType::getUnqual(LoadTy));
5614 
5615     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
5616             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
5617       return Builder.getValue(LoadCst);
5618   }
5619 
5620   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
5621   // still constant memory, the input chain can be the entry node.
5622   SDValue Root;
5623   bool ConstantMemory = false;
5624 
5625   // Do not serialize (non-volatile) loads of constant memory with anything.
5626   if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5627     Root = Builder.DAG.getEntryNode();
5628     ConstantMemory = true;
5629   } else {
5630     // Do not serialize non-volatile loads against each other.
5631     Root = Builder.DAG.getRoot();
5632   }
5633 
5634   SDValue Ptr = Builder.getValue(PtrVal);
5635   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5636                                         Ptr, MachinePointerInfo(PtrVal),
5637                                         false /*volatile*/,
5638                                         false /*nontemporal*/,
5639                                         false /*isinvariant*/, 1 /* align=1 */);
5640 
5641   if (!ConstantMemory)
5642     Builder.PendingLoads.push_back(LoadVal.getValue(1));
5643   return LoadVal;
5644 }
5645 
5646 /// processIntegerCallValue - Record the value for an instruction that
5647 /// produces an integer result, converting the type where necessary.
5648 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5649                                                   SDValue Value,
5650                                                   bool IsSigned) {
5651   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
5652                                                     I.getType(), true);
5653   if (IsSigned)
5654     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5655   else
5656     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5657   setValue(&I, Value);
5658 }
5659 
5660 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5661 /// If so, return true and lower it, otherwise return false and it will be
5662 /// lowered like a normal call.
5663 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5664   // Verify that the prototype makes sense.  int memcmp(void*,void*,size_t)
5665   if (I.getNumArgOperands() != 3)
5666     return false;
5667 
5668   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5669   if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5670       !I.getArgOperand(2)->getType()->isIntegerTy() ||
5671       !I.getType()->isIntegerTy())
5672     return false;
5673 
5674   const Value *Size = I.getArgOperand(2);
5675   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5676   if (CSize && CSize->getZExtValue() == 0) {
5677     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
5678                                                           I.getType(), true);
5679     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
5680     return true;
5681   }
5682 
5683   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5684   std::pair<SDValue, SDValue> Res =
5685     TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5686                                 getValue(LHS), getValue(RHS), getValue(Size),
5687                                 MachinePointerInfo(LHS),
5688                                 MachinePointerInfo(RHS));
5689   if (Res.first.getNode()) {
5690     processIntegerCallValue(I, Res.first, true);
5691     PendingLoads.push_back(Res.second);
5692     return true;
5693   }
5694 
5695   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
5696   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
5697   if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5698     bool ActuallyDoIt = true;
5699     MVT LoadVT;
5700     Type *LoadTy;
5701     switch (CSize->getZExtValue()) {
5702     default:
5703       LoadVT = MVT::Other;
5704       LoadTy = nullptr;
5705       ActuallyDoIt = false;
5706       break;
5707     case 2:
5708       LoadVT = MVT::i16;
5709       LoadTy = Type::getInt16Ty(CSize->getContext());
5710       break;
5711     case 4:
5712       LoadVT = MVT::i32;
5713       LoadTy = Type::getInt32Ty(CSize->getContext());
5714       break;
5715     case 8:
5716       LoadVT = MVT::i64;
5717       LoadTy = Type::getInt64Ty(CSize->getContext());
5718       break;
5719         /*
5720     case 16:
5721       LoadVT = MVT::v4i32;
5722       LoadTy = Type::getInt32Ty(CSize->getContext());
5723       LoadTy = VectorType::get(LoadTy, 4);
5724       break;
5725          */
5726     }
5727 
5728     // This turns into unaligned loads.  We only do this if the target natively
5729     // supports the MVT we'll be loading or if it is small enough (<= 4) that
5730     // we'll only produce a small number of byte loads.
5731 
5732     // Require that we can find a legal MVT, and only do this if the target
5733     // supports unaligned loads of that type.  Expanding into byte loads would
5734     // bloat the code.
5735     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5736     if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5737       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5738       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
5739       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5740       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5741       // TODO: Check alignment of src and dest ptrs.
5742       if (!TLI.isTypeLegal(LoadVT) ||
5743           !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
5744           !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
5745         ActuallyDoIt = false;
5746     }
5747 
5748     if (ActuallyDoIt) {
5749       SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5750       SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5751 
5752       SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5753                                  ISD::SETNE);
5754       processIntegerCallValue(I, Res, false);
5755       return true;
5756     }
5757   }
5758 
5759 
5760   return false;
5761 }
5762 
5763 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5764 /// form.  If so, return true and lower it, otherwise return false and it
5765 /// will be lowered like a normal call.
5766 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5767   // Verify that the prototype makes sense.  void *memchr(void *, int, size_t)
5768   if (I.getNumArgOperands() != 3)
5769     return false;
5770 
5771   const Value *Src = I.getArgOperand(0);
5772   const Value *Char = I.getArgOperand(1);
5773   const Value *Length = I.getArgOperand(2);
5774   if (!Src->getType()->isPointerTy() ||
5775       !Char->getType()->isIntegerTy() ||
5776       !Length->getType()->isIntegerTy() ||
5777       !I.getType()->isPointerTy())
5778     return false;
5779 
5780   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5781   std::pair<SDValue, SDValue> Res =
5782     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5783                                 getValue(Src), getValue(Char), getValue(Length),
5784                                 MachinePointerInfo(Src));
5785   if (Res.first.getNode()) {
5786     setValue(&I, Res.first);
5787     PendingLoads.push_back(Res.second);
5788     return true;
5789   }
5790 
5791   return false;
5792 }
5793 
5794 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5795 /// optimized form.  If so, return true and lower it, otherwise return false
5796 /// and it will be lowered like a normal call.
5797 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5798   // Verify that the prototype makes sense.  char *strcpy(char *, char *)
5799   if (I.getNumArgOperands() != 2)
5800     return false;
5801 
5802   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5803   if (!Arg0->getType()->isPointerTy() ||
5804       !Arg1->getType()->isPointerTy() ||
5805       !I.getType()->isPointerTy())
5806     return false;
5807 
5808   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5809   std::pair<SDValue, SDValue> Res =
5810     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5811                                 getValue(Arg0), getValue(Arg1),
5812                                 MachinePointerInfo(Arg0),
5813                                 MachinePointerInfo(Arg1), isStpcpy);
5814   if (Res.first.getNode()) {
5815     setValue(&I, Res.first);
5816     DAG.setRoot(Res.second);
5817     return true;
5818   }
5819 
5820   return false;
5821 }
5822 
5823 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5824 /// If so, return true and lower it, otherwise return false and it will be
5825 /// lowered like a normal call.
5826 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5827   // Verify that the prototype makes sense.  int strcmp(void*,void*)
5828   if (I.getNumArgOperands() != 2)
5829     return false;
5830 
5831   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5832   if (!Arg0->getType()->isPointerTy() ||
5833       !Arg1->getType()->isPointerTy() ||
5834       !I.getType()->isIntegerTy())
5835     return false;
5836 
5837   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5838   std::pair<SDValue, SDValue> Res =
5839     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5840                                 getValue(Arg0), getValue(Arg1),
5841                                 MachinePointerInfo(Arg0),
5842                                 MachinePointerInfo(Arg1));
5843   if (Res.first.getNode()) {
5844     processIntegerCallValue(I, Res.first, true);
5845     PendingLoads.push_back(Res.second);
5846     return true;
5847   }
5848 
5849   return false;
5850 }
5851 
5852 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5853 /// form.  If so, return true and lower it, otherwise return false and it
5854 /// will be lowered like a normal call.
5855 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5856   // Verify that the prototype makes sense.  size_t strlen(char *)
5857   if (I.getNumArgOperands() != 1)
5858     return false;
5859 
5860   const Value *Arg0 = I.getArgOperand(0);
5861   if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5862     return false;
5863 
5864   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5865   std::pair<SDValue, SDValue> Res =
5866     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5867                                 getValue(Arg0), MachinePointerInfo(Arg0));
5868   if (Res.first.getNode()) {
5869     processIntegerCallValue(I, Res.first, false);
5870     PendingLoads.push_back(Res.second);
5871     return true;
5872   }
5873 
5874   return false;
5875 }
5876 
5877 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5878 /// form.  If so, return true and lower it, otherwise return false and it
5879 /// will be lowered like a normal call.
5880 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5881   // Verify that the prototype makes sense.  size_t strnlen(char *, size_t)
5882   if (I.getNumArgOperands() != 2)
5883     return false;
5884 
5885   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5886   if (!Arg0->getType()->isPointerTy() ||
5887       !Arg1->getType()->isIntegerTy() ||
5888       !I.getType()->isIntegerTy())
5889     return false;
5890 
5891   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5892   std::pair<SDValue, SDValue> Res =
5893     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5894                                  getValue(Arg0), getValue(Arg1),
5895                                  MachinePointerInfo(Arg0));
5896   if (Res.first.getNode()) {
5897     processIntegerCallValue(I, Res.first, false);
5898     PendingLoads.push_back(Res.second);
5899     return true;
5900   }
5901 
5902   return false;
5903 }
5904 
5905 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
5906 /// operation (as expected), translate it to an SDNode with the specified opcode
5907 /// and return true.
5908 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5909                                               unsigned Opcode) {
5910   // Sanity check that it really is a unary floating-point call.
5911   if (I.getNumArgOperands() != 1 ||
5912       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5913       I.getType() != I.getArgOperand(0)->getType() ||
5914       !I.onlyReadsMemory())
5915     return false;
5916 
5917   SDValue Tmp = getValue(I.getArgOperand(0));
5918   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
5919   return true;
5920 }
5921 
5922 /// visitBinaryFloatCall - If a call instruction is a binary floating-point
5923 /// operation (as expected), translate it to an SDNode with the specified opcode
5924 /// and return true.
5925 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
5926                                                unsigned Opcode) {
5927   // Sanity check that it really is a binary floating-point call.
5928   if (I.getNumArgOperands() != 2 ||
5929       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5930       I.getType() != I.getArgOperand(0)->getType() ||
5931       I.getType() != I.getArgOperand(1)->getType() ||
5932       !I.onlyReadsMemory())
5933     return false;
5934 
5935   SDValue Tmp0 = getValue(I.getArgOperand(0));
5936   SDValue Tmp1 = getValue(I.getArgOperand(1));
5937   EVT VT = Tmp0.getValueType();
5938   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
5939   return true;
5940 }
5941 
5942 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5943   // Handle inline assembly differently.
5944   if (isa<InlineAsm>(I.getCalledValue())) {
5945     visitInlineAsm(&I);
5946     return;
5947   }
5948 
5949   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5950   ComputeUsesVAFloatArgument(I, &MMI);
5951 
5952   const char *RenameFn = nullptr;
5953   if (Function *F = I.getCalledFunction()) {
5954     if (F->isDeclaration()) {
5955       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5956         if (unsigned IID = II->getIntrinsicID(F)) {
5957           RenameFn = visitIntrinsicCall(I, IID);
5958           if (!RenameFn)
5959             return;
5960         }
5961       }
5962       if (Intrinsic::ID IID = F->getIntrinsicID()) {
5963         RenameFn = visitIntrinsicCall(I, IID);
5964         if (!RenameFn)
5965           return;
5966       }
5967     }
5968 
5969     // Check for well-known libc/libm calls.  If the function is internal, it
5970     // can't be a library call.
5971     LibFunc::Func Func;
5972     if (!F->hasLocalLinkage() && F->hasName() &&
5973         LibInfo->getLibFunc(F->getName(), Func) &&
5974         LibInfo->hasOptimizedCodeGen(Func)) {
5975       switch (Func) {
5976       default: break;
5977       case LibFunc::copysign:
5978       case LibFunc::copysignf:
5979       case LibFunc::copysignl:
5980         if (I.getNumArgOperands() == 2 &&   // Basic sanity checks.
5981             I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5982             I.getType() == I.getArgOperand(0)->getType() &&
5983             I.getType() == I.getArgOperand(1)->getType() &&
5984             I.onlyReadsMemory()) {
5985           SDValue LHS = getValue(I.getArgOperand(0));
5986           SDValue RHS = getValue(I.getArgOperand(1));
5987           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
5988                                    LHS.getValueType(), LHS, RHS));
5989           return;
5990         }
5991         break;
5992       case LibFunc::fabs:
5993       case LibFunc::fabsf:
5994       case LibFunc::fabsl:
5995         if (visitUnaryFloatCall(I, ISD::FABS))
5996           return;
5997         break;
5998       case LibFunc::fmin:
5999       case LibFunc::fminf:
6000       case LibFunc::fminl:
6001         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6002           return;
6003         break;
6004       case LibFunc::fmax:
6005       case LibFunc::fmaxf:
6006       case LibFunc::fmaxl:
6007         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6008           return;
6009         break;
6010       case LibFunc::sin:
6011       case LibFunc::sinf:
6012       case LibFunc::sinl:
6013         if (visitUnaryFloatCall(I, ISD::FSIN))
6014           return;
6015         break;
6016       case LibFunc::cos:
6017       case LibFunc::cosf:
6018       case LibFunc::cosl:
6019         if (visitUnaryFloatCall(I, ISD::FCOS))
6020           return;
6021         break;
6022       case LibFunc::sqrt:
6023       case LibFunc::sqrtf:
6024       case LibFunc::sqrtl:
6025       case LibFunc::sqrt_finite:
6026       case LibFunc::sqrtf_finite:
6027       case LibFunc::sqrtl_finite:
6028         if (visitUnaryFloatCall(I, ISD::FSQRT))
6029           return;
6030         break;
6031       case LibFunc::floor:
6032       case LibFunc::floorf:
6033       case LibFunc::floorl:
6034         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6035           return;
6036         break;
6037       case LibFunc::nearbyint:
6038       case LibFunc::nearbyintf:
6039       case LibFunc::nearbyintl:
6040         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6041           return;
6042         break;
6043       case LibFunc::ceil:
6044       case LibFunc::ceilf:
6045       case LibFunc::ceill:
6046         if (visitUnaryFloatCall(I, ISD::FCEIL))
6047           return;
6048         break;
6049       case LibFunc::rint:
6050       case LibFunc::rintf:
6051       case LibFunc::rintl:
6052         if (visitUnaryFloatCall(I, ISD::FRINT))
6053           return;
6054         break;
6055       case LibFunc::round:
6056       case LibFunc::roundf:
6057       case LibFunc::roundl:
6058         if (visitUnaryFloatCall(I, ISD::FROUND))
6059           return;
6060         break;
6061       case LibFunc::trunc:
6062       case LibFunc::truncf:
6063       case LibFunc::truncl:
6064         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6065           return;
6066         break;
6067       case LibFunc::log2:
6068       case LibFunc::log2f:
6069       case LibFunc::log2l:
6070         if (visitUnaryFloatCall(I, ISD::FLOG2))
6071           return;
6072         break;
6073       case LibFunc::exp2:
6074       case LibFunc::exp2f:
6075       case LibFunc::exp2l:
6076         if (visitUnaryFloatCall(I, ISD::FEXP2))
6077           return;
6078         break;
6079       case LibFunc::memcmp:
6080         if (visitMemCmpCall(I))
6081           return;
6082         break;
6083       case LibFunc::memchr:
6084         if (visitMemChrCall(I))
6085           return;
6086         break;
6087       case LibFunc::strcpy:
6088         if (visitStrCpyCall(I, false))
6089           return;
6090         break;
6091       case LibFunc::stpcpy:
6092         if (visitStrCpyCall(I, true))
6093           return;
6094         break;
6095       case LibFunc::strcmp:
6096         if (visitStrCmpCall(I))
6097           return;
6098         break;
6099       case LibFunc::strlen:
6100         if (visitStrLenCall(I))
6101           return;
6102         break;
6103       case LibFunc::strnlen:
6104         if (visitStrNLenCall(I))
6105           return;
6106         break;
6107       }
6108     }
6109   }
6110 
6111   SDValue Callee;
6112   if (!RenameFn)
6113     Callee = getValue(I.getCalledValue());
6114   else
6115     Callee = DAG.getExternalSymbol(
6116         RenameFn,
6117         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6118 
6119 #ifndef NDEBUG
6120   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
6121   // have to do anything here to lower funclet bundles.
6122   for (unsigned i = 0, e = I.getNumOperandBundles(); i != e; ++i)
6123     assert((I.getOperandBundleAt(i).isDeoptOperandBundle() ||
6124             I.getOperandBundleAt(i).isFuncletOperandBundle()) &&
6125            "Cannot lower calls with arbitrary operand bundles!");
6126 #endif
6127 
6128   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
6129     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
6130   else
6131     // Check if we can potentially perform a tail call. More detailed checking
6132     // is be done within LowerCallTo, after more information about the call is
6133     // known.
6134     LowerCallTo(&I, Callee, I.isTailCall());
6135 }
6136 
6137 namespace {
6138 
6139 /// AsmOperandInfo - This contains information for each constraint that we are
6140 /// lowering.
6141 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6142 public:
6143   /// CallOperand - If this is the result output operand or a clobber
6144   /// this is null, otherwise it is the incoming operand to the CallInst.
6145   /// This gets modified as the asm is processed.
6146   SDValue CallOperand;
6147 
6148   /// AssignedRegs - If this is a register or register class operand, this
6149   /// contains the set of register corresponding to the operand.
6150   RegsForValue AssignedRegs;
6151 
6152   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6153     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
6154   }
6155 
6156   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6157   /// corresponds to.  If there is no Value* for this operand, it returns
6158   /// MVT::Other.
6159   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
6160                            const DataLayout &DL) const {
6161     if (!CallOperandVal) return MVT::Other;
6162 
6163     if (isa<BasicBlock>(CallOperandVal))
6164       return TLI.getPointerTy(DL);
6165 
6166     llvm::Type *OpTy = CallOperandVal->getType();
6167 
6168     // FIXME: code duplicated from TargetLowering::ParseConstraints().
6169     // If this is an indirect operand, the operand is a pointer to the
6170     // accessed type.
6171     if (isIndirect) {
6172       llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6173       if (!PtrTy)
6174         report_fatal_error("Indirect operand for inline asm not a pointer!");
6175       OpTy = PtrTy->getElementType();
6176     }
6177 
6178     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6179     if (StructType *STy = dyn_cast<StructType>(OpTy))
6180       if (STy->getNumElements() == 1)
6181         OpTy = STy->getElementType(0);
6182 
6183     // If OpTy is not a single value, it may be a struct/union that we
6184     // can tile with integers.
6185     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6186       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6187       switch (BitSize) {
6188       default: break;
6189       case 1:
6190       case 8:
6191       case 16:
6192       case 32:
6193       case 64:
6194       case 128:
6195         OpTy = IntegerType::get(Context, BitSize);
6196         break;
6197       }
6198     }
6199 
6200     return TLI.getValueType(DL, OpTy, true);
6201   }
6202 };
6203 
6204 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6205 
6206 } // end anonymous namespace
6207 
6208 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6209 /// specified operand.  We prefer to assign virtual registers, to allow the
6210 /// register allocator to handle the assignment process.  However, if the asm
6211 /// uses features that we can't model on machineinstrs, we have SDISel do the
6212 /// allocation.  This produces generally horrible, but correct, code.
6213 ///
6214 ///   OpInfo describes the operand.
6215 ///
6216 static void GetRegistersForValue(SelectionDAG &DAG,
6217                                  const TargetLowering &TLI,
6218                                  SDLoc DL,
6219                                  SDISelAsmOperandInfo &OpInfo) {
6220   LLVMContext &Context = *DAG.getContext();
6221 
6222   MachineFunction &MF = DAG.getMachineFunction();
6223   SmallVector<unsigned, 4> Regs;
6224 
6225   // If this is a constraint for a single physreg, or a constraint for a
6226   // register class, find it.
6227   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
6228       TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(),
6229                                        OpInfo.ConstraintCode,
6230                                        OpInfo.ConstraintVT);
6231 
6232   unsigned NumRegs = 1;
6233   if (OpInfo.ConstraintVT != MVT::Other) {
6234     // If this is a FP input in an integer register (or visa versa) insert a bit
6235     // cast of the input value.  More generally, handle any case where the input
6236     // value disagrees with the register class we plan to stick this in.
6237     if (OpInfo.Type == InlineAsm::isInput &&
6238         PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
6239       // Try to convert to the first EVT that the reg class contains.  If the
6240       // types are identical size, use a bitcast to convert (e.g. two differing
6241       // vector types).
6242       MVT RegVT = *PhysReg.second->vt_begin();
6243       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
6244         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6245                                          RegVT, OpInfo.CallOperand);
6246         OpInfo.ConstraintVT = RegVT;
6247       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6248         // If the input is a FP value and we want it in FP registers, do a
6249         // bitcast to the corresponding integer type.  This turns an f64 value
6250         // into i64, which can be passed with two i32 values on a 32-bit
6251         // machine.
6252         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6253         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6254                                          RegVT, OpInfo.CallOperand);
6255         OpInfo.ConstraintVT = RegVT;
6256       }
6257     }
6258 
6259     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6260   }
6261 
6262   MVT RegVT;
6263   EVT ValueVT = OpInfo.ConstraintVT;
6264 
6265   // If this is a constraint for a specific physical register, like {r17},
6266   // assign it now.
6267   if (unsigned AssignedReg = PhysReg.first) {
6268     const TargetRegisterClass *RC = PhysReg.second;
6269     if (OpInfo.ConstraintVT == MVT::Other)
6270       ValueVT = *RC->vt_begin();
6271 
6272     // Get the actual register value type.  This is important, because the user
6273     // may have asked for (e.g.) the AX register in i32 type.  We need to
6274     // remember that AX is actually i16 to get the right extension.
6275     RegVT = *RC->vt_begin();
6276 
6277     // This is a explicit reference to a physical register.
6278     Regs.push_back(AssignedReg);
6279 
6280     // If this is an expanded reference, add the rest of the regs to Regs.
6281     if (NumRegs != 1) {
6282       TargetRegisterClass::iterator I = RC->begin();
6283       for (; *I != AssignedReg; ++I)
6284         assert(I != RC->end() && "Didn't find reg!");
6285 
6286       // Already added the first reg.
6287       --NumRegs; ++I;
6288       for (; NumRegs; --NumRegs, ++I) {
6289         assert(I != RC->end() && "Ran out of registers to allocate!");
6290         Regs.push_back(*I);
6291       }
6292     }
6293 
6294     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6295     return;
6296   }
6297 
6298   // Otherwise, if this was a reference to an LLVM register class, create vregs
6299   // for this reference.
6300   if (const TargetRegisterClass *RC = PhysReg.second) {
6301     RegVT = *RC->vt_begin();
6302     if (OpInfo.ConstraintVT == MVT::Other)
6303       ValueVT = RegVT;
6304 
6305     // Create the appropriate number of virtual registers.
6306     MachineRegisterInfo &RegInfo = MF.getRegInfo();
6307     for (; NumRegs; --NumRegs)
6308       Regs.push_back(RegInfo.createVirtualRegister(RC));
6309 
6310     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6311     return;
6312   }
6313 
6314   // Otherwise, we couldn't allocate enough registers for this.
6315 }
6316 
6317 /// visitInlineAsm - Handle a call to an InlineAsm object.
6318 ///
6319 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6320   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6321 
6322   /// ConstraintOperands - Information about all of the constraints.
6323   SDISelAsmOperandInfoVector ConstraintOperands;
6324 
6325   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6326   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
6327       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
6328 
6329   bool hasMemory = false;
6330 
6331   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
6332   unsigned ResNo = 0;   // ResNo - The result number of the next output.
6333   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6334     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
6335     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
6336 
6337     MVT OpVT = MVT::Other;
6338 
6339     // Compute the value type for each operand.
6340     switch (OpInfo.Type) {
6341     case InlineAsm::isOutput:
6342       // Indirect outputs just consume an argument.
6343       if (OpInfo.isIndirect) {
6344         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6345         break;
6346       }
6347 
6348       // The return value of the call is this value.  As such, there is no
6349       // corresponding argument.
6350       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6351       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
6352         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
6353                                       STy->getElementType(ResNo));
6354       } else {
6355         assert(ResNo == 0 && "Asm only has one result!");
6356         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
6357       }
6358       ++ResNo;
6359       break;
6360     case InlineAsm::isInput:
6361       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6362       break;
6363     case InlineAsm::isClobber:
6364       // Nothing to do.
6365       break;
6366     }
6367 
6368     // If this is an input or an indirect output, process the call argument.
6369     // BasicBlocks are labels, currently appearing only in asm's.
6370     if (OpInfo.CallOperandVal) {
6371       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
6372         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
6373       } else {
6374         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
6375       }
6376 
6377       OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
6378                                          DAG.getDataLayout()).getSimpleVT();
6379     }
6380 
6381     OpInfo.ConstraintVT = OpVT;
6382 
6383     // Indirect operand accesses access memory.
6384     if (OpInfo.isIndirect)
6385       hasMemory = true;
6386     else {
6387       for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
6388         TargetLowering::ConstraintType
6389           CType = TLI.getConstraintType(OpInfo.Codes[j]);
6390         if (CType == TargetLowering::C_Memory) {
6391           hasMemory = true;
6392           break;
6393         }
6394       }
6395     }
6396   }
6397 
6398   SDValue Chain, Flag;
6399 
6400   // We won't need to flush pending loads if this asm doesn't touch
6401   // memory and is nonvolatile.
6402   if (hasMemory || IA->hasSideEffects())
6403     Chain = getRoot();
6404   else
6405     Chain = DAG.getRoot();
6406 
6407   // Second pass over the constraints: compute which constraint option to use
6408   // and assign registers to constraints that want a specific physreg.
6409   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6410     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6411 
6412     // If this is an output operand with a matching input operand, look up the
6413     // matching input. If their types mismatch, e.g. one is an integer, the
6414     // other is floating point, or their sizes are different, flag it as an
6415     // error.
6416     if (OpInfo.hasMatchingInput()) {
6417       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6418 
6419       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6420         const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
6421         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6422             TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6423                                              OpInfo.ConstraintVT);
6424         std::pair<unsigned, const TargetRegisterClass *> InputRC =
6425             TLI.getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6426                                              Input.ConstraintVT);
6427         if ((OpInfo.ConstraintVT.isInteger() !=
6428              Input.ConstraintVT.isInteger()) ||
6429             (MatchRC.second != InputRC.second)) {
6430           report_fatal_error("Unsupported asm: input constraint"
6431                              " with a matching output constraint of"
6432                              " incompatible type!");
6433         }
6434         Input.ConstraintVT = OpInfo.ConstraintVT;
6435       }
6436     }
6437 
6438     // Compute the constraint code and ConstraintType to use.
6439     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
6440 
6441     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6442         OpInfo.Type == InlineAsm::isClobber)
6443       continue;
6444 
6445     // If this is a memory input, and if the operand is not indirect, do what we
6446     // need to to provide an address for the memory input.
6447     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6448         !OpInfo.isIndirect) {
6449       assert((OpInfo.isMultipleAlternative ||
6450               (OpInfo.Type == InlineAsm::isInput)) &&
6451              "Can only indirectify direct input operands!");
6452 
6453       // Memory operands really want the address of the value.  If we don't have
6454       // an indirect input, put it in the constpool if we can, otherwise spill
6455       // it to a stack slot.
6456       // TODO: This isn't quite right. We need to handle these according to
6457       // the addressing mode that the constraint wants. Also, this may take
6458       // an additional register for the computation and we don't want that
6459       // either.
6460 
6461       // If the operand is a float, integer, or vector constant, spill to a
6462       // constant pool entry to get its address.
6463       const Value *OpVal = OpInfo.CallOperandVal;
6464       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6465           isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6466         OpInfo.CallOperand = DAG.getConstantPool(
6467             cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
6468       } else {
6469         // Otherwise, create a stack slot and emit a store to it before the
6470         // asm.
6471         Type *Ty = OpVal->getType();
6472         auto &DL = DAG.getDataLayout();
6473         uint64_t TySize = DL.getTypeAllocSize(Ty);
6474         unsigned Align = DL.getPrefTypeAlignment(Ty);
6475         MachineFunction &MF = DAG.getMachineFunction();
6476         int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6477         SDValue StackSlot =
6478             DAG.getFrameIndex(SSFI, TLI.getPointerTy(DAG.getDataLayout()));
6479         Chain = DAG.getStore(
6480             Chain, getCurSDLoc(), OpInfo.CallOperand, StackSlot,
6481             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
6482             false, false, 0);
6483         OpInfo.CallOperand = StackSlot;
6484       }
6485 
6486       // There is no longer a Value* corresponding to this operand.
6487       OpInfo.CallOperandVal = nullptr;
6488 
6489       // It is now an indirect operand.
6490       OpInfo.isIndirect = true;
6491     }
6492 
6493     // If this constraint is for a specific register, allocate it before
6494     // anything else.
6495     if (OpInfo.ConstraintType == TargetLowering::C_Register)
6496       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6497   }
6498 
6499   // Second pass - Loop over all of the operands, assigning virtual or physregs
6500   // to register class operands.
6501   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6502     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6503 
6504     // C_Register operands have already been allocated, Other/Memory don't need
6505     // to be.
6506     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6507       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6508   }
6509 
6510   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6511   std::vector<SDValue> AsmNodeOperands;
6512   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
6513   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
6514       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
6515 
6516   // If we have a !srcloc metadata node associated with it, we want to attach
6517   // this to the ultimately generated inline asm machineinstr.  To do this, we
6518   // pass in the third operand as this (potentially null) inline asm MDNode.
6519   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6520   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6521 
6522   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6523   // bits as operand 3.
6524   unsigned ExtraInfo = 0;
6525   if (IA->hasSideEffects())
6526     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6527   if (IA->isAlignStack())
6528     ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6529   // Set the asm dialect.
6530   ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6531 
6532   // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6533   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6534     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6535 
6536     // Compute the constraint code and ConstraintType to use.
6537     TLI.ComputeConstraintToUse(OpInfo, SDValue());
6538 
6539     // Ideally, we would only check against memory constraints.  However, the
6540     // meaning of an other constraint can be target-specific and we can't easily
6541     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
6542     // for other constriants as well.
6543     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6544         OpInfo.ConstraintType == TargetLowering::C_Other) {
6545       if (OpInfo.Type == InlineAsm::isInput)
6546         ExtraInfo |= InlineAsm::Extra_MayLoad;
6547       else if (OpInfo.Type == InlineAsm::isOutput)
6548         ExtraInfo |= InlineAsm::Extra_MayStore;
6549       else if (OpInfo.Type == InlineAsm::isClobber)
6550         ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6551     }
6552   }
6553 
6554   AsmNodeOperands.push_back(DAG.getTargetConstant(
6555       ExtraInfo, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6556 
6557   // Loop over all of the inputs, copying the operand values into the
6558   // appropriate registers and processing the output regs.
6559   RegsForValue RetValRegs;
6560 
6561   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6562   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6563 
6564   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6565     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6566 
6567     switch (OpInfo.Type) {
6568     case InlineAsm::isOutput: {
6569       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6570           OpInfo.ConstraintType != TargetLowering::C_Register) {
6571         // Memory output, or 'other' output (e.g. 'X' constraint).
6572         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6573 
6574         unsigned ConstraintID =
6575             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6576         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6577                "Failed to convert memory constraint code to constraint id.");
6578 
6579         // Add information to the INLINEASM node to know about this output.
6580         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6581         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
6582         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
6583                                                         MVT::i32));
6584         AsmNodeOperands.push_back(OpInfo.CallOperand);
6585         break;
6586       }
6587 
6588       // Otherwise, this is a register or register class output.
6589 
6590       // Copy the output from the appropriate register.  Find a register that
6591       // we can use.
6592       if (OpInfo.AssignedRegs.Regs.empty()) {
6593         LLVMContext &Ctx = *DAG.getContext();
6594         Ctx.emitError(CS.getInstruction(),
6595                       "couldn't allocate output register for constraint '" +
6596                           Twine(OpInfo.ConstraintCode) + "'");
6597         return;
6598       }
6599 
6600       // If this is an indirect operand, store through the pointer after the
6601       // asm.
6602       if (OpInfo.isIndirect) {
6603         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6604                                                       OpInfo.CallOperandVal));
6605       } else {
6606         // This is the result value of the call.
6607         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6608         // Concatenate this output onto the outputs list.
6609         RetValRegs.append(OpInfo.AssignedRegs);
6610       }
6611 
6612       // Add information to the INLINEASM node to know that this register is
6613       // set.
6614       OpInfo.AssignedRegs
6615           .AddInlineAsmOperands(OpInfo.isEarlyClobber
6616                                     ? InlineAsm::Kind_RegDefEarlyClobber
6617                                     : InlineAsm::Kind_RegDef,
6618                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
6619       break;
6620     }
6621     case InlineAsm::isInput: {
6622       SDValue InOperandVal = OpInfo.CallOperand;
6623 
6624       if (OpInfo.isMatchingInputConstraint()) {   // Matching constraint?
6625         // If this is required to match an output register we have already set,
6626         // just use its register.
6627         unsigned OperandNo = OpInfo.getMatchedOperand();
6628 
6629         // Scan until we find the definition we already emitted of this operand.
6630         // When we find it, create a RegsForValue operand.
6631         unsigned CurOp = InlineAsm::Op_FirstOperand;
6632         for (; OperandNo; --OperandNo) {
6633           // Advance to the next operand.
6634           unsigned OpFlag =
6635             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6636           assert((InlineAsm::isRegDefKind(OpFlag) ||
6637                   InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6638                   InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6639           CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6640         }
6641 
6642         unsigned OpFlag =
6643           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6644         if (InlineAsm::isRegDefKind(OpFlag) ||
6645             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6646           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6647           if (OpInfo.isIndirect) {
6648             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6649             LLVMContext &Ctx = *DAG.getContext();
6650             Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6651                                                " don't know how to handle tied "
6652                                                "indirect register inputs");
6653             return;
6654           }
6655 
6656           RegsForValue MatchedRegs;
6657           MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6658           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6659           MatchedRegs.RegVTs.push_back(RegVT);
6660           MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6661           for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6662                i != e; ++i) {
6663             if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
6664               MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6665             else {
6666               LLVMContext &Ctx = *DAG.getContext();
6667               Ctx.emitError(CS.getInstruction(),
6668                             "inline asm error: This value"
6669                             " type register class is not natively supported!");
6670               return;
6671             }
6672           }
6673           SDLoc dl = getCurSDLoc();
6674           // Use the produced MatchedRegs object to
6675           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6676                                     Chain, &Flag, CS.getInstruction());
6677           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6678                                            true, OpInfo.getMatchedOperand(), dl,
6679                                            DAG, AsmNodeOperands);
6680           break;
6681         }
6682 
6683         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6684         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6685                "Unexpected number of operands");
6686         // Add information to the INLINEASM node to know about this input.
6687         // See InlineAsm.h isUseOperandTiedToDef.
6688         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
6689         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6690                                                     OpInfo.getMatchedOperand());
6691         AsmNodeOperands.push_back(DAG.getTargetConstant(
6692             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6693         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6694         break;
6695       }
6696 
6697       // Treat indirect 'X' constraint as memory.
6698       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6699           OpInfo.isIndirect)
6700         OpInfo.ConstraintType = TargetLowering::C_Memory;
6701 
6702       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6703         std::vector<SDValue> Ops;
6704         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6705                                           Ops, DAG);
6706         if (Ops.empty()) {
6707           LLVMContext &Ctx = *DAG.getContext();
6708           Ctx.emitError(CS.getInstruction(),
6709                         "invalid operand for inline asm constraint '" +
6710                             Twine(OpInfo.ConstraintCode) + "'");
6711           return;
6712         }
6713 
6714         // Add information to the INLINEASM node to know about this input.
6715         unsigned ResOpType =
6716           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6717         AsmNodeOperands.push_back(DAG.getTargetConstant(
6718             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6719         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6720         break;
6721       }
6722 
6723       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6724         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6725         assert(InOperandVal.getValueType() ==
6726                    TLI.getPointerTy(DAG.getDataLayout()) &&
6727                "Memory operands expect pointer values");
6728 
6729         unsigned ConstraintID =
6730             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6731         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6732                "Failed to convert memory constraint code to constraint id.");
6733 
6734         // Add information to the INLINEASM node to know about this input.
6735         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6736         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
6737         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6738                                                         getCurSDLoc(),
6739                                                         MVT::i32));
6740         AsmNodeOperands.push_back(InOperandVal);
6741         break;
6742       }
6743 
6744       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6745               OpInfo.ConstraintType == TargetLowering::C_Register) &&
6746              "Unknown constraint type!");
6747 
6748       // TODO: Support this.
6749       if (OpInfo.isIndirect) {
6750         LLVMContext &Ctx = *DAG.getContext();
6751         Ctx.emitError(CS.getInstruction(),
6752                       "Don't know how to handle indirect register inputs yet "
6753                       "for constraint '" +
6754                           Twine(OpInfo.ConstraintCode) + "'");
6755         return;
6756       }
6757 
6758       // Copy the input into the appropriate registers.
6759       if (OpInfo.AssignedRegs.Regs.empty()) {
6760         LLVMContext &Ctx = *DAG.getContext();
6761         Ctx.emitError(CS.getInstruction(),
6762                       "couldn't allocate input reg for constraint '" +
6763                           Twine(OpInfo.ConstraintCode) + "'");
6764         return;
6765       }
6766 
6767       SDLoc dl = getCurSDLoc();
6768 
6769       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6770                                         Chain, &Flag, CS.getInstruction());
6771 
6772       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6773                                                dl, DAG, AsmNodeOperands);
6774       break;
6775     }
6776     case InlineAsm::isClobber: {
6777       // Add the clobbered value to the operand list, so that the register
6778       // allocator is aware that the physreg got clobbered.
6779       if (!OpInfo.AssignedRegs.Regs.empty())
6780         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6781                                                  false, 0, getCurSDLoc(), DAG,
6782                                                  AsmNodeOperands);
6783       break;
6784     }
6785     }
6786   }
6787 
6788   // Finish up input operands.  Set the input chain and add the flag last.
6789   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6790   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6791 
6792   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6793                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
6794   Flag = Chain.getValue(1);
6795 
6796   // If this asm returns a register value, copy the result from that register
6797   // and set it as the value of the call.
6798   if (!RetValRegs.Regs.empty()) {
6799     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6800                                              Chain, &Flag, CS.getInstruction());
6801 
6802     // FIXME: Why don't we do this for inline asms with MRVs?
6803     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6804       EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
6805 
6806       // If any of the results of the inline asm is a vector, it may have the
6807       // wrong width/num elts.  This can happen for register classes that can
6808       // contain multiple different value types.  The preg or vreg allocated may
6809       // not have the same VT as was expected.  Convert it to the right type
6810       // with bit_convert.
6811       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6812         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6813                           ResultType, Val);
6814 
6815       } else if (ResultType != Val.getValueType() &&
6816                  ResultType.isInteger() && Val.getValueType().isInteger()) {
6817         // If a result value was tied to an input value, the computed result may
6818         // have a wider width than the expected result.  Extract the relevant
6819         // portion.
6820         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6821       }
6822 
6823       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6824     }
6825 
6826     setValue(CS.getInstruction(), Val);
6827     // Don't need to use this as a chain in this case.
6828     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6829       return;
6830   }
6831 
6832   std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6833 
6834   // Process indirect outputs, first output all of the flagged copies out of
6835   // physregs.
6836   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6837     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6838     const Value *Ptr = IndirectStoresToEmit[i].second;
6839     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6840                                              Chain, &Flag, IA);
6841     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6842   }
6843 
6844   // Emit the non-flagged stores from the physregs.
6845   SmallVector<SDValue, 8> OutChains;
6846   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6847     SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6848                                StoresToEmit[i].first,
6849                                getValue(StoresToEmit[i].second),
6850                                MachinePointerInfo(StoresToEmit[i].second),
6851                                false, false, 0);
6852     OutChains.push_back(Val);
6853   }
6854 
6855   if (!OutChains.empty())
6856     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
6857 
6858   DAG.setRoot(Chain);
6859 }
6860 
6861 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6862   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6863                           MVT::Other, getRoot(),
6864                           getValue(I.getArgOperand(0)),
6865                           DAG.getSrcValue(I.getArgOperand(0))));
6866 }
6867 
6868 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6870   const DataLayout &DL = DAG.getDataLayout();
6871   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6872                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
6873                            DAG.getSrcValue(I.getOperand(0)),
6874                            DL.getABITypeAlignment(I.getType()));
6875   setValue(&I, V);
6876   DAG.setRoot(V.getValue(1));
6877 }
6878 
6879 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6880   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6881                           MVT::Other, getRoot(),
6882                           getValue(I.getArgOperand(0)),
6883                           DAG.getSrcValue(I.getArgOperand(0))));
6884 }
6885 
6886 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6887   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6888                           MVT::Other, getRoot(),
6889                           getValue(I.getArgOperand(0)),
6890                           getValue(I.getArgOperand(1)),
6891                           DAG.getSrcValue(I.getArgOperand(0)),
6892                           DAG.getSrcValue(I.getArgOperand(1))));
6893 }
6894 
6895 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
6896                                                     const Instruction &I,
6897                                                     SDValue Op) {
6898   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
6899   if (!Range)
6900     return Op;
6901 
6902   Constant *Lo = cast<ConstantAsMetadata>(Range->getOperand(0))->getValue();
6903   if (!Lo->isNullValue())
6904     return Op;
6905 
6906   Constant *Hi = cast<ConstantAsMetadata>(Range->getOperand(1))->getValue();
6907   unsigned Bits = cast<ConstantInt>(Hi)->getValue().logBase2();
6908 
6909   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
6910 
6911   SDLoc SL = getCurSDLoc();
6912 
6913   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(),
6914                              Op, DAG.getValueType(SmallVT));
6915   unsigned NumVals = Op.getNode()->getNumValues();
6916   if (NumVals == 1)
6917     return ZExt;
6918 
6919   SmallVector<SDValue, 4> Ops;
6920 
6921   Ops.push_back(ZExt);
6922   for (unsigned I = 1; I != NumVals; ++I)
6923     Ops.push_back(Op.getValue(I));
6924 
6925   return DAG.getMergeValues(Ops, SL);
6926 }
6927 
6928 /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of
6929 /// the call being lowered.
6930 ///
6931 /// This is a helper for lowering intrinsics that follow a target calling
6932 /// convention or require stack pointer adjustment. Only a subset of the
6933 /// intrinsic's operands need to participate in the calling convention.
6934 void SelectionDAGBuilder::populateCallLoweringInfo(
6935     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
6936     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
6937     bool IsPatchPoint) {
6938   TargetLowering::ArgListTy Args;
6939   Args.reserve(NumArgs);
6940 
6941   // Populate the argument list.
6942   // Attributes for args start at offset 1, after the return attribute.
6943   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6944        ArgI != ArgE; ++ArgI) {
6945     const Value *V = CS->getOperand(ArgI);
6946 
6947     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6948 
6949     TargetLowering::ArgListEntry Entry;
6950     Entry.Node = getValue(V);
6951     Entry.Ty = V->getType();
6952     Entry.setAttributes(&CS, AttrI);
6953     Args.push_back(Entry);
6954   }
6955 
6956   CLI.setDebugLoc(getCurSDLoc())
6957       .setChain(getRoot())
6958       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args),
6959                  NumArgs)
6960       .setDiscardResult(CS->use_empty())
6961       .setIsPatchPoint(IsPatchPoint);
6962 }
6963 
6964 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6965 /// or patchpoint target node's operand list.
6966 ///
6967 /// Constants are converted to TargetConstants purely as an optimization to
6968 /// avoid constant materialization and register allocation.
6969 ///
6970 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6971 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
6972 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6973 /// address materialization and register allocation, but may also be required
6974 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6975 /// alloca in the entry block, then the runtime may assume that the alloca's
6976 /// StackMap location can be read immediately after compilation and that the
6977 /// location is valid at any point during execution (this is similar to the
6978 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6979 /// only available in a register, then the runtime would need to trap when
6980 /// execution reaches the StackMap in order to read the alloca's location.
6981 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
6982                                 SDLoc DL, SmallVectorImpl<SDValue> &Ops,
6983                                 SelectionDAGBuilder &Builder) {
6984   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
6985     SDValue OpVal = Builder.getValue(CS.getArgument(i));
6986     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6987       Ops.push_back(
6988         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
6989       Ops.push_back(
6990         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
6991     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6992       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6993       Ops.push_back(Builder.DAG.getTargetFrameIndex(
6994           FI->getIndex(), TLI.getPointerTy(Builder.DAG.getDataLayout())));
6995     } else
6996       Ops.push_back(OpVal);
6997   }
6998 }
6999 
7000 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
7001 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7002   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7003   //                                  [live variables...])
7004 
7005   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
7006 
7007   SDValue Chain, InFlag, Callee, NullPtr;
7008   SmallVector<SDValue, 32> Ops;
7009 
7010   SDLoc DL = getCurSDLoc();
7011   Callee = getValue(CI.getCalledValue());
7012   NullPtr = DAG.getIntPtrConstant(0, DL, true);
7013 
7014   // The stackmap intrinsic only records the live variables (the arguemnts
7015   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7016   // intrinsic, this won't be lowered to a function call. This means we don't
7017   // have to worry about calling conventions and target specific lowering code.
7018   // Instead we perform the call lowering right here.
7019   //
7020   // chain, flag = CALLSEQ_START(chain, 0)
7021   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7022   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7023   //
7024   Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
7025   InFlag = Chain.getValue(1);
7026 
7027   // Add the <id> and <numBytes> constants.
7028   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7029   Ops.push_back(DAG.getTargetConstant(
7030                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
7031   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7032   Ops.push_back(DAG.getTargetConstant(
7033                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
7034                   MVT::i32));
7035 
7036   // Push live variables for the stack map.
7037   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
7038 
7039   // We are not pushing any register mask info here on the operands list,
7040   // because the stackmap doesn't clobber anything.
7041 
7042   // Push the chain and the glue flag.
7043   Ops.push_back(Chain);
7044   Ops.push_back(InFlag);
7045 
7046   // Create the STACKMAP node.
7047   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7048   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7049   Chain = SDValue(SM, 0);
7050   InFlag = Chain.getValue(1);
7051 
7052   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7053 
7054   // Stackmaps don't generate values, so nothing goes into the NodeMap.
7055 
7056   // Set the root to the target-lowered call chain.
7057   DAG.setRoot(Chain);
7058 
7059   // Inform the Frame Information that we have a stackmap in this function.
7060   FuncInfo.MF->getFrameInfo()->setHasStackMap();
7061 }
7062 
7063 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
7064 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7065                                           const BasicBlock *EHPadBB) {
7066   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7067   //                                                 i32 <numBytes>,
7068   //                                                 i8* <target>,
7069   //                                                 i32 <numArgs>,
7070   //                                                 [Args...],
7071   //                                                 [live variables...])
7072 
7073   CallingConv::ID CC = CS.getCallingConv();
7074   bool IsAnyRegCC = CC == CallingConv::AnyReg;
7075   bool HasDef = !CS->getType()->isVoidTy();
7076   SDLoc dl = getCurSDLoc();
7077   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
7078 
7079   // Handle immediate and symbolic callees.
7080   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
7081     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
7082                                    /*isTarget=*/true);
7083   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
7084     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
7085                                          SDLoc(SymbolicCallee),
7086                                          SymbolicCallee->getValueType(0));
7087 
7088   // Get the real number of arguments participating in the call <numArgs>
7089   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7090   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7091 
7092   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7093   // Intrinsics include all meta-operands up to but not including CC.
7094   unsigned NumMetaOpers = PatchPointOpers::CCPos;
7095   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
7096          "Not enough arguments provided to the patchpoint intrinsic");
7097 
7098   // For AnyRegCC the arguments are lowered later on manually.
7099   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7100   Type *ReturnTy =
7101     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
7102 
7103   TargetLowering::CallLoweringInfo CLI(DAG);
7104   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
7105                            true);
7106   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7107 
7108   SDNode *CallEnd = Result.second.getNode();
7109   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7110     CallEnd = CallEnd->getOperand(0).getNode();
7111 
7112   /// Get a call instruction from the call sequence chain.
7113   /// Tail calls are not allowed.
7114   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7115          "Expected a callseq node.");
7116   SDNode *Call = CallEnd->getOperand(0).getNode();
7117   bool HasGlue = Call->getGluedNode();
7118 
7119   // Replace the target specific call node with the patchable intrinsic.
7120   SmallVector<SDValue, 8> Ops;
7121 
7122   // Add the <id> and <numBytes> constants.
7123   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
7124   Ops.push_back(DAG.getTargetConstant(
7125                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
7126   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
7127   Ops.push_back(DAG.getTargetConstant(
7128                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
7129                   MVT::i32));
7130 
7131   // Add the callee.
7132   Ops.push_back(Callee);
7133 
7134   // Adjust <numArgs> to account for any arguments that have been passed on the
7135   // stack instead.
7136   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7137   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7138   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
7139   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
7140 
7141   // Add the calling convention
7142   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
7143 
7144   // Add the arguments we omitted previously. The register allocator should
7145   // place these in any free register.
7146   if (IsAnyRegCC)
7147     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
7148       Ops.push_back(getValue(CS.getArgument(i)));
7149 
7150   // Push the arguments from the call instruction up to the register mask.
7151   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
7152   Ops.append(Call->op_begin() + 2, e);
7153 
7154   // Push live variables for the stack map.
7155   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
7156 
7157   // Push the register mask info.
7158   if (HasGlue)
7159     Ops.push_back(*(Call->op_end()-2));
7160   else
7161     Ops.push_back(*(Call->op_end()-1));
7162 
7163   // Push the chain (this is originally the first operand of the call, but
7164   // becomes now the last or second to last operand).
7165   Ops.push_back(*(Call->op_begin()));
7166 
7167   // Push the glue flag (last operand).
7168   if (HasGlue)
7169     Ops.push_back(*(Call->op_end()-1));
7170 
7171   SDVTList NodeTys;
7172   if (IsAnyRegCC && HasDef) {
7173     // Create the return types based on the intrinsic definition
7174     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7175     SmallVector<EVT, 3> ValueVTs;
7176     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7177     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
7178 
7179     // There is always a chain and a glue type at the end
7180     ValueVTs.push_back(MVT::Other);
7181     ValueVTs.push_back(MVT::Glue);
7182     NodeTys = DAG.getVTList(ValueVTs);
7183   } else
7184     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7185 
7186   // Replace the target specific call node with a PATCHPOINT node.
7187   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7188                                          dl, NodeTys, Ops);
7189 
7190   // Update the NodeMap.
7191   if (HasDef) {
7192     if (IsAnyRegCC)
7193       setValue(CS.getInstruction(), SDValue(MN, 0));
7194     else
7195       setValue(CS.getInstruction(), Result.first);
7196   }
7197 
7198   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7199   // call sequence. Furthermore the location of the chain and glue can change
7200   // when the AnyReg calling convention is used and the intrinsic returns a
7201   // value.
7202   if (IsAnyRegCC && HasDef) {
7203     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7204     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7205     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7206   } else
7207     DAG.ReplaceAllUsesWith(Call, MN);
7208   DAG.DeleteNode(Call);
7209 
7210   // Inform the Frame Information that we have a patchpoint in this function.
7211   FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
7212 }
7213 
7214 /// Returns an AttributeSet representing the attributes applied to the return
7215 /// value of the given call.
7216 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
7217   SmallVector<Attribute::AttrKind, 2> Attrs;
7218   if (CLI.RetSExt)
7219     Attrs.push_back(Attribute::SExt);
7220   if (CLI.RetZExt)
7221     Attrs.push_back(Attribute::ZExt);
7222   if (CLI.IsInReg)
7223     Attrs.push_back(Attribute::InReg);
7224 
7225   return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
7226                            Attrs);
7227 }
7228 
7229 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
7230 /// implementation, which just calls LowerCall.
7231 /// FIXME: When all targets are
7232 /// migrated to using LowerCall, this hook should be integrated into SDISel.
7233 std::pair<SDValue, SDValue>
7234 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
7235   // Handle the incoming return values from the call.
7236   CLI.Ins.clear();
7237   Type *OrigRetTy = CLI.RetTy;
7238   SmallVector<EVT, 4> RetTys;
7239   SmallVector<uint64_t, 4> Offsets;
7240   auto &DL = CLI.DAG.getDataLayout();
7241   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
7242 
7243   SmallVector<ISD::OutputArg, 4> Outs;
7244   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
7245 
7246   bool CanLowerReturn =
7247       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
7248                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
7249 
7250   SDValue DemoteStackSlot;
7251   int DemoteStackIdx = -100;
7252   if (!CanLowerReturn) {
7253     // FIXME: equivalent assert?
7254     // assert(!CS.hasInAllocaArgument() &&
7255     //        "sret demotion is incompatible with inalloca");
7256     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
7257     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
7258     MachineFunction &MF = CLI.DAG.getMachineFunction();
7259     DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
7260     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
7261 
7262     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy(DL));
7263     ArgListEntry Entry;
7264     Entry.Node = DemoteStackSlot;
7265     Entry.Ty = StackSlotPtrType;
7266     Entry.isSExt = false;
7267     Entry.isZExt = false;
7268     Entry.isInReg = false;
7269     Entry.isSRet = true;
7270     Entry.isNest = false;
7271     Entry.isByVal = false;
7272     Entry.isReturned = false;
7273     Entry.Alignment = Align;
7274     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
7275     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
7276 
7277     // sret demotion isn't compatible with tail-calls, since the sret argument
7278     // points into the callers stack frame.
7279     CLI.IsTailCall = false;
7280   } else {
7281     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7282       EVT VT = RetTys[I];
7283       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7284       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7285       for (unsigned i = 0; i != NumRegs; ++i) {
7286         ISD::InputArg MyFlags;
7287         MyFlags.VT = RegisterVT;
7288         MyFlags.ArgVT = VT;
7289         MyFlags.Used = CLI.IsReturnValueUsed;
7290         if (CLI.RetSExt)
7291           MyFlags.Flags.setSExt();
7292         if (CLI.RetZExt)
7293           MyFlags.Flags.setZExt();
7294         if (CLI.IsInReg)
7295           MyFlags.Flags.setInReg();
7296         CLI.Ins.push_back(MyFlags);
7297       }
7298     }
7299   }
7300 
7301   // Handle all of the outgoing arguments.
7302   CLI.Outs.clear();
7303   CLI.OutVals.clear();
7304   ArgListTy &Args = CLI.getArgs();
7305   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
7306     SmallVector<EVT, 4> ValueVTs;
7307     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
7308     Type *FinalType = Args[i].Ty;
7309     if (Args[i].isByVal)
7310       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
7311     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
7312         FinalType, CLI.CallConv, CLI.IsVarArg);
7313     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
7314          ++Value) {
7315       EVT VT = ValueVTs[Value];
7316       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
7317       SDValue Op = SDValue(Args[i].Node.getNode(),
7318                            Args[i].Node.getResNo() + Value);
7319       ISD::ArgFlagsTy Flags;
7320       unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
7321 
7322       if (Args[i].isZExt)
7323         Flags.setZExt();
7324       if (Args[i].isSExt)
7325         Flags.setSExt();
7326       if (Args[i].isInReg)
7327         Flags.setInReg();
7328       if (Args[i].isSRet)
7329         Flags.setSRet();
7330       if (Args[i].isByVal)
7331         Flags.setByVal();
7332       if (Args[i].isInAlloca) {
7333         Flags.setInAlloca();
7334         // Set the byval flag for CCAssignFn callbacks that don't know about
7335         // inalloca.  This way we can know how many bytes we should've allocated
7336         // and how many bytes a callee cleanup function will pop.  If we port
7337         // inalloca to more targets, we'll have to add custom inalloca handling
7338         // in the various CC lowering callbacks.
7339         Flags.setByVal();
7340       }
7341       if (Args[i].isByVal || Args[i].isInAlloca) {
7342         PointerType *Ty = cast<PointerType>(Args[i].Ty);
7343         Type *ElementTy = Ty->getElementType();
7344         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
7345         // For ByVal, alignment should come from FE.  BE will guess if this
7346         // info is not there but there are cases it cannot get right.
7347         unsigned FrameAlign;
7348         if (Args[i].Alignment)
7349           FrameAlign = Args[i].Alignment;
7350         else
7351           FrameAlign = getByValTypeAlignment(ElementTy, DL);
7352         Flags.setByValAlign(FrameAlign);
7353       }
7354       if (Args[i].isNest)
7355         Flags.setNest();
7356       if (NeedsRegBlock)
7357         Flags.setInConsecutiveRegs();
7358       Flags.setOrigAlign(OriginalAlignment);
7359 
7360       MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
7361       unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
7362       SmallVector<SDValue, 4> Parts(NumParts);
7363       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7364 
7365       if (Args[i].isSExt)
7366         ExtendKind = ISD::SIGN_EXTEND;
7367       else if (Args[i].isZExt)
7368         ExtendKind = ISD::ZERO_EXTEND;
7369 
7370       // Conservatively only handle 'returned' on non-vectors for now
7371       if (Args[i].isReturned && !Op.getValueType().isVector()) {
7372         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7373                "unexpected use of 'returned'");
7374         // Before passing 'returned' to the target lowering code, ensure that
7375         // either the register MVT and the actual EVT are the same size or that
7376         // the return value and argument are extended in the same way; in these
7377         // cases it's safe to pass the argument register value unchanged as the
7378         // return register value (although it's at the target's option whether
7379         // to do so)
7380         // TODO: allow code generation to take advantage of partially preserved
7381         // registers rather than clobbering the entire register when the
7382         // parameter extension method is not compatible with the return
7383         // extension method
7384         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7385             (ExtendKind != ISD::ANY_EXTEND &&
7386              CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7387         Flags.setReturned();
7388       }
7389 
7390       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
7391                      CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
7392 
7393       for (unsigned j = 0; j != NumParts; ++j) {
7394         // if it isn't first piece, alignment must be 1
7395         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
7396                                i < CLI.NumFixedArgs,
7397                                i, j*Parts[j].getValueType().getStoreSize());
7398         if (NumParts > 1 && j == 0)
7399           MyFlags.Flags.setSplit();
7400         else if (j != 0) {
7401           MyFlags.Flags.setOrigAlign(1);
7402           if (j == NumParts - 1)
7403             MyFlags.Flags.setSplitEnd();
7404         }
7405 
7406         CLI.Outs.push_back(MyFlags);
7407         CLI.OutVals.push_back(Parts[j]);
7408       }
7409 
7410       if (NeedsRegBlock && Value == NumValues - 1)
7411         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
7412     }
7413   }
7414 
7415   SmallVector<SDValue, 4> InVals;
7416   CLI.Chain = LowerCall(CLI, InVals);
7417 
7418   // Verify that the target's LowerCall behaved as expected.
7419   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
7420          "LowerCall didn't return a valid chain!");
7421   assert((!CLI.IsTailCall || InVals.empty()) &&
7422          "LowerCall emitted a return value for a tail call!");
7423   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
7424          "LowerCall didn't emit the correct number of values!");
7425 
7426   // For a tail call, the return value is merely live-out and there aren't
7427   // any nodes in the DAG representing it. Return a special value to
7428   // indicate that a tail call has been emitted and no more Instructions
7429   // should be processed in the current block.
7430   if (CLI.IsTailCall) {
7431     CLI.DAG.setRoot(CLI.Chain);
7432     return std::make_pair(SDValue(), SDValue());
7433   }
7434 
7435   DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
7436           assert(InVals[i].getNode() &&
7437                  "LowerCall emitted a null value!");
7438           assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
7439                  "LowerCall emitted a value with the wrong type!");
7440         });
7441 
7442   SmallVector<SDValue, 4> ReturnValues;
7443   if (!CanLowerReturn) {
7444     // The instruction result is the result of loading from the
7445     // hidden sret parameter.
7446     SmallVector<EVT, 1> PVTs;
7447     Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
7448 
7449     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
7450     assert(PVTs.size() == 1 && "Pointers should fit in one register");
7451     EVT PtrVT = PVTs[0];
7452 
7453     unsigned NumValues = RetTys.size();
7454     ReturnValues.resize(NumValues);
7455     SmallVector<SDValue, 4> Chains(NumValues);
7456 
7457     // An aggregate return value cannot wrap around the address space, so
7458     // offsets to its parts don't wrap either.
7459     SDNodeFlags Flags;
7460     Flags.setNoUnsignedWrap(true);
7461 
7462     for (unsigned i = 0; i < NumValues; ++i) {
7463       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
7464                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
7465                                                         PtrVT), &Flags);
7466       SDValue L = CLI.DAG.getLoad(
7467           RetTys[i], CLI.DL, CLI.Chain, Add,
7468           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
7469                                             DemoteStackIdx, Offsets[i]),
7470           false, false, false, 1);
7471       ReturnValues[i] = L;
7472       Chains[i] = L.getValue(1);
7473     }
7474 
7475     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
7476   } else {
7477     // Collect the legal value parts into potentially illegal values
7478     // that correspond to the original function's return values.
7479     ISD::NodeType AssertOp = ISD::DELETED_NODE;
7480     if (CLI.RetSExt)
7481       AssertOp = ISD::AssertSext;
7482     else if (CLI.RetZExt)
7483       AssertOp = ISD::AssertZext;
7484     unsigned CurReg = 0;
7485     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7486       EVT VT = RetTys[I];
7487       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7488       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7489 
7490       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7491                                               NumRegs, RegisterVT, VT, nullptr,
7492                                               AssertOp));
7493       CurReg += NumRegs;
7494     }
7495 
7496     // For a function returning void, there is no return value. We can't create
7497     // such a node, so we just return a null return value in that case. In
7498     // that case, nothing will actually look at the value.
7499     if (ReturnValues.empty())
7500       return std::make_pair(SDValue(), CLI.Chain);
7501   }
7502 
7503   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7504                                 CLI.DAG.getVTList(RetTys), ReturnValues);
7505   return std::make_pair(Res, CLI.Chain);
7506 }
7507 
7508 void TargetLowering::LowerOperationWrapper(SDNode *N,
7509                                            SmallVectorImpl<SDValue> &Results,
7510                                            SelectionDAG &DAG) const {
7511   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
7512     Results.push_back(Res);
7513 }
7514 
7515 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7516   llvm_unreachable("LowerOperation not implemented for this target!");
7517 }
7518 
7519 void
7520 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
7521   SDValue Op = getNonRegisterValue(V);
7522   assert((Op.getOpcode() != ISD::CopyFromReg ||
7523           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7524          "Copy from a reg to the same reg!");
7525   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7526 
7527   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7528   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
7529                    V->getType());
7530   SDValue Chain = DAG.getEntryNode();
7531 
7532   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
7533                               FuncInfo.PreferredExtendType.end())
7534                                  ? ISD::ANY_EXTEND
7535                                  : FuncInfo.PreferredExtendType[V];
7536   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
7537   PendingExports.push_back(Chain);
7538 }
7539 
7540 #include "llvm/CodeGen/SelectionDAGISel.h"
7541 
7542 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7543 /// entry block, return true.  This includes arguments used by switches, since
7544 /// the switch may expand into multiple basic blocks.
7545 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7546   // With FastISel active, we may be splitting blocks, so force creation
7547   // of virtual registers for all non-dead arguments.
7548   if (FastISel)
7549     return A->use_empty();
7550 
7551   const BasicBlock &Entry = A->getParent()->front();
7552   for (const User *U : A->users())
7553     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
7554       return false;  // Use not in entry block.
7555 
7556   return true;
7557 }
7558 
7559 void SelectionDAGISel::LowerArguments(const Function &F) {
7560   SelectionDAG &DAG = SDB->DAG;
7561   SDLoc dl = SDB->getCurSDLoc();
7562   const DataLayout &DL = DAG.getDataLayout();
7563   SmallVector<ISD::InputArg, 16> Ins;
7564 
7565   if (!FuncInfo->CanLowerReturn) {
7566     // Put in an sret pointer parameter before all the other parameters.
7567     SmallVector<EVT, 1> ValueVTs;
7568     ComputeValueVTs(*TLI, DAG.getDataLayout(),
7569                     PointerType::getUnqual(F.getReturnType()), ValueVTs);
7570 
7571     // NOTE: Assuming that a pointer will never break down to more than one VT
7572     // or one register.
7573     ISD::ArgFlagsTy Flags;
7574     Flags.setSRet();
7575     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7576     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
7577                          ISD::InputArg::NoArgIndex, 0);
7578     Ins.push_back(RetArg);
7579   }
7580 
7581   // Set up the incoming argument description vector.
7582   unsigned Idx = 1;
7583   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7584        I != E; ++I, ++Idx) {
7585     SmallVector<EVT, 4> ValueVTs;
7586     ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
7587     bool isArgValueUsed = !I->use_empty();
7588     unsigned PartBase = 0;
7589     Type *FinalType = I->getType();
7590     if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7591       FinalType = cast<PointerType>(FinalType)->getElementType();
7592     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
7593         FinalType, F.getCallingConv(), F.isVarArg());
7594     for (unsigned Value = 0, NumValues = ValueVTs.size();
7595          Value != NumValues; ++Value) {
7596       EVT VT = ValueVTs[Value];
7597       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7598       ISD::ArgFlagsTy Flags;
7599       unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
7600 
7601       if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7602         Flags.setZExt();
7603       if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7604         Flags.setSExt();
7605       if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7606         Flags.setInReg();
7607       if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7608         Flags.setSRet();
7609       if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7610         Flags.setByVal();
7611       if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7612         Flags.setInAlloca();
7613         // Set the byval flag for CCAssignFn callbacks that don't know about
7614         // inalloca.  This way we can know how many bytes we should've allocated
7615         // and how many bytes a callee cleanup function will pop.  If we port
7616         // inalloca to more targets, we'll have to add custom inalloca handling
7617         // in the various CC lowering callbacks.
7618         Flags.setByVal();
7619       }
7620       if (F.getCallingConv() == CallingConv::X86_INTR) {
7621         // IA Interrupt passes frame (1st parameter) by value in the stack.
7622         if (Idx == 1)
7623           Flags.setByVal();
7624       }
7625       if (Flags.isByVal() || Flags.isInAlloca()) {
7626         PointerType *Ty = cast<PointerType>(I->getType());
7627         Type *ElementTy = Ty->getElementType();
7628         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
7629         // For ByVal, alignment should be passed from FE.  BE will guess if
7630         // this info is not there but there are cases it cannot get right.
7631         unsigned FrameAlign;
7632         if (F.getParamAlignment(Idx))
7633           FrameAlign = F.getParamAlignment(Idx);
7634         else
7635           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
7636         Flags.setByValAlign(FrameAlign);
7637       }
7638       if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7639         Flags.setNest();
7640       if (NeedsRegBlock)
7641         Flags.setInConsecutiveRegs();
7642       Flags.setOrigAlign(OriginalAlignment);
7643 
7644       MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7645       unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7646       for (unsigned i = 0; i != NumRegs; ++i) {
7647         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7648                               Idx-1, PartBase+i*RegisterVT.getStoreSize());
7649         if (NumRegs > 1 && i == 0)
7650           MyFlags.Flags.setSplit();
7651         // if it isn't first piece, alignment must be 1
7652         else if (i > 0) {
7653           MyFlags.Flags.setOrigAlign(1);
7654           if (i == NumRegs - 1)
7655             MyFlags.Flags.setSplitEnd();
7656         }
7657         Ins.push_back(MyFlags);
7658       }
7659       if (NeedsRegBlock && Value == NumValues - 1)
7660         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
7661       PartBase += VT.getStoreSize();
7662     }
7663   }
7664 
7665   // Call the target to set up the argument values.
7666   SmallVector<SDValue, 8> InVals;
7667   SDValue NewRoot = TLI->LowerFormalArguments(
7668       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
7669 
7670   // Verify that the target's LowerFormalArguments behaved as expected.
7671   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7672          "LowerFormalArguments didn't return a valid chain!");
7673   assert(InVals.size() == Ins.size() &&
7674          "LowerFormalArguments didn't emit the correct number of values!");
7675   DEBUG({
7676       for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7677         assert(InVals[i].getNode() &&
7678                "LowerFormalArguments emitted a null value!");
7679         assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7680                "LowerFormalArguments emitted a value with the wrong type!");
7681       }
7682     });
7683 
7684   // Update the DAG with the new chain value resulting from argument lowering.
7685   DAG.setRoot(NewRoot);
7686 
7687   // Set up the argument values.
7688   unsigned i = 0;
7689   Idx = 1;
7690   if (!FuncInfo->CanLowerReturn) {
7691     // Create a virtual register for the sret pointer, and put in a copy
7692     // from the sret argument into it.
7693     SmallVector<EVT, 1> ValueVTs;
7694     ComputeValueVTs(*TLI, DAG.getDataLayout(),
7695                     PointerType::getUnqual(F.getReturnType()), ValueVTs);
7696     MVT VT = ValueVTs[0].getSimpleVT();
7697     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7698     ISD::NodeType AssertOp = ISD::DELETED_NODE;
7699     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7700                                         RegVT, VT, nullptr, AssertOp);
7701 
7702     MachineFunction& MF = SDB->DAG.getMachineFunction();
7703     MachineRegisterInfo& RegInfo = MF.getRegInfo();
7704     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7705     FuncInfo->DemoteRegister = SRetReg;
7706     NewRoot =
7707         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
7708     DAG.setRoot(NewRoot);
7709 
7710     // i indexes lowered arguments.  Bump it past the hidden sret argument.
7711     // Idx indexes LLVM arguments.  Don't touch it.
7712     ++i;
7713   }
7714 
7715   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7716       ++I, ++Idx) {
7717     SmallVector<SDValue, 4> ArgValues;
7718     SmallVector<EVT, 4> ValueVTs;
7719     ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
7720     unsigned NumValues = ValueVTs.size();
7721 
7722     // If this argument is unused then remember its value. It is used to generate
7723     // debugging information.
7724     if (I->use_empty() && NumValues) {
7725       SDB->setUnusedArgValue(&*I, InVals[i]);
7726 
7727       // Also remember any frame index for use in FastISel.
7728       if (FrameIndexSDNode *FI =
7729           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7730         FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
7731     }
7732 
7733     for (unsigned Val = 0; Val != NumValues; ++Val) {
7734       EVT VT = ValueVTs[Val];
7735       MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7736       unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7737 
7738       if (!I->use_empty()) {
7739         ISD::NodeType AssertOp = ISD::DELETED_NODE;
7740         if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7741           AssertOp = ISD::AssertSext;
7742         else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7743           AssertOp = ISD::AssertZext;
7744 
7745         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7746                                              NumParts, PartVT, VT,
7747                                              nullptr, AssertOp));
7748       }
7749 
7750       i += NumParts;
7751     }
7752 
7753     // We don't need to do anything else for unused arguments.
7754     if (ArgValues.empty())
7755       continue;
7756 
7757     // Note down frame index.
7758     if (FrameIndexSDNode *FI =
7759         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7760       FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
7761 
7762     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
7763                                      SDB->getCurSDLoc());
7764 
7765     SDB->setValue(&*I, Res);
7766     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7767       if (LoadSDNode *LNode =
7768           dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7769         if (FrameIndexSDNode *FI =
7770             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7771         FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
7772     }
7773 
7774     // If this argument is live outside of the entry block, insert a copy from
7775     // wherever we got it to the vreg that other BB's will reference it as.
7776     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7777       // If we can, though, try to skip creating an unnecessary vreg.
7778       // FIXME: This isn't very clean... it would be nice to make this more
7779       // general.  It's also subtly incompatible with the hacks FastISel
7780       // uses with vregs.
7781       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7782       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7783         FuncInfo->ValueMap[&*I] = Reg;
7784         continue;
7785       }
7786     }
7787     if (!isOnlyUsedInEntryBlock(&*I, TM.Options.EnableFastISel)) {
7788       FuncInfo->InitializeRegForValue(&*I);
7789       SDB->CopyToExportRegsIfNeeded(&*I);
7790     }
7791   }
7792 
7793   assert(i == InVals.size() && "Argument register count mismatch!");
7794 
7795   // Finally, if the target has anything special to do, allow it to do so.
7796   EmitFunctionEntryCode();
7797 }
7798 
7799 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
7800 /// ensure constants are generated when needed.  Remember the virtual registers
7801 /// that need to be added to the Machine PHI nodes as input.  We cannot just
7802 /// directly add them, because expansion might result in multiple MBB's for one
7803 /// BB.  As such, the start of the BB might correspond to a different MBB than
7804 /// the end.
7805 ///
7806 void
7807 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7808   const TerminatorInst *TI = LLVMBB->getTerminator();
7809 
7810   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7811 
7812   // Check PHI nodes in successors that expect a value to be available from this
7813   // block.
7814   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7815     const BasicBlock *SuccBB = TI->getSuccessor(succ);
7816     if (!isa<PHINode>(SuccBB->begin())) continue;
7817     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7818 
7819     // If this terminator has multiple identical successors (common for
7820     // switches), only handle each succ once.
7821     if (!SuccsHandled.insert(SuccMBB).second)
7822       continue;
7823 
7824     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7825 
7826     // At this point we know that there is a 1-1 correspondence between LLVM PHI
7827     // nodes and Machine PHI nodes, but the incoming operands have not been
7828     // emitted yet.
7829     for (BasicBlock::const_iterator I = SuccBB->begin();
7830          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7831       // Ignore dead phi's.
7832       if (PN->use_empty()) continue;
7833 
7834       // Skip empty types
7835       if (PN->getType()->isEmptyTy())
7836         continue;
7837 
7838       unsigned Reg;
7839       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7840 
7841       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7842         unsigned &RegOut = ConstantsOut[C];
7843         if (RegOut == 0) {
7844           RegOut = FuncInfo.CreateRegs(C->getType());
7845           CopyValueToVirtualRegister(C, RegOut);
7846         }
7847         Reg = RegOut;
7848       } else {
7849         DenseMap<const Value *, unsigned>::iterator I =
7850           FuncInfo.ValueMap.find(PHIOp);
7851         if (I != FuncInfo.ValueMap.end())
7852           Reg = I->second;
7853         else {
7854           assert(isa<AllocaInst>(PHIOp) &&
7855                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7856                  "Didn't codegen value into a register!??");
7857           Reg = FuncInfo.CreateRegs(PHIOp->getType());
7858           CopyValueToVirtualRegister(PHIOp, Reg);
7859         }
7860       }
7861 
7862       // Remember that this register needs to added to the machine PHI node as
7863       // the input for this MBB.
7864       SmallVector<EVT, 4> ValueVTs;
7865       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7866       ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs);
7867       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7868         EVT VT = ValueVTs[vti];
7869         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
7870         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7871           FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7872         Reg += NumRegisters;
7873       }
7874     }
7875   }
7876 
7877   ConstantsOut.clear();
7878 }
7879 
7880 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7881 /// is 0.
7882 MachineBasicBlock *
7883 SelectionDAGBuilder::StackProtectorDescriptor::
7884 AddSuccessorMBB(const BasicBlock *BB,
7885                 MachineBasicBlock *ParentMBB,
7886                 bool IsLikely,
7887                 MachineBasicBlock *SuccMBB) {
7888   // If SuccBB has not been created yet, create it.
7889   if (!SuccMBB) {
7890     MachineFunction *MF = ParentMBB->getParent();
7891     MachineFunction::iterator BBI(ParentMBB);
7892     SuccMBB = MF->CreateMachineBasicBlock(BB);
7893     MF->insert(++BBI, SuccMBB);
7894   }
7895   // Add it as a successor of ParentMBB.
7896   ParentMBB->addSuccessor(
7897       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
7898   return SuccMBB;
7899 }
7900 
7901 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
7902   MachineFunction::iterator I(MBB);
7903   if (++I == FuncInfo.MF->end())
7904     return nullptr;
7905   return &*I;
7906 }
7907 
7908 /// During lowering new call nodes can be created (such as memset, etc.).
7909 /// Those will become new roots of the current DAG, but complications arise
7910 /// when they are tail calls. In such cases, the call lowering will update
7911 /// the root, but the builder still needs to know that a tail call has been
7912 /// lowered in order to avoid generating an additional return.
7913 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
7914   // If the node is null, we do have a tail call.
7915   if (MaybeTC.getNode() != nullptr)
7916     DAG.setRoot(MaybeTC);
7917   else
7918     HasTailCall = true;
7919 }
7920 
7921 bool SelectionDAGBuilder::isDense(const CaseClusterVector &Clusters,
7922                                   unsigned *TotalCases, unsigned First,
7923                                   unsigned Last) {
7924   assert(Last >= First);
7925   assert(TotalCases[Last] >= TotalCases[First]);
7926 
7927   APInt LowCase = Clusters[First].Low->getValue();
7928   APInt HighCase = Clusters[Last].High->getValue();
7929   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
7930 
7931   // FIXME: A range of consecutive cases has 100% density, but only requires one
7932   // comparison to lower. We should discriminate against such consecutive ranges
7933   // in jump tables.
7934 
7935   uint64_t Diff = (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100);
7936   uint64_t Range = Diff + 1;
7937 
7938   uint64_t NumCases =
7939       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
7940 
7941   assert(NumCases < UINT64_MAX / 100);
7942   assert(Range >= NumCases);
7943 
7944   return NumCases * 100 >= Range * MinJumpTableDensity;
7945 }
7946 
7947 static inline bool areJTsAllowed(const TargetLowering &TLI) {
7948   return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
7949          TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
7950 }
7951 
7952 bool SelectionDAGBuilder::buildJumpTable(CaseClusterVector &Clusters,
7953                                          unsigned First, unsigned Last,
7954                                          const SwitchInst *SI,
7955                                          MachineBasicBlock *DefaultMBB,
7956                                          CaseCluster &JTCluster) {
7957   assert(First <= Last);
7958 
7959   auto Prob = BranchProbability::getZero();
7960   unsigned NumCmps = 0;
7961   std::vector<MachineBasicBlock*> Table;
7962   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
7963 
7964   // Initialize probabilities in JTProbs.
7965   for (unsigned I = First; I <= Last; ++I)
7966     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
7967 
7968   for (unsigned I = First; I <= Last; ++I) {
7969     assert(Clusters[I].Kind == CC_Range);
7970     Prob += Clusters[I].Prob;
7971     APInt Low = Clusters[I].Low->getValue();
7972     APInt High = Clusters[I].High->getValue();
7973     NumCmps += (Low == High) ? 1 : 2;
7974     if (I != First) {
7975       // Fill the gap between this and the previous cluster.
7976       APInt PreviousHigh = Clusters[I - 1].High->getValue();
7977       assert(PreviousHigh.slt(Low));
7978       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
7979       for (uint64_t J = 0; J < Gap; J++)
7980         Table.push_back(DefaultMBB);
7981     }
7982     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
7983     for (uint64_t J = 0; J < ClusterSize; ++J)
7984       Table.push_back(Clusters[I].MBB);
7985     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
7986   }
7987 
7988   unsigned NumDests = JTProbs.size();
7989   if (isSuitableForBitTests(NumDests, NumCmps,
7990                             Clusters[First].Low->getValue(),
7991                             Clusters[Last].High->getValue())) {
7992     // Clusters[First..Last] should be lowered as bit tests instead.
7993     return false;
7994   }
7995 
7996   // Create the MBB that will load from and jump through the table.
7997   // Note: We create it here, but it's not inserted into the function yet.
7998   MachineFunction *CurMF = FuncInfo.MF;
7999   MachineBasicBlock *JumpTableMBB =
8000       CurMF->CreateMachineBasicBlock(SI->getParent());
8001 
8002   // Add successors. Note: use table order for determinism.
8003   SmallPtrSet<MachineBasicBlock *, 8> Done;
8004   for (MachineBasicBlock *Succ : Table) {
8005     if (Done.count(Succ))
8006       continue;
8007     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
8008     Done.insert(Succ);
8009   }
8010   JumpTableMBB->normalizeSuccProbs();
8011 
8012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8013   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
8014                      ->createJumpTableIndex(Table);
8015 
8016   // Set up the jump table info.
8017   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
8018   JumpTableHeader JTH(Clusters[First].Low->getValue(),
8019                       Clusters[Last].High->getValue(), SI->getCondition(),
8020                       nullptr, false);
8021   JTCases.emplace_back(std::move(JTH), std::move(JT));
8022 
8023   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
8024                                      JTCases.size() - 1, Prob);
8025   return true;
8026 }
8027 
8028 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
8029                                          const SwitchInst *SI,
8030                                          MachineBasicBlock *DefaultMBB) {
8031 #ifndef NDEBUG
8032   // Clusters must be non-empty, sorted, and only contain Range clusters.
8033   assert(!Clusters.empty());
8034   for (CaseCluster &C : Clusters)
8035     assert(C.Kind == CC_Range);
8036   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
8037     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
8038 #endif
8039 
8040   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8041   if (!areJTsAllowed(TLI))
8042     return;
8043 
8044   const int64_t N = Clusters.size();
8045   const unsigned MinJumpTableSize = TLI.getMinimumJumpTableEntries();
8046 
8047   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
8048   SmallVector<unsigned, 8> TotalCases(N);
8049 
8050   for (unsigned i = 0; i < N; ++i) {
8051     APInt Hi = Clusters[i].High->getValue();
8052     APInt Lo = Clusters[i].Low->getValue();
8053     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
8054     if (i != 0)
8055       TotalCases[i] += TotalCases[i - 1];
8056   }
8057 
8058   if (N >= MinJumpTableSize && isDense(Clusters, &TotalCases[0], 0, N - 1)) {
8059     // Cheap case: the whole range might be suitable for jump table.
8060     CaseCluster JTCluster;
8061     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
8062       Clusters[0] = JTCluster;
8063       Clusters.resize(1);
8064       return;
8065     }
8066   }
8067 
8068   // The algorithm below is not suitable for -O0.
8069   if (TM.getOptLevel() == CodeGenOpt::None)
8070     return;
8071 
8072   // Split Clusters into minimum number of dense partitions. The algorithm uses
8073   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
8074   // for the Case Statement'" (1994), but builds the MinPartitions array in
8075   // reverse order to make it easier to reconstruct the partitions in ascending
8076   // order. In the choice between two optimal partitionings, it picks the one
8077   // which yields more jump tables.
8078 
8079   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
8080   SmallVector<unsigned, 8> MinPartitions(N);
8081   // LastElement[i] is the last element of the partition starting at i.
8082   SmallVector<unsigned, 8> LastElement(N);
8083   // NumTables[i]: nbr of >= MinJumpTableSize partitions from Clusters[i..N-1].
8084   SmallVector<unsigned, 8> NumTables(N);
8085 
8086   // Base case: There is only one way to partition Clusters[N-1].
8087   MinPartitions[N - 1] = 1;
8088   LastElement[N - 1] = N - 1;
8089   assert(MinJumpTableSize > 1);
8090   NumTables[N - 1] = 0;
8091 
8092   // Note: loop indexes are signed to avoid underflow.
8093   for (int64_t i = N - 2; i >= 0; i--) {
8094     // Find optimal partitioning of Clusters[i..N-1].
8095     // Baseline: Put Clusters[i] into a partition on its own.
8096     MinPartitions[i] = MinPartitions[i + 1] + 1;
8097     LastElement[i] = i;
8098     NumTables[i] = NumTables[i + 1];
8099 
8100     // Search for a solution that results in fewer partitions.
8101     for (int64_t j = N - 1; j > i; j--) {
8102       // Try building a partition from Clusters[i..j].
8103       if (isDense(Clusters, &TotalCases[0], i, j)) {
8104         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
8105         bool IsTable = j - i + 1 >= MinJumpTableSize;
8106         unsigned Tables = IsTable + (j == N - 1 ? 0 : NumTables[j + 1]);
8107 
8108         // If this j leads to fewer partitions, or same number of partitions
8109         // with more lookup tables, it is a better partitioning.
8110         if (NumPartitions < MinPartitions[i] ||
8111             (NumPartitions == MinPartitions[i] && Tables > NumTables[i])) {
8112           MinPartitions[i] = NumPartitions;
8113           LastElement[i] = j;
8114           NumTables[i] = Tables;
8115         }
8116       }
8117     }
8118   }
8119 
8120   // Iterate over the partitions, replacing some with jump tables in-place.
8121   unsigned DstIndex = 0;
8122   for (unsigned First = 0, Last; First < N; First = Last + 1) {
8123     Last = LastElement[First];
8124     assert(Last >= First);
8125     assert(DstIndex <= First);
8126     unsigned NumClusters = Last - First + 1;
8127 
8128     CaseCluster JTCluster;
8129     if (NumClusters >= MinJumpTableSize &&
8130         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
8131       Clusters[DstIndex++] = JTCluster;
8132     } else {
8133       for (unsigned I = First; I <= Last; ++I)
8134         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
8135     }
8136   }
8137   Clusters.resize(DstIndex);
8138 }
8139 
8140 bool SelectionDAGBuilder::rangeFitsInWord(const APInt &Low, const APInt &High) {
8141   // FIXME: Using the pointer type doesn't seem ideal.
8142   uint64_t BW = DAG.getDataLayout().getPointerSizeInBits();
8143   uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
8144   return Range <= BW;
8145 }
8146 
8147 bool SelectionDAGBuilder::isSuitableForBitTests(unsigned NumDests,
8148                                                 unsigned NumCmps,
8149                                                 const APInt &Low,
8150                                                 const APInt &High) {
8151   // FIXME: I don't think NumCmps is the correct metric: a single case and a
8152   // range of cases both require only one branch to lower. Just looking at the
8153   // number of clusters and destinations should be enough to decide whether to
8154   // build bit tests.
8155 
8156   // To lower a range with bit tests, the range must fit the bitwidth of a
8157   // machine word.
8158   if (!rangeFitsInWord(Low, High))
8159     return false;
8160 
8161   // Decide whether it's profitable to lower this range with bit tests. Each
8162   // destination requires a bit test and branch, and there is an overall range
8163   // check branch. For a small number of clusters, separate comparisons might be
8164   // cheaper, and for many destinations, splitting the range might be better.
8165   return (NumDests == 1 && NumCmps >= 3) ||
8166          (NumDests == 2 && NumCmps >= 5) ||
8167          (NumDests == 3 && NumCmps >= 6);
8168 }
8169 
8170 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
8171                                         unsigned First, unsigned Last,
8172                                         const SwitchInst *SI,
8173                                         CaseCluster &BTCluster) {
8174   assert(First <= Last);
8175   if (First == Last)
8176     return false;
8177 
8178   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
8179   unsigned NumCmps = 0;
8180   for (int64_t I = First; I <= Last; ++I) {
8181     assert(Clusters[I].Kind == CC_Range);
8182     Dests.set(Clusters[I].MBB->getNumber());
8183     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
8184   }
8185   unsigned NumDests = Dests.count();
8186 
8187   APInt Low = Clusters[First].Low->getValue();
8188   APInt High = Clusters[Last].High->getValue();
8189   assert(Low.slt(High));
8190 
8191   if (!isSuitableForBitTests(NumDests, NumCmps, Low, High))
8192     return false;
8193 
8194   APInt LowBound;
8195   APInt CmpRange;
8196 
8197   const int BitWidth = DAG.getTargetLoweringInfo()
8198                            .getPointerTy(DAG.getDataLayout())
8199                            .getSizeInBits();
8200   assert(rangeFitsInWord(Low, High) && "Case range must fit in bit mask!");
8201 
8202   // Check if the clusters cover a contiguous range such that no value in the
8203   // range will jump to the default statement.
8204   bool ContiguousRange = true;
8205   for (int64_t I = First + 1; I <= Last; ++I) {
8206     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
8207       ContiguousRange = false;
8208       break;
8209     }
8210   }
8211 
8212   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
8213     // Optimize the case where all the case values fit in a word without having
8214     // to subtract minValue. In this case, we can optimize away the subtraction.
8215     LowBound = APInt::getNullValue(Low.getBitWidth());
8216     CmpRange = High;
8217     ContiguousRange = false;
8218   } else {
8219     LowBound = Low;
8220     CmpRange = High - Low;
8221   }
8222 
8223   CaseBitsVector CBV;
8224   auto TotalProb = BranchProbability::getZero();
8225   for (unsigned i = First; i <= Last; ++i) {
8226     // Find the CaseBits for this destination.
8227     unsigned j;
8228     for (j = 0; j < CBV.size(); ++j)
8229       if (CBV[j].BB == Clusters[i].MBB)
8230         break;
8231     if (j == CBV.size())
8232       CBV.push_back(
8233           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
8234     CaseBits *CB = &CBV[j];
8235 
8236     // Update Mask, Bits and ExtraProb.
8237     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
8238     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
8239     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
8240     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
8241     CB->Bits += Hi - Lo + 1;
8242     CB->ExtraProb += Clusters[i].Prob;
8243     TotalProb += Clusters[i].Prob;
8244   }
8245 
8246   BitTestInfo BTI;
8247   std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
8248     // Sort by probability first, number of bits second.
8249     if (a.ExtraProb != b.ExtraProb)
8250       return a.ExtraProb > b.ExtraProb;
8251     return a.Bits > b.Bits;
8252   });
8253 
8254   for (auto &CB : CBV) {
8255     MachineBasicBlock *BitTestBB =
8256         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
8257     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
8258   }
8259   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
8260                             SI->getCondition(), -1U, MVT::Other, false,
8261                             ContiguousRange, nullptr, nullptr, std::move(BTI),
8262                             TotalProb);
8263 
8264   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
8265                                     BitTestCases.size() - 1, TotalProb);
8266   return true;
8267 }
8268 
8269 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
8270                                               const SwitchInst *SI) {
8271 // Partition Clusters into as few subsets as possible, where each subset has a
8272 // range that fits in a machine word and has <= 3 unique destinations.
8273 
8274 #ifndef NDEBUG
8275   // Clusters must be sorted and contain Range or JumpTable clusters.
8276   assert(!Clusters.empty());
8277   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
8278   for (const CaseCluster &C : Clusters)
8279     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
8280   for (unsigned i = 1; i < Clusters.size(); ++i)
8281     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
8282 #endif
8283 
8284   // The algorithm below is not suitable for -O0.
8285   if (TM.getOptLevel() == CodeGenOpt::None)
8286     return;
8287 
8288   // If target does not have legal shift left, do not emit bit tests at all.
8289   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8290   EVT PTy = TLI.getPointerTy(DAG.getDataLayout());
8291   if (!TLI.isOperationLegal(ISD::SHL, PTy))
8292     return;
8293 
8294   int BitWidth = PTy.getSizeInBits();
8295   const int64_t N = Clusters.size();
8296 
8297   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
8298   SmallVector<unsigned, 8> MinPartitions(N);
8299   // LastElement[i] is the last element of the partition starting at i.
8300   SmallVector<unsigned, 8> LastElement(N);
8301 
8302   // FIXME: This might not be the best algorithm for finding bit test clusters.
8303 
8304   // Base case: There is only one way to partition Clusters[N-1].
8305   MinPartitions[N - 1] = 1;
8306   LastElement[N - 1] = N - 1;
8307 
8308   // Note: loop indexes are signed to avoid underflow.
8309   for (int64_t i = N - 2; i >= 0; --i) {
8310     // Find optimal partitioning of Clusters[i..N-1].
8311     // Baseline: Put Clusters[i] into a partition on its own.
8312     MinPartitions[i] = MinPartitions[i + 1] + 1;
8313     LastElement[i] = i;
8314 
8315     // Search for a solution that results in fewer partitions.
8316     // Note: the search is limited by BitWidth, reducing time complexity.
8317     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
8318       // Try building a partition from Clusters[i..j].
8319 
8320       // Check the range.
8321       if (!rangeFitsInWord(Clusters[i].Low->getValue(),
8322                            Clusters[j].High->getValue()))
8323         continue;
8324 
8325       // Check nbr of destinations and cluster types.
8326       // FIXME: This works, but doesn't seem very efficient.
8327       bool RangesOnly = true;
8328       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
8329       for (int64_t k = i; k <= j; k++) {
8330         if (Clusters[k].Kind != CC_Range) {
8331           RangesOnly = false;
8332           break;
8333         }
8334         Dests.set(Clusters[k].MBB->getNumber());
8335       }
8336       if (!RangesOnly || Dests.count() > 3)
8337         break;
8338 
8339       // Check if it's a better partition.
8340       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
8341       if (NumPartitions < MinPartitions[i]) {
8342         // Found a better partition.
8343         MinPartitions[i] = NumPartitions;
8344         LastElement[i] = j;
8345       }
8346     }
8347   }
8348 
8349   // Iterate over the partitions, replacing with bit-test clusters in-place.
8350   unsigned DstIndex = 0;
8351   for (unsigned First = 0, Last; First < N; First = Last + 1) {
8352     Last = LastElement[First];
8353     assert(First <= Last);
8354     assert(DstIndex <= First);
8355 
8356     CaseCluster BitTestCluster;
8357     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
8358       Clusters[DstIndex++] = BitTestCluster;
8359     } else {
8360       size_t NumClusters = Last - First + 1;
8361       std::memmove(&Clusters[DstIndex], &Clusters[First],
8362                    sizeof(Clusters[0]) * NumClusters);
8363       DstIndex += NumClusters;
8364     }
8365   }
8366   Clusters.resize(DstIndex);
8367 }
8368 
8369 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
8370                                         MachineBasicBlock *SwitchMBB,
8371                                         MachineBasicBlock *DefaultMBB) {
8372   MachineFunction *CurMF = FuncInfo.MF;
8373   MachineBasicBlock *NextMBB = nullptr;
8374   MachineFunction::iterator BBI(W.MBB);
8375   if (++BBI != FuncInfo.MF->end())
8376     NextMBB = &*BBI;
8377 
8378   unsigned Size = W.LastCluster - W.FirstCluster + 1;
8379 
8380   BranchProbabilityInfo *BPI = FuncInfo.BPI;
8381 
8382   if (Size == 2 && W.MBB == SwitchMBB) {
8383     // If any two of the cases has the same destination, and if one value
8384     // is the same as the other, but has one bit unset that the other has set,
8385     // use bit manipulation to do two compares at once.  For example:
8386     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
8387     // TODO: This could be extended to merge any 2 cases in switches with 3
8388     // cases.
8389     // TODO: Handle cases where W.CaseBB != SwitchBB.
8390     CaseCluster &Small = *W.FirstCluster;
8391     CaseCluster &Big = *W.LastCluster;
8392 
8393     if (Small.Low == Small.High && Big.Low == Big.High &&
8394         Small.MBB == Big.MBB) {
8395       const APInt &SmallValue = Small.Low->getValue();
8396       const APInt &BigValue = Big.Low->getValue();
8397 
8398       // Check that there is only one bit different.
8399       APInt CommonBit = BigValue ^ SmallValue;
8400       if (CommonBit.isPowerOf2()) {
8401         SDValue CondLHS = getValue(Cond);
8402         EVT VT = CondLHS.getValueType();
8403         SDLoc DL = getCurSDLoc();
8404 
8405         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
8406                                  DAG.getConstant(CommonBit, DL, VT));
8407         SDValue Cond = DAG.getSetCC(
8408             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
8409             ISD::SETEQ);
8410 
8411         // Update successor info.
8412         // Both Small and Big will jump to Small.BB, so we sum up the
8413         // probabilities.
8414         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
8415         if (BPI)
8416           addSuccessorWithProb(
8417               SwitchMBB, DefaultMBB,
8418               // The default destination is the first successor in IR.
8419               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
8420         else
8421           addSuccessorWithProb(SwitchMBB, DefaultMBB);
8422 
8423         // Insert the true branch.
8424         SDValue BrCond =
8425             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
8426                         DAG.getBasicBlock(Small.MBB));
8427         // Insert the false branch.
8428         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
8429                              DAG.getBasicBlock(DefaultMBB));
8430 
8431         DAG.setRoot(BrCond);
8432         return;
8433       }
8434     }
8435   }
8436 
8437   if (TM.getOptLevel() != CodeGenOpt::None) {
8438     // Order cases by probability so the most likely case will be checked first.
8439     std::sort(W.FirstCluster, W.LastCluster + 1,
8440               [](const CaseCluster &a, const CaseCluster &b) {
8441       return a.Prob > b.Prob;
8442     });
8443 
8444     // Rearrange the case blocks so that the last one falls through if possible
8445     // without without changing the order of probabilities.
8446     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
8447       --I;
8448       if (I->Prob > W.LastCluster->Prob)
8449         break;
8450       if (I->Kind == CC_Range && I->MBB == NextMBB) {
8451         std::swap(*I, *W.LastCluster);
8452         break;
8453       }
8454     }
8455   }
8456 
8457   // Compute total probability.
8458   BranchProbability DefaultProb = W.DefaultProb;
8459   BranchProbability UnhandledProbs = DefaultProb;
8460   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
8461     UnhandledProbs += I->Prob;
8462 
8463   MachineBasicBlock *CurMBB = W.MBB;
8464   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
8465     MachineBasicBlock *Fallthrough;
8466     if (I == W.LastCluster) {
8467       // For the last cluster, fall through to the default destination.
8468       Fallthrough = DefaultMBB;
8469     } else {
8470       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
8471       CurMF->insert(BBI, Fallthrough);
8472       // Put Cond in a virtual register to make it available from the new blocks.
8473       ExportFromCurrentBlock(Cond);
8474     }
8475     UnhandledProbs -= I->Prob;
8476 
8477     switch (I->Kind) {
8478       case CC_JumpTable: {
8479         // FIXME: Optimize away range check based on pivot comparisons.
8480         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
8481         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
8482 
8483         // The jump block hasn't been inserted yet; insert it here.
8484         MachineBasicBlock *JumpMBB = JT->MBB;
8485         CurMF->insert(BBI, JumpMBB);
8486 
8487         auto JumpProb = I->Prob;
8488         auto FallthroughProb = UnhandledProbs;
8489 
8490         // If the default statement is a target of the jump table, we evenly
8491         // distribute the default probability to successors of CurMBB. Also
8492         // update the probability on the edge from JumpMBB to Fallthrough.
8493         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
8494                                               SE = JumpMBB->succ_end();
8495              SI != SE; ++SI) {
8496           if (*SI == DefaultMBB) {
8497             JumpProb += DefaultProb / 2;
8498             FallthroughProb -= DefaultProb / 2;
8499             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
8500             JumpMBB->normalizeSuccProbs();
8501             break;
8502           }
8503         }
8504 
8505         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
8506         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
8507         CurMBB->normalizeSuccProbs();
8508 
8509         // The jump table header will be inserted in our current block, do the
8510         // range check, and fall through to our fallthrough block.
8511         JTH->HeaderBB = CurMBB;
8512         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
8513 
8514         // If we're in the right place, emit the jump table header right now.
8515         if (CurMBB == SwitchMBB) {
8516           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
8517           JTH->Emitted = true;
8518         }
8519         break;
8520       }
8521       case CC_BitTests: {
8522         // FIXME: Optimize away range check based on pivot comparisons.
8523         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
8524 
8525         // The bit test blocks haven't been inserted yet; insert them here.
8526         for (BitTestCase &BTC : BTB->Cases)
8527           CurMF->insert(BBI, BTC.ThisBB);
8528 
8529         // Fill in fields of the BitTestBlock.
8530         BTB->Parent = CurMBB;
8531         BTB->Default = Fallthrough;
8532 
8533         BTB->DefaultProb = UnhandledProbs;
8534         // If the cases in bit test don't form a contiguous range, we evenly
8535         // distribute the probability on the edge to Fallthrough to two
8536         // successors of CurMBB.
8537         if (!BTB->ContiguousRange) {
8538           BTB->Prob += DefaultProb / 2;
8539           BTB->DefaultProb -= DefaultProb / 2;
8540         }
8541 
8542         // If we're in the right place, emit the bit test header right now.
8543         if (CurMBB == SwitchMBB) {
8544           visitBitTestHeader(*BTB, SwitchMBB);
8545           BTB->Emitted = true;
8546         }
8547         break;
8548       }
8549       case CC_Range: {
8550         const Value *RHS, *LHS, *MHS;
8551         ISD::CondCode CC;
8552         if (I->Low == I->High) {
8553           // Check Cond == I->Low.
8554           CC = ISD::SETEQ;
8555           LHS = Cond;
8556           RHS=I->Low;
8557           MHS = nullptr;
8558         } else {
8559           // Check I->Low <= Cond <= I->High.
8560           CC = ISD::SETLE;
8561           LHS = I->Low;
8562           MHS = Cond;
8563           RHS = I->High;
8564         }
8565 
8566         // The false probability is the sum of all unhandled cases.
8567         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Prob,
8568                      UnhandledProbs);
8569 
8570         if (CurMBB == SwitchMBB)
8571           visitSwitchCase(CB, SwitchMBB);
8572         else
8573           SwitchCases.push_back(CB);
8574 
8575         break;
8576       }
8577     }
8578     CurMBB = Fallthrough;
8579   }
8580 }
8581 
8582 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
8583                                               CaseClusterIt First,
8584                                               CaseClusterIt Last) {
8585   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
8586     if (X.Prob != CC.Prob)
8587       return X.Prob > CC.Prob;
8588 
8589     // Ties are broken by comparing the case value.
8590     return X.Low->getValue().slt(CC.Low->getValue());
8591   });
8592 }
8593 
8594 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
8595                                         const SwitchWorkListItem &W,
8596                                         Value *Cond,
8597                                         MachineBasicBlock *SwitchMBB) {
8598   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
8599          "Clusters not sorted?");
8600 
8601   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
8602 
8603   // Balance the tree based on branch probabilities to create a near-optimal (in
8604   // terms of search time given key frequency) binary search tree. See e.g. Kurt
8605   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
8606   CaseClusterIt LastLeft = W.FirstCluster;
8607   CaseClusterIt FirstRight = W.LastCluster;
8608   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
8609   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
8610 
8611   // Move LastLeft and FirstRight towards each other from opposite directions to
8612   // find a partitioning of the clusters which balances the probability on both
8613   // sides. If LeftProb and RightProb are equal, alternate which side is
8614   // taken to ensure 0-probability nodes are distributed evenly.
8615   unsigned I = 0;
8616   while (LastLeft + 1 < FirstRight) {
8617     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
8618       LeftProb += (++LastLeft)->Prob;
8619     else
8620       RightProb += (--FirstRight)->Prob;
8621     I++;
8622   }
8623 
8624   for (;;) {
8625     // Our binary search tree differs from a typical BST in that ours can have up
8626     // to three values in each leaf. The pivot selection above doesn't take that
8627     // into account, which means the tree might require more nodes and be less
8628     // efficient. We compensate for this here.
8629 
8630     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
8631     unsigned NumRight = W.LastCluster - FirstRight + 1;
8632 
8633     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
8634       // If one side has less than 3 clusters, and the other has more than 3,
8635       // consider taking a cluster from the other side.
8636 
8637       if (NumLeft < NumRight) {
8638         // Consider moving the first cluster on the right to the left side.
8639         CaseCluster &CC = *FirstRight;
8640         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
8641         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
8642         if (LeftSideRank <= RightSideRank) {
8643           // Moving the cluster to the left does not demote it.
8644           ++LastLeft;
8645           ++FirstRight;
8646           continue;
8647         }
8648       } else {
8649         assert(NumRight < NumLeft);
8650         // Consider moving the last element on the left to the right side.
8651         CaseCluster &CC = *LastLeft;
8652         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
8653         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
8654         if (RightSideRank <= LeftSideRank) {
8655           // Moving the cluster to the right does not demot it.
8656           --LastLeft;
8657           --FirstRight;
8658           continue;
8659         }
8660       }
8661     }
8662     break;
8663   }
8664 
8665   assert(LastLeft + 1 == FirstRight);
8666   assert(LastLeft >= W.FirstCluster);
8667   assert(FirstRight <= W.LastCluster);
8668 
8669   // Use the first element on the right as pivot since we will make less-than
8670   // comparisons against it.
8671   CaseClusterIt PivotCluster = FirstRight;
8672   assert(PivotCluster > W.FirstCluster);
8673   assert(PivotCluster <= W.LastCluster);
8674 
8675   CaseClusterIt FirstLeft = W.FirstCluster;
8676   CaseClusterIt LastRight = W.LastCluster;
8677 
8678   const ConstantInt *Pivot = PivotCluster->Low;
8679 
8680   // New blocks will be inserted immediately after the current one.
8681   MachineFunction::iterator BBI(W.MBB);
8682   ++BBI;
8683 
8684   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
8685   // we can branch to its destination directly if it's squeezed exactly in
8686   // between the known lower bound and Pivot - 1.
8687   MachineBasicBlock *LeftMBB;
8688   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
8689       FirstLeft->Low == W.GE &&
8690       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
8691     LeftMBB = FirstLeft->MBB;
8692   } else {
8693     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8694     FuncInfo.MF->insert(BBI, LeftMBB);
8695     WorkList.push_back(
8696         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
8697     // Put Cond in a virtual register to make it available from the new blocks.
8698     ExportFromCurrentBlock(Cond);
8699   }
8700 
8701   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
8702   // single cluster, RHS.Low == Pivot, and we can branch to its destination
8703   // directly if RHS.High equals the current upper bound.
8704   MachineBasicBlock *RightMBB;
8705   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
8706       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
8707     RightMBB = FirstRight->MBB;
8708   } else {
8709     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8710     FuncInfo.MF->insert(BBI, RightMBB);
8711     WorkList.push_back(
8712         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
8713     // Put Cond in a virtual register to make it available from the new blocks.
8714     ExportFromCurrentBlock(Cond);
8715   }
8716 
8717   // Create the CaseBlock record that will be used to lower the branch.
8718   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
8719                LeftProb, RightProb);
8720 
8721   if (W.MBB == SwitchMBB)
8722     visitSwitchCase(CB, SwitchMBB);
8723   else
8724     SwitchCases.push_back(CB);
8725 }
8726 
8727 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
8728   // Extract cases from the switch.
8729   BranchProbabilityInfo *BPI = FuncInfo.BPI;
8730   CaseClusterVector Clusters;
8731   Clusters.reserve(SI.getNumCases());
8732   for (auto I : SI.cases()) {
8733     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
8734     const ConstantInt *CaseVal = I.getCaseValue();
8735     BranchProbability Prob =
8736         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
8737             : BranchProbability(1, SI.getNumCases() + 1);
8738     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
8739   }
8740 
8741   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
8742 
8743   // Cluster adjacent cases with the same destination. We do this at all
8744   // optimization levels because it's cheap to do and will make codegen faster
8745   // if there are many clusters.
8746   sortAndRangeify(Clusters);
8747 
8748   if (TM.getOptLevel() != CodeGenOpt::None) {
8749     // Replace an unreachable default with the most popular destination.
8750     // FIXME: Exploit unreachable default more aggressively.
8751     bool UnreachableDefault =
8752         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
8753     if (UnreachableDefault && !Clusters.empty()) {
8754       DenseMap<const BasicBlock *, unsigned> Popularity;
8755       unsigned MaxPop = 0;
8756       const BasicBlock *MaxBB = nullptr;
8757       for (auto I : SI.cases()) {
8758         const BasicBlock *BB = I.getCaseSuccessor();
8759         if (++Popularity[BB] > MaxPop) {
8760           MaxPop = Popularity[BB];
8761           MaxBB = BB;
8762         }
8763       }
8764       // Set new default.
8765       assert(MaxPop > 0 && MaxBB);
8766       DefaultMBB = FuncInfo.MBBMap[MaxBB];
8767 
8768       // Remove cases that were pointing to the destination that is now the
8769       // default.
8770       CaseClusterVector New;
8771       New.reserve(Clusters.size());
8772       for (CaseCluster &CC : Clusters) {
8773         if (CC.MBB != DefaultMBB)
8774           New.push_back(CC);
8775       }
8776       Clusters = std::move(New);
8777     }
8778   }
8779 
8780   // If there is only the default destination, jump there directly.
8781   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
8782   if (Clusters.empty()) {
8783     SwitchMBB->addSuccessor(DefaultMBB);
8784     if (DefaultMBB != NextBlock(SwitchMBB)) {
8785       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
8786                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
8787     }
8788     return;
8789   }
8790 
8791   findJumpTables(Clusters, &SI, DefaultMBB);
8792   findBitTestClusters(Clusters, &SI);
8793 
8794   DEBUG({
8795     dbgs() << "Case clusters: ";
8796     for (const CaseCluster &C : Clusters) {
8797       if (C.Kind == CC_JumpTable) dbgs() << "JT:";
8798       if (C.Kind == CC_BitTests) dbgs() << "BT:";
8799 
8800       C.Low->getValue().print(dbgs(), true);
8801       if (C.Low != C.High) {
8802         dbgs() << '-';
8803         C.High->getValue().print(dbgs(), true);
8804       }
8805       dbgs() << ' ';
8806     }
8807     dbgs() << '\n';
8808   });
8809 
8810   assert(!Clusters.empty());
8811   SwitchWorkList WorkList;
8812   CaseClusterIt First = Clusters.begin();
8813   CaseClusterIt Last = Clusters.end() - 1;
8814   auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
8815   WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
8816 
8817   while (!WorkList.empty()) {
8818     SwitchWorkListItem W = WorkList.back();
8819     WorkList.pop_back();
8820     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
8821 
8822     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None) {
8823       // For optimized builds, lower large range as a balanced binary tree.
8824       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
8825       continue;
8826     }
8827 
8828     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
8829   }
8830 }
8831