1 //===-- lib/CodeGen/GlobalISel/InlineAsmLowering.cpp ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements the lowering from LLVM IR inline asm to MIR INLINEASM
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/GlobalISel/InlineAsmLowering.h"
15 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
16 #include "llvm/CodeGen/MachineOperand.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/TargetLowering.h"
19 #include "llvm/IR/Module.h"
20 
21 #define DEBUG_TYPE "inline-asm-lowering"
22 
23 using namespace llvm;
24 
25 void InlineAsmLowering::anchor() {}
26 
27 namespace {
28 
29 /// GISelAsmOperandInfo - This contains information for each constraint that we
30 /// are lowering.
31 class GISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
32 public:
33   /// Regs - If this is a register or register class operand, this
34   /// contains the set of assigned registers corresponding to the operand.
35   SmallVector<Register, 1> Regs;
36 
37   explicit GISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &Info)
38       : TargetLowering::AsmOperandInfo(Info) {}
39 };
40 
41 using GISelAsmOperandInfoVector = SmallVector<GISelAsmOperandInfo, 16>;
42 
43 class ExtraFlags {
44   unsigned Flags = 0;
45 
46 public:
47   explicit ExtraFlags(const CallBase &CB) {
48     const InlineAsm *IA = cast<InlineAsm>(CB.getCalledOperand());
49     if (IA->hasSideEffects())
50       Flags |= InlineAsm::Extra_HasSideEffects;
51     if (IA->isAlignStack())
52       Flags |= InlineAsm::Extra_IsAlignStack;
53     if (CB.isConvergent())
54       Flags |= InlineAsm::Extra_IsConvergent;
55     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
56   }
57 
58   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
59     // Ideally, we would only check against memory constraints.  However, the
60     // meaning of an Other constraint can be target-specific and we can't easily
61     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
62     // for Other constraints as well.
63     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
64         OpInfo.ConstraintType == TargetLowering::C_Other) {
65       if (OpInfo.Type == InlineAsm::isInput)
66         Flags |= InlineAsm::Extra_MayLoad;
67       else if (OpInfo.Type == InlineAsm::isOutput)
68         Flags |= InlineAsm::Extra_MayStore;
69       else if (OpInfo.Type == InlineAsm::isClobber)
70         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
71     }
72   }
73 
74   unsigned get() const { return Flags; }
75 };
76 
77 } // namespace
78 
79 /// Assign virtual/physical registers for the specified register operand.
80 static void getRegistersForValue(MachineFunction &MF,
81                                  MachineIRBuilder &MIRBuilder,
82                                  GISelAsmOperandInfo &OpInfo,
83                                  GISelAsmOperandInfo &RefOpInfo) {
84 
85   const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
86   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
87 
88   // No work to do for memory operations.
89   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
90     return;
91 
92   // If this is a constraint for a single physreg, or a constraint for a
93   // register class, find it.
94   Register AssignedReg;
95   const TargetRegisterClass *RC;
96   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
97       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
98   // RC is unset only on failure. Return immediately.
99   if (!RC)
100     return;
101 
102   // No need to allocate a matching input constraint since the constraint it's
103   // matching to has already been allocated.
104   if (OpInfo.isMatchingInputConstraint())
105     return;
106 
107   // Initialize NumRegs.
108   unsigned NumRegs = 1;
109   if (OpInfo.ConstraintVT != MVT::Other)
110     NumRegs =
111         TLI.getNumRegisters(MF.getFunction().getContext(), OpInfo.ConstraintVT);
112 
113   // If this is a constraint for a specific physical register, but the type of
114   // the operand requires more than one register to be passed, we allocate the
115   // required amount of physical registers, starting from the selected physical
116   // register.
117   // For this, first retrieve a register iterator for the given register class
118   TargetRegisterClass::iterator I = RC->begin();
119   MachineRegisterInfo &RegInfo = MF.getRegInfo();
120 
121   // Advance the iterator to the assigned register (if set)
122   if (AssignedReg) {
123     for (; *I != AssignedReg; ++I)
124       assert(I != RC->end() && "AssignedReg should be a member of provided RC");
125   }
126 
127   // Finally, assign the registers. If the AssignedReg isn't set, create virtual
128   // registers with the provided register class
129   for (; NumRegs; --NumRegs, ++I) {
130     assert(I != RC->end() && "Ran out of registers to allocate!");
131     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
132     OpInfo.Regs.push_back(R);
133   }
134 }
135 
136 /// Return an integer indicating how general CT is.
137 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
138   switch (CT) {
139   case TargetLowering::C_Immediate:
140   case TargetLowering::C_Other:
141   case TargetLowering::C_Unknown:
142     return 0;
143   case TargetLowering::C_Register:
144     return 1;
145   case TargetLowering::C_RegisterClass:
146     return 2;
147   case TargetLowering::C_Memory:
148     return 3;
149   }
150   llvm_unreachable("Invalid constraint type");
151 }
152 
153 static void chooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
154                              const TargetLowering *TLI) {
155   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
156   unsigned BestIdx = 0;
157   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
158   int BestGenerality = -1;
159 
160   // Loop over the options, keeping track of the most general one.
161   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
162     TargetLowering::ConstraintType CType =
163         TLI->getConstraintType(OpInfo.Codes[i]);
164 
165     // Indirect 'other' or 'immediate' constraints are not allowed.
166     if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
167                                CType == TargetLowering::C_Register ||
168                                CType == TargetLowering::C_RegisterClass))
169       continue;
170 
171     // If this is an 'other' or 'immediate' constraint, see if the operand is
172     // valid for it. For example, on X86 we might have an 'rI' constraint. If
173     // the operand is an integer in the range [0..31] we want to use I (saving a
174     // load of a register), otherwise we must use 'r'.
175     if (CType == TargetLowering::C_Other ||
176         CType == TargetLowering::C_Immediate) {
177       assert(OpInfo.Codes[i].size() == 1 &&
178              "Unhandled multi-letter 'other' constraint");
179       // FIXME: prefer immediate constraints if the target allows it
180     }
181 
182     // Things with matching constraints can only be registers, per gcc
183     // documentation.  This mainly affects "g" constraints.
184     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
185       continue;
186 
187     // This constraint letter is more general than the previous one, use it.
188     int Generality = getConstraintGenerality(CType);
189     if (Generality > BestGenerality) {
190       BestType = CType;
191       BestIdx = i;
192       BestGenerality = Generality;
193     }
194   }
195 
196   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
197   OpInfo.ConstraintType = BestType;
198 }
199 
200 static void computeConstraintToUse(const TargetLowering *TLI,
201                                    TargetLowering::AsmOperandInfo &OpInfo) {
202   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
203 
204   // Single-letter constraints ('r') are very common.
205   if (OpInfo.Codes.size() == 1) {
206     OpInfo.ConstraintCode = OpInfo.Codes[0];
207     OpInfo.ConstraintType = TLI->getConstraintType(OpInfo.ConstraintCode);
208   } else {
209     chooseConstraint(OpInfo, TLI);
210   }
211 
212   // 'X' matches anything.
213   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
214     // Labels and constants are handled elsewhere ('X' is the only thing
215     // that matches labels).  For Functions, the type here is the type of
216     // the result, which is not what we want to look at; leave them alone.
217     Value *Val = OpInfo.CallOperandVal;
218     if (isa<BasicBlock>(Val) || isa<ConstantInt>(Val) || isa<Function>(Val))
219       return;
220 
221     // Otherwise, try to resolve it to something we know about by looking at
222     // the actual operand type.
223     if (const char *Repl = TLI->LowerXConstraint(OpInfo.ConstraintVT)) {
224       OpInfo.ConstraintCode = Repl;
225       OpInfo.ConstraintType = TLI->getConstraintType(OpInfo.ConstraintCode);
226     }
227   }
228 }
229 
230 static unsigned getNumOpRegs(const MachineInstr &I, unsigned OpIdx) {
231   unsigned Flag = I.getOperand(OpIdx).getImm();
232   return InlineAsm::getNumOperandRegisters(Flag);
233 }
234 
235 static bool buildAnyextOrCopy(Register Dst, Register Src,
236                               MachineIRBuilder &MIRBuilder) {
237   const TargetRegisterInfo *TRI =
238       MIRBuilder.getMF().getSubtarget().getRegisterInfo();
239   MachineRegisterInfo *MRI = MIRBuilder.getMRI();
240 
241   auto SrcTy = MRI->getType(Src);
242   if (!SrcTy.isValid()) {
243     LLVM_DEBUG(dbgs() << "Source type for copy is not valid\n");
244     return false;
245   }
246   unsigned SrcSize = TRI->getRegSizeInBits(Src, *MRI);
247   unsigned DstSize = TRI->getRegSizeInBits(Dst, *MRI);
248 
249   if (DstSize < SrcSize) {
250     LLVM_DEBUG(dbgs() << "Input can't fit in destination reg class\n");
251     return false;
252   }
253 
254   // Attempt to anyext small scalar sources.
255   if (DstSize > SrcSize) {
256     if (!SrcTy.isScalar()) {
257       LLVM_DEBUG(dbgs() << "Can't extend non-scalar input to size of"
258                            "destination register class\n");
259       return false;
260     }
261     Src = MIRBuilder.buildAnyExt(LLT::scalar(DstSize), Src).getReg(0);
262   }
263 
264   MIRBuilder.buildCopy(Dst, Src);
265   return true;
266 }
267 
268 bool InlineAsmLowering::lowerInlineAsm(
269     MachineIRBuilder &MIRBuilder, const CallBase &Call,
270     std::function<ArrayRef<Register>(const Value &Val)> GetOrCreateVRegs)
271     const {
272   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
273 
274   /// ConstraintOperands - Information about all of the constraints.
275   GISelAsmOperandInfoVector ConstraintOperands;
276 
277   MachineFunction &MF = MIRBuilder.getMF();
278   const Function &F = MF.getFunction();
279   const DataLayout &DL = F.getParent()->getDataLayout();
280   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
281 
282   MachineRegisterInfo *MRI = MIRBuilder.getMRI();
283 
284   TargetLowering::AsmOperandInfoVector TargetConstraints =
285       TLI->ParseConstraints(DL, TRI, Call);
286 
287   ExtraFlags ExtraInfo(Call);
288   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
289   unsigned ResNo = 0; // ResNo - The result number of the next output.
290   for (auto &T : TargetConstraints) {
291     ConstraintOperands.push_back(GISelAsmOperandInfo(T));
292     GISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
293 
294     // Compute the value type for each operand.
295     if (OpInfo.hasArg()) {
296       OpInfo.CallOperandVal = const_cast<Value *>(Call.getArgOperand(ArgNo));
297 
298       if (isa<BasicBlock>(OpInfo.CallOperandVal)) {
299         LLVM_DEBUG(dbgs() << "Basic block input operands not supported yet\n");
300         return false;
301       }
302 
303       Type *OpTy = OpInfo.CallOperandVal->getType();
304 
305       // If this is an indirect operand, the operand is a pointer to the
306       // accessed type.
307       if (OpInfo.isIndirect) {
308         OpTy = Call.getParamElementType(ArgNo);
309         assert(OpTy && "Indirect operand must have elementtype attribute");
310       }
311 
312       // FIXME: Support aggregate input operands
313       if (!OpTy->isSingleValueType()) {
314         LLVM_DEBUG(
315             dbgs() << "Aggregate input operands are not supported yet\n");
316         return false;
317       }
318 
319       OpInfo.ConstraintVT =
320           TLI->getAsmOperandValueType(DL, OpTy, true).getSimpleVT();
321       ++ArgNo;
322     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
323       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
324       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
325         OpInfo.ConstraintVT =
326             TLI->getSimpleValueType(DL, STy->getElementType(ResNo));
327       } else {
328         assert(ResNo == 0 && "Asm only has one result!");
329         OpInfo.ConstraintVT =
330             TLI->getAsmOperandValueType(DL, Call.getType()).getSimpleVT();
331       }
332       ++ResNo;
333     } else {
334       OpInfo.ConstraintVT = MVT::Other;
335     }
336 
337     if (OpInfo.ConstraintVT == MVT::i64x8)
338       return false;
339 
340     // Compute the constraint code and ConstraintType to use.
341     computeConstraintToUse(TLI, OpInfo);
342 
343     // The selected constraint type might expose new sideeffects
344     ExtraInfo.update(OpInfo);
345   }
346 
347   // At this point, all operand types are decided.
348   // Create the MachineInstr, but don't insert it yet since input
349   // operands still need to insert instructions before this one
350   auto Inst = MIRBuilder.buildInstrNoInsert(TargetOpcode::INLINEASM)
351                   .addExternalSymbol(IA->getAsmString().c_str())
352                   .addImm(ExtraInfo.get());
353 
354   // Starting from this operand: flag followed by register(s) will be added as
355   // operands to Inst for each constraint. Used for matching input constraints.
356   unsigned StartIdx = Inst->getNumOperands();
357 
358   // Collects the output operands for later processing
359   GISelAsmOperandInfoVector OutputOperands;
360 
361   for (auto &OpInfo : ConstraintOperands) {
362     GISelAsmOperandInfo &RefOpInfo =
363         OpInfo.isMatchingInputConstraint()
364             ? ConstraintOperands[OpInfo.getMatchedOperand()]
365             : OpInfo;
366 
367     // Assign registers for register operands
368     getRegistersForValue(MF, MIRBuilder, OpInfo, RefOpInfo);
369 
370     switch (OpInfo.Type) {
371     case InlineAsm::isOutput:
372       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
373         unsigned ConstraintID =
374             TLI->getInlineAsmMemConstraint(OpInfo.ConstraintCode);
375         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
376                "Failed to convert memory constraint code to constraint id.");
377 
378         // Add information to the INLINEASM instruction to know about this
379         // output.
380         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
381         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
382         Inst.addImm(OpFlags);
383         ArrayRef<Register> SourceRegs =
384             GetOrCreateVRegs(*OpInfo.CallOperandVal);
385         assert(
386             SourceRegs.size() == 1 &&
387             "Expected the memory output to fit into a single virtual register");
388         Inst.addReg(SourceRegs[0]);
389       } else {
390         // Otherwise, this outputs to a register (directly for C_Register /
391         // C_RegisterClass. Find a register that we can use.
392         assert(OpInfo.ConstraintType == TargetLowering::C_Register ||
393                OpInfo.ConstraintType == TargetLowering::C_RegisterClass);
394 
395         if (OpInfo.Regs.empty()) {
396           LLVM_DEBUG(dbgs()
397                      << "Couldn't allocate output register for constraint\n");
398           return false;
399         }
400 
401         // Add information to the INLINEASM instruction to know that this
402         // register is set.
403         unsigned Flag = InlineAsm::getFlagWord(
404             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
405                                   : InlineAsm::Kind_RegDef,
406             OpInfo.Regs.size());
407         if (OpInfo.Regs.front().isVirtual()) {
408           // Put the register class of the virtual registers in the flag word.
409           // That way, later passes can recompute register class constraints for
410           // inline assembly as well as normal instructions. Don't do this for
411           // tied operands that can use the regclass information from the def.
412           const TargetRegisterClass *RC = MRI->getRegClass(OpInfo.Regs.front());
413           Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
414         }
415 
416         Inst.addImm(Flag);
417 
418         for (Register Reg : OpInfo.Regs) {
419           Inst.addReg(Reg,
420                       RegState::Define | getImplRegState(Reg.isPhysical()) |
421                           (OpInfo.isEarlyClobber ? RegState::EarlyClobber : 0));
422         }
423 
424         // Remember this output operand for later processing
425         OutputOperands.push_back(OpInfo);
426       }
427 
428       break;
429     case InlineAsm::isInput: {
430       if (OpInfo.isMatchingInputConstraint()) {
431         unsigned DefIdx = OpInfo.getMatchedOperand();
432         // Find operand with register def that corresponds to DefIdx.
433         unsigned InstFlagIdx = StartIdx;
434         for (unsigned i = 0; i < DefIdx; ++i)
435           InstFlagIdx += getNumOpRegs(*Inst, InstFlagIdx) + 1;
436         assert(getNumOpRegs(*Inst, InstFlagIdx) == 1 && "Wrong flag");
437 
438         unsigned MatchedOperandFlag = Inst->getOperand(InstFlagIdx).getImm();
439         if (InlineAsm::isMemKind(MatchedOperandFlag)) {
440           LLVM_DEBUG(dbgs() << "Matching input constraint to mem operand not "
441                                "supported. This should be target specific.\n");
442           return false;
443         }
444         if (!InlineAsm::isRegDefKind(MatchedOperandFlag) &&
445             !InlineAsm::isRegDefEarlyClobberKind(MatchedOperandFlag)) {
446           LLVM_DEBUG(dbgs() << "Unknown matching constraint\n");
447           return false;
448         }
449 
450         // We want to tie input to register in next operand.
451         unsigned DefRegIdx = InstFlagIdx + 1;
452         Register Def = Inst->getOperand(DefRegIdx).getReg();
453 
454         ArrayRef<Register> SrcRegs = GetOrCreateVRegs(*OpInfo.CallOperandVal);
455         assert(SrcRegs.size() == 1 && "Single register is expected here");
456 
457         // When Def is physreg: use given input.
458         Register In = SrcRegs[0];
459         // When Def is vreg: copy input to new vreg with same reg class as Def.
460         if (Def.isVirtual()) {
461           In = MRI->createVirtualRegister(MRI->getRegClass(Def));
462           if (!buildAnyextOrCopy(In, SrcRegs[0], MIRBuilder))
463             return false;
464         }
465 
466         // Add Flag and input register operand (In) to Inst. Tie In to Def.
467         unsigned UseFlag = InlineAsm::getFlagWord(InlineAsm::Kind_RegUse, 1);
468         unsigned Flag = InlineAsm::getFlagWordForMatchingOp(UseFlag, DefIdx);
469         Inst.addImm(Flag);
470         Inst.addReg(In);
471         Inst->tieOperands(DefRegIdx, Inst->getNumOperands() - 1);
472         break;
473       }
474 
475       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
476           OpInfo.isIndirect) {
477         LLVM_DEBUG(dbgs() << "Indirect input operands with unknown constraint "
478                              "not supported yet\n");
479         return false;
480       }
481 
482       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
483           OpInfo.ConstraintType == TargetLowering::C_Other) {
484 
485         std::vector<MachineOperand> Ops;
486         if (!lowerAsmOperandForConstraint(OpInfo.CallOperandVal,
487                                           OpInfo.ConstraintCode, Ops,
488                                           MIRBuilder)) {
489           LLVM_DEBUG(dbgs() << "Don't support constraint: "
490                             << OpInfo.ConstraintCode << " yet\n");
491           return false;
492         }
493 
494         assert(Ops.size() > 0 &&
495                "Expected constraint to be lowered to at least one operand");
496 
497         // Add information to the INLINEASM node to know about this input.
498         unsigned OpFlags =
499             InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
500         Inst.addImm(OpFlags);
501         Inst.add(Ops);
502         break;
503       }
504 
505       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
506 
507         if (!OpInfo.isIndirect) {
508           LLVM_DEBUG(dbgs()
509                      << "Cannot indirectify memory input operands yet\n");
510           return false;
511         }
512 
513         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
514 
515         unsigned ConstraintID =
516             TLI->getInlineAsmMemConstraint(OpInfo.ConstraintCode);
517         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
518         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
519         Inst.addImm(OpFlags);
520         ArrayRef<Register> SourceRegs =
521             GetOrCreateVRegs(*OpInfo.CallOperandVal);
522         assert(
523             SourceRegs.size() == 1 &&
524             "Expected the memory input to fit into a single virtual register");
525         Inst.addReg(SourceRegs[0]);
526         break;
527       }
528 
529       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
530               OpInfo.ConstraintType == TargetLowering::C_Register) &&
531              "Unknown constraint type!");
532 
533       if (OpInfo.isIndirect) {
534         LLVM_DEBUG(dbgs() << "Can't handle indirect register inputs yet "
535                              "for constraint '"
536                           << OpInfo.ConstraintCode << "'\n");
537         return false;
538       }
539 
540       // Copy the input into the appropriate registers.
541       if (OpInfo.Regs.empty()) {
542         LLVM_DEBUG(
543             dbgs()
544             << "Couldn't allocate input register for register constraint\n");
545         return false;
546       }
547 
548       unsigned NumRegs = OpInfo.Regs.size();
549       ArrayRef<Register> SourceRegs = GetOrCreateVRegs(*OpInfo.CallOperandVal);
550       assert(NumRegs == SourceRegs.size() &&
551              "Expected the number of input registers to match the number of "
552              "source registers");
553 
554       if (NumRegs > 1) {
555         LLVM_DEBUG(dbgs() << "Input operands with multiple input registers are "
556                              "not supported yet\n");
557         return false;
558       }
559 
560       unsigned Flag = InlineAsm::getFlagWord(InlineAsm::Kind_RegUse, NumRegs);
561       if (OpInfo.Regs.front().isVirtual()) {
562         // Put the register class of the virtual registers in the flag word.
563         const TargetRegisterClass *RC = MRI->getRegClass(OpInfo.Regs.front());
564         Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
565       }
566       Inst.addImm(Flag);
567       if (!buildAnyextOrCopy(OpInfo.Regs[0], SourceRegs[0], MIRBuilder))
568         return false;
569       Inst.addReg(OpInfo.Regs[0]);
570       break;
571     }
572 
573     case InlineAsm::isClobber: {
574 
575       unsigned NumRegs = OpInfo.Regs.size();
576       if (NumRegs > 0) {
577         unsigned Flag =
578             InlineAsm::getFlagWord(InlineAsm::Kind_Clobber, NumRegs);
579         Inst.addImm(Flag);
580 
581         for (Register Reg : OpInfo.Regs) {
582           Inst.addReg(Reg, RegState::Define | RegState::EarlyClobber |
583                                getImplRegState(Reg.isPhysical()));
584         }
585       }
586       break;
587     }
588     }
589   }
590 
591   if (const MDNode *SrcLoc = Call.getMetadata("srcloc"))
592     Inst.addMetadata(SrcLoc);
593 
594   // All inputs are handled, insert the instruction now
595   MIRBuilder.insertInstr(Inst);
596 
597   // Finally, copy the output operands into the output registers
598   ArrayRef<Register> ResRegs = GetOrCreateVRegs(Call);
599   if (ResRegs.size() != OutputOperands.size()) {
600     LLVM_DEBUG(dbgs() << "Expected the number of output registers to match the "
601                          "number of destination registers\n");
602     return false;
603   }
604   for (unsigned int i = 0, e = ResRegs.size(); i < e; i++) {
605     GISelAsmOperandInfo &OpInfo = OutputOperands[i];
606 
607     if (OpInfo.Regs.empty())
608       continue;
609 
610     switch (OpInfo.ConstraintType) {
611     case TargetLowering::C_Register:
612     case TargetLowering::C_RegisterClass: {
613       if (OpInfo.Regs.size() > 1) {
614         LLVM_DEBUG(dbgs() << "Output operands with multiple defining "
615                              "registers are not supported yet\n");
616         return false;
617       }
618 
619       Register SrcReg = OpInfo.Regs[0];
620       unsigned SrcSize = TRI->getRegSizeInBits(SrcReg, *MRI);
621       LLT ResTy = MRI->getType(ResRegs[i]);
622       if (ResTy.isScalar() && ResTy.getSizeInBits() < SrcSize) {
623         // First copy the non-typed virtual register into a generic virtual
624         // register
625         Register Tmp1Reg =
626             MRI->createGenericVirtualRegister(LLT::scalar(SrcSize));
627         MIRBuilder.buildCopy(Tmp1Reg, SrcReg);
628         // Need to truncate the result of the register
629         MIRBuilder.buildTrunc(ResRegs[i], Tmp1Reg);
630       } else if (ResTy.getSizeInBits() == SrcSize) {
631         MIRBuilder.buildCopy(ResRegs[i], SrcReg);
632       } else {
633         LLVM_DEBUG(dbgs() << "Unhandled output operand with "
634                              "mismatched register size\n");
635         return false;
636       }
637 
638       break;
639     }
640     case TargetLowering::C_Immediate:
641     case TargetLowering::C_Other:
642       LLVM_DEBUG(
643           dbgs() << "Cannot lower target specific output constraints yet\n");
644       return false;
645     case TargetLowering::C_Memory:
646       break; // Already handled.
647     case TargetLowering::C_Unknown:
648       LLVM_DEBUG(dbgs() << "Unexpected unknown constraint\n");
649       return false;
650     }
651   }
652 
653   return true;
654 }
655 
656 bool InlineAsmLowering::lowerAsmOperandForConstraint(
657     Value *Val, StringRef Constraint, std::vector<MachineOperand> &Ops,
658     MachineIRBuilder &MIRBuilder) const {
659   if (Constraint.size() > 1)
660     return false;
661 
662   char ConstraintLetter = Constraint[0];
663   switch (ConstraintLetter) {
664   default:
665     return false;
666   case 'i': // Simple Integer or Relocatable Constant
667   case 'n': // immediate integer with a known value.
668     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
669       assert(CI->getBitWidth() <= 64 &&
670              "expected immediate to fit into 64-bits");
671       // Boolean constants should be zero-extended, others are sign-extended
672       bool IsBool = CI->getBitWidth() == 1;
673       int64_t ExtVal = IsBool ? CI->getZExtValue() : CI->getSExtValue();
674       Ops.push_back(MachineOperand::CreateImm(ExtVal));
675       return true;
676     }
677     return false;
678   }
679 }
680