InlineAsm.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. //===- InlineAsm.cpp - Implement the InlineAsm class ----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the InlineAsm class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/InlineAsm.h"
  13. #include "ConstantsContext.h"
  14. #include "LLVMContextImpl.h"
  15. #include "llvm/ADT/StringRef.h"
  16. #include "llvm/IR/DerivedTypes.h"
  17. #include "llvm/IR/LLVMContext.h"
  18. #include "llvm/IR/Value.h"
  19. #include "llvm/Support/Casting.h"
  20. #include "llvm/Support/Compiler.h"
  21. #include "llvm/Support/Errc.h"
  22. #include <algorithm>
  23. #include <cassert>
  24. #include <cctype>
  25. #include <cstdlib>
  26. using namespace llvm;
  27. InlineAsm::InlineAsm(FunctionType *FTy, const std::string &asmString,
  28. const std::string &constraints, bool hasSideEffects,
  29. bool isAlignStack, AsmDialect asmDialect, bool canThrow)
  30. : Value(PointerType::getUnqual(FTy), Value::InlineAsmVal),
  31. AsmString(asmString), Constraints(constraints), FTy(FTy),
  32. HasSideEffects(hasSideEffects), IsAlignStack(isAlignStack),
  33. Dialect(asmDialect), CanThrow(canThrow) {
  34. #ifndef NDEBUG
  35. // Do various checks on the constraint string and type.
  36. cantFail(verify(getFunctionType(), constraints));
  37. #endif
  38. }
  39. InlineAsm *InlineAsm::get(FunctionType *FTy, StringRef AsmString,
  40. StringRef Constraints, bool hasSideEffects,
  41. bool isAlignStack, AsmDialect asmDialect,
  42. bool canThrow) {
  43. InlineAsmKeyType Key(AsmString, Constraints, FTy, hasSideEffects,
  44. isAlignStack, asmDialect, canThrow);
  45. LLVMContextImpl *pImpl = FTy->getContext().pImpl;
  46. return pImpl->InlineAsms.getOrCreate(PointerType::getUnqual(FTy), Key);
  47. }
  48. void InlineAsm::destroyConstant() {
  49. getType()->getContext().pImpl->InlineAsms.remove(this);
  50. delete this;
  51. }
  52. FunctionType *InlineAsm::getFunctionType() const {
  53. return FTy;
  54. }
  55. void InlineAsm::collectAsmStrs(SmallVectorImpl<StringRef> &AsmStrs) const {
  56. StringRef AsmStr(AsmString);
  57. AsmStrs.clear();
  58. // TODO: 1) Unify delimiter for inline asm, we also meet other delimiters
  59. // for example "\0A", ";".
  60. // 2) Enhance StringRef. Some of the special delimiter ("\0") can't be
  61. // split in StringRef. Also empty StringRef can not call split (will stuck).
  62. if (AsmStr.empty())
  63. return;
  64. AsmStr.split(AsmStrs, "\n\t", -1, false);
  65. }
  66. /// Parse - Analyze the specified string (e.g. "==&{eax}") and fill in the
  67. /// fields in this structure. If the constraint string is not understood,
  68. /// return true, otherwise return false.
  69. bool InlineAsm::ConstraintInfo::Parse(StringRef Str,
  70. InlineAsm::ConstraintInfoVector &ConstraintsSoFar) {
  71. StringRef::iterator I = Str.begin(), E = Str.end();
  72. unsigned multipleAlternativeCount = Str.count('|') + 1;
  73. unsigned multipleAlternativeIndex = 0;
  74. ConstraintCodeVector *pCodes = &Codes;
  75. // Initialize
  76. isMultipleAlternative = multipleAlternativeCount > 1;
  77. if (isMultipleAlternative) {
  78. multipleAlternatives.resize(multipleAlternativeCount);
  79. pCodes = &multipleAlternatives[0].Codes;
  80. }
  81. Type = isInput;
  82. isEarlyClobber = false;
  83. MatchingInput = -1;
  84. isCommutative = false;
  85. isIndirect = false;
  86. currentAlternativeIndex = 0;
  87. // Parse prefixes.
  88. if (*I == '~') {
  89. Type = isClobber;
  90. ++I;
  91. // '{' must immediately follow '~'.
  92. if (I != E && *I != '{')
  93. return true;
  94. } else if (*I == '=') {
  95. ++I;
  96. Type = isOutput;
  97. } else if (*I == '!') {
  98. ++I;
  99. Type = isLabel;
  100. }
  101. if (*I == '*') {
  102. isIndirect = true;
  103. ++I;
  104. }
  105. if (I == E) return true; // Just a prefix, like "==" or "~".
  106. // Parse the modifiers.
  107. bool DoneWithModifiers = false;
  108. while (!DoneWithModifiers) {
  109. switch (*I) {
  110. default:
  111. DoneWithModifiers = true;
  112. break;
  113. case '&': // Early clobber.
  114. if (Type != isOutput || // Cannot early clobber anything but output.
  115. isEarlyClobber) // Reject &&&&&&
  116. return true;
  117. isEarlyClobber = true;
  118. break;
  119. case '%': // Commutative.
  120. if (Type == isClobber || // Cannot commute clobbers.
  121. isCommutative) // Reject %%%%%
  122. return true;
  123. isCommutative = true;
  124. break;
  125. case '#': // Comment.
  126. case '*': // Register preferencing.
  127. return true; // Not supported.
  128. }
  129. if (!DoneWithModifiers) {
  130. ++I;
  131. if (I == E) return true; // Just prefixes and modifiers!
  132. }
  133. }
  134. // Parse the various constraints.
  135. while (I != E) {
  136. if (*I == '{') { // Physical register reference.
  137. // Find the end of the register name.
  138. StringRef::iterator ConstraintEnd = std::find(I+1, E, '}');
  139. if (ConstraintEnd == E) return true; // "{foo"
  140. pCodes->push_back(std::string(StringRef(I, ConstraintEnd + 1 - I)));
  141. I = ConstraintEnd+1;
  142. } else if (isdigit(static_cast<unsigned char>(*I))) { // Matching Constraint
  143. // Maximal munch numbers.
  144. StringRef::iterator NumStart = I;
  145. while (I != E && isdigit(static_cast<unsigned char>(*I)))
  146. ++I;
  147. pCodes->push_back(std::string(StringRef(NumStart, I - NumStart)));
  148. unsigned N = atoi(pCodes->back().c_str());
  149. // Check that this is a valid matching constraint!
  150. if (N >= ConstraintsSoFar.size() || ConstraintsSoFar[N].Type != isOutput||
  151. Type != isInput)
  152. return true; // Invalid constraint number.
  153. // If Operand N already has a matching input, reject this. An output
  154. // can't be constrained to the same value as multiple inputs.
  155. if (isMultipleAlternative) {
  156. if (multipleAlternativeIndex >=
  157. ConstraintsSoFar[N].multipleAlternatives.size())
  158. return true;
  159. InlineAsm::SubConstraintInfo &scInfo =
  160. ConstraintsSoFar[N].multipleAlternatives[multipleAlternativeIndex];
  161. if (scInfo.MatchingInput != -1)
  162. return true;
  163. // Note that operand #n has a matching input.
  164. scInfo.MatchingInput = ConstraintsSoFar.size();
  165. assert(scInfo.MatchingInput >= 0);
  166. } else {
  167. if (ConstraintsSoFar[N].hasMatchingInput() &&
  168. (size_t)ConstraintsSoFar[N].MatchingInput !=
  169. ConstraintsSoFar.size())
  170. return true;
  171. // Note that operand #n has a matching input.
  172. ConstraintsSoFar[N].MatchingInput = ConstraintsSoFar.size();
  173. assert(ConstraintsSoFar[N].MatchingInput >= 0);
  174. }
  175. } else if (*I == '|') {
  176. multipleAlternativeIndex++;
  177. pCodes = &multipleAlternatives[multipleAlternativeIndex].Codes;
  178. ++I;
  179. } else if (*I == '^') {
  180. // Multi-letter constraint
  181. // FIXME: For now assuming these are 2-character constraints.
  182. pCodes->push_back(std::string(StringRef(I + 1, 2)));
  183. I += 3;
  184. } else if (*I == '@') {
  185. // Multi-letter constraint
  186. ++I;
  187. unsigned char C = static_cast<unsigned char>(*I);
  188. assert(isdigit(C) && "Expected a digit!");
  189. int N = C - '0';
  190. assert(N > 0 && "Found a zero letter constraint!");
  191. ++I;
  192. pCodes->push_back(std::string(StringRef(I, N)));
  193. I += N;
  194. } else {
  195. // Single letter constraint.
  196. pCodes->push_back(std::string(StringRef(I, 1)));
  197. ++I;
  198. }
  199. }
  200. return false;
  201. }
  202. /// selectAlternative - Point this constraint to the alternative constraint
  203. /// indicated by the index.
  204. void InlineAsm::ConstraintInfo::selectAlternative(unsigned index) {
  205. if (index < multipleAlternatives.size()) {
  206. currentAlternativeIndex = index;
  207. InlineAsm::SubConstraintInfo &scInfo =
  208. multipleAlternatives[currentAlternativeIndex];
  209. MatchingInput = scInfo.MatchingInput;
  210. Codes = scInfo.Codes;
  211. }
  212. }
  213. InlineAsm::ConstraintInfoVector
  214. InlineAsm::ParseConstraints(StringRef Constraints) {
  215. ConstraintInfoVector Result;
  216. // Scan the constraints string.
  217. for (StringRef::iterator I = Constraints.begin(),
  218. E = Constraints.end(); I != E; ) {
  219. ConstraintInfo Info;
  220. // Find the end of this constraint.
  221. StringRef::iterator ConstraintEnd = std::find(I, E, ',');
  222. if (ConstraintEnd == I || // Empty constraint like ",,"
  223. Info.Parse(StringRef(I, ConstraintEnd-I), Result)) {
  224. Result.clear(); // Erroneous constraint?
  225. break;
  226. }
  227. Result.push_back(Info);
  228. // ConstraintEnd may be either the next comma or the end of the string. In
  229. // the former case, we skip the comma.
  230. I = ConstraintEnd;
  231. if (I != E) {
  232. ++I;
  233. if (I == E) {
  234. Result.clear();
  235. break;
  236. } // don't allow "xyz,"
  237. }
  238. }
  239. return Result;
  240. }
  241. static Error makeStringError(const char *Msg) {
  242. return createStringError(errc::invalid_argument, Msg);
  243. }
  244. Error InlineAsm::verify(FunctionType *Ty, StringRef ConstStr) {
  245. if (Ty->isVarArg())
  246. return makeStringError("inline asm cannot be variadic");
  247. ConstraintInfoVector Constraints = ParseConstraints(ConstStr);
  248. // Error parsing constraints.
  249. if (Constraints.empty() && !ConstStr.empty())
  250. return makeStringError("failed to parse constraints");
  251. unsigned NumOutputs = 0, NumInputs = 0, NumClobbers = 0;
  252. unsigned NumIndirect = 0, NumLabels = 0;
  253. for (const ConstraintInfo &Constraint : Constraints) {
  254. switch (Constraint.Type) {
  255. case InlineAsm::isOutput:
  256. if ((NumInputs-NumIndirect) != 0 || NumClobbers != 0 || NumLabels != 0)
  257. return makeStringError("output constraint occurs after input, "
  258. "clobber or label constraint");
  259. if (!Constraint.isIndirect) {
  260. ++NumOutputs;
  261. break;
  262. }
  263. ++NumIndirect;
  264. [[fallthrough]]; // We fall through for Indirect Outputs.
  265. case InlineAsm::isInput:
  266. if (NumClobbers)
  267. return makeStringError("input constraint occurs after clobber "
  268. "constraint");
  269. ++NumInputs;
  270. break;
  271. case InlineAsm::isClobber:
  272. ++NumClobbers;
  273. break;
  274. case InlineAsm::isLabel:
  275. if (NumClobbers)
  276. return makeStringError("label constraint occurs after clobber "
  277. "constraint");
  278. ++NumLabels;
  279. break;
  280. }
  281. }
  282. switch (NumOutputs) {
  283. case 0:
  284. if (!Ty->getReturnType()->isVoidTy())
  285. return makeStringError("inline asm without outputs must return void");
  286. break;
  287. case 1:
  288. if (Ty->getReturnType()->isStructTy())
  289. return makeStringError("inline asm with one output cannot return struct");
  290. break;
  291. default:
  292. StructType *STy = dyn_cast<StructType>(Ty->getReturnType());
  293. if (!STy || STy->getNumElements() != NumOutputs)
  294. return makeStringError("number of output constraints does not match "
  295. "number of return struct elements");
  296. break;
  297. }
  298. if (Ty->getNumParams() != NumInputs)
  299. return makeStringError("number of input constraints does not match number "
  300. "of parameters");
  301. // We don't have access to labels here, NumLabels will be checked separately.
  302. return Error::success();
  303. }