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   bool ValidateConstraints =
128       DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl());
129 
130   for (unsigned i = 0; i != NumOutputs; i++) {
131     StringLiteral *Literal = Constraints[i];
132     assert(Literal->isAscii());
133 
134     StringRef OutputName;
135     if (Names[i])
136       OutputName = Names[i]->getName();
137 
138     TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
139     if (ValidateConstraints &&
140         !Context.getTargetInfo().validateOutputConstraint(Info))
141       return StmtError(Diag(Literal->getLocStart(),
142                             diag::err_asm_invalid_output_constraint)
143                        << Info.getConstraintStr());
144 
145     ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
146     if (ER.isInvalid())
147       return StmtError();
148     Exprs[i] = ER.get();
149 
150     // Check that the output exprs are valid lvalues.
151     Expr *OutputExpr = Exprs[i];
152 
153     // Referring to parameters is not allowed in naked functions.
154     if (CheckNakedParmReference(OutputExpr, *this))
155       return StmtError();
156 
157     // Bitfield can't be referenced with a pointer.
158     if (Info.allowsMemory() && OutputExpr->refersToBitField())
159       return StmtError(Diag(OutputExpr->getLocStart(),
160                             diag::err_asm_bitfield_in_memory_constraint)
161                        << 1
162                        << Info.getConstraintStr()
163                        << OutputExpr->getSourceRange());
164 
165     OutputConstraintInfos.push_back(Info);
166 
167     // If this is dependent, just continue.
168     if (OutputExpr->isTypeDependent())
169       continue;
170 
171     Expr::isModifiableLvalueResult IsLV =
172         OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
173     switch (IsLV) {
174     case Expr::MLV_Valid:
175       // Cool, this is an lvalue.
176       break;
177     case Expr::MLV_ArrayType:
178       // This is OK too.
179       break;
180     case Expr::MLV_LValueCast: {
181       const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
182       if (!getLangOpts().HeinousExtensions) {
183         Diag(LVal->getLocStart(), diag::err_invalid_asm_cast_lvalue)
184             << OutputExpr->getSourceRange();
185       } else {
186         Diag(LVal->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
187             << OutputExpr->getSourceRange();
188       }
189       // Accept, even if we emitted an error diagnostic.
190       break;
191     }
192     case Expr::MLV_IncompleteType:
193     case Expr::MLV_IncompleteVoidType:
194       if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
195                               diag::err_dereference_incomplete_type))
196         return StmtError();
197     default:
198       return StmtError(Diag(OutputExpr->getLocStart(),
199                             diag::err_asm_invalid_lvalue_in_output)
200                        << OutputExpr->getSourceRange());
201     }
202 
203     unsigned Size = Context.getTypeSize(OutputExpr->getType());
204     if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
205                                                     Size))
206       return StmtError(Diag(OutputExpr->getLocStart(),
207                             diag::err_asm_invalid_output_size)
208                        << Info.getConstraintStr());
209   }
210 
211   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
212 
213   for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
214     StringLiteral *Literal = Constraints[i];
215     assert(Literal->isAscii());
216 
217     StringRef InputName;
218     if (Names[i])
219       InputName = Names[i]->getName();
220 
221     TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
222     if (ValidateConstraints &&
223         !Context.getTargetInfo().validateInputConstraint(
224             OutputConstraintInfos.data(), NumOutputs, Info)) {
225       return StmtError(Diag(Literal->getLocStart(),
226                             diag::err_asm_invalid_input_constraint)
227                        << Info.getConstraintStr());
228     }
229 
230     ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
231     if (ER.isInvalid())
232       return StmtError();
233     Exprs[i] = ER.get();
234 
235     Expr *InputExpr = Exprs[i];
236 
237     // Referring to parameters is not allowed in naked functions.
238     if (CheckNakedParmReference(InputExpr, *this))
239       return StmtError();
240 
241     // Bitfield can't be referenced with a pointer.
242     if (Info.allowsMemory() && InputExpr->refersToBitField())
243       return StmtError(Diag(InputExpr->getLocStart(),
244                             diag::err_asm_bitfield_in_memory_constraint)
245                        << 0
246                        << Info.getConstraintStr()
247                        << InputExpr->getSourceRange());
248 
249     // Only allow void types for memory constraints.
250     if (Info.allowsMemory() && !Info.allowsRegister()) {
251       if (CheckAsmLValue(InputExpr, *this))
252         return StmtError(Diag(InputExpr->getLocStart(),
253                               diag::err_asm_invalid_lvalue_in_input)
254                          << Info.getConstraintStr()
255                          << InputExpr->getSourceRange());
256     } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
257       llvm::APSInt Result;
258       if (!InputExpr->EvaluateAsInt(Result, Context))
259         return StmtError(
260             Diag(InputExpr->getLocStart(), diag::err_asm_immediate_expected)
261             << Info.getConstraintStr() << InputExpr->getSourceRange());
262       if (Result.slt(Info.getImmConstantMin()) ||
263           Result.sgt(Info.getImmConstantMax()))
264         return StmtError(Diag(InputExpr->getLocStart(),
265                               diag::err_invalid_asm_value_for_constraint)
266                          << Result.toString(10) << Info.getConstraintStr()
267                          << InputExpr->getSourceRange());
268 
269     } else {
270       ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
271       if (Result.isInvalid())
272         return StmtError();
273 
274       Exprs[i] = Result.get();
275     }
276 
277     if (Info.allowsRegister()) {
278       if (InputExpr->getType()->isVoidType()) {
279         return StmtError(Diag(InputExpr->getLocStart(),
280                               diag::err_asm_invalid_type_in_input)
281           << InputExpr->getType() << Info.getConstraintStr()
282           << InputExpr->getSourceRange());
283       }
284     }
285 
286     InputConstraintInfos.push_back(Info);
287 
288     const Type *Ty = Exprs[i]->getType().getTypePtr();
289     if (Ty->isDependentType())
290       continue;
291 
292     if (!Ty->isVoidType() || !Info.allowsMemory())
293       if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
294                               diag::err_dereference_incomplete_type))
295         return StmtError();
296 
297     unsigned Size = Context.getTypeSize(Ty);
298     if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
299                                                    Size))
300       return StmtError(Diag(InputExpr->getLocStart(),
301                             diag::err_asm_invalid_input_size)
302                        << Info.getConstraintStr());
303   }
304 
305   // Check that the clobbers are valid.
306   for (unsigned i = 0; i != NumClobbers; i++) {
307     StringLiteral *Literal = Clobbers[i];
308     assert(Literal->isAscii());
309 
310     StringRef Clobber = Literal->getString();
311 
312     if (!Context.getTargetInfo().isValidClobber(Clobber))
313       return StmtError(Diag(Literal->getLocStart(),
314                   diag::err_asm_unknown_register_name) << Clobber);
315   }
316 
317   GCCAsmStmt *NS =
318     new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
319                              NumInputs, Names, Constraints, Exprs.data(),
320                              AsmString, NumClobbers, Clobbers, RParenLoc);
321   // Validate the asm string, ensuring it makes sense given the operands we
322   // have.
323   SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
324   unsigned DiagOffs;
325   if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
326     Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
327            << AsmString->getSourceRange();
328     return StmtError();
329   }
330 
331   // Validate constraints and modifiers.
332   for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
333     GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
334     if (!Piece.isOperand()) continue;
335 
336     // Look for the correct constraint index.
337     unsigned ConstraintIdx = Piece.getOperandNo();
338     unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
339 
340     // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
341     // modifier '+'.
342     if (ConstraintIdx >= NumOperands) {
343       unsigned I = 0, E = NS->getNumOutputs();
344 
345       for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
346         if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
347           ConstraintIdx = I;
348           break;
349         }
350 
351       assert(I != E && "Invalid operand number should have been caught in "
352                        " AnalyzeAsmString");
353     }
354 
355     // Now that we have the right indexes go ahead and check.
356     StringLiteral *Literal = Constraints[ConstraintIdx];
357     const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
358     if (Ty->isDependentType() || Ty->isIncompleteType())
359       continue;
360 
361     unsigned Size = Context.getTypeSize(Ty);
362     std::string SuggestedModifier;
363     if (!Context.getTargetInfo().validateConstraintModifier(
364             Literal->getString(), Piece.getModifier(), Size,
365             SuggestedModifier)) {
366       Diag(Exprs[ConstraintIdx]->getLocStart(),
367            diag::warn_asm_mismatched_size_modifier);
368 
369       if (!SuggestedModifier.empty()) {
370         auto B = Diag(Piece.getRange().getBegin(),
371                       diag::note_asm_missing_constraint_modifier)
372                  << SuggestedModifier;
373         SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
374         B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
375                                                     SuggestedModifier));
376       }
377     }
378   }
379 
380   // Validate tied input operands for type mismatches.
381   unsigned NumAlternatives = ~0U;
382   for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
383     TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
384     StringRef ConstraintStr = Info.getConstraintStr();
385     unsigned AltCount = ConstraintStr.count(',') + 1;
386     if (NumAlternatives == ~0U)
387       NumAlternatives = AltCount;
388     else if (NumAlternatives != AltCount)
389       return StmtError(Diag(NS->getOutputExpr(i)->getLocStart(),
390                             diag::err_asm_unexpected_constraint_alternatives)
391                        << NumAlternatives << AltCount);
392   }
393   for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
394     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
395     StringRef ConstraintStr = Info.getConstraintStr();
396     unsigned AltCount = ConstraintStr.count(',') + 1;
397     if (NumAlternatives == ~0U)
398       NumAlternatives = AltCount;
399     else if (NumAlternatives != AltCount)
400       return StmtError(Diag(NS->getInputExpr(i)->getLocStart(),
401                             diag::err_asm_unexpected_constraint_alternatives)
402                        << NumAlternatives << AltCount);
403 
404     // If this is a tied constraint, verify that the output and input have
405     // either exactly the same type, or that they are int/ptr operands with the
406     // same size (int/long, int*/long, are ok etc).
407     if (!Info.hasTiedOperand()) continue;
408 
409     unsigned TiedTo = Info.getTiedOperand();
410     unsigned InputOpNo = i+NumOutputs;
411     Expr *OutputExpr = Exprs[TiedTo];
412     Expr *InputExpr = Exprs[InputOpNo];
413 
414     if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
415       continue;
416 
417     QualType InTy = InputExpr->getType();
418     QualType OutTy = OutputExpr->getType();
419     if (Context.hasSameType(InTy, OutTy))
420       continue;  // All types can be tied to themselves.
421 
422     // Decide if the input and output are in the same domain (integer/ptr or
423     // floating point.
424     enum AsmDomain {
425       AD_Int, AD_FP, AD_Other
426     } InputDomain, OutputDomain;
427 
428     if (InTy->isIntegerType() || InTy->isPointerType())
429       InputDomain = AD_Int;
430     else if (InTy->isRealFloatingType())
431       InputDomain = AD_FP;
432     else
433       InputDomain = AD_Other;
434 
435     if (OutTy->isIntegerType() || OutTy->isPointerType())
436       OutputDomain = AD_Int;
437     else if (OutTy->isRealFloatingType())
438       OutputDomain = AD_FP;
439     else
440       OutputDomain = AD_Other;
441 
442     // They are ok if they are the same size and in the same domain.  This
443     // allows tying things like:
444     //   void* to int*
445     //   void* to int            if they are the same size.
446     //   double to long double   if they are the same size.
447     //
448     uint64_t OutSize = Context.getTypeSize(OutTy);
449     uint64_t InSize = Context.getTypeSize(InTy);
450     if (OutSize == InSize && InputDomain == OutputDomain &&
451         InputDomain != AD_Other)
452       continue;
453 
454     // If the smaller input/output operand is not mentioned in the asm string,
455     // then we can promote the smaller one to a larger input and the asm string
456     // won't notice.
457     bool SmallerValueMentioned = false;
458 
459     // If this is a reference to the input and if the input was the smaller
460     // one, then we have to reject this asm.
461     if (isOperandMentioned(InputOpNo, Pieces)) {
462       // This is a use in the asm string of the smaller operand.  Since we
463       // codegen this by promoting to a wider value, the asm will get printed
464       // "wrong".
465       SmallerValueMentioned |= InSize < OutSize;
466     }
467     if (isOperandMentioned(TiedTo, Pieces)) {
468       // If this is a reference to the output, and if the output is the larger
469       // value, then it's ok because we'll promote the input to the larger type.
470       SmallerValueMentioned |= OutSize < InSize;
471     }
472 
473     // If the smaller value wasn't mentioned in the asm string, and if the
474     // output was a register, just extend the shorter one to the size of the
475     // larger one.
476     if (!SmallerValueMentioned && InputDomain != AD_Other &&
477         OutputConstraintInfos[TiedTo].allowsRegister())
478       continue;
479 
480     // Either both of the operands were mentioned or the smaller one was
481     // mentioned.  One more special case that we'll allow: if the tied input is
482     // integer, unmentioned, and is a constant, then we'll allow truncating it
483     // down to the size of the destination.
484     if (InputDomain == AD_Int && OutputDomain == AD_Int &&
485         !isOperandMentioned(InputOpNo, Pieces) &&
486         InputExpr->isEvaluatable(Context)) {
487       CastKind castKind =
488         (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
489       InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
490       Exprs[InputOpNo] = InputExpr;
491       NS->setInputExpr(i, InputExpr);
492       continue;
493     }
494 
495     Diag(InputExpr->getLocStart(),
496          diag::err_asm_tying_incompatible_types)
497       << InTy << OutTy << OutputExpr->getSourceRange()
498       << InputExpr->getSourceRange();
499     return StmtError();
500   }
501 
502   return NS;
503 }
504 
505 ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
506                                            SourceLocation TemplateKWLoc,
507                                            UnqualifiedId &Id,
508                                            llvm::InlineAsmIdentifierInfo &Info,
509                                            bool IsUnevaluatedContext) {
510   Info.clear();
511 
512   if (IsUnevaluatedContext)
513     PushExpressionEvaluationContext(UnevaluatedAbstract,
514                                     ReuseLambdaContextDecl);
515 
516   ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
517                                         /*trailing lparen*/ false,
518                                         /*is & operand*/ false,
519                                         /*CorrectionCandidateCallback=*/nullptr,
520                                         /*IsInlineAsmIdentifier=*/ true);
521 
522   if (IsUnevaluatedContext)
523     PopExpressionEvaluationContext();
524 
525   if (!Result.isUsable()) return Result;
526 
527   Result = CheckPlaceholderExpr(Result.get());
528   if (!Result.isUsable()) return Result;
529 
530   // Referring to parameters is not allowed in naked functions.
531   if (CheckNakedParmReference(Result.get(), *this))
532     return ExprError();
533 
534   QualType T = Result.get()->getType();
535 
536   // For now, reject dependent types.
537   if (T->isDependentType()) {
538     Diag(Id.getLocStart(), diag::err_asm_incomplete_type) << T;
539     return ExprError();
540   }
541 
542   // Any sort of function type is fine.
543   if (T->isFunctionType()) {
544     return Result;
545   }
546 
547   // Otherwise, it needs to be a complete type.
548   if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
549     return ExprError();
550   }
551 
552   // Compute the type size (and array length if applicable?).
553   Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
554   if (T->isArrayType()) {
555     const ArrayType *ATy = Context.getAsArrayType(T);
556     Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
557     Info.Length = Info.Size / Info.Type;
558   }
559 
560   // We can work with the expression as long as it's not an r-value.
561   if (!Result.get()->isRValue())
562     Info.IsVarDecl = true;
563 
564   return Result;
565 }
566 
567 bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
568                                 unsigned &Offset, SourceLocation AsmLoc) {
569   Offset = 0;
570   LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
571                           LookupOrdinaryName);
572 
573   if (!LookupName(BaseResult, getCurScope()))
574     return true;
575 
576   if (!BaseResult.isSingleResult())
577     return true;
578 
579   const RecordType *RT = nullptr;
580   NamedDecl *FoundDecl = BaseResult.getFoundDecl();
581   if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
582     RT = VD->getType()->getAs<RecordType>();
583   else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
584     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
585     RT = TD->getUnderlyingType()->getAs<RecordType>();
586   } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
587     RT = TD->getTypeForDecl()->getAs<RecordType>();
588   if (!RT)
589     return true;
590 
591   if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
592     return true;
593 
594   LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
595                            LookupMemberName);
596 
597   if (!LookupQualifiedName(FieldResult, RT->getDecl()))
598     return true;
599 
600   // FIXME: Handle IndirectFieldDecl?
601   FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
602   if (!FD)
603     return true;
604 
605   const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
606   unsigned i = FD->getFieldIndex();
607   CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
608   Offset = (unsigned)Result.getQuantity();
609 
610   return false;
611 }
612 
613 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
614                                 ArrayRef<Token> AsmToks,
615                                 StringRef AsmString,
616                                 unsigned NumOutputs, unsigned NumInputs,
617                                 ArrayRef<StringRef> Constraints,
618                                 ArrayRef<StringRef> Clobbers,
619                                 ArrayRef<Expr*> Exprs,
620                                 SourceLocation EndLoc) {
621   bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
622   getCurFunction()->setHasBranchProtectedScope();
623   MSAsmStmt *NS =
624     new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
625                             /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
626                             Constraints, Exprs, AsmString,
627                             Clobbers, EndLoc);
628   return NS;
629 }
630 
631 LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
632                                        SourceLocation Location,
633                                        bool AlwaysCreate) {
634   LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
635                                          Location);
636 
637   if (Label->isMSAsmLabel()) {
638     // If we have previously created this label implicitly, mark it as used.
639     Label->markUsed(Context);
640   } else {
641     // Otherwise, insert it, but only resolve it if we have seen the label itself.
642     std::string InternalName;
643     llvm::raw_string_ostream OS(InternalName);
644     // Create an internal name for the label.  The name should not be a valid mangled
645     // name, and should be unique.  We use a dot to make the name an invalid mangled
646     // name.
647     OS << "__MSASMLABEL_." << MSAsmLabelNameCounter++ << "__" << ExternalLabelName;
648     Label->setMSAsmLabel(OS.str());
649   }
650   if (AlwaysCreate) {
651     // The label might have been created implicitly from a previously encountered
652     // goto statement.  So, for both newly created and looked up labels, we mark
653     // them as resolved.
654     Label->setMSAsmLabelResolved();
655   }
656   // Adjust their location for being able to generate accurate diagnostics.
657   Label->setLocation(Location);
658 
659   return Label;
660 }
661