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