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