InlineAsmLowering.cpp 25 KB

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