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/ExprCXX.h"
16 #include "clang/AST/RecordLayout.h"
17 #include "clang/AST/TypeLoc.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Sema/Initialization.h"
21 #include "clang/Sema/Lookup.h"
22 #include "clang/Sema/Scope.h"
23 #include "clang/Sema/ScopeInfo.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 using namespace clang;
28 using 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.
37 static 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.
65 static bool isOperandMentioned(unsigned OpNo,
66                          ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
67   for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
68     const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
69     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 
79 static 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();
90     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     }
95     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 
110 StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
111                                  bool IsVolatile, unsigned NumOutputs,
112                                  unsigned NumInputs, IdentifierInfo **Names,
113                                  MultiExprArg constraints, MultiExprArg Exprs,
114                                  Expr *asmString, MultiExprArg clobbers,
115                                  SourceLocation RParenLoc) {
116   unsigned NumClobbers = clobbers.size();
117   StringLiteral **Constraints =
118     reinterpret_cast<StringLiteral**>(constraints.data());
119   StringLiteral *AsmString = cast<StringLiteral>(asmString);
120   StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
121 
122   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
123 
124   // The parser verifies that there is a string literal here.
125   assert(AsmString->isAscii());
126 
127   for (unsigned i = 0; i != NumOutputs; i++) {
128     StringLiteral *Literal = Constraints[i];
129     assert(Literal->isAscii());
130 
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 
141     ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
142     if (ER.isInvalid())
143       return StmtError();
144     Exprs[i] = ER.get();
145 
146     // Check that the output exprs are valid lvalues.
147     Expr *OutputExpr = Exprs[i];
148 
149     // Referring to parameters is not allowed in naked functions.
150     if (CheckNakedParmReference(OutputExpr, *this))
151       return StmtError();
152 
153     OutputConstraintInfos.push_back(Info);
154 
155     // If this is dependent, just continue.
156     if (OutputExpr->isTypeDependent())
157       continue;
158 
159     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());
192     if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
193                                                     Size))
194       return StmtError(Diag(OutputExpr->getLocStart(),
195                             diag::err_asm_invalid_output_size)
196                        << Info.getConstraintStr());
197   }
198 
199   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
200 
201   for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
202     StringLiteral *Literal = Constraints[i];
203     assert(Literal->isAscii());
204 
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 
217     ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
218     if (ER.isInvalid())
219       return StmtError();
220     Exprs[i] = ER.get();
221 
222     Expr *InputExpr = Exprs[i];
223 
224     // Referring to parameters is not allowed in naked functions.
225     if (CheckNakedParmReference(InputExpr, *this))
226       return StmtError();
227 
228     // 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());
235     } 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 
248     } else {
249       ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
250       if (Result.isInvalid())
251         return StmtError();
252 
253       Exprs[i] = Result.get();
254     }
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 
265     InputConstraintInfos.push_back(Info);
266 
267     const Type *Ty = Exprs[i]->getType().getTypePtr();
268     if (Ty->isDependentType())
269       continue;
270 
271     if (!Ty->isVoidType() || !Info.allowsMemory())
272       if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
273                               diag::err_dereference_incomplete_type))
274         return StmtError();
275 
276     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());
282   }
283 
284   // Check that the clobbers are valid.
285   for (unsigned i = 0; i != NumClobbers; i++) {
286     StringLiteral *Literal = Clobbers[i];
287     assert(Literal->isAscii());
288 
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 
296   GCCAsmStmt *NS =
297     new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
298                              NumInputs, Names, Constraints, Exprs.data(),
299                              AsmString, NumClobbers, Clobbers, RParenLoc);
300   // Validate the asm string, ensuring it makes sense given the operands we
301   // have.
302   SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
303   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 
310   // 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.
316     unsigned ConstraintIdx = Piece.getOperandNo();
317     unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
318 
319     // 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;
327           break;
328         }
329 
330       assert(I != E && "Invalid operand number should have been caught in "
331                        " AnalyzeAsmString");
332     }
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);
341     std::string SuggestedModifier;
342     if (!Context.getTargetInfo().validateConstraintModifier(
343             Literal->getString(), Piece.getModifier(), Size,
344             SuggestedModifier)) {
345       Diag(Exprs[ConstraintIdx]->getLocStart(),
346            diag::warn_asm_mismatched_size_modifier);
347 
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     }
357   }
358 
359   // Validate tied input operands for type mismatches.
360   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   }
372   for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
373     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
374     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);
382 
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);
468       InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
469       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 
481   return NS;
482 }
483 
484 ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
485                                            SourceLocation TemplateKWLoc,
486                                            UnqualifiedId &Id,
487                                            llvm::InlineAsmIdentifierInfo &Info,
488                                            bool IsUnevaluatedContext) {
489   Info.clear();
490 
491   if (IsUnevaluatedContext)
492     PushExpressionEvaluationContext(UnevaluatedAbstract,
493                                     ReuseLambdaContextDecl);
494 
495   ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
496                                         /*trailing lparen*/ false,
497                                         /*is & operand*/ false,
498                                         /*CorrectionCandidateCallback=*/nullptr,
499                                         /*IsInlineAsmIdentifier=*/ true);
500 
501   if (IsUnevaluatedContext)
502     PopExpressionEvaluationContext();
503 
504   if (!Result.isUsable()) return Result;
505 
506   Result = CheckPlaceholderExpr(Result.get());
507   if (!Result.isUsable()) return Result;
508 
509   // Referring to parameters is not allowed in naked functions.
510   if (CheckNakedParmReference(Result.get(), *this))
511     return ExprError();
512 
513   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();
519   }
520 
521   // Any sort of function type is fine.
522   if (T->isFunctionType()) {
523     return Result;
524   }
525 
526   // 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())
541     Info.IsVarDecl = true;
542 
543   return Result;
544 }
545 
546 bool 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 
558   const RecordType *RT = nullptr;
559   NamedDecl *FoundDecl = BaseResult.getFoundDecl();
560   if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
561     RT = VD->getType()->getAs<RecordType>();
562   else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
563     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
564     RT = TD->getUnderlyingType()->getAs<RecordType>();
565   } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
566     RT = TD->getTypeForDecl()->getAs<RecordType>();
567   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 
592 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
593                                 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);
601   getCurFunction()->setHasBranchProtectedScope();
602   MSAsmStmt *NS =
603     new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
604                             /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
605                             Constraints, Exprs, AsmString,
606                             Clobbers, EndLoc);
607   return NS;
608 }
609 
610 LabelDecl *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 }
640