blob: c091cf88a92c3204e6c50255e3c7f6573a734c18 [file] [log] [blame]
Chad Rosier3d45a772012-08-17 21:27:25 +00001//===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
Chad Rosier4b5e48d2012-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"
Stephen Hines0e2c34f2015-03-23 12:09:02 -070015#include "clang/AST/ExprCXX.h"
Chad Rosier802f9372012-10-25 21:49:22 +000016#include "clang/AST/RecordLayout.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000017#include "clang/AST/TypeLoc.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000018#include "clang/Basic/TargetInfo.h"
Stephen Hines176edba2014-12-01 14:53:08 -080019#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-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 Rosier4b5e48d2012-08-17 21:19:40 +000024#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/BitVector.h"
Stephen Hinesc568f1e2014-07-21 00:47:37 -070026#include "llvm/MC/MCParser/MCAsmParser.h"
Chad Rosier4b5e48d2012-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 Rosierdf5faf52012-08-25 00:11:56 +000066 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +000067 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
Chad Rosierdf5faf52012-08-25 00:11:56 +000068 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
Chad Rosier4b5e48d2012-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
Stephen Hines176edba2014-12-01 14:53:08 -080079static 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();
Stephen Hines0e2c34f2015-03-23 12:09:02 -070090 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 }
Stephen Hines176edba2014-12-01 14:53:08 -080095 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 Rosierdf5faf52012-08-25 00:11:56 +0000110StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
111 bool IsVolatile, unsigned NumOutputs,
112 unsigned NumInputs, IdentifierInfo **Names,
Dmitri Gribenko96c24732013-05-10 01:14:26 +0000113 MultiExprArg constraints, MultiExprArg Exprs,
Chad Rosierdf5faf52012-08-25 00:11:56 +0000114 Expr *asmString, MultiExprArg clobbers,
115 SourceLocation RParenLoc) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000116 unsigned NumClobbers = clobbers.size();
117 StringLiteral **Constraints =
Benjamin Kramer5354e772012-08-23 23:38:35 +0000118 reinterpret_cast<StringLiteral**>(constraints.data());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000119 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000120 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000121
122 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
123
124 // The parser verifies that there is a string literal here.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700125 assert(AsmString->isAscii());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000126
127 for (unsigned i = 0; i != NumOutputs; i++) {
128 StringLiteral *Literal = Constraints[i];
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700129 assert(Literal->isAscii());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000130
131 StringRef OutputName;
132 if (Names[i])
133 OutputName = Names[i]->getName();
134
135 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
136 if (!Context.getTargetInfo().validateOutputConstraint(Info))
137 return StmtError(Diag(Literal->getLocStart(),
138 diag::err_asm_invalid_output_constraint)
139 << Info.getConstraintStr());
140
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700141 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
142 if (ER.isInvalid())
143 return StmtError();
144 Exprs[i] = ER.get();
145
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000146 // Check that the output exprs are valid lvalues.
147 Expr *OutputExpr = Exprs[i];
Bill Wendling14df23b2013-03-25 21:09:49 +0000148
Stephen Hines176edba2014-12-01 14:53:08 -0800149 // Referring to parameters is not allowed in naked functions.
150 if (CheckNakedParmReference(OutputExpr, *this))
151 return StmtError();
152
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000153 OutputConstraintInfos.push_back(Info);
Stephen Hines176edba2014-12-01 14:53:08 -0800154
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700155 // If this is dependent, just continue.
156 if (OutputExpr->isTypeDependent())
Stephen Hines176edba2014-12-01 14:53:08 -0800157 continue;
158
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700159 Expr::isModifiableLvalueResult IsLV =
160 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
161 switch (IsLV) {
162 case Expr::MLV_Valid:
163 // Cool, this is an lvalue.
164 break;
165 case Expr::MLV_ArrayType:
166 // This is OK too.
167 break;
168 case Expr::MLV_LValueCast: {
169 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
170 if (!getLangOpts().HeinousExtensions) {
171 Diag(LVal->getLocStart(), diag::err_invalid_asm_cast_lvalue)
172 << OutputExpr->getSourceRange();
173 } else {
174 Diag(LVal->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
175 << OutputExpr->getSourceRange();
176 }
177 // Accept, even if we emitted an error diagnostic.
178 break;
179 }
180 case Expr::MLV_IncompleteType:
181 case Expr::MLV_IncompleteVoidType:
182 if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
183 diag::err_dereference_incomplete_type))
184 return StmtError();
185 default:
186 return StmtError(Diag(OutputExpr->getLocStart(),
187 diag::err_asm_invalid_lvalue_in_output)
188 << OutputExpr->getSourceRange());
189 }
190
191 unsigned Size = Context.getTypeSize(OutputExpr->getType());
Stephen Hines176edba2014-12-01 14:53:08 -0800192 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
193 Size))
194 return StmtError(Diag(OutputExpr->getLocStart(),
195 diag::err_asm_invalid_output_size)
196 << Info.getConstraintStr());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000197 }
198
199 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
200
201 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
202 StringLiteral *Literal = Constraints[i];
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700203 assert(Literal->isAscii());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000204
205 StringRef InputName;
206 if (Names[i])
207 InputName = Names[i]->getName();
208
209 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
210 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
211 NumOutputs, Info)) {
212 return StmtError(Diag(Literal->getLocStart(),
213 diag::err_asm_invalid_input_constraint)
214 << Info.getConstraintStr());
215 }
216
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700217 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
218 if (ER.isInvalid())
219 return StmtError();
220 Exprs[i] = ER.get();
221
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000222 Expr *InputExpr = Exprs[i];
223
Stephen Hines176edba2014-12-01 14:53:08 -0800224 // Referring to parameters is not allowed in naked functions.
225 if (CheckNakedParmReference(InputExpr, *this))
226 return StmtError();
227
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000228 // Only allow void types for memory constraints.
229 if (Info.allowsMemory() && !Info.allowsRegister()) {
230 if (CheckAsmLValue(InputExpr, *this))
231 return StmtError(Diag(InputExpr->getLocStart(),
232 diag::err_asm_invalid_lvalue_in_input)
233 << Info.getConstraintStr()
234 << InputExpr->getSourceRange());
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700235 } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
236 llvm::APSInt Result;
237 if (!InputExpr->EvaluateAsInt(Result, Context))
238 return StmtError(
239 Diag(InputExpr->getLocStart(), diag::err_asm_immediate_expected)
240 << Info.getConstraintStr() << InputExpr->getSourceRange());
241 if (Result.slt(Info.getImmConstantMin()) ||
242 Result.sgt(Info.getImmConstantMax()))
243 return StmtError(Diag(InputExpr->getLocStart(),
244 diag::err_invalid_asm_value_for_constraint)
245 << Result.toString(10) << Info.getConstraintStr()
246 << InputExpr->getSourceRange());
247
Stephen Hines176edba2014-12-01 14:53:08 -0800248 } else {
249 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
250 if (Result.isInvalid())
251 return StmtError();
252
253 Exprs[i] = Result.get();
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000254 }
255
256 if (Info.allowsRegister()) {
257 if (InputExpr->getType()->isVoidType()) {
258 return StmtError(Diag(InputExpr->getLocStart(),
259 diag::err_asm_invalid_type_in_input)
260 << InputExpr->getType() << Info.getConstraintStr()
261 << InputExpr->getSourceRange());
262 }
263 }
264
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000265 InputConstraintInfos.push_back(Info);
Bill Wendling68fd6082012-11-12 06:42:51 +0000266
267 const Type *Ty = Exprs[i]->getType().getTypePtr();
Bill Wendling14df23b2013-03-25 21:09:49 +0000268 if (Ty->isDependentType())
Eric Christopher6ceb3772012-11-12 23:13:34 +0000269 continue;
270
Bill Wendling14df23b2013-03-25 21:09:49 +0000271 if (!Ty->isVoidType() || !Info.allowsMemory())
Bill Wendlingd835d942013-03-27 06:06:26 +0000272 if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
273 diag::err_dereference_incomplete_type))
274 return StmtError();
Bill Wendling14df23b2013-03-25 21:09:49 +0000275
Bill Wendling68fd6082012-11-12 06:42:51 +0000276 unsigned Size = Context.getTypeSize(Ty);
277 if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
278 Size))
279 return StmtError(Diag(InputExpr->getLocStart(),
280 diag::err_asm_invalid_input_size)
281 << Info.getConstraintStr());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000282 }
283
284 // Check that the clobbers are valid.
285 for (unsigned i = 0; i != NumClobbers; i++) {
286 StringLiteral *Literal = Clobbers[i];
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700287 assert(Literal->isAscii());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000288
289 StringRef Clobber = Literal->getString();
290
291 if (!Context.getTargetInfo().isValidClobber(Clobber))
292 return StmtError(Diag(Literal->getLocStart(),
293 diag::err_asm_unknown_register_name) << Clobber);
294 }
295
Chad Rosierdf5faf52012-08-25 00:11:56 +0000296 GCCAsmStmt *NS =
297 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
Dmitri Gribenko96c24732013-05-10 01:14:26 +0000298 NumInputs, Names, Constraints, Exprs.data(),
299 AsmString, NumClobbers, Clobbers, RParenLoc);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000300 // Validate the asm string, ensuring it makes sense given the operands we
301 // have.
Chad Rosierdf5faf52012-08-25 00:11:56 +0000302 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000303 unsigned DiagOffs;
304 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
305 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
306 << AsmString->getSourceRange();
307 return StmtError();
308 }
309
Bill Wendling50d46ca2012-10-25 23:28:48 +0000310 // Validate constraints and modifiers.
311 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
312 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
313 if (!Piece.isOperand()) continue;
314
315 // Look for the correct constraint index.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700316 unsigned ConstraintIdx = Piece.getOperandNo();
317 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
Bill Wendling50d46ca2012-10-25 23:28:48 +0000318
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700319 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
320 // modifier '+'.
321 if (ConstraintIdx >= NumOperands) {
322 unsigned I = 0, E = NS->getNumOutputs();
323
324 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
325 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
326 ConstraintIdx = I;
Bill Wendling50d46ca2012-10-25 23:28:48 +0000327 break;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700328 }
Bill Wendling50d46ca2012-10-25 23:28:48 +0000329
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700330 assert(I != E && "Invalid operand number should have been caught in "
331 " AnalyzeAsmString");
Bill Wendling50d46ca2012-10-25 23:28:48 +0000332 }
333
334 // Now that we have the right indexes go ahead and check.
335 StringLiteral *Literal = Constraints[ConstraintIdx];
336 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
337 if (Ty->isDependentType() || Ty->isIncompleteType())
338 continue;
339
340 unsigned Size = Context.getTypeSize(Ty);
Stephen Hines176edba2014-12-01 14:53:08 -0800341 std::string SuggestedModifier;
342 if (!Context.getTargetInfo().validateConstraintModifier(
343 Literal->getString(), Piece.getModifier(), Size,
344 SuggestedModifier)) {
Bill Wendling50d46ca2012-10-25 23:28:48 +0000345 Diag(Exprs[ConstraintIdx]->getLocStart(),
346 diag::warn_asm_mismatched_size_modifier);
Stephen Hines176edba2014-12-01 14:53:08 -0800347
348 if (!SuggestedModifier.empty()) {
349 auto B = Diag(Piece.getRange().getBegin(),
350 diag::note_asm_missing_constraint_modifier)
351 << SuggestedModifier;
352 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
353 B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
354 SuggestedModifier));
355 }
356 }
Bill Wendling50d46ca2012-10-25 23:28:48 +0000357 }
358
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000359 // Validate tied input operands for type mismatches.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700360 unsigned NumAlternatives = ~0U;
361 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
362 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
363 StringRef ConstraintStr = Info.getConstraintStr();
364 unsigned AltCount = ConstraintStr.count(',') + 1;
365 if (NumAlternatives == ~0U)
366 NumAlternatives = AltCount;
367 else if (NumAlternatives != AltCount)
368 return StmtError(Diag(NS->getOutputExpr(i)->getLocStart(),
369 diag::err_asm_unexpected_constraint_alternatives)
370 << NumAlternatives << AltCount);
371 }
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000372 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
373 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700374 StringRef ConstraintStr = Info.getConstraintStr();
375 unsigned AltCount = ConstraintStr.count(',') + 1;
376 if (NumAlternatives == ~0U)
377 NumAlternatives = AltCount;
378 else if (NumAlternatives != AltCount)
379 return StmtError(Diag(NS->getInputExpr(i)->getLocStart(),
380 diag::err_asm_unexpected_constraint_alternatives)
381 << NumAlternatives << AltCount);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000382
383 // If this is a tied constraint, verify that the output and input have
384 // either exactly the same type, or that they are int/ptr operands with the
385 // same size (int/long, int*/long, are ok etc).
386 if (!Info.hasTiedOperand()) continue;
387
388 unsigned TiedTo = Info.getTiedOperand();
389 unsigned InputOpNo = i+NumOutputs;
390 Expr *OutputExpr = Exprs[TiedTo];
391 Expr *InputExpr = Exprs[InputOpNo];
392
393 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
394 continue;
395
396 QualType InTy = InputExpr->getType();
397 QualType OutTy = OutputExpr->getType();
398 if (Context.hasSameType(InTy, OutTy))
399 continue; // All types can be tied to themselves.
400
401 // Decide if the input and output are in the same domain (integer/ptr or
402 // floating point.
403 enum AsmDomain {
404 AD_Int, AD_FP, AD_Other
405 } InputDomain, OutputDomain;
406
407 if (InTy->isIntegerType() || InTy->isPointerType())
408 InputDomain = AD_Int;
409 else if (InTy->isRealFloatingType())
410 InputDomain = AD_FP;
411 else
412 InputDomain = AD_Other;
413
414 if (OutTy->isIntegerType() || OutTy->isPointerType())
415 OutputDomain = AD_Int;
416 else if (OutTy->isRealFloatingType())
417 OutputDomain = AD_FP;
418 else
419 OutputDomain = AD_Other;
420
421 // They are ok if they are the same size and in the same domain. This
422 // allows tying things like:
423 // void* to int*
424 // void* to int if they are the same size.
425 // double to long double if they are the same size.
426 //
427 uint64_t OutSize = Context.getTypeSize(OutTy);
428 uint64_t InSize = Context.getTypeSize(InTy);
429 if (OutSize == InSize && InputDomain == OutputDomain &&
430 InputDomain != AD_Other)
431 continue;
432
433 // If the smaller input/output operand is not mentioned in the asm string,
434 // then we can promote the smaller one to a larger input and the asm string
435 // won't notice.
436 bool SmallerValueMentioned = false;
437
438 // If this is a reference to the input and if the input was the smaller
439 // one, then we have to reject this asm.
440 if (isOperandMentioned(InputOpNo, Pieces)) {
441 // This is a use in the asm string of the smaller operand. Since we
442 // codegen this by promoting to a wider value, the asm will get printed
443 // "wrong".
444 SmallerValueMentioned |= InSize < OutSize;
445 }
446 if (isOperandMentioned(TiedTo, Pieces)) {
447 // If this is a reference to the output, and if the output is the larger
448 // value, then it's ok because we'll promote the input to the larger type.
449 SmallerValueMentioned |= OutSize < InSize;
450 }
451
452 // If the smaller value wasn't mentioned in the asm string, and if the
453 // output was a register, just extend the shorter one to the size of the
454 // larger one.
455 if (!SmallerValueMentioned && InputDomain != AD_Other &&
456 OutputConstraintInfos[TiedTo].allowsRegister())
457 continue;
458
459 // Either both of the operands were mentioned or the smaller one was
460 // mentioned. One more special case that we'll allow: if the tied input is
461 // integer, unmentioned, and is a constant, then we'll allow truncating it
462 // down to the size of the destination.
463 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
464 !isOperandMentioned(InputOpNo, Pieces) &&
465 InputExpr->isEvaluatable(Context)) {
466 CastKind castKind =
467 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700468 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000469 Exprs[InputOpNo] = InputExpr;
470 NS->setInputExpr(i, InputExpr);
471 continue;
472 }
473
474 Diag(InputExpr->getLocStart(),
475 diag::err_asm_tying_incompatible_types)
476 << InTy << OutTy << OutputExpr->getSourceRange()
477 << InputExpr->getSourceRange();
478 return StmtError();
479 }
480
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700481 return NS;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000482}
483
John McCallaeeacf72013-05-03 00:10:13 +0000484ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
485 SourceLocation TemplateKWLoc,
486 UnqualifiedId &Id,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700487 llvm::InlineAsmIdentifierInfo &Info,
John McCallaeeacf72013-05-03 00:10:13 +0000488 bool IsUnevaluatedContext) {
Chad Rosier1e7ca622013-04-22 17:01:37 +0000489 Info.clear();
Chad Rosier7fd00b12012-10-18 15:49:40 +0000490
John McCallaeeacf72013-05-03 00:10:13 +0000491 if (IsUnevaluatedContext)
492 PushExpressionEvaluationContext(UnevaluatedAbstract,
493 ReuseLambdaContextDecl);
494
495 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
496 /*trailing lparen*/ false,
Chad Rosier942dfe22013-05-24 18:32:55 +0000497 /*is & operand*/ false,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700498 /*CorrectionCandidateCallback=*/nullptr,
Chad Rosier942dfe22013-05-24 18:32:55 +0000499 /*IsInlineAsmIdentifier=*/ true);
John McCallaeeacf72013-05-03 00:10:13 +0000500
501 if (IsUnevaluatedContext)
502 PopExpressionEvaluationContext();
503
504 if (!Result.isUsable()) return Result;
505
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700506 Result = CheckPlaceholderExpr(Result.get());
John McCallaeeacf72013-05-03 00:10:13 +0000507 if (!Result.isUsable()) return Result;
508
Stephen Hines176edba2014-12-01 14:53:08 -0800509 // Referring to parameters is not allowed in naked functions.
510 if (CheckNakedParmReference(Result.get(), *this))
511 return ExprError();
512
John McCallaeeacf72013-05-03 00:10:13 +0000513 QualType T = Result.get()->getType();
514
515 // For now, reject dependent types.
516 if (T->isDependentType()) {
517 Diag(Id.getLocStart(), diag::err_asm_incomplete_type) << T;
518 return ExprError();
Chad Rosier7fd00b12012-10-18 15:49:40 +0000519 }
520
John McCallaeeacf72013-05-03 00:10:13 +0000521 // Any sort of function type is fine.
522 if (T->isFunctionType()) {
523 return Result;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000524 }
525
John McCallaeeacf72013-05-03 00:10:13 +0000526 // Otherwise, it needs to be a complete type.
527 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
528 return ExprError();
529 }
530
531 // Compute the type size (and array length if applicable?).
532 Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
533 if (T->isArrayType()) {
534 const ArrayType *ATy = Context.getAsArrayType(T);
535 Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
536 Info.Length = Info.Size / Info.Type;
537 }
538
539 // We can work with the expression as long as it's not an r-value.
540 if (!Result.get()->isRValue())
Chad Rosier1e7ca622013-04-22 17:01:37 +0000541 Info.IsVarDecl = true;
Chad Rosier7fd00b12012-10-18 15:49:40 +0000542
John McCallaeeacf72013-05-03 00:10:13 +0000543 return Result;
Chad Rosierd9b56ed2012-10-15 19:56:10 +0000544}
Chad Rosier2735df22012-08-22 19:18:30 +0000545
Chad Rosier802f9372012-10-25 21:49:22 +0000546bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
547 unsigned &Offset, SourceLocation AsmLoc) {
548 Offset = 0;
549 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
550 LookupOrdinaryName);
551
552 if (!LookupName(BaseResult, getCurScope()))
553 return true;
554
555 if (!BaseResult.isSingleResult())
556 return true;
557
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700558 const RecordType *RT = nullptr;
Chad Rosiere3faa6e2013-04-01 17:58:03 +0000559 NamedDecl *FoundDecl = BaseResult.getFoundDecl();
560 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
Chad Rosier802f9372012-10-25 21:49:22 +0000561 RT = VD->getType()->getAs<RecordType>();
Stephen Hines176edba2014-12-01 14:53:08 -0800562 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
563 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
Chad Rosier802f9372012-10-25 21:49:22 +0000564 RT = TD->getUnderlyingType()->getAs<RecordType>();
Stephen Hines176edba2014-12-01 14:53:08 -0800565 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700566 RT = TD->getTypeForDecl()->getAs<RecordType>();
Chad Rosier802f9372012-10-25 21:49:22 +0000567 if (!RT)
568 return true;
569
570 if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
571 return true;
572
573 LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
574 LookupMemberName);
575
576 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
577 return true;
578
579 // FIXME: Handle IndirectFieldDecl?
580 FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
581 if (!FD)
582 return true;
583
584 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
585 unsigned i = FD->getFieldIndex();
586 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
587 Offset = (unsigned)Result.getQuantity();
588
589 return false;
590}
591
Chad Rosierb55e6022012-09-13 00:06:55 +0000592StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
John McCallaeeacf72013-05-03 00:10:13 +0000593 ArrayRef<Token> AsmToks,
594 StringRef AsmString,
595 unsigned NumOutputs, unsigned NumInputs,
596 ArrayRef<StringRef> Constraints,
597 ArrayRef<StringRef> Clobbers,
598 ArrayRef<Expr*> Exprs,
599 SourceLocation EndLoc) {
600 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
Stephen Hines176edba2014-12-01 14:53:08 -0800601 getCurFunction()->setHasBranchProtectedScope();
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000602 MSAsmStmt *NS =
Chad Rosier7fd00b12012-10-18 15:49:40 +0000603 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
604 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
John McCallaeeacf72013-05-03 00:10:13 +0000605 Constraints, Exprs, AsmString,
606 Clobbers, EndLoc);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700607 return NS;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000608}
Stephen Hines176edba2014-12-01 14:53:08 -0800609
610LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
611 SourceLocation Location,
612 bool AlwaysCreate) {
613 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
614 Location);
615
616 if (Label->isMSAsmLabel()) {
617 // If we have previously created this label implicitly, mark it as used.
618 Label->markUsed(Context);
619 } else {
620 // Otherwise, insert it, but only resolve it if we have seen the label itself.
621 std::string InternalName;
622 llvm::raw_string_ostream OS(InternalName);
623 // Create an internal name for the label. The name should not be a valid mangled
624 // name, and should be unique. We use a dot to make the name an invalid mangled
625 // name.
626 OS << "__MSASMLABEL_." << MSAsmLabelNameCounter++ << "__" << ExternalLabelName;
627 Label->setMSAsmLabel(OS.str());
628 }
629 if (AlwaysCreate) {
630 // The label might have been created implicitly from a previously encountered
631 // goto statement. So, for both newly created and looked up labels, we mark
632 // them as resolved.
633 Label->setMSAsmLabelResolved();
634 }
635 // Adjust their location for being able to generate accurate diagnostics.
636 Label->setLocation(Location);
637
638 return Label;
639}