1 //===- InlineAsm.cpp - Implement the InlineAsm class ----------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the InlineAsm class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/IR/InlineAsm.h"
14 #include "ConstantsContext.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/Value.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Errc.h"
30 InlineAsm::InlineAsm(FunctionType
*FTy
, const std::string
&asmString
,
31 const std::string
&constraints
, bool hasSideEffects
,
32 bool isAlignStack
, AsmDialect asmDialect
, bool canThrow
)
33 : Value(PointerType::getUnqual(FTy
->getContext()), Value::InlineAsmVal
),
34 AsmString(asmString
), Constraints(constraints
), FTy(FTy
),
35 HasSideEffects(hasSideEffects
), IsAlignStack(isAlignStack
),
36 Dialect(asmDialect
), CanThrow(canThrow
) {
38 // Do various checks on the constraint string and type.
39 cantFail(verify(getFunctionType(), constraints
));
43 InlineAsm
*InlineAsm::get(FunctionType
*FTy
, StringRef AsmString
,
44 StringRef Constraints
, bool hasSideEffects
,
45 bool isAlignStack
, AsmDialect asmDialect
,
47 InlineAsmKeyType
Key(AsmString
, Constraints
, FTy
, hasSideEffects
,
48 isAlignStack
, asmDialect
, canThrow
);
49 LLVMContextImpl
*pImpl
= FTy
->getContext().pImpl
;
50 return pImpl
->InlineAsms
.getOrCreate(
51 PointerType::getUnqual(FTy
->getContext()), Key
);
54 void InlineAsm::destroyConstant() {
55 getType()->getContext().pImpl
->InlineAsms
.remove(this);
59 FunctionType
*InlineAsm::getFunctionType() const {
63 void InlineAsm::collectAsmStrs(SmallVectorImpl
<StringRef
> &AsmStrs
) const {
64 StringRef
AsmStr(AsmString
);
67 // TODO: 1) Unify delimiter for inline asm, we also meet other delimiters
68 // for example "\0A", ";".
69 // 2) Enhance StringRef. Some of the special delimiter ("\0") can't be
70 // split in StringRef. Also empty StringRef can not call split (will stuck).
73 AsmStr
.split(AsmStrs
, "\n\t", -1, false);
76 /// Parse - Analyze the specified string (e.g. "==&{eax}") and fill in the
77 /// fields in this structure. If the constraint string is not understood,
78 /// return true, otherwise return false.
79 bool InlineAsm::ConstraintInfo::Parse(StringRef Str
,
80 InlineAsm::ConstraintInfoVector
&ConstraintsSoFar
) {
81 StringRef::iterator I
= Str
.begin(), E
= Str
.end();
82 unsigned multipleAlternativeCount
= Str
.count('|') + 1;
83 unsigned multipleAlternativeIndex
= 0;
84 ConstraintCodeVector
*pCodes
= &Codes
;
87 isMultipleAlternative
= multipleAlternativeCount
> 1;
88 if (isMultipleAlternative
) {
89 multipleAlternatives
.resize(multipleAlternativeCount
);
90 pCodes
= &multipleAlternatives
[0].Codes
;
93 isEarlyClobber
= false;
95 isCommutative
= false;
97 currentAlternativeIndex
= 0;
104 // '{' must immediately follow '~'.
105 if (I
!= E
&& *I
!= '{')
107 } else if (*I
== '=') {
110 } else if (*I
== '!') {
120 if (I
== E
) return true; // Just a prefix, like "==" or "~".
122 // Parse the modifiers.
123 bool DoneWithModifiers
= false;
124 while (!DoneWithModifiers
) {
127 DoneWithModifiers
= true;
129 case '&': // Early clobber.
130 if (Type
!= isOutput
|| // Cannot early clobber anything but output.
131 isEarlyClobber
) // Reject &&&&&&
133 isEarlyClobber
= true;
135 case '%': // Commutative.
136 if (Type
== isClobber
|| // Cannot commute clobbers.
137 isCommutative
) // Reject %%%%%
139 isCommutative
= true;
141 case '#': // Comment.
142 case '*': // Register preferencing.
143 return true; // Not supported.
146 if (!DoneWithModifiers
) {
148 if (I
== E
) return true; // Just prefixes and modifiers!
152 // Parse the various constraints.
154 if (*I
== '{') { // Physical register reference.
155 // Find the end of the register name.
156 StringRef::iterator ConstraintEnd
= std::find(I
+1, E
, '}');
157 if (ConstraintEnd
== E
) return true; // "{foo"
158 pCodes
->push_back(std::string(StringRef(I
, ConstraintEnd
+ 1 - I
)));
160 } else if (isdigit(static_cast<unsigned char>(*I
))) { // Matching Constraint
161 // Maximal munch numbers.
162 StringRef::iterator NumStart
= I
;
163 while (I
!= E
&& isdigit(static_cast<unsigned char>(*I
)))
165 pCodes
->push_back(std::string(StringRef(NumStart
, I
- NumStart
)));
166 unsigned N
= atoi(pCodes
->back().c_str());
167 // Check that this is a valid matching constraint!
168 if (N
>= ConstraintsSoFar
.size() || ConstraintsSoFar
[N
].Type
!= isOutput
||
170 return true; // Invalid constraint number.
172 // If Operand N already has a matching input, reject this. An output
173 // can't be constrained to the same value as multiple inputs.
174 if (isMultipleAlternative
) {
175 if (multipleAlternativeIndex
>=
176 ConstraintsSoFar
[N
].multipleAlternatives
.size())
178 InlineAsm::SubConstraintInfo
&scInfo
=
179 ConstraintsSoFar
[N
].multipleAlternatives
[multipleAlternativeIndex
];
180 if (scInfo
.MatchingInput
!= -1)
182 // Note that operand #n has a matching input.
183 scInfo
.MatchingInput
= ConstraintsSoFar
.size();
184 assert(scInfo
.MatchingInput
>= 0);
186 if (ConstraintsSoFar
[N
].hasMatchingInput() &&
187 (size_t)ConstraintsSoFar
[N
].MatchingInput
!=
188 ConstraintsSoFar
.size())
190 // Note that operand #n has a matching input.
191 ConstraintsSoFar
[N
].MatchingInput
= ConstraintsSoFar
.size();
192 assert(ConstraintsSoFar
[N
].MatchingInput
>= 0);
194 } else if (*I
== '|') {
195 multipleAlternativeIndex
++;
196 pCodes
= &multipleAlternatives
[multipleAlternativeIndex
].Codes
;
198 } else if (*I
== '^') {
199 // Multi-letter constraint
200 // FIXME: For now assuming these are 2-character constraints.
201 pCodes
->push_back(std::string(StringRef(I
+ 1, 2)));
203 } else if (*I
== '@') {
204 // Multi-letter constraint
206 unsigned char C
= static_cast<unsigned char>(*I
);
207 assert(isdigit(C
) && "Expected a digit!");
209 assert(N
> 0 && "Found a zero letter constraint!");
211 pCodes
->push_back(std::string(StringRef(I
, N
)));
214 // Single letter constraint.
215 pCodes
->push_back(std::string(StringRef(I
, 1)));
223 /// selectAlternative - Point this constraint to the alternative constraint
224 /// indicated by the index.
225 void InlineAsm::ConstraintInfo::selectAlternative(unsigned index
) {
226 if (index
< multipleAlternatives
.size()) {
227 currentAlternativeIndex
= index
;
228 InlineAsm::SubConstraintInfo
&scInfo
=
229 multipleAlternatives
[currentAlternativeIndex
];
230 MatchingInput
= scInfo
.MatchingInput
;
231 Codes
= scInfo
.Codes
;
235 InlineAsm::ConstraintInfoVector
236 InlineAsm::ParseConstraints(StringRef Constraints
) {
237 ConstraintInfoVector Result
;
239 // Scan the constraints string.
240 for (StringRef::iterator I
= Constraints
.begin(),
241 E
= Constraints
.end(); I
!= E
; ) {
244 // Find the end of this constraint.
245 StringRef::iterator ConstraintEnd
= std::find(I
, E
, ',');
247 if (ConstraintEnd
== I
|| // Empty constraint like ",,"
248 Info
.Parse(StringRef(I
, ConstraintEnd
-I
), Result
)) {
249 Result
.clear(); // Erroneous constraint?
253 Result
.push_back(Info
);
255 // ConstraintEnd may be either the next comma or the end of the string. In
256 // the former case, we skip the comma.
263 } // don't allow "xyz,"
270 static Error
makeStringError(const char *Msg
) {
271 return createStringError(errc::invalid_argument
, Msg
);
274 Error
InlineAsm::verify(FunctionType
*Ty
, StringRef ConstStr
) {
276 return makeStringError("inline asm cannot be variadic");
278 ConstraintInfoVector Constraints
= ParseConstraints(ConstStr
);
280 // Error parsing constraints.
281 if (Constraints
.empty() && !ConstStr
.empty())
282 return makeStringError("failed to parse constraints");
284 unsigned NumOutputs
= 0, NumInputs
= 0, NumClobbers
= 0;
285 unsigned NumIndirect
= 0, NumLabels
= 0;
287 for (const ConstraintInfo
&Constraint
: Constraints
) {
288 switch (Constraint
.Type
) {
289 case InlineAsm::isOutput
:
290 if ((NumInputs
-NumIndirect
) != 0 || NumClobbers
!= 0 || NumLabels
!= 0)
291 return makeStringError("output constraint occurs after input, "
292 "clobber or label constraint");
294 if (!Constraint
.isIndirect
) {
299 [[fallthrough
]]; // We fall through for Indirect Outputs.
300 case InlineAsm::isInput
:
302 return makeStringError("input constraint occurs after clobber "
306 case InlineAsm::isClobber
:
309 case InlineAsm::isLabel
:
311 return makeStringError("label constraint occurs after clobber "
319 switch (NumOutputs
) {
321 if (!Ty
->getReturnType()->isVoidTy())
322 return makeStringError("inline asm without outputs must return void");
325 if (Ty
->getReturnType()->isStructTy())
326 return makeStringError("inline asm with one output cannot return struct");
329 StructType
*STy
= dyn_cast
<StructType
>(Ty
->getReturnType());
330 if (!STy
|| STy
->getNumElements() != NumOutputs
)
331 return makeStringError("number of output constraints does not match "
332 "number of return struct elements");
336 if (Ty
->getNumParams() != NumInputs
)
337 return makeStringError("number of input constraints does not match number "
340 // We don't have access to labels here, NumLabels will be checked separately.
341 return Error::success();