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