SemaStmtAsm.cpp 25 KB

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