1 //===- FastISel.cpp - Implementation of the FastISel class ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the FastISel class.
10 //
11 // "Fast" instruction selection is designed to emit very poor code quickly.
12 // Also, it is not designed to be able to do much lowering, so most illegal
13 // types (e.g. i64 on 32-bit targets) and operations are not supported.  It is
14 // also not intended to be able to do much optimization, except in a few cases
15 // where doing optimizations reduces overall compile time.  For example, folding
16 // constants into immediate fields is often done, because it's cheap and it
17 // reduces the number of instructions later phases have to examine.
18 //
19 // "Fast" instruction selection is able to fail gracefully and transfer
20 // control to the SelectionDAG selector for operations that it doesn't
21 // support.  In many cases, this allows us to avoid duplicating a lot of
22 // the complicated lowering logic that SelectionDAG currently has.
23 //
24 // The intended use for "fast" instruction selection is "-O0" mode
25 // compilation, where the quality of the generated code is irrelevant when
26 // weighed against the speed at which the code can be generated.  Also,
27 // at -O0, the LLVM optimizers are not running, and this makes the
28 // compile time of codegen a much higher portion of the overall compile
29 // time.  Despite its limitations, "fast" instruction selection is able to
30 // handle enough code on its own to provide noticeable overall speedups
31 // in -O0 compiles.
32 //
33 // Basic operations are supported in a target-independent way, by reading
34 // the same instruction descriptions that the SelectionDAG selector reads,
35 // and identifying simple arithmetic operations that can be directly selected
36 // from simple operators.  More complicated operations currently require
37 // target-specific code.
38 //
39 //===----------------------------------------------------------------------===//
40 
41 #include "llvm/CodeGen/FastISel.h"
42 #include "llvm/ADT/APFloat.h"
43 #include "llvm/ADT/APSInt.h"
44 #include "llvm/ADT/DenseMap.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/SmallVector.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/Analysis/BranchProbabilityInfo.h"
50 #include "llvm/Analysis/TargetLibraryInfo.h"
51 #include "llvm/CodeGen/Analysis.h"
52 #include "llvm/CodeGen/FunctionLoweringInfo.h"
53 #include "llvm/CodeGen/ISDOpcodes.h"
54 #include "llvm/CodeGen/MachineBasicBlock.h"
55 #include "llvm/CodeGen/MachineFrameInfo.h"
56 #include "llvm/CodeGen/MachineInstr.h"
57 #include "llvm/CodeGen/MachineInstrBuilder.h"
58 #include "llvm/CodeGen/MachineMemOperand.h"
59 #include "llvm/CodeGen/MachineModuleInfo.h"
60 #include "llvm/CodeGen/MachineOperand.h"
61 #include "llvm/CodeGen/MachineRegisterInfo.h"
62 #include "llvm/CodeGen/MachineValueType.h"
63 #include "llvm/CodeGen/StackMaps.h"
64 #include "llvm/CodeGen/TargetInstrInfo.h"
65 #include "llvm/CodeGen/TargetLowering.h"
66 #include "llvm/CodeGen/TargetSubtargetInfo.h"
67 #include "llvm/CodeGen/ValueTypes.h"
68 #include "llvm/IR/Argument.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/BasicBlock.h"
71 #include "llvm/IR/CallingConv.h"
72 #include "llvm/IR/Constant.h"
73 #include "llvm/IR/Constants.h"
74 #include "llvm/IR/DataLayout.h"
75 #include "llvm/IR/DebugLoc.h"
76 #include "llvm/IR/DerivedTypes.h"
77 #include "llvm/IR/DiagnosticInfo.h"
78 #include "llvm/IR/Function.h"
79 #include "llvm/IR/GetElementPtrTypeIterator.h"
80 #include "llvm/IR/GlobalValue.h"
81 #include "llvm/IR/InlineAsm.h"
82 #include "llvm/IR/InstrTypes.h"
83 #include "llvm/IR/Instruction.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/LLVMContext.h"
87 #include "llvm/IR/Mangler.h"
88 #include "llvm/IR/Metadata.h"
89 #include "llvm/IR/Operator.h"
90 #include "llvm/IR/PatternMatch.h"
91 #include "llvm/IR/Type.h"
92 #include "llvm/IR/User.h"
93 #include "llvm/IR/Value.h"
94 #include "llvm/MC/MCContext.h"
95 #include "llvm/MC/MCInstrDesc.h"
96 #include "llvm/Support/Casting.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/ErrorHandling.h"
99 #include "llvm/Support/MathExtras.h"
100 #include "llvm/Support/raw_ostream.h"
101 #include "llvm/Target/TargetMachine.h"
102 #include "llvm/Target/TargetOptions.h"
103 #include <algorithm>
104 #include <cassert>
105 #include <cstdint>
106 #include <iterator>
107 #include <optional>
108 #include <utility>
109 
110 using namespace llvm;
111 using namespace PatternMatch;
112 
113 #define DEBUG_TYPE "isel"
114 
115 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
116                                          "target-independent selector");
117 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
118                                     "target-specific selector");
119 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
120 
121 /// Set the current block to which generated machine instructions will be
122 /// appended.
123 void FastISel::startNewBlock() {
124   assert(LocalValueMap.empty() &&
125          "local values should be cleared after finishing a BB");
126 
127   // Instructions are appended to FuncInfo.MBB. If the basic block already
128   // contains labels or copies, use the last instruction as the last local
129   // value.
130   EmitStartPt = nullptr;
131   if (!FuncInfo.MBB->empty())
132     EmitStartPt = &FuncInfo.MBB->back();
133   LastLocalValue = EmitStartPt;
134 }
135 
136 void FastISel::finishBasicBlock() { flushLocalValueMap(); }
137 
138 bool FastISel::lowerArguments() {
139   if (!FuncInfo.CanLowerReturn)
140     // Fallback to SDISel argument lowering code to deal with sret pointer
141     // parameter.
142     return false;
143 
144   if (!fastLowerArguments())
145     return false;
146 
147   // Enter arguments into ValueMap for uses in non-entry BBs.
148   for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
149                                     E = FuncInfo.Fn->arg_end();
150        I != E; ++I) {
151     DenseMap<const Value *, Register>::iterator VI = LocalValueMap.find(&*I);
152     assert(VI != LocalValueMap.end() && "Missed an argument?");
153     FuncInfo.ValueMap[&*I] = VI->second;
154   }
155   return true;
156 }
157 
158 /// Return the defined register if this instruction defines exactly one
159 /// virtual register and uses no other virtual registers. Otherwise return 0.
160 static Register findLocalRegDef(MachineInstr &MI) {
161   Register RegDef;
162   for (const MachineOperand &MO : MI.operands()) {
163     if (!MO.isReg())
164       continue;
165     if (MO.isDef()) {
166       if (RegDef)
167         return Register();
168       RegDef = MO.getReg();
169     } else if (MO.getReg().isVirtual()) {
170       // This is another use of a vreg. Don't delete it.
171       return Register();
172     }
173   }
174   return RegDef;
175 }
176 
177 static bool isRegUsedByPhiNodes(Register DefReg,
178                                 FunctionLoweringInfo &FuncInfo) {
179   for (auto &P : FuncInfo.PHINodesToUpdate)
180     if (P.second == DefReg)
181       return true;
182   return false;
183 }
184 
185 void FastISel::flushLocalValueMap() {
186   // If FastISel bails out, it could leave local value instructions behind
187   // that aren't used for anything.  Detect and erase those.
188   if (LastLocalValue != EmitStartPt) {
189     // Save the first instruction after local values, for later.
190     MachineBasicBlock::iterator FirstNonValue(LastLocalValue);
191     ++FirstNonValue;
192 
193     MachineBasicBlock::reverse_iterator RE =
194         EmitStartPt ? MachineBasicBlock::reverse_iterator(EmitStartPt)
195                     : FuncInfo.MBB->rend();
196     MachineBasicBlock::reverse_iterator RI(LastLocalValue);
197     for (MachineInstr &LocalMI :
198          llvm::make_early_inc_range(llvm::make_range(RI, RE))) {
199       Register DefReg = findLocalRegDef(LocalMI);
200       if (!DefReg)
201         continue;
202       if (FuncInfo.RegsWithFixups.count(DefReg))
203         continue;
204       bool UsedByPHI = isRegUsedByPhiNodes(DefReg, FuncInfo);
205       if (!UsedByPHI && MRI.use_nodbg_empty(DefReg)) {
206         if (EmitStartPt == &LocalMI)
207           EmitStartPt = EmitStartPt->getPrevNode();
208         LLVM_DEBUG(dbgs() << "removing dead local value materialization"
209                           << LocalMI);
210         LocalMI.eraseFromParent();
211       }
212     }
213 
214     if (FirstNonValue != FuncInfo.MBB->end()) {
215       // See if there are any local value instructions left.  If so, we want to
216       // make sure the first one has a debug location; if it doesn't, use the
217       // first non-value instruction's debug location.
218 
219       // If EmitStartPt is non-null, this block had copies at the top before
220       // FastISel started doing anything; it points to the last one, so the
221       // first local value instruction is the one after EmitStartPt.
222       // If EmitStartPt is null, the first local value instruction is at the
223       // top of the block.
224       MachineBasicBlock::iterator FirstLocalValue =
225           EmitStartPt ? ++MachineBasicBlock::iterator(EmitStartPt)
226                       : FuncInfo.MBB->begin();
227       if (FirstLocalValue != FirstNonValue && !FirstLocalValue->getDebugLoc())
228         FirstLocalValue->setDebugLoc(FirstNonValue->getDebugLoc());
229     }
230   }
231 
232   LocalValueMap.clear();
233   LastLocalValue = EmitStartPt;
234   recomputeInsertPt();
235   SavedInsertPt = FuncInfo.InsertPt;
236 }
237 
238 Register FastISel::getRegForValue(const Value *V) {
239   EVT RealVT = TLI.getValueType(DL, V->getType(), /*AllowUnknown=*/true);
240   // Don't handle non-simple values in FastISel.
241   if (!RealVT.isSimple())
242     return Register();
243 
244   // Ignore illegal types. We must do this before looking up the value
245   // in ValueMap because Arguments are given virtual registers regardless
246   // of whether FastISel can handle them.
247   MVT VT = RealVT.getSimpleVT();
248   if (!TLI.isTypeLegal(VT)) {
249     // Handle integer promotions, though, because they're common and easy.
250     if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
251       VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
252     else
253       return Register();
254   }
255 
256   // Look up the value to see if we already have a register for it.
257   Register Reg = lookUpRegForValue(V);
258   if (Reg)
259     return Reg;
260 
261   // In bottom-up mode, just create the virtual register which will be used
262   // to hold the value. It will be materialized later.
263   if (isa<Instruction>(V) &&
264       (!isa<AllocaInst>(V) ||
265        !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
266     return FuncInfo.InitializeRegForValue(V);
267 
268   SavePoint SaveInsertPt = enterLocalValueArea();
269 
270   // Materialize the value in a register. Emit any instructions in the
271   // local value area.
272   Reg = materializeRegForValue(V, VT);
273 
274   leaveLocalValueArea(SaveInsertPt);
275 
276   return Reg;
277 }
278 
279 Register FastISel::materializeConstant(const Value *V, MVT VT) {
280   Register Reg;
281   if (const auto *CI = dyn_cast<ConstantInt>(V)) {
282     if (CI->getValue().getActiveBits() <= 64)
283       Reg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
284   } else if (isa<AllocaInst>(V))
285     Reg = fastMaterializeAlloca(cast<AllocaInst>(V));
286   else if (isa<ConstantPointerNull>(V))
287     // Translate this as an integer zero so that it can be
288     // local-CSE'd with actual integer zeros.
289     Reg =
290         getRegForValue(Constant::getNullValue(DL.getIntPtrType(V->getType())));
291   else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
292     if (CF->isNullValue())
293       Reg = fastMaterializeFloatZero(CF);
294     else
295       // Try to emit the constant directly.
296       Reg = fastEmit_f(VT, VT, ISD::ConstantFP, CF);
297 
298     if (!Reg) {
299       // Try to emit the constant by using an integer constant with a cast.
300       const APFloat &Flt = CF->getValueAPF();
301       EVT IntVT = TLI.getPointerTy(DL);
302       uint32_t IntBitWidth = IntVT.getSizeInBits();
303       APSInt SIntVal(IntBitWidth, /*isUnsigned=*/false);
304       bool isExact;
305       (void)Flt.convertToInteger(SIntVal, APFloat::rmTowardZero, &isExact);
306       if (isExact) {
307         Register IntegerReg =
308             getRegForValue(ConstantInt::get(V->getContext(), SIntVal));
309         if (IntegerReg)
310           Reg = fastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
311                            IntegerReg);
312       }
313     }
314   } else if (const auto *Op = dyn_cast<Operator>(V)) {
315     if (!selectOperator(Op, Op->getOpcode()))
316       if (!isa<Instruction>(Op) ||
317           !fastSelectInstruction(cast<Instruction>(Op)))
318         return 0;
319     Reg = lookUpRegForValue(Op);
320   } else if (isa<UndefValue>(V)) {
321     Reg = createResultReg(TLI.getRegClassFor(VT));
322     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
323             TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
324   }
325   return Reg;
326 }
327 
328 /// Helper for getRegForValue. This function is called when the value isn't
329 /// already available in a register and must be materialized with new
330 /// instructions.
331 Register FastISel::materializeRegForValue(const Value *V, MVT VT) {
332   Register Reg;
333   // Give the target-specific code a try first.
334   if (isa<Constant>(V))
335     Reg = fastMaterializeConstant(cast<Constant>(V));
336 
337   // If target-specific code couldn't or didn't want to handle the value, then
338   // give target-independent code a try.
339   if (!Reg)
340     Reg = materializeConstant(V, VT);
341 
342   // Don't cache constant materializations in the general ValueMap.
343   // To do so would require tracking what uses they dominate.
344   if (Reg) {
345     LocalValueMap[V] = Reg;
346     LastLocalValue = MRI.getVRegDef(Reg);
347   }
348   return Reg;
349 }
350 
351 Register FastISel::lookUpRegForValue(const Value *V) {
352   // Look up the value to see if we already have a register for it. We
353   // cache values defined by Instructions across blocks, and other values
354   // only locally. This is because Instructions already have the SSA
355   // def-dominates-use requirement enforced.
356   DenseMap<const Value *, Register>::iterator I = FuncInfo.ValueMap.find(V);
357   if (I != FuncInfo.ValueMap.end())
358     return I->second;
359   return LocalValueMap[V];
360 }
361 
362 void FastISel::updateValueMap(const Value *I, Register Reg, unsigned NumRegs) {
363   if (!isa<Instruction>(I)) {
364     LocalValueMap[I] = Reg;
365     return;
366   }
367 
368   Register &AssignedReg = FuncInfo.ValueMap[I];
369   if (!AssignedReg)
370     // Use the new register.
371     AssignedReg = Reg;
372   else if (Reg != AssignedReg) {
373     // Arrange for uses of AssignedReg to be replaced by uses of Reg.
374     for (unsigned i = 0; i < NumRegs; i++) {
375       FuncInfo.RegFixups[AssignedReg + i] = Reg + i;
376       FuncInfo.RegsWithFixups.insert(Reg + i);
377     }
378 
379     AssignedReg = Reg;
380   }
381 }
382 
383 Register FastISel::getRegForGEPIndex(const Value *Idx) {
384   Register IdxN = getRegForValue(Idx);
385   if (!IdxN)
386     // Unhandled operand. Halt "fast" selection and bail.
387     return Register();
388 
389   // If the index is smaller or larger than intptr_t, truncate or extend it.
390   MVT PtrVT = TLI.getPointerTy(DL);
391   EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
392   if (IdxVT.bitsLT(PtrVT)) {
393     IdxN = fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN);
394   } else if (IdxVT.bitsGT(PtrVT)) {
395     IdxN =
396         fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN);
397   }
398   return IdxN;
399 }
400 
401 void FastISel::recomputeInsertPt() {
402   if (getLastLocalValue()) {
403     FuncInfo.InsertPt = getLastLocalValue();
404     FuncInfo.MBB = FuncInfo.InsertPt->getParent();
405     ++FuncInfo.InsertPt;
406   } else
407     FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
408 }
409 
410 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
411                               MachineBasicBlock::iterator E) {
412   assert(I.isValid() && E.isValid() && std::distance(I, E) > 0 &&
413          "Invalid iterator!");
414   while (I != E) {
415     if (SavedInsertPt == I)
416       SavedInsertPt = E;
417     if (EmitStartPt == I)
418       EmitStartPt = E.isValid() ? &*E : nullptr;
419     if (LastLocalValue == I)
420       LastLocalValue = E.isValid() ? &*E : nullptr;
421 
422     MachineInstr *Dead = &*I;
423     ++I;
424     Dead->eraseFromParent();
425     ++NumFastIselDead;
426   }
427   recomputeInsertPt();
428 }
429 
430 FastISel::SavePoint FastISel::enterLocalValueArea() {
431   SavePoint OldInsertPt = FuncInfo.InsertPt;
432   recomputeInsertPt();
433   return OldInsertPt;
434 }
435 
436 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
437   if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
438     LastLocalValue = &*std::prev(FuncInfo.InsertPt);
439 
440   // Restore the previous insert position.
441   FuncInfo.InsertPt = OldInsertPt;
442 }
443 
444 bool FastISel::selectBinaryOp(const User *I, unsigned ISDOpcode) {
445   EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
446   if (VT == MVT::Other || !VT.isSimple())
447     // Unhandled type. Halt "fast" selection and bail.
448     return false;
449 
450   // We only handle legal types. For example, on x86-32 the instruction
451   // selector contains all of the 64-bit instructions from x86-64,
452   // under the assumption that i64 won't be used if the target doesn't
453   // support it.
454   if (!TLI.isTypeLegal(VT)) {
455     // MVT::i1 is special. Allow AND, OR, or XOR because they
456     // don't require additional zeroing, which makes them easy.
457     if (VT == MVT::i1 && ISD::isBitwiseLogicOp(ISDOpcode))
458       VT = TLI.getTypeToTransformTo(I->getContext(), VT);
459     else
460       return false;
461   }
462 
463   // Check if the first operand is a constant, and handle it as "ri".  At -O0,
464   // we don't have anything that canonicalizes operand order.
465   if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
466     if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
467       Register Op1 = getRegForValue(I->getOperand(1));
468       if (!Op1)
469         return false;
470 
471       Register ResultReg =
472           fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1, CI->getZExtValue(),
473                        VT.getSimpleVT());
474       if (!ResultReg)
475         return false;
476 
477       // We successfully emitted code for the given LLVM Instruction.
478       updateValueMap(I, ResultReg);
479       return true;
480     }
481 
482   Register Op0 = getRegForValue(I->getOperand(0));
483   if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
484     return false;
485 
486   // Check if the second operand is a constant and handle it appropriately.
487   if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
488     uint64_t Imm = CI->getSExtValue();
489 
490     // Transform "sdiv exact X, 8" -> "sra X, 3".
491     if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
492         cast<BinaryOperator>(I)->isExact() && isPowerOf2_64(Imm)) {
493       Imm = Log2_64(Imm);
494       ISDOpcode = ISD::SRA;
495     }
496 
497     // Transform "urem x, pow2" -> "and x, pow2-1".
498     if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
499         isPowerOf2_64(Imm)) {
500       --Imm;
501       ISDOpcode = ISD::AND;
502     }
503 
504     Register ResultReg = fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0, Imm,
505                                       VT.getSimpleVT());
506     if (!ResultReg)
507       return false;
508 
509     // We successfully emitted code for the given LLVM Instruction.
510     updateValueMap(I, ResultReg);
511     return true;
512   }
513 
514   Register Op1 = getRegForValue(I->getOperand(1));
515   if (!Op1) // Unhandled operand. Halt "fast" selection and bail.
516     return false;
517 
518   // Now we have both operands in registers. Emit the instruction.
519   Register ResultReg = fastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
520                                    ISDOpcode, Op0, Op1);
521   if (!ResultReg)
522     // Target-specific code wasn't able to find a machine opcode for
523     // the given ISD opcode and type. Halt "fast" selection and bail.
524     return false;
525 
526   // We successfully emitted code for the given LLVM Instruction.
527   updateValueMap(I, ResultReg);
528   return true;
529 }
530 
531 bool FastISel::selectGetElementPtr(const User *I) {
532   Register N = getRegForValue(I->getOperand(0));
533   if (!N) // Unhandled operand. Halt "fast" selection and bail.
534     return false;
535 
536   // FIXME: The code below does not handle vector GEPs. Halt "fast" selection
537   // and bail.
538   if (isa<VectorType>(I->getType()))
539     return false;
540 
541   // Keep a running tab of the total offset to coalesce multiple N = N + Offset
542   // into a single N = N + TotalOffset.
543   uint64_t TotalOffs = 0;
544   // FIXME: What's a good SWAG number for MaxOffs?
545   uint64_t MaxOffs = 2048;
546   MVT VT = TLI.getPointerTy(DL);
547   for (gep_type_iterator GTI = gep_type_begin(I), E = gep_type_end(I);
548        GTI != E; ++GTI) {
549     const Value *Idx = GTI.getOperand();
550     if (StructType *StTy = GTI.getStructTypeOrNull()) {
551       uint64_t Field = cast<ConstantInt>(Idx)->getZExtValue();
552       if (Field) {
553         // N = N + Offset
554         TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
555         if (TotalOffs >= MaxOffs) {
556           N = fastEmit_ri_(VT, ISD::ADD, N, TotalOffs, VT);
557           if (!N) // Unhandled operand. Halt "fast" selection and bail.
558             return false;
559           TotalOffs = 0;
560         }
561       }
562     } else {
563       // If this is a constant subscript, handle it quickly.
564       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
565         if (CI->isZero())
566           continue;
567         // N = N + Offset
568         uint64_t IdxN = CI->getValue().sextOrTrunc(64).getSExtValue();
569         TotalOffs += GTI.getSequentialElementStride(DL) * IdxN;
570         if (TotalOffs >= MaxOffs) {
571           N = fastEmit_ri_(VT, ISD::ADD, N, TotalOffs, VT);
572           if (!N) // Unhandled operand. Halt "fast" selection and bail.
573             return false;
574           TotalOffs = 0;
575         }
576         continue;
577       }
578       if (TotalOffs) {
579         N = fastEmit_ri_(VT, ISD::ADD, N, TotalOffs, VT);
580         if (!N) // Unhandled operand. Halt "fast" selection and bail.
581           return false;
582         TotalOffs = 0;
583       }
584 
585       // N = N + Idx * ElementSize;
586       uint64_t ElementSize = GTI.getSequentialElementStride(DL);
587       Register IdxN = getRegForGEPIndex(Idx);
588       if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
589         return false;
590 
591       if (ElementSize != 1) {
592         IdxN = fastEmit_ri_(VT, ISD::MUL, IdxN, ElementSize, VT);
593         if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
594           return false;
595       }
596       N = fastEmit_rr(VT, VT, ISD::ADD, N, IdxN);
597       if (!N) // Unhandled operand. Halt "fast" selection and bail.
598         return false;
599     }
600   }
601   if (TotalOffs) {
602     N = fastEmit_ri_(VT, ISD::ADD, N, TotalOffs, VT);
603     if (!N) // Unhandled operand. Halt "fast" selection and bail.
604       return false;
605   }
606 
607   // We successfully emitted code for the given LLVM Instruction.
608   updateValueMap(I, N);
609   return true;
610 }
611 
612 bool FastISel::addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops,
613                                    const CallInst *CI, unsigned StartIdx) {
614   for (unsigned i = StartIdx, e = CI->arg_size(); i != e; ++i) {
615     Value *Val = CI->getArgOperand(i);
616     // Check for constants and encode them with a StackMaps::ConstantOp prefix.
617     if (const auto *C = dyn_cast<ConstantInt>(Val)) {
618       Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
619       Ops.push_back(MachineOperand::CreateImm(C->getSExtValue()));
620     } else if (isa<ConstantPointerNull>(Val)) {
621       Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
622       Ops.push_back(MachineOperand::CreateImm(0));
623     } else if (auto *AI = dyn_cast<AllocaInst>(Val)) {
624       // Values coming from a stack location also require a special encoding,
625       // but that is added later on by the target specific frame index
626       // elimination implementation.
627       auto SI = FuncInfo.StaticAllocaMap.find(AI);
628       if (SI != FuncInfo.StaticAllocaMap.end())
629         Ops.push_back(MachineOperand::CreateFI(SI->second));
630       else
631         return false;
632     } else {
633       Register Reg = getRegForValue(Val);
634       if (!Reg)
635         return false;
636       Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false));
637     }
638   }
639   return true;
640 }
641 
642 bool FastISel::selectStackmap(const CallInst *I) {
643   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
644   //                                  [live variables...])
645   assert(I->getCalledFunction()->getReturnType()->isVoidTy() &&
646          "Stackmap cannot return a value.");
647 
648   // The stackmap intrinsic only records the live variables (the arguments
649   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
650   // intrinsic, this won't be lowered to a function call. This means we don't
651   // have to worry about calling conventions and target-specific lowering code.
652   // Instead we perform the call lowering right here.
653   //
654   // CALLSEQ_START(0, 0...)
655   // STACKMAP(id, nbytes, ...)
656   // CALLSEQ_END(0, 0)
657   //
658   SmallVector<MachineOperand, 32> Ops;
659 
660   // Add the <id> and <numBytes> constants.
661   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
662          "Expected a constant integer.");
663   const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
664   Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
665 
666   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
667          "Expected a constant integer.");
668   const auto *NumBytes =
669       cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
670   Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
671 
672   // Push live variables for the stack map (skipping the first two arguments
673   // <id> and <numBytes>).
674   if (!addStackMapLiveVars(Ops, I, 2))
675     return false;
676 
677   // We are not adding any register mask info here, because the stackmap doesn't
678   // clobber anything.
679 
680   // Add scratch registers as implicit def and early clobber.
681   CallingConv::ID CC = I->getCallingConv();
682   const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
683   for (unsigned i = 0; ScratchRegs[i]; ++i)
684     Ops.push_back(MachineOperand::CreateReg(
685         ScratchRegs[i], /*isDef=*/true, /*isImp=*/true, /*isKill=*/false,
686         /*isDead=*/false, /*isUndef=*/false, /*isEarlyClobber=*/true));
687 
688   // Issue CALLSEQ_START
689   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
690   auto Builder =
691       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(AdjStackDown));
692   const MCInstrDesc &MCID = Builder.getInstr()->getDesc();
693   for (unsigned I = 0, E = MCID.getNumOperands(); I < E; ++I)
694     Builder.addImm(0);
695 
696   // Issue STACKMAP.
697   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
698                                     TII.get(TargetOpcode::STACKMAP));
699   for (auto const &MO : Ops)
700     MIB.add(MO);
701 
702   // Issue CALLSEQ_END
703   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
704   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(AdjStackUp))
705       .addImm(0)
706       .addImm(0);
707 
708   // Inform the Frame Information that we have a stackmap in this function.
709   FuncInfo.MF->getFrameInfo().setHasStackMap();
710 
711   return true;
712 }
713 
714 /// Lower an argument list according to the target calling convention.
715 ///
716 /// This is a helper for lowering intrinsics that follow a target calling
717 /// convention or require stack pointer adjustment. Only a subset of the
718 /// intrinsic's operands need to participate in the calling convention.
719 bool FastISel::lowerCallOperands(const CallInst *CI, unsigned ArgIdx,
720                                  unsigned NumArgs, const Value *Callee,
721                                  bool ForceRetVoidTy, CallLoweringInfo &CLI) {
722   ArgListTy Args;
723   Args.reserve(NumArgs);
724 
725   // Populate the argument list.
726   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; ArgI != ArgE; ++ArgI) {
727     Value *V = CI->getOperand(ArgI);
728 
729     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
730 
731     ArgListEntry Entry;
732     Entry.Val = V;
733     Entry.Ty = V->getType();
734     Entry.setAttributes(CI, ArgI);
735     Args.push_back(Entry);
736   }
737 
738   Type *RetTy = ForceRetVoidTy ? Type::getVoidTy(CI->getType()->getContext())
739                                : CI->getType();
740   CLI.setCallee(CI->getCallingConv(), RetTy, Callee, std::move(Args), NumArgs);
741 
742   return lowerCallTo(CLI);
743 }
744 
745 FastISel::CallLoweringInfo &FastISel::CallLoweringInfo::setCallee(
746     const DataLayout &DL, MCContext &Ctx, CallingConv::ID CC, Type *ResultTy,
747     StringRef Target, ArgListTy &&ArgsList, unsigned FixedArgs) {
748   SmallString<32> MangledName;
749   Mangler::getNameWithPrefix(MangledName, Target, DL);
750   MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
751   return setCallee(CC, ResultTy, Sym, std::move(ArgsList), FixedArgs);
752 }
753 
754 bool FastISel::selectPatchpoint(const CallInst *I) {
755   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
756   //                                                 i32 <numBytes>,
757   //                                                 i8* <target>,
758   //                                                 i32 <numArgs>,
759   //                                                 [Args...],
760   //                                                 [live variables...])
761   CallingConv::ID CC = I->getCallingConv();
762   bool IsAnyRegCC = CC == CallingConv::AnyReg;
763   bool HasDef = !I->getType()->isVoidTy();
764   Value *Callee = I->getOperand(PatchPointOpers::TargetPos)->stripPointerCasts();
765 
766   // Get the real number of arguments participating in the call <numArgs>
767   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)) &&
768          "Expected a constant integer.");
769   const auto *NumArgsVal =
770       cast<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos));
771   unsigned NumArgs = NumArgsVal->getZExtValue();
772 
773   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
774   // This includes all meta-operands up to but not including CC.
775   unsigned NumMetaOpers = PatchPointOpers::CCPos;
776   assert(I->arg_size() >= NumMetaOpers + NumArgs &&
777          "Not enough arguments provided to the patchpoint intrinsic");
778 
779   // For AnyRegCC the arguments are lowered later on manually.
780   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
781   CallLoweringInfo CLI;
782   CLI.setIsPatchPoint();
783   if (!lowerCallOperands(I, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC, CLI))
784     return false;
785 
786   assert(CLI.Call && "No call instruction specified.");
787 
788   SmallVector<MachineOperand, 32> Ops;
789 
790   // Add an explicit result reg if we use the anyreg calling convention.
791   if (IsAnyRegCC && HasDef) {
792     assert(CLI.NumResultRegs == 0 && "Unexpected result register.");
793     CLI.ResultReg = createResultReg(TLI.getRegClassFor(MVT::i64));
794     CLI.NumResultRegs = 1;
795     Ops.push_back(MachineOperand::CreateReg(CLI.ResultReg, /*isDef=*/true));
796   }
797 
798   // Add the <id> and <numBytes> constants.
799   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
800          "Expected a constant integer.");
801   const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
802   Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
803 
804   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
805          "Expected a constant integer.");
806   const auto *NumBytes =
807       cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
808   Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
809 
810   // Add the call target.
811   if (const auto *C = dyn_cast<IntToPtrInst>(Callee)) {
812     uint64_t CalleeConstAddr =
813       cast<ConstantInt>(C->getOperand(0))->getZExtValue();
814     Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
815   } else if (const auto *C = dyn_cast<ConstantExpr>(Callee)) {
816     if (C->getOpcode() == Instruction::IntToPtr) {
817       uint64_t CalleeConstAddr =
818         cast<ConstantInt>(C->getOperand(0))->getZExtValue();
819       Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
820     } else
821       llvm_unreachable("Unsupported ConstantExpr.");
822   } else if (const auto *GV = dyn_cast<GlobalValue>(Callee)) {
823     Ops.push_back(MachineOperand::CreateGA(GV, 0));
824   } else if (isa<ConstantPointerNull>(Callee))
825     Ops.push_back(MachineOperand::CreateImm(0));
826   else
827     llvm_unreachable("Unsupported callee address.");
828 
829   // Adjust <numArgs> to account for any arguments that have been passed on
830   // the stack instead.
831   unsigned NumCallRegArgs = IsAnyRegCC ? NumArgs : CLI.OutRegs.size();
832   Ops.push_back(MachineOperand::CreateImm(NumCallRegArgs));
833 
834   // Add the calling convention
835   Ops.push_back(MachineOperand::CreateImm((unsigned)CC));
836 
837   // Add the arguments we omitted previously. The register allocator should
838   // place these in any free register.
839   if (IsAnyRegCC) {
840     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) {
841       Register Reg = getRegForValue(I->getArgOperand(i));
842       if (!Reg)
843         return false;
844       Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false));
845     }
846   }
847 
848   // Push the arguments from the call instruction.
849   for (auto Reg : CLI.OutRegs)
850     Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false));
851 
852   // Push live variables for the stack map.
853   if (!addStackMapLiveVars(Ops, I, NumMetaOpers + NumArgs))
854     return false;
855 
856   // Push the register mask info.
857   Ops.push_back(MachineOperand::CreateRegMask(
858       TRI.getCallPreservedMask(*FuncInfo.MF, CC)));
859 
860   // Add scratch registers as implicit def and early clobber.
861   const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
862   for (unsigned i = 0; ScratchRegs[i]; ++i)
863     Ops.push_back(MachineOperand::CreateReg(
864         ScratchRegs[i], /*isDef=*/true, /*isImp=*/true, /*isKill=*/false,
865         /*isDead=*/false, /*isUndef=*/false, /*isEarlyClobber=*/true));
866 
867   // Add implicit defs (return values).
868   for (auto Reg : CLI.InRegs)
869     Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/true,
870                                             /*isImp=*/true));
871 
872   // Insert the patchpoint instruction before the call generated by the target.
873   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, CLI.Call, MIMD,
874                                     TII.get(TargetOpcode::PATCHPOINT));
875 
876   for (auto &MO : Ops)
877     MIB.add(MO);
878 
879   MIB->setPhysRegsDeadExcept(CLI.InRegs, TRI);
880 
881   // Delete the original call instruction.
882   CLI.Call->eraseFromParent();
883 
884   // Inform the Frame Information that we have a patchpoint in this function.
885   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
886 
887   if (CLI.NumResultRegs)
888     updateValueMap(I, CLI.ResultReg, CLI.NumResultRegs);
889   return true;
890 }
891 
892 bool FastISel::selectXRayCustomEvent(const CallInst *I) {
893   const auto &Triple = TM.getTargetTriple();
894   if (Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
895     return true; // don't do anything to this instruction.
896   SmallVector<MachineOperand, 8> Ops;
897   Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)),
898                                           /*isDef=*/false));
899   Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)),
900                                           /*isDef=*/false));
901   MachineInstrBuilder MIB =
902       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
903               TII.get(TargetOpcode::PATCHABLE_EVENT_CALL));
904   for (auto &MO : Ops)
905     MIB.add(MO);
906 
907   // Insert the Patchable Event Call instruction, that gets lowered properly.
908   return true;
909 }
910 
911 bool FastISel::selectXRayTypedEvent(const CallInst *I) {
912   const auto &Triple = TM.getTargetTriple();
913   if (Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
914     return true; // don't do anything to this instruction.
915   SmallVector<MachineOperand, 8> Ops;
916   Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)),
917                                           /*isDef=*/false));
918   Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)),
919                                           /*isDef=*/false));
920   Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(2)),
921                                           /*isDef=*/false));
922   MachineInstrBuilder MIB =
923       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
924               TII.get(TargetOpcode::PATCHABLE_TYPED_EVENT_CALL));
925   for (auto &MO : Ops)
926     MIB.add(MO);
927 
928   // Insert the Patchable Typed Event Call instruction, that gets lowered properly.
929   return true;
930 }
931 
932 /// Returns an AttributeList representing the attributes applied to the return
933 /// value of the given call.
934 static AttributeList getReturnAttrs(FastISel::CallLoweringInfo &CLI) {
935   SmallVector<Attribute::AttrKind, 2> Attrs;
936   if (CLI.RetSExt)
937     Attrs.push_back(Attribute::SExt);
938   if (CLI.RetZExt)
939     Attrs.push_back(Attribute::ZExt);
940   if (CLI.IsInReg)
941     Attrs.push_back(Attribute::InReg);
942 
943   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
944                             Attrs);
945 }
946 
947 bool FastISel::lowerCallTo(const CallInst *CI, const char *SymName,
948                            unsigned NumArgs) {
949   MCContext &Ctx = MF->getContext();
950   SmallString<32> MangledName;
951   Mangler::getNameWithPrefix(MangledName, SymName, DL);
952   MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
953   return lowerCallTo(CI, Sym, NumArgs);
954 }
955 
956 bool FastISel::lowerCallTo(const CallInst *CI, MCSymbol *Symbol,
957                            unsigned NumArgs) {
958   FunctionType *FTy = CI->getFunctionType();
959   Type *RetTy = CI->getType();
960 
961   ArgListTy Args;
962   Args.reserve(NumArgs);
963 
964   // Populate the argument list.
965   // Attributes for args start at offset 1, after the return attribute.
966   for (unsigned ArgI = 0; ArgI != NumArgs; ++ArgI) {
967     Value *V = CI->getOperand(ArgI);
968 
969     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
970 
971     ArgListEntry Entry;
972     Entry.Val = V;
973     Entry.Ty = V->getType();
974     Entry.setAttributes(CI, ArgI);
975     Args.push_back(Entry);
976   }
977   TLI.markLibCallAttributes(MF, CI->getCallingConv(), Args);
978 
979   CallLoweringInfo CLI;
980   CLI.setCallee(RetTy, FTy, Symbol, std::move(Args), *CI, NumArgs);
981 
982   return lowerCallTo(CLI);
983 }
984 
985 bool FastISel::lowerCallTo(CallLoweringInfo &CLI) {
986   // Handle the incoming return values from the call.
987   CLI.clearIns();
988   SmallVector<EVT, 4> RetTys;
989   ComputeValueVTs(TLI, DL, CLI.RetTy, RetTys);
990 
991   SmallVector<ISD::OutputArg, 4> Outs;
992   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, TLI, DL);
993 
994   bool CanLowerReturn = TLI.CanLowerReturn(
995       CLI.CallConv, *FuncInfo.MF, CLI.IsVarArg, Outs, CLI.RetTy->getContext());
996 
997   // FIXME: sret demotion isn't supported yet - bail out.
998   if (!CanLowerReturn)
999     return false;
1000 
1001   for (EVT VT : RetTys) {
1002     MVT RegisterVT = TLI.getRegisterType(CLI.RetTy->getContext(), VT);
1003     unsigned NumRegs = TLI.getNumRegisters(CLI.RetTy->getContext(), VT);
1004     for (unsigned i = 0; i != NumRegs; ++i) {
1005       ISD::InputArg MyFlags;
1006       MyFlags.VT = RegisterVT;
1007       MyFlags.ArgVT = VT;
1008       MyFlags.Used = CLI.IsReturnValueUsed;
1009       if (CLI.RetSExt)
1010         MyFlags.Flags.setSExt();
1011       if (CLI.RetZExt)
1012         MyFlags.Flags.setZExt();
1013       if (CLI.IsInReg)
1014         MyFlags.Flags.setInReg();
1015       CLI.Ins.push_back(MyFlags);
1016     }
1017   }
1018 
1019   // Handle all of the outgoing arguments.
1020   CLI.clearOuts();
1021   for (auto &Arg : CLI.getArgs()) {
1022     Type *FinalType = Arg.Ty;
1023     if (Arg.IsByVal)
1024       FinalType = Arg.IndirectType;
1025     bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1026         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
1027 
1028     ISD::ArgFlagsTy Flags;
1029     if (Arg.IsZExt)
1030       Flags.setZExt();
1031     if (Arg.IsSExt)
1032       Flags.setSExt();
1033     if (Arg.IsInReg)
1034       Flags.setInReg();
1035     if (Arg.IsSRet)
1036       Flags.setSRet();
1037     if (Arg.IsSwiftSelf)
1038       Flags.setSwiftSelf();
1039     if (Arg.IsSwiftAsync)
1040       Flags.setSwiftAsync();
1041     if (Arg.IsSwiftError)
1042       Flags.setSwiftError();
1043     if (Arg.IsCFGuardTarget)
1044       Flags.setCFGuardTarget();
1045     if (Arg.IsByVal)
1046       Flags.setByVal();
1047     if (Arg.IsInAlloca) {
1048       Flags.setInAlloca();
1049       // Set the byval flag for CCAssignFn callbacks that don't know about
1050       // inalloca. This way we can know how many bytes we should've allocated
1051       // and how many bytes a callee cleanup function will pop.  If we port
1052       // inalloca to more targets, we'll have to add custom inalloca handling in
1053       // the various CC lowering callbacks.
1054       Flags.setByVal();
1055     }
1056     if (Arg.IsPreallocated) {
1057       Flags.setPreallocated();
1058       // Set the byval flag for CCAssignFn callbacks that don't know about
1059       // preallocated. This way we can know how many bytes we should've
1060       // allocated and how many bytes a callee cleanup function will pop.  If we
1061       // port preallocated to more targets, we'll have to add custom
1062       // preallocated handling in the various CC lowering callbacks.
1063       Flags.setByVal();
1064     }
1065     MaybeAlign MemAlign = Arg.Alignment;
1066     if (Arg.IsByVal || Arg.IsInAlloca || Arg.IsPreallocated) {
1067       unsigned FrameSize = DL.getTypeAllocSize(Arg.IndirectType);
1068 
1069       // For ByVal, alignment should come from FE. BE will guess if this info
1070       // is not there, but there are cases it cannot get right.
1071       if (!MemAlign)
1072         MemAlign = Align(TLI.getByValTypeAlignment(Arg.IndirectType, DL));
1073       Flags.setByValSize(FrameSize);
1074     } else if (!MemAlign) {
1075       MemAlign = DL.getABITypeAlign(Arg.Ty);
1076     }
1077     Flags.setMemAlign(*MemAlign);
1078     if (Arg.IsNest)
1079       Flags.setNest();
1080     if (NeedsRegBlock)
1081       Flags.setInConsecutiveRegs();
1082     Flags.setOrigAlign(DL.getABITypeAlign(Arg.Ty));
1083     CLI.OutVals.push_back(Arg.Val);
1084     CLI.OutFlags.push_back(Flags);
1085   }
1086 
1087   if (!fastLowerCall(CLI))
1088     return false;
1089 
1090   // Set all unused physreg defs as dead.
1091   assert(CLI.Call && "No call instruction specified.");
1092   CLI.Call->setPhysRegsDeadExcept(CLI.InRegs, TRI);
1093 
1094   if (CLI.NumResultRegs && CLI.CB)
1095     updateValueMap(CLI.CB, CLI.ResultReg, CLI.NumResultRegs);
1096 
1097   // Set labels for heapallocsite call.
1098   if (CLI.CB)
1099     if (MDNode *MD = CLI.CB->getMetadata("heapallocsite"))
1100       CLI.Call->setHeapAllocMarker(*MF, MD);
1101 
1102   return true;
1103 }
1104 
1105 bool FastISel::lowerCall(const CallInst *CI) {
1106   FunctionType *FuncTy = CI->getFunctionType();
1107   Type *RetTy = CI->getType();
1108 
1109   ArgListTy Args;
1110   ArgListEntry Entry;
1111   Args.reserve(CI->arg_size());
1112 
1113   for (auto i = CI->arg_begin(), e = CI->arg_end(); i != e; ++i) {
1114     Value *V = *i;
1115 
1116     // Skip empty types
1117     if (V->getType()->isEmptyTy())
1118       continue;
1119 
1120     Entry.Val = V;
1121     Entry.Ty = V->getType();
1122 
1123     // Skip the first return-type Attribute to get to params.
1124     Entry.setAttributes(CI, i - CI->arg_begin());
1125     Args.push_back(Entry);
1126   }
1127 
1128   // Check if target-independent constraints permit a tail call here.
1129   // Target-dependent constraints are checked within fastLowerCall.
1130   bool IsTailCall = CI->isTailCall();
1131   if (IsTailCall && !isInTailCallPosition(*CI, TM))
1132     IsTailCall = false;
1133   if (IsTailCall && !CI->isMustTailCall() &&
1134       MF->getFunction().getFnAttribute("disable-tail-calls").getValueAsBool())
1135     IsTailCall = false;
1136 
1137   CallLoweringInfo CLI;
1138   CLI.setCallee(RetTy, FuncTy, CI->getCalledOperand(), std::move(Args), *CI)
1139       .setTailCall(IsTailCall);
1140 
1141   diagnoseDontCall(*CI);
1142 
1143   return lowerCallTo(CLI);
1144 }
1145 
1146 bool FastISel::selectCall(const User *I) {
1147   const CallInst *Call = cast<CallInst>(I);
1148 
1149   // Handle simple inline asms.
1150   if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledOperand())) {
1151     // Don't attempt to handle constraints.
1152     if (!IA->getConstraintString().empty())
1153       return false;
1154 
1155     unsigned ExtraInfo = 0;
1156     if (IA->hasSideEffects())
1157       ExtraInfo |= InlineAsm::Extra_HasSideEffects;
1158     if (IA->isAlignStack())
1159       ExtraInfo |= InlineAsm::Extra_IsAlignStack;
1160     if (Call->isConvergent())
1161       ExtraInfo |= InlineAsm::Extra_IsConvergent;
1162     ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
1163 
1164     MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1165                                       TII.get(TargetOpcode::INLINEASM));
1166     MIB.addExternalSymbol(IA->getAsmString().c_str());
1167     MIB.addImm(ExtraInfo);
1168 
1169     const MDNode *SrcLoc = Call->getMetadata("srcloc");
1170     if (SrcLoc)
1171       MIB.addMetadata(SrcLoc);
1172 
1173     return true;
1174   }
1175 
1176   // Handle intrinsic function calls.
1177   if (const auto *II = dyn_cast<IntrinsicInst>(Call))
1178     return selectIntrinsicCall(II);
1179 
1180   return lowerCall(Call);
1181 }
1182 
1183 void FastISel::handleDbgInfo(const Instruction *II) {
1184   if (!II->hasDbgValues())
1185     return;
1186 
1187   // Clear any metadata.
1188   MIMD = MIMetadata();
1189 
1190   // Reverse order of debug records, because fast-isel walks through backwards.
1191   for (DPValue &DPV : llvm::reverse(II->getDbgValueRange())) {
1192     flushLocalValueMap();
1193     recomputeInsertPt();
1194 
1195     Value *V = nullptr;
1196     if (!DPV.hasArgList())
1197       V = DPV.getVariableLocationOp(0);
1198 
1199     bool Res = false;
1200     if (DPV.getType() == DPValue::LocationType::Value) {
1201       Res = lowerDbgValue(V, DPV.getExpression(), DPV.getVariable(),
1202                           DPV.getDebugLoc());
1203     } else {
1204       assert(DPV.getType() == DPValue::LocationType::Declare);
1205       if (FuncInfo.PreprocessedDPVDeclares.contains(&DPV))
1206         continue;
1207       Res = lowerDbgDeclare(V, DPV.getExpression(), DPV.getVariable(),
1208                             DPV.getDebugLoc());
1209     }
1210 
1211     if (!Res)
1212       LLVM_DEBUG(dbgs() << "Dropping debug-info for " << DPV << "\n";);
1213   }
1214 }
1215 
1216 bool FastISel::lowerDbgValue(const Value *V, DIExpression *Expr,
1217                              DILocalVariable *Var, const DebugLoc &DL) {
1218   // This form of DBG_VALUE is target-independent.
1219   const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1220   if (!V || isa<UndefValue>(V)) {
1221     // DI is either undef or cannot produce a valid DBG_VALUE, so produce an
1222     // undef DBG_VALUE to terminate any prior location.
1223     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, false, 0U, Var, Expr);
1224     return true;
1225   }
1226   if (const auto *CI = dyn_cast<ConstantInt>(V)) {
1227     // See if there's an expression to constant-fold.
1228     if (Expr)
1229       std::tie(Expr, CI) = Expr->constantFold(CI);
1230     if (CI->getBitWidth() > 64)
1231       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1232           .addCImm(CI)
1233           .addImm(0U)
1234           .addMetadata(Var)
1235           .addMetadata(Expr);
1236     else
1237       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1238           .addImm(CI->getZExtValue())
1239           .addImm(0U)
1240           .addMetadata(Var)
1241           .addMetadata(Expr);
1242     return true;
1243   }
1244   if (const auto *CF = dyn_cast<ConstantFP>(V)) {
1245     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1246         .addFPImm(CF)
1247         .addImm(0U)
1248         .addMetadata(Var)
1249         .addMetadata(Expr);
1250     return true;
1251   }
1252   if (const auto *Arg = dyn_cast<Argument>(V);
1253       Arg && Expr && Expr->isEntryValue()) {
1254     // As per the Verifier, this case is only valid for swift async Args.
1255     assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
1256 
1257     Register Reg = getRegForValue(Arg);
1258     for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
1259       if (Reg == VirtReg || Reg == PhysReg) {
1260         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, false /*IsIndirect*/,
1261                 PhysReg, Var, Expr);
1262         return true;
1263       }
1264 
1265     LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
1266                          "couldn't find a physical register\n");
1267     return false;
1268   }
1269   if (auto SI = FuncInfo.StaticAllocaMap.find(dyn_cast<AllocaInst>(V));
1270       SI != FuncInfo.StaticAllocaMap.end()) {
1271     MachineOperand FrameIndexOp = MachineOperand::CreateFI(SI->second);
1272     bool IsIndirect = false;
1273     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, IsIndirect, FrameIndexOp,
1274             Var, Expr);
1275     return true;
1276   }
1277   if (Register Reg = lookUpRegForValue(V)) {
1278     // FIXME: This does not handle register-indirect values at offset 0.
1279     if (!FuncInfo.MF->useDebugInstrRef()) {
1280       bool IsIndirect = false;
1281       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, IsIndirect, Reg, Var,
1282               Expr);
1283       return true;
1284     }
1285     // If using instruction referencing, produce this as a DBG_INSTR_REF,
1286     // to be later patched up by finalizeDebugInstrRefs.
1287     SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
1288         /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
1289         /* isKill */ false, /* isDead */ false,
1290         /* isUndef */ false, /* isEarlyClobber */ false,
1291         /* SubReg */ 0, /* isDebug */ true)});
1292     SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
1293     auto *NewExpr = DIExpression::prependOpcodes(Expr, Ops);
1294     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1295             TII.get(TargetOpcode::DBG_INSTR_REF), /*IsIndirect*/ false, MOs,
1296             Var, NewExpr);
1297     return true;
1298   }
1299   return false;
1300 }
1301 
1302 bool FastISel::lowerDbgDeclare(const Value *Address, DIExpression *Expr,
1303                                DILocalVariable *Var, const DebugLoc &DL) {
1304   if (!Address || isa<UndefValue>(Address)) {
1305     LLVM_DEBUG(dbgs() << "Dropping debug info (bad/undef address)\n");
1306     return false;
1307   }
1308 
1309   std::optional<MachineOperand> Op;
1310   if (Register Reg = lookUpRegForValue(Address))
1311     Op = MachineOperand::CreateReg(Reg, false);
1312 
1313   // If we have a VLA that has a "use" in a metadata node that's then used
1314   // here but it has no other uses, then we have a problem. E.g.,
1315   //
1316   //   int foo (const int *x) {
1317   //     char a[*x];
1318   //     return 0;
1319   //   }
1320   //
1321   // If we assign 'a' a vreg and fast isel later on has to use the selection
1322   // DAG isel, it will want to copy the value to the vreg. However, there are
1323   // no uses, which goes counter to what selection DAG isel expects.
1324   if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
1325       (!isa<AllocaInst>(Address) ||
1326        !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
1327     Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
1328                                    false);
1329 
1330   if (Op) {
1331     assert(Var->isValidLocationForIntrinsic(DL) &&
1332            "Expected inlined-at fields to agree");
1333     if (FuncInfo.MF->useDebugInstrRef() && Op->isReg()) {
1334       // If using instruction referencing, produce this as a DBG_INSTR_REF,
1335       // to be later patched up by finalizeDebugInstrRefs. Tack a deref onto
1336       // the expression, we don't have an "indirect" flag in DBG_INSTR_REF.
1337       SmallVector<uint64_t, 3> Ops(
1338           {dwarf::DW_OP_LLVM_arg, 0, dwarf::DW_OP_deref});
1339       auto *NewExpr = DIExpression::prependOpcodes(Expr, Ops);
1340       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1341               TII.get(TargetOpcode::DBG_INSTR_REF), /*IsIndirect*/ false, *Op,
1342               Var, NewExpr);
1343       return true;
1344     }
1345 
1346     // A dbg.declare describes the address of a source variable, so lower it
1347     // into an indirect DBG_VALUE.
1348     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1349             TII.get(TargetOpcode::DBG_VALUE), /*IsIndirect*/ true, *Op, Var,
1350             Expr);
1351     return true;
1352   }
1353 
1354   // We can't yet handle anything else here because it would require
1355   // generating code, thus altering codegen because of debug info.
1356   LLVM_DEBUG(
1357       dbgs() << "Dropping debug info (no materialized reg for address)\n");
1358   return false;
1359 }
1360 
1361 bool FastISel::selectIntrinsicCall(const IntrinsicInst *II) {
1362   switch (II->getIntrinsicID()) {
1363   default:
1364     break;
1365   // At -O0 we don't care about the lifetime intrinsics.
1366   case Intrinsic::lifetime_start:
1367   case Intrinsic::lifetime_end:
1368   // The donothing intrinsic does, well, nothing.
1369   case Intrinsic::donothing:
1370   // Neither does the sideeffect intrinsic.
1371   case Intrinsic::sideeffect:
1372   // Neither does the assume intrinsic; it's also OK not to codegen its operand.
1373   case Intrinsic::assume:
1374   // Neither does the llvm.experimental.noalias.scope.decl intrinsic
1375   case Intrinsic::experimental_noalias_scope_decl:
1376     return true;
1377   case Intrinsic::dbg_declare: {
1378     const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
1379     assert(DI->getVariable() && "Missing variable");
1380     if (!FuncInfo.MF->getMMI().hasDebugInfo()) {
1381       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI
1382                         << " (!hasDebugInfo)\n");
1383       return true;
1384     }
1385 
1386     if (FuncInfo.PreprocessedDbgDeclares.contains(DI))
1387       return true;
1388 
1389     const Value *Address = DI->getAddress();
1390     if (!lowerDbgDeclare(Address, DI->getExpression(), DI->getVariable(),
1391                          MIMD.getDL()))
1392       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI);
1393 
1394     return true;
1395   }
1396   case Intrinsic::dbg_value: {
1397     // This form of DBG_VALUE is target-independent.
1398     const DbgValueInst *DI = cast<DbgValueInst>(II);
1399     const Value *V = DI->getValue();
1400     DIExpression *Expr = DI->getExpression();
1401     DILocalVariable *Var = DI->getVariable();
1402     if (DI->hasArgList())
1403       // Signal that we don't have a location for this.
1404       V = nullptr;
1405 
1406     assert(Var->isValidLocationForIntrinsic(MIMD.getDL()) &&
1407            "Expected inlined-at fields to agree");
1408 
1409     if (!lowerDbgValue(V, Expr, Var, MIMD.getDL()))
1410       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1411 
1412     return true;
1413   }
1414   case Intrinsic::dbg_label: {
1415     const DbgLabelInst *DI = cast<DbgLabelInst>(II);
1416     assert(DI->getLabel() && "Missing label");
1417     if (!FuncInfo.MF->getMMI().hasDebugInfo()) {
1418       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1419       return true;
1420     }
1421 
1422     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1423             TII.get(TargetOpcode::DBG_LABEL)).addMetadata(DI->getLabel());
1424     return true;
1425   }
1426   case Intrinsic::objectsize:
1427     llvm_unreachable("llvm.objectsize.* should have been lowered already");
1428 
1429   case Intrinsic::is_constant:
1430     llvm_unreachable("llvm.is.constant.* should have been lowered already");
1431 
1432   case Intrinsic::launder_invariant_group:
1433   case Intrinsic::strip_invariant_group:
1434   case Intrinsic::expect: {
1435     Register ResultReg = getRegForValue(II->getArgOperand(0));
1436     if (!ResultReg)
1437       return false;
1438     updateValueMap(II, ResultReg);
1439     return true;
1440   }
1441   case Intrinsic::experimental_stackmap:
1442     return selectStackmap(II);
1443   case Intrinsic::experimental_patchpoint_void:
1444   case Intrinsic::experimental_patchpoint_i64:
1445     return selectPatchpoint(II);
1446 
1447   case Intrinsic::xray_customevent:
1448     return selectXRayCustomEvent(II);
1449   case Intrinsic::xray_typedevent:
1450     return selectXRayTypedEvent(II);
1451   }
1452 
1453   return fastLowerIntrinsicCall(II);
1454 }
1455 
1456 bool FastISel::selectCast(const User *I, unsigned Opcode) {
1457   EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
1458   EVT DstVT = TLI.getValueType(DL, I->getType());
1459 
1460   if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other ||
1461       !DstVT.isSimple())
1462     // Unhandled type. Halt "fast" selection and bail.
1463     return false;
1464 
1465   // Check if the destination type is legal.
1466   if (!TLI.isTypeLegal(DstVT))
1467     return false;
1468 
1469   // Check if the source operand is legal.
1470   if (!TLI.isTypeLegal(SrcVT))
1471     return false;
1472 
1473   Register InputReg = getRegForValue(I->getOperand(0));
1474   if (!InputReg)
1475     // Unhandled operand.  Halt "fast" selection and bail.
1476     return false;
1477 
1478   Register ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
1479                                   Opcode, InputReg);
1480   if (!ResultReg)
1481     return false;
1482 
1483   updateValueMap(I, ResultReg);
1484   return true;
1485 }
1486 
1487 bool FastISel::selectBitCast(const User *I) {
1488   EVT SrcEVT = TLI.getValueType(DL, I->getOperand(0)->getType());
1489   EVT DstEVT = TLI.getValueType(DL, I->getType());
1490   if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
1491       !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
1492     // Unhandled type. Halt "fast" selection and bail.
1493     return false;
1494 
1495   MVT SrcVT = SrcEVT.getSimpleVT();
1496   MVT DstVT = DstEVT.getSimpleVT();
1497   Register Op0 = getRegForValue(I->getOperand(0));
1498   if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
1499     return false;
1500 
1501   // If the bitcast doesn't change the type, just use the operand value.
1502   if (SrcVT == DstVT) {
1503     updateValueMap(I, Op0);
1504     return true;
1505   }
1506 
1507   // Otherwise, select a BITCAST opcode.
1508   Register ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0);
1509   if (!ResultReg)
1510     return false;
1511 
1512   updateValueMap(I, ResultReg);
1513   return true;
1514 }
1515 
1516 bool FastISel::selectFreeze(const User *I) {
1517   Register Reg = getRegForValue(I->getOperand(0));
1518   if (!Reg)
1519     // Unhandled operand.
1520     return false;
1521 
1522   EVT ETy = TLI.getValueType(DL, I->getOperand(0)->getType());
1523   if (ETy == MVT::Other || !TLI.isTypeLegal(ETy))
1524     // Unhandled type, bail out.
1525     return false;
1526 
1527   MVT Ty = ETy.getSimpleVT();
1528   const TargetRegisterClass *TyRegClass = TLI.getRegClassFor(Ty);
1529   Register ResultReg = createResultReg(TyRegClass);
1530   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1531           TII.get(TargetOpcode::COPY), ResultReg).addReg(Reg);
1532 
1533   updateValueMap(I, ResultReg);
1534   return true;
1535 }
1536 
1537 // Remove local value instructions starting from the instruction after
1538 // SavedLastLocalValue to the current function insert point.
1539 void FastISel::removeDeadLocalValueCode(MachineInstr *SavedLastLocalValue)
1540 {
1541   MachineInstr *CurLastLocalValue = getLastLocalValue();
1542   if (CurLastLocalValue != SavedLastLocalValue) {
1543     // Find the first local value instruction to be deleted.
1544     // This is the instruction after SavedLastLocalValue if it is non-NULL.
1545     // Otherwise it's the first instruction in the block.
1546     MachineBasicBlock::iterator FirstDeadInst(SavedLastLocalValue);
1547     if (SavedLastLocalValue)
1548       ++FirstDeadInst;
1549     else
1550       FirstDeadInst = FuncInfo.MBB->getFirstNonPHI();
1551     setLastLocalValue(SavedLastLocalValue);
1552     removeDeadCode(FirstDeadInst, FuncInfo.InsertPt);
1553   }
1554 }
1555 
1556 bool FastISel::selectInstruction(const Instruction *I) {
1557   // Flush the local value map before starting each instruction.
1558   // This improves locality and debugging, and can reduce spills.
1559   // Reuse of values across IR instructions is relatively uncommon.
1560   flushLocalValueMap();
1561 
1562   MachineInstr *SavedLastLocalValue = getLastLocalValue();
1563   // Just before the terminator instruction, insert instructions to
1564   // feed PHI nodes in successor blocks.
1565   if (I->isTerminator()) {
1566     if (!handlePHINodesInSuccessorBlocks(I->getParent())) {
1567       // PHI node handling may have generated local value instructions,
1568       // even though it failed to handle all PHI nodes.
1569       // We remove these instructions because SelectionDAGISel will generate
1570       // them again.
1571       removeDeadLocalValueCode(SavedLastLocalValue);
1572       return false;
1573     }
1574   }
1575 
1576   // FastISel does not handle any operand bundles except OB_funclet.
1577   if (auto *Call = dyn_cast<CallBase>(I))
1578     for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i)
1579       if (Call->getOperandBundleAt(i).getTagID() != LLVMContext::OB_funclet)
1580         return false;
1581 
1582   MIMD = MIMetadata(*I);
1583 
1584   SavedInsertPt = FuncInfo.InsertPt;
1585 
1586   if (const auto *Call = dyn_cast<CallInst>(I)) {
1587     const Function *F = Call->getCalledFunction();
1588     LibFunc Func;
1589 
1590     // As a special case, don't handle calls to builtin library functions that
1591     // may be translated directly to target instructions.
1592     if (F && !F->hasLocalLinkage() && F->hasName() &&
1593         LibInfo->getLibFunc(F->getName(), Func) &&
1594         LibInfo->hasOptimizedCodeGen(Func))
1595       return false;
1596 
1597     // Don't handle Intrinsic::trap if a trap function is specified.
1598     if (F && F->getIntrinsicID() == Intrinsic::trap &&
1599         Call->hasFnAttr("trap-func-name"))
1600       return false;
1601   }
1602 
1603   // First, try doing target-independent selection.
1604   if (!SkipTargetIndependentISel) {
1605     if (selectOperator(I, I->getOpcode())) {
1606       ++NumFastIselSuccessIndependent;
1607       MIMD = {};
1608       return true;
1609     }
1610     // Remove dead code.
1611     recomputeInsertPt();
1612     if (SavedInsertPt != FuncInfo.InsertPt)
1613       removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
1614     SavedInsertPt = FuncInfo.InsertPt;
1615   }
1616   // Next, try calling the target to attempt to handle the instruction.
1617   if (fastSelectInstruction(I)) {
1618     ++NumFastIselSuccessTarget;
1619     MIMD = {};
1620     return true;
1621   }
1622   // Remove dead code.
1623   recomputeInsertPt();
1624   if (SavedInsertPt != FuncInfo.InsertPt)
1625     removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
1626 
1627   MIMD = {};
1628   // Undo phi node updates, because they will be added again by SelectionDAG.
1629   if (I->isTerminator()) {
1630     // PHI node handling may have generated local value instructions.
1631     // We remove them because SelectionDAGISel will generate them again.
1632     removeDeadLocalValueCode(SavedLastLocalValue);
1633     FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
1634   }
1635   return false;
1636 }
1637 
1638 /// Emit an unconditional branch to the given block, unless it is the immediate
1639 /// (fall-through) successor, and update the CFG.
1640 void FastISel::fastEmitBranch(MachineBasicBlock *MSucc,
1641                               const DebugLoc &DbgLoc) {
1642   if (FuncInfo.MBB->getBasicBlock()->sizeWithoutDebug() > 1 &&
1643       FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
1644     // For more accurate line information if this is the only non-debug
1645     // instruction in the block then emit it, otherwise we have the
1646     // unconditional fall-through case, which needs no instructions.
1647   } else {
1648     // The unconditional branch case.
1649     TII.insertBranch(*FuncInfo.MBB, MSucc, nullptr,
1650                      SmallVector<MachineOperand, 0>(), DbgLoc);
1651   }
1652   if (FuncInfo.BPI) {
1653     auto BranchProbability = FuncInfo.BPI->getEdgeProbability(
1654         FuncInfo.MBB->getBasicBlock(), MSucc->getBasicBlock());
1655     FuncInfo.MBB->addSuccessor(MSucc, BranchProbability);
1656   } else
1657     FuncInfo.MBB->addSuccessorWithoutProb(MSucc);
1658 }
1659 
1660 void FastISel::finishCondBranch(const BasicBlock *BranchBB,
1661                                 MachineBasicBlock *TrueMBB,
1662                                 MachineBasicBlock *FalseMBB) {
1663   // Add TrueMBB as successor unless it is equal to the FalseMBB: This can
1664   // happen in degenerate IR and MachineIR forbids to have a block twice in the
1665   // successor/predecessor lists.
1666   if (TrueMBB != FalseMBB) {
1667     if (FuncInfo.BPI) {
1668       auto BranchProbability =
1669           FuncInfo.BPI->getEdgeProbability(BranchBB, TrueMBB->getBasicBlock());
1670       FuncInfo.MBB->addSuccessor(TrueMBB, BranchProbability);
1671     } else
1672       FuncInfo.MBB->addSuccessorWithoutProb(TrueMBB);
1673   }
1674 
1675   fastEmitBranch(FalseMBB, MIMD.getDL());
1676 }
1677 
1678 /// Emit an FNeg operation.
1679 bool FastISel::selectFNeg(const User *I, const Value *In) {
1680   Register OpReg = getRegForValue(In);
1681   if (!OpReg)
1682     return false;
1683 
1684   // If the target has ISD::FNEG, use it.
1685   EVT VT = TLI.getValueType(DL, I->getType());
1686   Register ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG,
1687                                   OpReg);
1688   if (ResultReg) {
1689     updateValueMap(I, ResultReg);
1690     return true;
1691   }
1692 
1693   // Bitcast the value to integer, twiddle the sign bit with xor,
1694   // and then bitcast it back to floating-point.
1695   if (VT.getSizeInBits() > 64)
1696     return false;
1697   EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
1698   if (!TLI.isTypeLegal(IntVT))
1699     return false;
1700 
1701   Register IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
1702                                ISD::BITCAST, OpReg);
1703   if (!IntReg)
1704     return false;
1705 
1706   Register IntResultReg = fastEmit_ri_(
1707       IntVT.getSimpleVT(), ISD::XOR, IntReg,
1708       UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT());
1709   if (!IntResultReg)
1710     return false;
1711 
1712   ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST,
1713                          IntResultReg);
1714   if (!ResultReg)
1715     return false;
1716 
1717   updateValueMap(I, ResultReg);
1718   return true;
1719 }
1720 
1721 bool FastISel::selectExtractValue(const User *U) {
1722   const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
1723   if (!EVI)
1724     return false;
1725 
1726   // Make sure we only try to handle extracts with a legal result.  But also
1727   // allow i1 because it's easy.
1728   EVT RealVT = TLI.getValueType(DL, EVI->getType(), /*AllowUnknown=*/true);
1729   if (!RealVT.isSimple())
1730     return false;
1731   MVT VT = RealVT.getSimpleVT();
1732   if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
1733     return false;
1734 
1735   const Value *Op0 = EVI->getOperand(0);
1736   Type *AggTy = Op0->getType();
1737 
1738   // Get the base result register.
1739   unsigned ResultReg;
1740   DenseMap<const Value *, Register>::iterator I = FuncInfo.ValueMap.find(Op0);
1741   if (I != FuncInfo.ValueMap.end())
1742     ResultReg = I->second;
1743   else if (isa<Instruction>(Op0))
1744     ResultReg = FuncInfo.InitializeRegForValue(Op0);
1745   else
1746     return false; // fast-isel can't handle aggregate constants at the moment
1747 
1748   // Get the actual result register, which is an offset from the base register.
1749   unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
1750 
1751   SmallVector<EVT, 4> AggValueVTs;
1752   ComputeValueVTs(TLI, DL, AggTy, AggValueVTs);
1753 
1754   for (unsigned i = 0; i < VTIndex; i++)
1755     ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
1756 
1757   updateValueMap(EVI, ResultReg);
1758   return true;
1759 }
1760 
1761 bool FastISel::selectOperator(const User *I, unsigned Opcode) {
1762   switch (Opcode) {
1763   case Instruction::Add:
1764     return selectBinaryOp(I, ISD::ADD);
1765   case Instruction::FAdd:
1766     return selectBinaryOp(I, ISD::FADD);
1767   case Instruction::Sub:
1768     return selectBinaryOp(I, ISD::SUB);
1769   case Instruction::FSub:
1770     return selectBinaryOp(I, ISD::FSUB);
1771   case Instruction::Mul:
1772     return selectBinaryOp(I, ISD::MUL);
1773   case Instruction::FMul:
1774     return selectBinaryOp(I, ISD::FMUL);
1775   case Instruction::SDiv:
1776     return selectBinaryOp(I, ISD::SDIV);
1777   case Instruction::UDiv:
1778     return selectBinaryOp(I, ISD::UDIV);
1779   case Instruction::FDiv:
1780     return selectBinaryOp(I, ISD::FDIV);
1781   case Instruction::SRem:
1782     return selectBinaryOp(I, ISD::SREM);
1783   case Instruction::URem:
1784     return selectBinaryOp(I, ISD::UREM);
1785   case Instruction::FRem:
1786     return selectBinaryOp(I, ISD::FREM);
1787   case Instruction::Shl:
1788     return selectBinaryOp(I, ISD::SHL);
1789   case Instruction::LShr:
1790     return selectBinaryOp(I, ISD::SRL);
1791   case Instruction::AShr:
1792     return selectBinaryOp(I, ISD::SRA);
1793   case Instruction::And:
1794     return selectBinaryOp(I, ISD::AND);
1795   case Instruction::Or:
1796     return selectBinaryOp(I, ISD::OR);
1797   case Instruction::Xor:
1798     return selectBinaryOp(I, ISD::XOR);
1799 
1800   case Instruction::FNeg:
1801     return selectFNeg(I, I->getOperand(0));
1802 
1803   case Instruction::GetElementPtr:
1804     return selectGetElementPtr(I);
1805 
1806   case Instruction::Br: {
1807     const BranchInst *BI = cast<BranchInst>(I);
1808 
1809     if (BI->isUnconditional()) {
1810       const BasicBlock *LLVMSucc = BI->getSuccessor(0);
1811       MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
1812       fastEmitBranch(MSucc, BI->getDebugLoc());
1813       return true;
1814     }
1815 
1816     // Conditional branches are not handed yet.
1817     // Halt "fast" selection and bail.
1818     return false;
1819   }
1820 
1821   case Instruction::Unreachable:
1822     if (TM.Options.TrapUnreachable)
1823       return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0;
1824     else
1825       return true;
1826 
1827   case Instruction::Alloca:
1828     // FunctionLowering has the static-sized case covered.
1829     if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
1830       return true;
1831 
1832     // Dynamic-sized alloca is not handled yet.
1833     return false;
1834 
1835   case Instruction::Call:
1836     // On AIX, normal call lowering uses the DAG-ISEL path currently so that the
1837     // callee of the direct function call instruction will be mapped to the
1838     // symbol for the function's entry point, which is distinct from the
1839     // function descriptor symbol. The latter is the symbol whose XCOFF symbol
1840     // name is the C-linkage name of the source level function.
1841     // But fast isel still has the ability to do selection for intrinsics.
1842     if (TM.getTargetTriple().isOSAIX() && !isa<IntrinsicInst>(I))
1843       return false;
1844     return selectCall(I);
1845 
1846   case Instruction::BitCast:
1847     return selectBitCast(I);
1848 
1849   case Instruction::FPToSI:
1850     return selectCast(I, ISD::FP_TO_SINT);
1851   case Instruction::ZExt:
1852     return selectCast(I, ISD::ZERO_EXTEND);
1853   case Instruction::SExt:
1854     return selectCast(I, ISD::SIGN_EXTEND);
1855   case Instruction::Trunc:
1856     return selectCast(I, ISD::TRUNCATE);
1857   case Instruction::SIToFP:
1858     return selectCast(I, ISD::SINT_TO_FP);
1859 
1860   case Instruction::IntToPtr: // Deliberate fall-through.
1861   case Instruction::PtrToInt: {
1862     EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
1863     EVT DstVT = TLI.getValueType(DL, I->getType());
1864     if (DstVT.bitsGT(SrcVT))
1865       return selectCast(I, ISD::ZERO_EXTEND);
1866     if (DstVT.bitsLT(SrcVT))
1867       return selectCast(I, ISD::TRUNCATE);
1868     Register Reg = getRegForValue(I->getOperand(0));
1869     if (!Reg)
1870       return false;
1871     updateValueMap(I, Reg);
1872     return true;
1873   }
1874 
1875   case Instruction::ExtractValue:
1876     return selectExtractValue(I);
1877 
1878   case Instruction::Freeze:
1879     return selectFreeze(I);
1880 
1881   case Instruction::PHI:
1882     llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1883 
1884   default:
1885     // Unhandled instruction. Halt "fast" selection and bail.
1886     return false;
1887   }
1888 }
1889 
1890 FastISel::FastISel(FunctionLoweringInfo &FuncInfo,
1891                    const TargetLibraryInfo *LibInfo,
1892                    bool SkipTargetIndependentISel)
1893     : FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()),
1894       MFI(FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()),
1895       TM(FuncInfo.MF->getTarget()), DL(MF->getDataLayout()),
1896       TII(*MF->getSubtarget().getInstrInfo()),
1897       TLI(*MF->getSubtarget().getTargetLowering()),
1898       TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo),
1899       SkipTargetIndependentISel(SkipTargetIndependentISel) {}
1900 
1901 FastISel::~FastISel() = default;
1902 
1903 bool FastISel::fastLowerArguments() { return false; }
1904 
1905 bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; }
1906 
1907 bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) {
1908   return false;
1909 }
1910 
1911 unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; }
1912 
1913 unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/) {
1914   return 0;
1915 }
1916 
1917 unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/,
1918                                unsigned /*Op1*/) {
1919   return 0;
1920 }
1921 
1922 unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1923   return 0;
1924 }
1925 
1926 unsigned FastISel::fastEmit_f(MVT, MVT, unsigned,
1927                               const ConstantFP * /*FPImm*/) {
1928   return 0;
1929 }
1930 
1931 unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/,
1932                                uint64_t /*Imm*/) {
1933   return 0;
1934 }
1935 
1936 /// This method is a wrapper of fastEmit_ri. It first tries to emit an
1937 /// instruction with an immediate operand using fastEmit_ri.
1938 /// If that fails, it materializes the immediate into a register and try
1939 /// fastEmit_rr instead.
1940 Register FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0,
1941                                 uint64_t Imm, MVT ImmType) {
1942   // If this is a multiply by a power of two, emit this as a shift left.
1943   if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1944     Opcode = ISD::SHL;
1945     Imm = Log2_64(Imm);
1946   } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1947     // div x, 8 -> srl x, 3
1948     Opcode = ISD::SRL;
1949     Imm = Log2_64(Imm);
1950   }
1951 
1952   // Horrible hack (to be removed), check to make sure shift amounts are
1953   // in-range.
1954   if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1955       Imm >= VT.getSizeInBits())
1956     return 0;
1957 
1958   // First check if immediate type is legal. If not, we can't use the ri form.
1959   Register ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Imm);
1960   if (ResultReg)
1961     return ResultReg;
1962   Register MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1963   if (!MaterialReg) {
1964     // This is a bit ugly/slow, but failing here means falling out of
1965     // fast-isel, which would be very slow.
1966     IntegerType *ITy =
1967         IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits());
1968     MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1969     if (!MaterialReg)
1970       return 0;
1971   }
1972   return fastEmit_rr(VT, VT, Opcode, Op0, MaterialReg);
1973 }
1974 
1975 Register FastISel::createResultReg(const TargetRegisterClass *RC) {
1976   return MRI.createVirtualRegister(RC);
1977 }
1978 
1979 Register FastISel::constrainOperandRegClass(const MCInstrDesc &II, Register Op,
1980                                             unsigned OpNum) {
1981   if (Op.isVirtual()) {
1982     const TargetRegisterClass *RegClass =
1983         TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF);
1984     if (!MRI.constrainRegClass(Op, RegClass)) {
1985       // If it's not legal to COPY between the register classes, something
1986       // has gone very wrong before we got here.
1987       Register NewOp = createResultReg(RegClass);
1988       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1989               TII.get(TargetOpcode::COPY), NewOp).addReg(Op);
1990       return NewOp;
1991     }
1992   }
1993   return Op;
1994 }
1995 
1996 Register FastISel::fastEmitInst_(unsigned MachineInstOpcode,
1997                                  const TargetRegisterClass *RC) {
1998   Register ResultReg = createResultReg(RC);
1999   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2000 
2001   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg);
2002   return ResultReg;
2003 }
2004 
2005 Register FastISel::fastEmitInst_r(unsigned MachineInstOpcode,
2006                                   const TargetRegisterClass *RC, unsigned Op0) {
2007   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2008 
2009   Register ResultReg = createResultReg(RC);
2010   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
2011 
2012   if (II.getNumDefs() >= 1)
2013     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg)
2014         .addReg(Op0);
2015   else {
2016     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II)
2017         .addReg(Op0);
2018     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
2019             ResultReg)
2020         .addReg(II.implicit_defs()[0]);
2021   }
2022 
2023   return ResultReg;
2024 }
2025 
2026 Register FastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
2027                                    const TargetRegisterClass *RC, unsigned Op0,
2028                                    unsigned Op1) {
2029   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2030 
2031   Register ResultReg = createResultReg(RC);
2032   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
2033   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
2034 
2035   if (II.getNumDefs() >= 1)
2036     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg)
2037         .addReg(Op0)
2038         .addReg(Op1);
2039   else {
2040     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II)
2041         .addReg(Op0)
2042         .addReg(Op1);
2043     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
2044             ResultReg)
2045         .addReg(II.implicit_defs()[0]);
2046   }
2047   return ResultReg;
2048 }
2049 
2050 Register FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode,
2051                                     const TargetRegisterClass *RC, unsigned Op0,
2052                                     unsigned Op1, unsigned Op2) {
2053   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2054 
2055   Register ResultReg = createResultReg(RC);
2056   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
2057   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
2058   Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
2059 
2060   if (II.getNumDefs() >= 1)
2061     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg)
2062         .addReg(Op0)
2063         .addReg(Op1)
2064         .addReg(Op2);
2065   else {
2066     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II)
2067         .addReg(Op0)
2068         .addReg(Op1)
2069         .addReg(Op2);
2070     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
2071             ResultReg)
2072         .addReg(II.implicit_defs()[0]);
2073   }
2074   return ResultReg;
2075 }
2076 
2077 Register FastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
2078                                    const TargetRegisterClass *RC, unsigned Op0,
2079                                    uint64_t Imm) {
2080   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2081 
2082   Register ResultReg = createResultReg(RC);
2083   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
2084 
2085   if (II.getNumDefs() >= 1)
2086     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg)
2087         .addReg(Op0)
2088         .addImm(Imm);
2089   else {
2090     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II)
2091         .addReg(Op0)
2092         .addImm(Imm);
2093     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
2094             ResultReg)
2095         .addReg(II.implicit_defs()[0]);
2096   }
2097   return ResultReg;
2098 }
2099 
2100 Register FastISel::fastEmitInst_rii(unsigned MachineInstOpcode,
2101                                     const TargetRegisterClass *RC, unsigned Op0,
2102                                     uint64_t Imm1, uint64_t Imm2) {
2103   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2104 
2105   Register ResultReg = createResultReg(RC);
2106   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
2107 
2108   if (II.getNumDefs() >= 1)
2109     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg)
2110         .addReg(Op0)
2111         .addImm(Imm1)
2112         .addImm(Imm2);
2113   else {
2114     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II)
2115         .addReg(Op0)
2116         .addImm(Imm1)
2117         .addImm(Imm2);
2118     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
2119             ResultReg)
2120         .addReg(II.implicit_defs()[0]);
2121   }
2122   return ResultReg;
2123 }
2124 
2125 Register FastISel::fastEmitInst_f(unsigned MachineInstOpcode,
2126                                   const TargetRegisterClass *RC,
2127                                   const ConstantFP *FPImm) {
2128   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2129 
2130   Register ResultReg = createResultReg(RC);
2131 
2132   if (II.getNumDefs() >= 1)
2133     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg)
2134         .addFPImm(FPImm);
2135   else {
2136     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II)
2137         .addFPImm(FPImm);
2138     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
2139             ResultReg)
2140         .addReg(II.implicit_defs()[0]);
2141   }
2142   return ResultReg;
2143 }
2144 
2145 Register FastISel::fastEmitInst_rri(unsigned MachineInstOpcode,
2146                                     const TargetRegisterClass *RC, unsigned Op0,
2147                                     unsigned Op1, uint64_t Imm) {
2148   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2149 
2150   Register ResultReg = createResultReg(RC);
2151   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
2152   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
2153 
2154   if (II.getNumDefs() >= 1)
2155     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg)
2156         .addReg(Op0)
2157         .addReg(Op1)
2158         .addImm(Imm);
2159   else {
2160     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II)
2161         .addReg(Op0)
2162         .addReg(Op1)
2163         .addImm(Imm);
2164     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
2165             ResultReg)
2166         .addReg(II.implicit_defs()[0]);
2167   }
2168   return ResultReg;
2169 }
2170 
2171 Register FastISel::fastEmitInst_i(unsigned MachineInstOpcode,
2172                                   const TargetRegisterClass *RC, uint64_t Imm) {
2173   Register ResultReg = createResultReg(RC);
2174   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2175 
2176   if (II.getNumDefs() >= 1)
2177     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg)
2178         .addImm(Imm);
2179   else {
2180     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II).addImm(Imm);
2181     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
2182             ResultReg)
2183         .addReg(II.implicit_defs()[0]);
2184   }
2185   return ResultReg;
2186 }
2187 
2188 Register FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0,
2189                                               uint32_t Idx) {
2190   Register ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
2191   assert(Register::isVirtualRegister(Op0) &&
2192          "Cannot yet extract from physregs");
2193   const TargetRegisterClass *RC = MRI.getRegClass(Op0);
2194   MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
2195   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
2196           ResultReg).addReg(Op0, 0, Idx);
2197   return ResultReg;
2198 }
2199 
2200 /// Emit MachineInstrs to compute the value of Op with all but the least
2201 /// significant bit set to zero.
2202 Register FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0) {
2203   return fastEmit_ri(VT, VT, ISD::AND, Op0, 1);
2204 }
2205 
2206 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
2207 /// Emit code to ensure constants are copied into registers when needed.
2208 /// Remember the virtual registers that need to be added to the Machine PHI
2209 /// nodes as input.  We cannot just directly add them, because expansion
2210 /// might result in multiple MBB's for one BB.  As such, the start of the
2211 /// BB might correspond to a different MBB than the end.
2212 bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
2213   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
2214   FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
2215 
2216   // Check successor nodes' PHI nodes that expect a constant to be available
2217   // from this block.
2218   for (const BasicBlock *SuccBB : successors(LLVMBB)) {
2219     if (!isa<PHINode>(SuccBB->begin()))
2220       continue;
2221     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
2222 
2223     // If this terminator has multiple identical successors (common for
2224     // switches), only handle each succ once.
2225     if (!SuccsHandled.insert(SuccMBB).second)
2226       continue;
2227 
2228     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
2229 
2230     // At this point we know that there is a 1-1 correspondence between LLVM PHI
2231     // nodes and Machine PHI nodes, but the incoming operands have not been
2232     // emitted yet.
2233     for (const PHINode &PN : SuccBB->phis()) {
2234       // Ignore dead phi's.
2235       if (PN.use_empty())
2236         continue;
2237 
2238       // Only handle legal types. Two interesting things to note here. First,
2239       // by bailing out early, we may leave behind some dead instructions,
2240       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
2241       // own moves. Second, this check is necessary because FastISel doesn't
2242       // use CreateRegs to create registers, so it always creates
2243       // exactly one register for each non-void instruction.
2244       EVT VT = TLI.getValueType(DL, PN.getType(), /*AllowUnknown=*/true);
2245       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
2246         // Handle integer promotions, though, because they're common and easy.
2247         if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) {
2248           FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
2249           return false;
2250         }
2251       }
2252 
2253       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
2254 
2255       // Set the DebugLoc for the copy. Use the location of the operand if
2256       // there is one; otherwise no location, flushLocalValueMap will fix it.
2257       MIMD = {};
2258       if (const auto *Inst = dyn_cast<Instruction>(PHIOp))
2259         MIMD = MIMetadata(*Inst);
2260 
2261       Register Reg = getRegForValue(PHIOp);
2262       if (!Reg) {
2263         FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
2264         return false;
2265       }
2266       FuncInfo.PHINodesToUpdate.push_back(std::make_pair(&*MBBI++, Reg));
2267       MIMD = {};
2268     }
2269   }
2270 
2271   return true;
2272 }
2273 
2274 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
2275   assert(LI->hasOneUse() &&
2276          "tryToFoldLoad expected a LoadInst with a single use");
2277   // We know that the load has a single use, but don't know what it is.  If it
2278   // isn't one of the folded instructions, then we can't succeed here.  Handle
2279   // this by scanning the single-use users of the load until we get to FoldInst.
2280   unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
2281 
2282   const Instruction *TheUser = LI->user_back();
2283   while (TheUser != FoldInst && // Scan up until we find FoldInst.
2284          // Stay in the right block.
2285          TheUser->getParent() == FoldInst->getParent() &&
2286          --MaxUsers) { // Don't scan too far.
2287     // If there are multiple or no uses of this instruction, then bail out.
2288     if (!TheUser->hasOneUse())
2289       return false;
2290 
2291     TheUser = TheUser->user_back();
2292   }
2293 
2294   // If we didn't find the fold instruction, then we failed to collapse the
2295   // sequence.
2296   if (TheUser != FoldInst)
2297     return false;
2298 
2299   // Don't try to fold volatile loads.  Target has to deal with alignment
2300   // constraints.
2301   if (LI->isVolatile())
2302     return false;
2303 
2304   // Figure out which vreg this is going into.  If there is no assigned vreg yet
2305   // then there actually was no reference to it.  Perhaps the load is referenced
2306   // by a dead instruction.
2307   Register LoadReg = getRegForValue(LI);
2308   if (!LoadReg)
2309     return false;
2310 
2311   // We can't fold if this vreg has no uses or more than one use.  Multiple uses
2312   // may mean that the instruction got lowered to multiple MIs, or the use of
2313   // the loaded value ended up being multiple operands of the result.
2314   if (!MRI.hasOneUse(LoadReg))
2315     return false;
2316 
2317   // If the register has fixups, there may be additional uses through a
2318   // different alias of the register.
2319   if (FuncInfo.RegsWithFixups.contains(LoadReg))
2320     return false;
2321 
2322   MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
2323   MachineInstr *User = RI->getParent();
2324 
2325   // Set the insertion point properly.  Folding the load can cause generation of
2326   // other random instructions (like sign extends) for addressing modes; make
2327   // sure they get inserted in a logical place before the new instruction.
2328   FuncInfo.InsertPt = User;
2329   FuncInfo.MBB = User->getParent();
2330 
2331   // Ask the target to try folding the load.
2332   return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);
2333 }
2334 
2335 bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) {
2336   // Must be an add.
2337   if (!isa<AddOperator>(Add))
2338     return false;
2339   // Type size needs to match.
2340   if (DL.getTypeSizeInBits(GEP->getType()) !=
2341       DL.getTypeSizeInBits(Add->getType()))
2342     return false;
2343   // Must be in the same basic block.
2344   if (isa<Instruction>(Add) &&
2345       FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB)
2346     return false;
2347   // Must have a constant operand.
2348   return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1));
2349 }
2350 
2351 MachineMemOperand *
2352 FastISel::createMachineMemOperandFor(const Instruction *I) const {
2353   const Value *Ptr;
2354   Type *ValTy;
2355   MaybeAlign Alignment;
2356   MachineMemOperand::Flags Flags;
2357   bool IsVolatile;
2358 
2359   if (const auto *LI = dyn_cast<LoadInst>(I)) {
2360     Alignment = LI->getAlign();
2361     IsVolatile = LI->isVolatile();
2362     Flags = MachineMemOperand::MOLoad;
2363     Ptr = LI->getPointerOperand();
2364     ValTy = LI->getType();
2365   } else if (const auto *SI = dyn_cast<StoreInst>(I)) {
2366     Alignment = SI->getAlign();
2367     IsVolatile = SI->isVolatile();
2368     Flags = MachineMemOperand::MOStore;
2369     Ptr = SI->getPointerOperand();
2370     ValTy = SI->getValueOperand()->getType();
2371   } else
2372     return nullptr;
2373 
2374   bool IsNonTemporal = I->hasMetadata(LLVMContext::MD_nontemporal);
2375   bool IsInvariant = I->hasMetadata(LLVMContext::MD_invariant_load);
2376   bool IsDereferenceable = I->hasMetadata(LLVMContext::MD_dereferenceable);
2377   const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range);
2378 
2379   AAMDNodes AAInfo = I->getAAMetadata();
2380 
2381   if (!Alignment) // Ensure that codegen never sees alignment 0.
2382     Alignment = DL.getABITypeAlign(ValTy);
2383 
2384   unsigned Size = DL.getTypeStoreSize(ValTy);
2385 
2386   if (IsVolatile)
2387     Flags |= MachineMemOperand::MOVolatile;
2388   if (IsNonTemporal)
2389     Flags |= MachineMemOperand::MONonTemporal;
2390   if (IsDereferenceable)
2391     Flags |= MachineMemOperand::MODereferenceable;
2392   if (IsInvariant)
2393     Flags |= MachineMemOperand::MOInvariant;
2394 
2395   return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size,
2396                                            *Alignment, AAInfo, Ranges);
2397 }
2398 
2399 CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const {
2400   // If both operands are the same, then try to optimize or fold the cmp.
2401   CmpInst::Predicate Predicate = CI->getPredicate();
2402   if (CI->getOperand(0) != CI->getOperand(1))
2403     return Predicate;
2404 
2405   switch (Predicate) {
2406   default: llvm_unreachable("Invalid predicate!");
2407   case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
2408   case CmpInst::FCMP_OEQ:   Predicate = CmpInst::FCMP_ORD;   break;
2409   case CmpInst::FCMP_OGT:   Predicate = CmpInst::FCMP_FALSE; break;
2410   case CmpInst::FCMP_OGE:   Predicate = CmpInst::FCMP_ORD;   break;
2411   case CmpInst::FCMP_OLT:   Predicate = CmpInst::FCMP_FALSE; break;
2412   case CmpInst::FCMP_OLE:   Predicate = CmpInst::FCMP_ORD;   break;
2413   case CmpInst::FCMP_ONE:   Predicate = CmpInst::FCMP_FALSE; break;
2414   case CmpInst::FCMP_ORD:   Predicate = CmpInst::FCMP_ORD;   break;
2415   case CmpInst::FCMP_UNO:   Predicate = CmpInst::FCMP_UNO;   break;
2416   case CmpInst::FCMP_UEQ:   Predicate = CmpInst::FCMP_TRUE;  break;
2417   case CmpInst::FCMP_UGT:   Predicate = CmpInst::FCMP_UNO;   break;
2418   case CmpInst::FCMP_UGE:   Predicate = CmpInst::FCMP_TRUE;  break;
2419   case CmpInst::FCMP_ULT:   Predicate = CmpInst::FCMP_UNO;   break;
2420   case CmpInst::FCMP_ULE:   Predicate = CmpInst::FCMP_TRUE;  break;
2421   case CmpInst::FCMP_UNE:   Predicate = CmpInst::FCMP_UNO;   break;
2422   case CmpInst::FCMP_TRUE:  Predicate = CmpInst::FCMP_TRUE;  break;
2423 
2424   case CmpInst::ICMP_EQ:    Predicate = CmpInst::FCMP_TRUE;  break;
2425   case CmpInst::ICMP_NE:    Predicate = CmpInst::FCMP_FALSE; break;
2426   case CmpInst::ICMP_UGT:   Predicate = CmpInst::FCMP_FALSE; break;
2427   case CmpInst::ICMP_UGE:   Predicate = CmpInst::FCMP_TRUE;  break;
2428   case CmpInst::ICMP_ULT:   Predicate = CmpInst::FCMP_FALSE; break;
2429   case CmpInst::ICMP_ULE:   Predicate = CmpInst::FCMP_TRUE;  break;
2430   case CmpInst::ICMP_SGT:   Predicate = CmpInst::FCMP_FALSE; break;
2431   case CmpInst::ICMP_SGE:   Predicate = CmpInst::FCMP_TRUE;  break;
2432   case CmpInst::ICMP_SLT:   Predicate = CmpInst::FCMP_FALSE; break;
2433   case CmpInst::ICMP_SLE:   Predicate = CmpInst::FCMP_TRUE;  break;
2434   }
2435 
2436   return Predicate;
2437 }
2438