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 #include "llvm/MC/MCParser/MCAsmParser.h"
26 using namespace clang;
27 using namespace sema;
28 
29 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
30 /// ignore "noop" casts in places where an lvalue is required by an inline asm.
31 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but
32 /// provide a strong guidance to not use it.
33 ///
34 /// This method checks to see if the argument is an acceptable l-value and
35 /// returns false if it is a case we can handle.
36 static bool CheckAsmLValue(const Expr *E, Sema &S) {
37   // Type dependent expressions will be checked during instantiation.
38   if (E->isTypeDependent())
39     return false;
40 
41   if (E->isLValue())
42     return false;  // Cool, this is an lvalue.
43 
44   // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
45   // are supposed to allow.
46   const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
47   if (E != E2 && E2->isLValue()) {
48     if (!S.getLangOpts().HeinousExtensions)
49       S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
50         << E->getSourceRange();
51     else
52       S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
53         << E->getSourceRange();
54     // Accept, even if we emitted an error diagnostic.
55     return false;
56   }
57 
58   // None of the above, just randomly invalid non-lvalue.
59   return true;
60 }
61 
62 /// isOperandMentioned - Return true if the specified operand # is mentioned
63 /// anywhere in the decomposed asm string.
64 static bool isOperandMentioned(unsigned OpNo,
65                          ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
66   for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
67     const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
68     if (!Piece.isOperand()) continue;
69 
70     // If this is a reference to the input and if the input was the smaller
71     // one, then we have to reject this asm.
72     if (Piece.getOperandNo() == OpNo)
73       return true;
74   }
75   return false;
76 }
77 
78 StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
79                                  bool IsVolatile, unsigned NumOutputs,
80                                  unsigned NumInputs, IdentifierInfo **Names,
81                                  MultiExprArg constraints, MultiExprArg Exprs,
82                                  Expr *asmString, MultiExprArg clobbers,
83                                  SourceLocation RParenLoc) {
84   unsigned NumClobbers = clobbers.size();
85   StringLiteral **Constraints =
86     reinterpret_cast<StringLiteral**>(constraints.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     const Type *Ty = OutputExpr->getType().getTypePtr();
127 
128     // If this is a dependent type, just continue. We don't know the size of a
129     // dependent type.
130     if (Ty->isDependentType())
131       continue;
132 
133     unsigned Size = Context.getTypeSize(Ty);
134     if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
135                                                     Size))
136       return StmtError(Diag(OutputExpr->getLocStart(),
137                             diag::err_asm_invalid_output_size)
138                        << Info.getConstraintStr());
139   }
140 
141   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
142 
143   for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
144     StringLiteral *Literal = Constraints[i];
145     if (!Literal->isAscii())
146       return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
147         << Literal->getSourceRange());
148 
149     StringRef InputName;
150     if (Names[i])
151       InputName = Names[i]->getName();
152 
153     TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
154     if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
155                                                 NumOutputs, Info)) {
156       return StmtError(Diag(Literal->getLocStart(),
157                             diag::err_asm_invalid_input_constraint)
158                        << Info.getConstraintStr());
159     }
160 
161     Expr *InputExpr = Exprs[i];
162 
163     // Only allow void types for memory constraints.
164     if (Info.allowsMemory() && !Info.allowsRegister()) {
165       if (CheckAsmLValue(InputExpr, *this))
166         return StmtError(Diag(InputExpr->getLocStart(),
167                               diag::err_asm_invalid_lvalue_in_input)
168                          << Info.getConstraintStr()
169                          << InputExpr->getSourceRange());
170     } else {
171       ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
172       if (Result.isInvalid())
173         return StmtError();
174 
175       Exprs[i] = Result.get();
176     }
177 
178     if (Info.allowsRegister()) {
179       if (InputExpr->getType()->isVoidType()) {
180         return StmtError(Diag(InputExpr->getLocStart(),
181                               diag::err_asm_invalid_type_in_input)
182           << InputExpr->getType() << Info.getConstraintStr()
183           << InputExpr->getSourceRange());
184       }
185     }
186 
187     InputConstraintInfos.push_back(Info);
188 
189     const Type *Ty = Exprs[i]->getType().getTypePtr();
190     if (Ty->isDependentType())
191       continue;
192 
193     if (!Ty->isVoidType() || !Info.allowsMemory())
194       if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
195                               diag::err_dereference_incomplete_type))
196         return StmtError();
197 
198     unsigned Size = Context.getTypeSize(Ty);
199     if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
200                                                    Size))
201       return StmtError(Diag(InputExpr->getLocStart(),
202                             diag::err_asm_invalid_input_size)
203                        << Info.getConstraintStr());
204   }
205 
206   // Check that the clobbers are valid.
207   for (unsigned i = 0; i != NumClobbers; i++) {
208     StringLiteral *Literal = Clobbers[i];
209     if (!Literal->isAscii())
210       return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
211         << Literal->getSourceRange());
212 
213     StringRef Clobber = Literal->getString();
214 
215     if (!Context.getTargetInfo().isValidClobber(Clobber))
216       return StmtError(Diag(Literal->getLocStart(),
217                   diag::err_asm_unknown_register_name) << Clobber);
218   }
219 
220   GCCAsmStmt *NS =
221     new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
222                              NumInputs, Names, Constraints, Exprs.data(),
223                              AsmString, NumClobbers, Clobbers, RParenLoc);
224   // Validate the asm string, ensuring it makes sense given the operands we
225   // have.
226   SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
227   unsigned DiagOffs;
228   if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
229     Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
230            << AsmString->getSourceRange();
231     return StmtError();
232   }
233 
234   // Validate constraints and modifiers.
235   for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
236     GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
237     if (!Piece.isOperand()) continue;
238 
239     // Look for the correct constraint index.
240     unsigned Idx = 0;
241     unsigned ConstraintIdx = 0;
242     for (unsigned i = 0, e = NS->getNumOutputs(); i != e; ++i, ++ConstraintIdx) {
243       TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
244       if (Idx == Piece.getOperandNo())
245         break;
246       ++Idx;
247 
248       if (Info.isReadWrite()) {
249         if (Idx == Piece.getOperandNo())
250           break;
251         ++Idx;
252       }
253     }
254 
255     for (unsigned i = 0, e = NS->getNumInputs(); i != e; ++i, ++ConstraintIdx) {
256       TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
257       if (Idx == Piece.getOperandNo())
258         break;
259       ++Idx;
260 
261       if (Info.isReadWrite()) {
262         if (Idx == Piece.getOperandNo())
263           break;
264         ++Idx;
265       }
266     }
267 
268     // Now that we have the right indexes go ahead and check.
269     StringLiteral *Literal = Constraints[ConstraintIdx];
270     const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
271     if (Ty->isDependentType() || Ty->isIncompleteType())
272       continue;
273 
274     unsigned Size = Context.getTypeSize(Ty);
275     std::string SuggestedModifier;
276     if (!Context.getTargetInfo().validateConstraintModifier(
277             Literal->getString(), Piece.getModifier(), Size,
278             SuggestedModifier)) {
279       Diag(Exprs[ConstraintIdx]->getLocStart(),
280            diag::warn_asm_mismatched_size_modifier);
281 
282       if (!SuggestedModifier.empty()) {
283         auto B = Diag(Piece.getRange().getBegin(),
284                       diag::note_asm_missing_constraint_modifier)
285                  << SuggestedModifier;
286         SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
287         B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
288                                                     SuggestedModifier));
289       }
290     }
291   }
292 
293   // Validate tied input operands for type mismatches.
294   for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
295     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
296 
297     // If this is a tied constraint, verify that the output and input have
298     // either exactly the same type, or that they are int/ptr operands with the
299     // same size (int/long, int*/long, are ok etc).
300     if (!Info.hasTiedOperand()) continue;
301 
302     unsigned TiedTo = Info.getTiedOperand();
303     unsigned InputOpNo = i+NumOutputs;
304     Expr *OutputExpr = Exprs[TiedTo];
305     Expr *InputExpr = Exprs[InputOpNo];
306 
307     if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
308       continue;
309 
310     QualType InTy = InputExpr->getType();
311     QualType OutTy = OutputExpr->getType();
312     if (Context.hasSameType(InTy, OutTy))
313       continue;  // All types can be tied to themselves.
314 
315     // Decide if the input and output are in the same domain (integer/ptr or
316     // floating point.
317     enum AsmDomain {
318       AD_Int, AD_FP, AD_Other
319     } InputDomain, OutputDomain;
320 
321     if (InTy->isIntegerType() || InTy->isPointerType())
322       InputDomain = AD_Int;
323     else if (InTy->isRealFloatingType())
324       InputDomain = AD_FP;
325     else
326       InputDomain = AD_Other;
327 
328     if (OutTy->isIntegerType() || OutTy->isPointerType())
329       OutputDomain = AD_Int;
330     else if (OutTy->isRealFloatingType())
331       OutputDomain = AD_FP;
332     else
333       OutputDomain = AD_Other;
334 
335     // They are ok if they are the same size and in the same domain.  This
336     // allows tying things like:
337     //   void* to int*
338     //   void* to int            if they are the same size.
339     //   double to long double   if they are the same size.
340     //
341     uint64_t OutSize = Context.getTypeSize(OutTy);
342     uint64_t InSize = Context.getTypeSize(InTy);
343     if (OutSize == InSize && InputDomain == OutputDomain &&
344         InputDomain != AD_Other)
345       continue;
346 
347     // If the smaller input/output operand is not mentioned in the asm string,
348     // then we can promote the smaller one to a larger input and the asm string
349     // won't notice.
350     bool SmallerValueMentioned = false;
351 
352     // If this is a reference to the input and if the input was the smaller
353     // one, then we have to reject this asm.
354     if (isOperandMentioned(InputOpNo, Pieces)) {
355       // This is a use in the asm string of the smaller operand.  Since we
356       // codegen this by promoting to a wider value, the asm will get printed
357       // "wrong".
358       SmallerValueMentioned |= InSize < OutSize;
359     }
360     if (isOperandMentioned(TiedTo, Pieces)) {
361       // If this is a reference to the output, and if the output is the larger
362       // value, then it's ok because we'll promote the input to the larger type.
363       SmallerValueMentioned |= OutSize < InSize;
364     }
365 
366     // If the smaller value wasn't mentioned in the asm string, and if the
367     // output was a register, just extend the shorter one to the size of the
368     // larger one.
369     if (!SmallerValueMentioned && InputDomain != AD_Other &&
370         OutputConstraintInfos[TiedTo].allowsRegister())
371       continue;
372 
373     // Either both of the operands were mentioned or the smaller one was
374     // mentioned.  One more special case that we'll allow: if the tied input is
375     // integer, unmentioned, and is a constant, then we'll allow truncating it
376     // down to the size of the destination.
377     if (InputDomain == AD_Int && OutputDomain == AD_Int &&
378         !isOperandMentioned(InputOpNo, Pieces) &&
379         InputExpr->isEvaluatable(Context)) {
380       CastKind castKind =
381         (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
382       InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
383       Exprs[InputOpNo] = InputExpr;
384       NS->setInputExpr(i, InputExpr);
385       continue;
386     }
387 
388     Diag(InputExpr->getLocStart(),
389          diag::err_asm_tying_incompatible_types)
390       << InTy << OutTy << OutputExpr->getSourceRange()
391       << InputExpr->getSourceRange();
392     return StmtError();
393   }
394 
395   return NS;
396 }
397 
398 ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
399                                            SourceLocation TemplateKWLoc,
400                                            UnqualifiedId &Id,
401                                            llvm::InlineAsmIdentifierInfo &Info,
402                                            bool IsUnevaluatedContext) {
403   Info.clear();
404 
405   if (IsUnevaluatedContext)
406     PushExpressionEvaluationContext(UnevaluatedAbstract,
407                                     ReuseLambdaContextDecl);
408 
409   ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
410                                         /*trailing lparen*/ false,
411                                         /*is & operand*/ false,
412                                         /*CorrectionCandidateCallback=*/nullptr,
413                                         /*IsInlineAsmIdentifier=*/ true);
414 
415   if (IsUnevaluatedContext)
416     PopExpressionEvaluationContext();
417 
418   if (!Result.isUsable()) return Result;
419 
420   Result = CheckPlaceholderExpr(Result.get());
421   if (!Result.isUsable()) return Result;
422 
423   // Referring to parameters is not allowed in naked functions.
424   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Result.get())) {
425     if (ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
426       if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
427         if (Func->hasAttr<NakedAttr>()) {
428           Diag(Id.getLocStart(), diag::err_asm_naked_parm_ref);
429           Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
430           return ExprError();
431         }
432       }
433     }
434   }
435 
436   QualType T = Result.get()->getType();
437 
438   // For now, reject dependent types.
439   if (T->isDependentType()) {
440     Diag(Id.getLocStart(), diag::err_asm_incomplete_type) << T;
441     return ExprError();
442   }
443 
444   // Any sort of function type is fine.
445   if (T->isFunctionType()) {
446     return Result;
447   }
448 
449   // Otherwise, it needs to be a complete type.
450   if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
451     return ExprError();
452   }
453 
454   // Compute the type size (and array length if applicable?).
455   Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
456   if (T->isArrayType()) {
457     const ArrayType *ATy = Context.getAsArrayType(T);
458     Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
459     Info.Length = Info.Size / Info.Type;
460   }
461 
462   // We can work with the expression as long as it's not an r-value.
463   if (!Result.get()->isRValue())
464     Info.IsVarDecl = true;
465 
466   return Result;
467 }
468 
469 bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
470                                 unsigned &Offset, SourceLocation AsmLoc) {
471   Offset = 0;
472   LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
473                           LookupOrdinaryName);
474 
475   if (!LookupName(BaseResult, getCurScope()))
476     return true;
477 
478   if (!BaseResult.isSingleResult())
479     return true;
480 
481   const RecordType *RT = nullptr;
482   NamedDecl *FoundDecl = BaseResult.getFoundDecl();
483   if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
484     RT = VD->getType()->getAs<RecordType>();
485   else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
486     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
487     RT = TD->getUnderlyingType()->getAs<RecordType>();
488   } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
489     RT = TD->getTypeForDecl()->getAs<RecordType>();
490   if (!RT)
491     return true;
492 
493   if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
494     return true;
495 
496   LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
497                            LookupMemberName);
498 
499   if (!LookupQualifiedName(FieldResult, RT->getDecl()))
500     return true;
501 
502   // FIXME: Handle IndirectFieldDecl?
503   FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
504   if (!FD)
505     return true;
506 
507   const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
508   unsigned i = FD->getFieldIndex();
509   CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
510   Offset = (unsigned)Result.getQuantity();
511 
512   return false;
513 }
514 
515 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
516                                 ArrayRef<Token> AsmToks,
517                                 StringRef AsmString,
518                                 unsigned NumOutputs, unsigned NumInputs,
519                                 ArrayRef<StringRef> Constraints,
520                                 ArrayRef<StringRef> Clobbers,
521                                 ArrayRef<Expr*> Exprs,
522                                 SourceLocation EndLoc) {
523   bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
524   getCurFunction()->setHasBranchProtectedScope();
525   MSAsmStmt *NS =
526     new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
527                             /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
528                             Constraints, Exprs, AsmString,
529                             Clobbers, EndLoc);
530   return NS;
531 }
532 
533 LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
534                                        SourceLocation Location,
535                                        bool AlwaysCreate) {
536   LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
537                                          Location);
538 
539   if (!Label->isMSAsmLabel()) {
540     // Otherwise, insert it, but only resolve it if we have seen the label itself.
541     std::string InternalName;
542     llvm::raw_string_ostream OS(InternalName);
543     // Create an internal name for the label.  The name should not be a valid mangled
544     // name, and should be unique.  We use a dot to make the name an invalid mangled
545     // name.
546     OS << "__MSASMLABEL_." << MSAsmLabelNameCounter++ << "__" << ExternalLabelName;
547     Label->setMSAsmLabel(OS.str());
548   }
549   if (AlwaysCreate) {
550     // The label might have been created implicitly from a previously encountered
551     // goto statement.  So, for both newly created and looked up labels, we mark
552     // them as resolved.
553     Label->setMSAsmLabelResolved();
554   }
555   // Adjust their location for being able to generate accurate diagnostics.
556   Label->setLocation(Location);
557 
558   return Label;
559 }
560