]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaStmtAsm.cpp
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / llvm / tools / clang / lib / Sema / SemaStmtAsm.cpp
1 //===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
2 //
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"
15 #include "clang/AST/RecordLayout.h"
16 #include "clang/AST/TypeLoc.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Sema/Initialization.h"
20 #include "clang/Sema/Lookup.h"
21 #include "clang/Sema/Scope.h"
22 #include "clang/Sema/ScopeInfo.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/BitVector.h"
25 using namespace clang;
26 using namespace sema;
27
28 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
29 /// ignore "noop" casts in places where an lvalue is required by an inline asm.
30 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but
31 /// provide a strong guidance to not use it.
32 ///
33 /// This method checks to see if the argument is an acceptable l-value and
34 /// returns false if it is a case we can handle.
35 static bool CheckAsmLValue(const Expr *E, Sema &S) {
36   // Type dependent expressions will be checked during instantiation.
37   if (E->isTypeDependent())
38     return false;
39
40   if (E->isLValue())
41     return false;  // Cool, this is an lvalue.
42
43   // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
44   // are supposed to allow.
45   const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
46   if (E != E2 && E2->isLValue()) {
47     if (!S.getLangOpts().HeinousExtensions)
48       S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
49         << E->getSourceRange();
50     else
51       S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
52         << E->getSourceRange();
53     // Accept, even if we emitted an error diagnostic.
54     return false;
55   }
56
57   // None of the above, just randomly invalid non-lvalue.
58   return true;
59 }
60
61 /// isOperandMentioned - Return true if the specified operand # is mentioned
62 /// anywhere in the decomposed asm string.
63 static bool isOperandMentioned(unsigned OpNo,
64                          ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
65   for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
66     const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
67     if (!Piece.isOperand()) continue;
68
69     // If this is a reference to the input and if the input was the smaller
70     // one, then we have to reject this asm.
71     if (Piece.getOperandNo() == OpNo)
72       return true;
73   }
74   return false;
75 }
76
77 StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
78                                  bool IsVolatile, unsigned NumOutputs,
79                                  unsigned NumInputs, IdentifierInfo **Names,
80                                  MultiExprArg constraints, MultiExprArg exprs,
81                                  Expr *asmString, MultiExprArg clobbers,
82                                  SourceLocation RParenLoc) {
83   unsigned NumClobbers = clobbers.size();
84   StringLiteral **Constraints =
85     reinterpret_cast<StringLiteral**>(constraints.data());
86   Expr **Exprs = exprs.data();
87   StringLiteral *AsmString = cast<StringLiteral>(asmString);
88   StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
89
90   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
91
92   // The parser verifies that there is a string literal here.
93   if (!AsmString->isAscii())
94     return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
95       << AsmString->getSourceRange());
96
97   for (unsigned i = 0; i != NumOutputs; i++) {
98     StringLiteral *Literal = Constraints[i];
99     if (!Literal->isAscii())
100       return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
101         << Literal->getSourceRange());
102
103     StringRef OutputName;
104     if (Names[i])
105       OutputName = Names[i]->getName();
106
107     TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
108     if (!Context.getTargetInfo().validateOutputConstraint(Info))
109       return StmtError(Diag(Literal->getLocStart(),
110                             diag::err_asm_invalid_output_constraint)
111                        << Info.getConstraintStr());
112
113     // Check that the output exprs are valid lvalues.
114     Expr *OutputExpr = Exprs[i];
115     if (CheckAsmLValue(OutputExpr, *this))
116       return StmtError(Diag(OutputExpr->getLocStart(),
117                             diag::err_asm_invalid_lvalue_in_output)
118                        << OutputExpr->getSourceRange());
119
120     if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
121                             diag::err_dereference_incomplete_type))
122       return StmtError();
123
124     OutputConstraintInfos.push_back(Info);
125   }
126
127   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
128
129   for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
130     StringLiteral *Literal = Constraints[i];
131     if (!Literal->isAscii())
132       return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
133         << Literal->getSourceRange());
134
135     StringRef InputName;
136     if (Names[i])
137       InputName = Names[i]->getName();
138
139     TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
140     if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
141                                                 NumOutputs, Info)) {
142       return StmtError(Diag(Literal->getLocStart(),
143                             diag::err_asm_invalid_input_constraint)
144                        << Info.getConstraintStr());
145     }
146
147     Expr *InputExpr = Exprs[i];
148
149     // Only allow void types for memory constraints.
150     if (Info.allowsMemory() && !Info.allowsRegister()) {
151       if (CheckAsmLValue(InputExpr, *this))
152         return StmtError(Diag(InputExpr->getLocStart(),
153                               diag::err_asm_invalid_lvalue_in_input)
154                          << Info.getConstraintStr()
155                          << InputExpr->getSourceRange());
156     }
157
158     if (Info.allowsRegister()) {
159       if (InputExpr->getType()->isVoidType()) {
160         return StmtError(Diag(InputExpr->getLocStart(),
161                               diag::err_asm_invalid_type_in_input)
162           << InputExpr->getType() << Info.getConstraintStr()
163           << InputExpr->getSourceRange());
164       }
165     }
166
167     ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
168     if (Result.isInvalid())
169       return StmtError();
170
171     Exprs[i] = Result.take();
172     InputConstraintInfos.push_back(Info);
173
174     const Type *Ty = Exprs[i]->getType().getTypePtr();
175     if (Ty->isDependentType())
176       continue;
177
178     if (!Ty->isVoidType() || !Info.allowsMemory())
179       if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
180                               diag::err_dereference_incomplete_type))
181         return StmtError();
182
183     unsigned Size = Context.getTypeSize(Ty);
184     if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
185                                                    Size))
186       return StmtError(Diag(InputExpr->getLocStart(),
187                             diag::err_asm_invalid_input_size)
188                        << Info.getConstraintStr());
189   }
190
191   // Check that the clobbers are valid.
192   for (unsigned i = 0; i != NumClobbers; i++) {
193     StringLiteral *Literal = Clobbers[i];
194     if (!Literal->isAscii())
195       return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
196         << Literal->getSourceRange());
197
198     StringRef Clobber = Literal->getString();
199
200     if (!Context.getTargetInfo().isValidClobber(Clobber))
201       return StmtError(Diag(Literal->getLocStart(),
202                   diag::err_asm_unknown_register_name) << Clobber);
203   }
204
205   GCCAsmStmt *NS =
206     new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
207                              NumInputs, Names, Constraints, Exprs, AsmString,
208                              NumClobbers, Clobbers, RParenLoc);
209   // Validate the asm string, ensuring it makes sense given the operands we
210   // have.
211   SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
212   unsigned DiagOffs;
213   if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
214     Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
215            << AsmString->getSourceRange();
216     return StmtError();
217   }
218
219   // Validate constraints and modifiers.
220   for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
221     GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
222     if (!Piece.isOperand()) continue;
223
224     // Look for the correct constraint index.
225     unsigned Idx = 0;
226     unsigned ConstraintIdx = 0;
227     for (unsigned i = 0, e = NS->getNumOutputs(); i != e; ++i, ++ConstraintIdx) {
228       TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
229       if (Idx == Piece.getOperandNo())
230         break;
231       ++Idx;
232
233       if (Info.isReadWrite()) {
234         if (Idx == Piece.getOperandNo())
235           break;
236         ++Idx;
237       }
238     }
239
240     for (unsigned i = 0, e = NS->getNumInputs(); i != e; ++i, ++ConstraintIdx) {
241       TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
242       if (Idx == Piece.getOperandNo())
243         break;
244       ++Idx;
245
246       if (Info.isReadWrite()) {
247         if (Idx == Piece.getOperandNo())
248           break;
249         ++Idx;
250       }
251     }
252
253     // Now that we have the right indexes go ahead and check.
254     StringLiteral *Literal = Constraints[ConstraintIdx];
255     const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
256     if (Ty->isDependentType() || Ty->isIncompleteType())
257       continue;
258
259     unsigned Size = Context.getTypeSize(Ty);
260     if (!Context.getTargetInfo()
261           .validateConstraintModifier(Literal->getString(), Piece.getModifier(),
262                                       Size))
263       Diag(Exprs[ConstraintIdx]->getLocStart(),
264            diag::warn_asm_mismatched_size_modifier);
265   }
266
267   // Validate tied input operands for type mismatches.
268   for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
269     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
270
271     // If this is a tied constraint, verify that the output and input have
272     // either exactly the same type, or that they are int/ptr operands with the
273     // same size (int/long, int*/long, are ok etc).
274     if (!Info.hasTiedOperand()) continue;
275
276     unsigned TiedTo = Info.getTiedOperand();
277     unsigned InputOpNo = i+NumOutputs;
278     Expr *OutputExpr = Exprs[TiedTo];
279     Expr *InputExpr = Exprs[InputOpNo];
280
281     if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
282       continue;
283
284     QualType InTy = InputExpr->getType();
285     QualType OutTy = OutputExpr->getType();
286     if (Context.hasSameType(InTy, OutTy))
287       continue;  // All types can be tied to themselves.
288
289     // Decide if the input and output are in the same domain (integer/ptr or
290     // floating point.
291     enum AsmDomain {
292       AD_Int, AD_FP, AD_Other
293     } InputDomain, OutputDomain;
294
295     if (InTy->isIntegerType() || InTy->isPointerType())
296       InputDomain = AD_Int;
297     else if (InTy->isRealFloatingType())
298       InputDomain = AD_FP;
299     else
300       InputDomain = AD_Other;
301
302     if (OutTy->isIntegerType() || OutTy->isPointerType())
303       OutputDomain = AD_Int;
304     else if (OutTy->isRealFloatingType())
305       OutputDomain = AD_FP;
306     else
307       OutputDomain = AD_Other;
308
309     // They are ok if they are the same size and in the same domain.  This
310     // allows tying things like:
311     //   void* to int*
312     //   void* to int            if they are the same size.
313     //   double to long double   if they are the same size.
314     //
315     uint64_t OutSize = Context.getTypeSize(OutTy);
316     uint64_t InSize = Context.getTypeSize(InTy);
317     if (OutSize == InSize && InputDomain == OutputDomain &&
318         InputDomain != AD_Other)
319       continue;
320
321     // If the smaller input/output operand is not mentioned in the asm string,
322     // then we can promote the smaller one to a larger input and the asm string
323     // won't notice.
324     bool SmallerValueMentioned = false;
325
326     // If this is a reference to the input and if the input was the smaller
327     // one, then we have to reject this asm.
328     if (isOperandMentioned(InputOpNo, Pieces)) {
329       // This is a use in the asm string of the smaller operand.  Since we
330       // codegen this by promoting to a wider value, the asm will get printed
331       // "wrong".
332       SmallerValueMentioned |= InSize < OutSize;
333     }
334     if (isOperandMentioned(TiedTo, Pieces)) {
335       // If this is a reference to the output, and if the output is the larger
336       // value, then it's ok because we'll promote the input to the larger type.
337       SmallerValueMentioned |= OutSize < InSize;
338     }
339
340     // If the smaller value wasn't mentioned in the asm string, and if the
341     // output was a register, just extend the shorter one to the size of the
342     // larger one.
343     if (!SmallerValueMentioned && InputDomain != AD_Other &&
344         OutputConstraintInfos[TiedTo].allowsRegister())
345       continue;
346
347     // Either both of the operands were mentioned or the smaller one was
348     // mentioned.  One more special case that we'll allow: if the tied input is
349     // integer, unmentioned, and is a constant, then we'll allow truncating it
350     // down to the size of the destination.
351     if (InputDomain == AD_Int && OutputDomain == AD_Int &&
352         !isOperandMentioned(InputOpNo, Pieces) &&
353         InputExpr->isEvaluatable(Context)) {
354       CastKind castKind =
355         (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
356       InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
357       Exprs[InputOpNo] = InputExpr;
358       NS->setInputExpr(i, InputExpr);
359       continue;
360     }
361
362     Diag(InputExpr->getLocStart(),
363          diag::err_asm_tying_incompatible_types)
364       << InTy << OutTy << OutputExpr->getSourceRange()
365       << InputExpr->getSourceRange();
366     return StmtError();
367   }
368
369   return Owned(NS);
370 }
371
372 ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
373                                            SourceLocation TemplateKWLoc,
374                                            UnqualifiedId &Id,
375                                            InlineAsmIdentifierInfo &Info,
376                                            bool IsUnevaluatedContext) {
377   Info.clear();
378
379   if (IsUnevaluatedContext)
380     PushExpressionEvaluationContext(UnevaluatedAbstract,
381                                     ReuseLambdaContextDecl);
382
383   ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
384                                         /*trailing lparen*/ false,
385                                         /*is & operand*/ false);
386
387   if (IsUnevaluatedContext)
388     PopExpressionEvaluationContext();
389
390   if (!Result.isUsable()) return Result;
391
392   Result = CheckPlaceholderExpr(Result.take());
393   if (!Result.isUsable()) return Result;
394
395   QualType T = Result.get()->getType();
396
397   // For now, reject dependent types.
398   if (T->isDependentType()) {
399     Diag(Id.getLocStart(), diag::err_asm_incomplete_type) << T;
400     return ExprError();
401   }
402
403   // Any sort of function type is fine.
404   if (T->isFunctionType()) {
405     return Result;
406   }
407
408   // Otherwise, it needs to be a complete type.
409   if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
410     return ExprError();
411   }
412
413   // Compute the type size (and array length if applicable?).
414   Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
415   if (T->isArrayType()) {
416     const ArrayType *ATy = Context.getAsArrayType(T);
417     Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
418     Info.Length = Info.Size / Info.Type;
419   }
420
421   // We can work with the expression as long as it's not an r-value.
422   if (!Result.get()->isRValue())
423     Info.IsVarDecl = true;
424
425   return Result;
426 }
427
428 bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
429                                 unsigned &Offset, SourceLocation AsmLoc) {
430   Offset = 0;
431   LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
432                           LookupOrdinaryName);
433
434   if (!LookupName(BaseResult, getCurScope()))
435     return true;
436
437   if (!BaseResult.isSingleResult())
438     return true;
439
440   const RecordType *RT = 0;
441   NamedDecl *FoundDecl = BaseResult.getFoundDecl();
442   if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
443     RT = VD->getType()->getAs<RecordType>();
444   else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(FoundDecl))
445     RT = TD->getUnderlyingType()->getAs<RecordType>();
446   if (!RT)
447     return true;
448
449   if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
450     return true;
451
452   LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
453                            LookupMemberName);
454
455   if (!LookupQualifiedName(FieldResult, RT->getDecl()))
456     return true;
457
458   // FIXME: Handle IndirectFieldDecl?
459   FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
460   if (!FD)
461     return true;
462
463   const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
464   unsigned i = FD->getFieldIndex();
465   CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
466   Offset = (unsigned)Result.getQuantity();
467
468   return false;
469 }
470
471 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
472                                 ArrayRef<Token> AsmToks,
473                                 StringRef AsmString,
474                                 unsigned NumOutputs, unsigned NumInputs,
475                                 ArrayRef<StringRef> Constraints,
476                                 ArrayRef<StringRef> Clobbers,
477                                 ArrayRef<Expr*> Exprs,
478                                 SourceLocation EndLoc) {
479   bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
480   MSAsmStmt *NS =
481     new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
482                             /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
483                             Constraints, Exprs, AsmString,
484                             Clobbers, EndLoc);
485   return Owned(NS);
486 }