blob: 8e584919363419481b2b4060495cd591b8bc950d [file] [log] [blame]
Chad Rosier571c5e92012-08-17 21:27:25 +00001//===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
Chad Rosier0731aff2012-08-17 21:19:40 +00002//
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 implements semantic analysis for inline asm statements.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
Weiming Zhao71ac2402015-02-03 22:35:58 +000015#include "clang/AST/ExprCXX.h"
Chad Rosier5c563642012-10-25 21:49:22 +000016#include "clang/AST/RecordLayout.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000017#include "clang/AST/TypeLoc.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000018#include "clang/Basic/TargetInfo.h"
Ehsan Akhgari31097582014-09-22 02:21:54 +000019#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Sema/Initialization.h"
21#include "clang/Sema/Lookup.h"
22#include "clang/Sema/Scope.h"
23#include "clang/Sema/ScopeInfo.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000024#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/BitVector.h"
Alp Toker10399272014-06-08 05:11:37 +000026#include "llvm/MC/MCParser/MCAsmParser.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000027using namespace clang;
28using namespace sema;
29
30/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
31/// ignore "noop" casts in places where an lvalue is required by an inline asm.
32/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
33/// provide a strong guidance to not use it.
34///
35/// This method checks to see if the argument is an acceptable l-value and
36/// returns false if it is a case we can handle.
37static bool CheckAsmLValue(const Expr *E, Sema &S) {
38 // Type dependent expressions will be checked during instantiation.
39 if (E->isTypeDependent())
40 return false;
41
42 if (E->isLValue())
43 return false; // Cool, this is an lvalue.
44
45 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
46 // are supposed to allow.
47 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
48 if (E != E2 && E2->isLValue()) {
49 if (!S.getLangOpts().HeinousExtensions)
50 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
51 << E->getSourceRange();
52 else
53 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
54 << E->getSourceRange();
55 // Accept, even if we emitted an error diagnostic.
56 return false;
57 }
58
59 // None of the above, just randomly invalid non-lvalue.
60 return true;
61}
62
63/// isOperandMentioned - Return true if the specified operand # is mentioned
64/// anywhere in the decomposed asm string.
65static bool isOperandMentioned(unsigned OpNo,
Chad Rosierde70e0e2012-08-25 00:11:56 +000066 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
Chad Rosier0731aff2012-08-17 21:19:40 +000067 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
Chad Rosierde70e0e2012-08-25 00:11:56 +000068 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
Chad Rosier0731aff2012-08-17 21:19:40 +000069 if (!Piece.isOperand()) continue;
70
71 // If this is a reference to the input and if the input was the smaller
72 // one, then we have to reject this asm.
73 if (Piece.getOperandNo() == OpNo)
74 return true;
75 }
76 return false;
77}
78
Hans Wennborge9d240a2014-10-08 01:58:02 +000079static bool CheckNakedParmReference(Expr *E, Sema &S) {
80 FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
81 if (!Func)
82 return false;
83 if (!Func->hasAttr<NakedAttr>())
84 return false;
85
86 SmallVector<Expr*, 4> WorkList;
87 WorkList.push_back(E);
88 while (WorkList.size()) {
89 Expr *E = WorkList.pop_back_val();
Weiming Zhao71ac2402015-02-03 22:35:58 +000090 if (isa<CXXThisExpr>(E)) {
91 S.Diag(E->getLocStart(), diag::err_asm_naked_this_ref);
92 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
93 return true;
94 }
Hans Wennborge9d240a2014-10-08 01:58:02 +000095 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
96 if (isa<ParmVarDecl>(DRE->getDecl())) {
97 S.Diag(DRE->getLocStart(), diag::err_asm_naked_parm_ref);
98 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
99 return true;
100 }
101 }
102 for (Stmt *Child : E->children()) {
103 if (Expr *E = dyn_cast_or_null<Expr>(Child))
104 WorkList.push_back(E);
105 }
106 }
107 return false;
108}
109
Chad Rosierde70e0e2012-08-25 00:11:56 +0000110StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
111 bool IsVolatile, unsigned NumOutputs,
112 unsigned NumInputs, IdentifierInfo **Names,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000113 MultiExprArg constraints, MultiExprArg Exprs,
Chad Rosierde70e0e2012-08-25 00:11:56 +0000114 Expr *asmString, MultiExprArg clobbers,
115 SourceLocation RParenLoc) {
Chad Rosier0731aff2012-08-17 21:19:40 +0000116 unsigned NumClobbers = clobbers.size();
117 StringLiteral **Constraints =
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000118 reinterpret_cast<StringLiteral**>(constraints.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000119 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000120 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000121
122 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
123
124 // The parser verifies that there is a string literal here.
David Majnemerb3e96f72014-12-11 01:00:48 +0000125 assert(AsmString->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000126
Artem Belevichfa62ad42015-04-27 19:37:53 +0000127 bool ValidateConstraints =
128 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl());
Artem Belevich5196fe72015-03-19 18:40:25 +0000129
Chad Rosier0731aff2012-08-17 21:19:40 +0000130 for (unsigned i = 0; i != NumOutputs; i++) {
131 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000132 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000133
134 StringRef OutputName;
135 if (Names[i])
136 OutputName = Names[i]->getName();
137
138 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Artem Belevich5196fe72015-03-19 18:40:25 +0000139 if (ValidateConstraints &&
140 !Context.getTargetInfo().validateOutputConstraint(Info))
Chad Rosier0731aff2012-08-17 21:19:40 +0000141 return StmtError(Diag(Literal->getLocStart(),
142 diag::err_asm_invalid_output_constraint)
143 << Info.getConstraintStr());
144
David Majnemer0f4d6412014-12-29 09:30:33 +0000145 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
146 if (ER.isInvalid())
147 return StmtError();
148 Exprs[i] = ER.get();
149
Chad Rosier0731aff2012-08-17 21:19:40 +0000150 // Check that the output exprs are valid lvalues.
151 Expr *OutputExpr = Exprs[i];
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000152
Hans Wennborge9d240a2014-10-08 01:58:02 +0000153 // Referring to parameters is not allowed in naked functions.
154 if (CheckNakedParmReference(OutputExpr, *this))
155 return StmtError();
156
Alexander Musmaneae29e22015-06-05 13:40:59 +0000157 // Bitfield can't be referenced with a pointer.
158 if (Info.allowsMemory() && OutputExpr->refersToBitField())
159 return StmtError(Diag(OutputExpr->getLocStart(),
160 diag::err_asm_bitfield_in_memory_constraint)
161 << 1
162 << Info.getConstraintStr()
163 << OutputExpr->getSourceRange());
164
Chad Rosier0731aff2012-08-17 21:19:40 +0000165 OutputConstraintInfos.push_back(Info);
Akira Hatanaka974131e2014-09-18 18:17:18 +0000166
David Majnemer0f4d6412014-12-29 09:30:33 +0000167 // If this is dependent, just continue.
168 if (OutputExpr->isTypeDependent())
Akira Hatanaka974131e2014-09-18 18:17:18 +0000169 continue;
170
David Majnemer0f4d6412014-12-29 09:30:33 +0000171 Expr::isModifiableLvalueResult IsLV =
172 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
173 switch (IsLV) {
174 case Expr::MLV_Valid:
175 // Cool, this is an lvalue.
176 break;
David Majnemer04b78412014-12-29 10:29:53 +0000177 case Expr::MLV_ArrayType:
178 // This is OK too.
179 break;
David Majnemer0f4d6412014-12-29 09:30:33 +0000180 case Expr::MLV_LValueCast: {
181 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
182 if (!getLangOpts().HeinousExtensions) {
183 Diag(LVal->getLocStart(), diag::err_invalid_asm_cast_lvalue)
184 << OutputExpr->getSourceRange();
185 } else {
186 Diag(LVal->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
187 << OutputExpr->getSourceRange();
188 }
189 // Accept, even if we emitted an error diagnostic.
190 break;
191 }
192 case Expr::MLV_IncompleteType:
193 case Expr::MLV_IncompleteVoidType:
194 if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
195 diag::err_dereference_incomplete_type))
196 return StmtError();
197 default:
198 return StmtError(Diag(OutputExpr->getLocStart(),
199 diag::err_asm_invalid_lvalue_in_output)
200 << OutputExpr->getSourceRange());
201 }
202
203 unsigned Size = Context.getTypeSize(OutputExpr->getType());
Akira Hatanaka974131e2014-09-18 18:17:18 +0000204 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
205 Size))
206 return StmtError(Diag(OutputExpr->getLocStart(),
207 diag::err_asm_invalid_output_size)
208 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000209 }
210
211 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
212
213 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
214 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000215 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000216
217 StringRef InputName;
218 if (Names[i])
219 InputName = Names[i]->getName();
220
221 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Artem Belevich5196fe72015-03-19 18:40:25 +0000222 if (ValidateConstraints &&
223 !Context.getTargetInfo().validateInputConstraint(
224 OutputConstraintInfos.data(), NumOutputs, Info)) {
Chad Rosier0731aff2012-08-17 21:19:40 +0000225 return StmtError(Diag(Literal->getLocStart(),
226 diag::err_asm_invalid_input_constraint)
227 << Info.getConstraintStr());
228 }
229
David Majnemer0f4d6412014-12-29 09:30:33 +0000230 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
231 if (ER.isInvalid())
232 return StmtError();
233 Exprs[i] = ER.get();
234
Chad Rosier0731aff2012-08-17 21:19:40 +0000235 Expr *InputExpr = Exprs[i];
236
Hans Wennborge9d240a2014-10-08 01:58:02 +0000237 // Referring to parameters is not allowed in naked functions.
238 if (CheckNakedParmReference(InputExpr, *this))
239 return StmtError();
240
Alexander Musmaneae29e22015-06-05 13:40:59 +0000241 // Bitfield can't be referenced with a pointer.
242 if (Info.allowsMemory() && InputExpr->refersToBitField())
243 return StmtError(Diag(InputExpr->getLocStart(),
244 diag::err_asm_bitfield_in_memory_constraint)
245 << 0
246 << Info.getConstraintStr()
247 << InputExpr->getSourceRange());
248
Chad Rosier0731aff2012-08-17 21:19:40 +0000249 // Only allow void types for memory constraints.
250 if (Info.allowsMemory() && !Info.allowsRegister()) {
251 if (CheckAsmLValue(InputExpr, *this))
252 return StmtError(Diag(InputExpr->getLocStart(),
253 diag::err_asm_invalid_lvalue_in_input)
254 << Info.getConstraintStr()
255 << InputExpr->getSourceRange());
Saleem Abdulrasoola2823572015-01-06 04:26:34 +0000256 } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
Sunil Srivastava780e5012015-07-14 18:08:50 +0000257 if (!InputExpr->isValueDependent()) {
258 llvm::APSInt Result;
259 if (!InputExpr->EvaluateAsInt(Result, Context))
260 return StmtError(
261 Diag(InputExpr->getLocStart(), diag::err_asm_immediate_expected)
262 << Info.getConstraintStr() << InputExpr->getSourceRange());
Alexey Bataev91e58602015-07-20 12:08:00 +0000263 if (!Info.isValidAsmImmediate(Result))
Sunil Srivastava780e5012015-07-14 18:08:50 +0000264 return StmtError(Diag(InputExpr->getLocStart(),
265 diag::err_invalid_asm_value_for_constraint)
266 << Result.toString(10) << Info.getConstraintStr()
267 << InputExpr->getSourceRange());
268 }
Saleem Abdulrasoola2823572015-01-06 04:26:34 +0000269
David Majnemerade4bee2014-07-14 16:27:53 +0000270 } else {
271 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
272 if (Result.isInvalid())
273 return StmtError();
274
275 Exprs[i] = Result.get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000276 }
277
278 if (Info.allowsRegister()) {
279 if (InputExpr->getType()->isVoidType()) {
280 return StmtError(Diag(InputExpr->getLocStart(),
281 diag::err_asm_invalid_type_in_input)
282 << InputExpr->getType() << Info.getConstraintStr()
283 << InputExpr->getSourceRange());
284 }
285 }
286
Chad Rosier0731aff2012-08-17 21:19:40 +0000287 InputConstraintInfos.push_back(Info);
Bill Wendling887b4852012-11-12 06:42:51 +0000288
289 const Type *Ty = Exprs[i]->getType().getTypePtr();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000290 if (Ty->isDependentType())
Eric Christopherd41010a2012-11-12 23:13:34 +0000291 continue;
292
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000293 if (!Ty->isVoidType() || !Info.allowsMemory())
Bill Wendlingb68b7572013-03-27 06:06:26 +0000294 if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
295 diag::err_dereference_incomplete_type))
296 return StmtError();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000297
Bill Wendling887b4852012-11-12 06:42:51 +0000298 unsigned Size = Context.getTypeSize(Ty);
299 if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
300 Size))
301 return StmtError(Diag(InputExpr->getLocStart(),
302 diag::err_asm_invalid_input_size)
303 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000304 }
305
306 // Check that the clobbers are valid.
307 for (unsigned i = 0; i != NumClobbers; i++) {
308 StringLiteral *Literal = Clobbers[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000309 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000310
311 StringRef Clobber = Literal->getString();
312
313 if (!Context.getTargetInfo().isValidClobber(Clobber))
314 return StmtError(Diag(Literal->getLocStart(),
315 diag::err_asm_unknown_register_name) << Clobber);
316 }
317
Chad Rosierde70e0e2012-08-25 00:11:56 +0000318 GCCAsmStmt *NS =
319 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000320 NumInputs, Names, Constraints, Exprs.data(),
321 AsmString, NumClobbers, Clobbers, RParenLoc);
Chad Rosier0731aff2012-08-17 21:19:40 +0000322 // Validate the asm string, ensuring it makes sense given the operands we
323 // have.
Chad Rosierde70e0e2012-08-25 00:11:56 +0000324 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
Chad Rosier0731aff2012-08-17 21:19:40 +0000325 unsigned DiagOffs;
326 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
327 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
328 << AsmString->getSourceRange();
329 return StmtError();
330 }
331
Bill Wendling9d1ee112012-10-25 23:28:48 +0000332 // Validate constraints and modifiers.
333 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
334 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
335 if (!Piece.isOperand()) continue;
336
337 // Look for the correct constraint index.
Akira Hatanaka96a36012015-02-04 00:27:13 +0000338 unsigned ConstraintIdx = Piece.getOperandNo();
339 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
Bill Wendling9d1ee112012-10-25 23:28:48 +0000340
Akira Hatanaka96a36012015-02-04 00:27:13 +0000341 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
342 // modifier '+'.
343 if (ConstraintIdx >= NumOperands) {
344 unsigned I = 0, E = NS->getNumOutputs();
345
346 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
347 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
348 ConstraintIdx = I;
Bill Wendling9d1ee112012-10-25 23:28:48 +0000349 break;
Akira Hatanaka96a36012015-02-04 00:27:13 +0000350 }
Bill Wendling9d1ee112012-10-25 23:28:48 +0000351
Akira Hatanaka96a36012015-02-04 00:27:13 +0000352 assert(I != E && "Invalid operand number should have been caught in "
353 " AnalyzeAsmString");
Bill Wendling9d1ee112012-10-25 23:28:48 +0000354 }
355
356 // Now that we have the right indexes go ahead and check.
357 StringLiteral *Literal = Constraints[ConstraintIdx];
358 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
359 if (Ty->isDependentType() || Ty->isIncompleteType())
360 continue;
361
362 unsigned Size = Context.getTypeSize(Ty);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000363 std::string SuggestedModifier;
364 if (!Context.getTargetInfo().validateConstraintModifier(
365 Literal->getString(), Piece.getModifier(), Size,
366 SuggestedModifier)) {
Bill Wendling9d1ee112012-10-25 23:28:48 +0000367 Diag(Exprs[ConstraintIdx]->getLocStart(),
368 diag::warn_asm_mismatched_size_modifier);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000369
370 if (!SuggestedModifier.empty()) {
371 auto B = Diag(Piece.getRange().getBegin(),
372 diag::note_asm_missing_constraint_modifier)
373 << SuggestedModifier;
374 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
375 B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
376 SuggestedModifier));
377 }
378 }
Bill Wendling9d1ee112012-10-25 23:28:48 +0000379 }
380
Chad Rosier0731aff2012-08-17 21:19:40 +0000381 // Validate tied input operands for type mismatches.
David Majnemerc63fa612014-12-29 04:09:59 +0000382 unsigned NumAlternatives = ~0U;
383 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
384 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
385 StringRef ConstraintStr = Info.getConstraintStr();
386 unsigned AltCount = ConstraintStr.count(',') + 1;
387 if (NumAlternatives == ~0U)
388 NumAlternatives = AltCount;
389 else if (NumAlternatives != AltCount)
390 return StmtError(Diag(NS->getOutputExpr(i)->getLocStart(),
391 diag::err_asm_unexpected_constraint_alternatives)
392 << NumAlternatives << AltCount);
393 }
Chad Rosier0731aff2012-08-17 21:19:40 +0000394 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
395 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
David Majnemerc63fa612014-12-29 04:09:59 +0000396 StringRef ConstraintStr = Info.getConstraintStr();
397 unsigned AltCount = ConstraintStr.count(',') + 1;
398 if (NumAlternatives == ~0U)
399 NumAlternatives = AltCount;
400 else if (NumAlternatives != AltCount)
401 return StmtError(Diag(NS->getInputExpr(i)->getLocStart(),
402 diag::err_asm_unexpected_constraint_alternatives)
403 << NumAlternatives << AltCount);
Chad Rosier0731aff2012-08-17 21:19:40 +0000404
405 // If this is a tied constraint, verify that the output and input have
406 // either exactly the same type, or that they are int/ptr operands with the
407 // same size (int/long, int*/long, are ok etc).
408 if (!Info.hasTiedOperand()) continue;
409
410 unsigned TiedTo = Info.getTiedOperand();
411 unsigned InputOpNo = i+NumOutputs;
412 Expr *OutputExpr = Exprs[TiedTo];
413 Expr *InputExpr = Exprs[InputOpNo];
414
415 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
416 continue;
417
418 QualType InTy = InputExpr->getType();
419 QualType OutTy = OutputExpr->getType();
420 if (Context.hasSameType(InTy, OutTy))
421 continue; // All types can be tied to themselves.
422
423 // Decide if the input and output are in the same domain (integer/ptr or
424 // floating point.
425 enum AsmDomain {
426 AD_Int, AD_FP, AD_Other
427 } InputDomain, OutputDomain;
428
429 if (InTy->isIntegerType() || InTy->isPointerType())
430 InputDomain = AD_Int;
431 else if (InTy->isRealFloatingType())
432 InputDomain = AD_FP;
433 else
434 InputDomain = AD_Other;
435
436 if (OutTy->isIntegerType() || OutTy->isPointerType())
437 OutputDomain = AD_Int;
438 else if (OutTy->isRealFloatingType())
439 OutputDomain = AD_FP;
440 else
441 OutputDomain = AD_Other;
442
443 // They are ok if they are the same size and in the same domain. This
444 // allows tying things like:
445 // void* to int*
446 // void* to int if they are the same size.
447 // double to long double if they are the same size.
448 //
449 uint64_t OutSize = Context.getTypeSize(OutTy);
450 uint64_t InSize = Context.getTypeSize(InTy);
451 if (OutSize == InSize && InputDomain == OutputDomain &&
452 InputDomain != AD_Other)
453 continue;
454
455 // If the smaller input/output operand is not mentioned in the asm string,
456 // then we can promote the smaller one to a larger input and the asm string
457 // won't notice.
458 bool SmallerValueMentioned = false;
459
460 // If this is a reference to the input and if the input was the smaller
461 // one, then we have to reject this asm.
462 if (isOperandMentioned(InputOpNo, Pieces)) {
463 // This is a use in the asm string of the smaller operand. Since we
464 // codegen this by promoting to a wider value, the asm will get printed
465 // "wrong".
466 SmallerValueMentioned |= InSize < OutSize;
467 }
468 if (isOperandMentioned(TiedTo, Pieces)) {
469 // If this is a reference to the output, and if the output is the larger
470 // value, then it's ok because we'll promote the input to the larger type.
471 SmallerValueMentioned |= OutSize < InSize;
472 }
473
474 // If the smaller value wasn't mentioned in the asm string, and if the
475 // output was a register, just extend the shorter one to the size of the
476 // larger one.
477 if (!SmallerValueMentioned && InputDomain != AD_Other &&
478 OutputConstraintInfos[TiedTo].allowsRegister())
479 continue;
480
481 // Either both of the operands were mentioned or the smaller one was
482 // mentioned. One more special case that we'll allow: if the tied input is
483 // integer, unmentioned, and is a constant, then we'll allow truncating it
484 // down to the size of the destination.
485 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
486 !isOperandMentioned(InputOpNo, Pieces) &&
487 InputExpr->isEvaluatable(Context)) {
488 CastKind castKind =
489 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000490 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000491 Exprs[InputOpNo] = InputExpr;
492 NS->setInputExpr(i, InputExpr);
493 continue;
494 }
495
496 Diag(InputExpr->getLocStart(),
497 diag::err_asm_tying_incompatible_types)
498 << InTy << OutTy << OutputExpr->getSourceRange()
499 << InputExpr->getSourceRange();
500 return StmtError();
501 }
502
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000503 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000504}
505
John McCallf413f5e2013-05-03 00:10:13 +0000506ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
507 SourceLocation TemplateKWLoc,
508 UnqualifiedId &Id,
Alp Toker10399272014-06-08 05:11:37 +0000509 llvm::InlineAsmIdentifierInfo &Info,
John McCallf413f5e2013-05-03 00:10:13 +0000510 bool IsUnevaluatedContext) {
Chad Rosierb18a2852013-04-22 17:01:37 +0000511 Info.clear();
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000512
John McCallf413f5e2013-05-03 00:10:13 +0000513 if (IsUnevaluatedContext)
514 PushExpressionEvaluationContext(UnevaluatedAbstract,
515 ReuseLambdaContextDecl);
516
517 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
518 /*trailing lparen*/ false,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000519 /*is & operand*/ false,
Craig Topperc3ec1492014-05-26 06:22:03 +0000520 /*CorrectionCandidateCallback=*/nullptr,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000521 /*IsInlineAsmIdentifier=*/ true);
John McCallf413f5e2013-05-03 00:10:13 +0000522
523 if (IsUnevaluatedContext)
524 PopExpressionEvaluationContext();
525
526 if (!Result.isUsable()) return Result;
527
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000528 Result = CheckPlaceholderExpr(Result.get());
John McCallf413f5e2013-05-03 00:10:13 +0000529 if (!Result.isUsable()) return Result;
530
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000531 // Referring to parameters is not allowed in naked functions.
Hans Wennborge9d240a2014-10-08 01:58:02 +0000532 if (CheckNakedParmReference(Result.get(), *this))
533 return ExprError();
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000534
John McCallf413f5e2013-05-03 00:10:13 +0000535 QualType T = Result.get()->getType();
536
537 // For now, reject dependent types.
538 if (T->isDependentType()) {
539 Diag(Id.getLocStart(), diag::err_asm_incomplete_type) << T;
540 return ExprError();
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000541 }
542
John McCallf413f5e2013-05-03 00:10:13 +0000543 // Any sort of function type is fine.
544 if (T->isFunctionType()) {
545 return Result;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000546 }
547
John McCallf413f5e2013-05-03 00:10:13 +0000548 // Otherwise, it needs to be a complete type.
549 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
550 return ExprError();
551 }
552
553 // Compute the type size (and array length if applicable?).
554 Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
555 if (T->isArrayType()) {
556 const ArrayType *ATy = Context.getAsArrayType(T);
557 Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
558 Info.Length = Info.Size / Info.Type;
559 }
560
561 // We can work with the expression as long as it's not an r-value.
562 if (!Result.get()->isRValue())
Chad Rosierb18a2852013-04-22 17:01:37 +0000563 Info.IsVarDecl = true;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000564
John McCallf413f5e2013-05-03 00:10:13 +0000565 return Result;
Chad Rosier4a0054f2012-10-15 19:56:10 +0000566}
Chad Rosierd997bd12012-08-22 19:18:30 +0000567
Chad Rosier5c563642012-10-25 21:49:22 +0000568bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
569 unsigned &Offset, SourceLocation AsmLoc) {
570 Offset = 0;
571 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
572 LookupOrdinaryName);
573
574 if (!LookupName(BaseResult, getCurScope()))
575 return true;
576
577 if (!BaseResult.isSingleResult())
578 return true;
579
Craig Topperc3ec1492014-05-26 06:22:03 +0000580 const RecordType *RT = nullptr;
Chad Rosier10230d42013-04-01 17:58:03 +0000581 NamedDecl *FoundDecl = BaseResult.getFoundDecl();
582 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
Chad Rosier5c563642012-10-25 21:49:22 +0000583 RT = VD->getType()->getAs<RecordType>();
Nico Weber72889432014-09-06 01:25:55 +0000584 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
585 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
Chad Rosier5c563642012-10-25 21:49:22 +0000586 RT = TD->getUnderlyingType()->getAs<RecordType>();
Nico Weber72889432014-09-06 01:25:55 +0000587 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
Nico Weber9ef9ca42014-05-06 03:13:27 +0000588 RT = TD->getTypeForDecl()->getAs<RecordType>();
Chad Rosier5c563642012-10-25 21:49:22 +0000589 if (!RT)
590 return true;
591
592 if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
593 return true;
594
595 LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
596 LookupMemberName);
597
598 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
599 return true;
600
601 // FIXME: Handle IndirectFieldDecl?
602 FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
603 if (!FD)
604 return true;
605
606 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
607 unsigned i = FD->getFieldIndex();
608 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
609 Offset = (unsigned)Result.getQuantity();
610
611 return false;
612}
613
Chad Rosierb261a502012-09-13 00:06:55 +0000614StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
John McCallf413f5e2013-05-03 00:10:13 +0000615 ArrayRef<Token> AsmToks,
616 StringRef AsmString,
617 unsigned NumOutputs, unsigned NumInputs,
618 ArrayRef<StringRef> Constraints,
619 ArrayRef<StringRef> Clobbers,
620 ArrayRef<Expr*> Exprs,
621 SourceLocation EndLoc) {
622 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000623 getCurFunction()->setHasBranchProtectedScope();
Chad Rosier0731aff2012-08-17 21:19:40 +0000624 MSAsmStmt *NS =
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000625 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
626 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
John McCallf413f5e2013-05-03 00:10:13 +0000627 Constraints, Exprs, AsmString,
628 Clobbers, EndLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000629 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000630}
Ehsan Akhgari31097582014-09-22 02:21:54 +0000631
632LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
633 SourceLocation Location,
634 bool AlwaysCreate) {
635 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
636 Location);
637
Ehsan Akhgari42924432014-10-08 17:28:34 +0000638 if (Label->isMSAsmLabel()) {
639 // If we have previously created this label implicitly, mark it as used.
640 Label->markUsed(Context);
641 } else {
Ehsan Akhgari31097582014-09-22 02:21:54 +0000642 // Otherwise, insert it, but only resolve it if we have seen the label itself.
643 std::string InternalName;
644 llvm::raw_string_ostream OS(InternalName);
645 // Create an internal name for the label. The name should not be a valid mangled
646 // name, and should be unique. We use a dot to make the name an invalid mangled
647 // name.
648 OS << "__MSASMLABEL_." << MSAsmLabelNameCounter++ << "__" << ExternalLabelName;
649 Label->setMSAsmLabel(OS.str());
650 }
651 if (AlwaysCreate) {
652 // The label might have been created implicitly from a previously encountered
653 // goto statement. So, for both newly created and looked up labels, we mark
654 // them as resolved.
655 Label->setMSAsmLabelResolved();
656 }
657 // Adjust their location for being able to generate accurate diagnostics.
658 Label->setLocation(Location);
659
660 return Label;
661}