SemaAttr.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. //===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for non-trivial attributes and
  10. // pragmas.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/Attr.h"
  15. #include "clang/AST/Expr.h"
  16. #include "clang/Basic/TargetInfo.h"
  17. #include "clang/Lex/Preprocessor.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "clang/Sema/SemaInternal.h"
  20. using namespace clang;
  21. //===----------------------------------------------------------------------===//
  22. // Pragma 'pack' and 'options align'
  23. //===----------------------------------------------------------------------===//
  24. Sema::PragmaStackSentinelRAII::PragmaStackSentinelRAII(Sema &S,
  25. StringRef SlotLabel,
  26. bool ShouldAct)
  27. : S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {
  28. if (ShouldAct) {
  29. S.VtorDispStack.SentinelAction(PSK_Push, SlotLabel);
  30. S.DataSegStack.SentinelAction(PSK_Push, SlotLabel);
  31. S.BSSSegStack.SentinelAction(PSK_Push, SlotLabel);
  32. S.ConstSegStack.SentinelAction(PSK_Push, SlotLabel);
  33. S.CodeSegStack.SentinelAction(PSK_Push, SlotLabel);
  34. }
  35. }
  36. Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {
  37. if (ShouldAct) {
  38. S.VtorDispStack.SentinelAction(PSK_Pop, SlotLabel);
  39. S.DataSegStack.SentinelAction(PSK_Pop, SlotLabel);
  40. S.BSSSegStack.SentinelAction(PSK_Pop, SlotLabel);
  41. S.ConstSegStack.SentinelAction(PSK_Pop, SlotLabel);
  42. S.CodeSegStack.SentinelAction(PSK_Pop, SlotLabel);
  43. }
  44. }
  45. void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
  46. // If there is no pack value, we don't need any attributes.
  47. if (!PackStack.CurrentValue)
  48. return;
  49. // Otherwise, check to see if we need a max field alignment attribute.
  50. if (unsigned Alignment = PackStack.CurrentValue) {
  51. if (Alignment == Sema::kMac68kAlignmentSentinel)
  52. RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
  53. else
  54. RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(Context,
  55. Alignment * 8));
  56. }
  57. if (PackIncludeStack.empty())
  58. return;
  59. // The #pragma pack affected a record in an included file, so Clang should
  60. // warn when that pragma was written in a file that included the included
  61. // file.
  62. for (auto &PackedInclude : llvm::reverse(PackIncludeStack)) {
  63. if (PackedInclude.CurrentPragmaLocation != PackStack.CurrentPragmaLocation)
  64. break;
  65. if (PackedInclude.HasNonDefaultValue)
  66. PackedInclude.ShouldWarnOnInclude = true;
  67. }
  68. }
  69. void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
  70. if (MSStructPragmaOn)
  71. RD->addAttr(MSStructAttr::CreateImplicit(Context));
  72. // FIXME: We should merge AddAlignmentAttributesForRecord with
  73. // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
  74. // all active pragmas and applies them as attributes to class definitions.
  75. if (VtorDispStack.CurrentValue != getLangOpts().VtorDispMode)
  76. RD->addAttr(
  77. MSVtorDispAttr::CreateImplicit(Context, VtorDispStack.CurrentValue));
  78. }
  79. void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
  80. SourceLocation PragmaLoc) {
  81. PragmaMsStackAction Action = Sema::PSK_Reset;
  82. unsigned Alignment = 0;
  83. switch (Kind) {
  84. // For all targets we support native and natural are the same.
  85. //
  86. // FIXME: This is not true on Darwin/PPC.
  87. case POAK_Native:
  88. case POAK_Power:
  89. case POAK_Natural:
  90. Action = Sema::PSK_Push_Set;
  91. Alignment = 0;
  92. break;
  93. // Note that '#pragma options align=packed' is not equivalent to attribute
  94. // packed, it has a different precedence relative to attribute aligned.
  95. case POAK_Packed:
  96. Action = Sema::PSK_Push_Set;
  97. Alignment = 1;
  98. break;
  99. case POAK_Mac68k:
  100. // Check if the target supports this.
  101. if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
  102. Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
  103. return;
  104. }
  105. Action = Sema::PSK_Push_Set;
  106. Alignment = Sema::kMac68kAlignmentSentinel;
  107. break;
  108. case POAK_Reset:
  109. // Reset just pops the top of the stack, or resets the current alignment to
  110. // default.
  111. Action = Sema::PSK_Pop;
  112. if (PackStack.Stack.empty()) {
  113. if (PackStack.CurrentValue) {
  114. Action = Sema::PSK_Reset;
  115. } else {
  116. Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
  117. << "stack empty";
  118. return;
  119. }
  120. }
  121. break;
  122. }
  123. PackStack.Act(PragmaLoc, Action, StringRef(), Alignment);
  124. }
  125. void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action,
  126. PragmaClangSectionKind SecKind, StringRef SecName) {
  127. PragmaClangSection *CSec;
  128. switch (SecKind) {
  129. case PragmaClangSectionKind::PCSK_BSS:
  130. CSec = &PragmaClangBSSSection;
  131. break;
  132. case PragmaClangSectionKind::PCSK_Data:
  133. CSec = &PragmaClangDataSection;
  134. break;
  135. case PragmaClangSectionKind::PCSK_Rodata:
  136. CSec = &PragmaClangRodataSection;
  137. break;
  138. case PragmaClangSectionKind::PCSK_Text:
  139. CSec = &PragmaClangTextSection;
  140. break;
  141. default:
  142. llvm_unreachable("invalid clang section kind");
  143. }
  144. if (Action == PragmaClangSectionAction::PCSA_Clear) {
  145. CSec->Valid = false;
  146. return;
  147. }
  148. CSec->Valid = true;
  149. CSec->SectionName = SecName;
  150. CSec->PragmaLocation = PragmaLoc;
  151. }
  152. void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
  153. StringRef SlotLabel, Expr *alignment) {
  154. Expr *Alignment = static_cast<Expr *>(alignment);
  155. // If specified then alignment must be a "small" power of two.
  156. unsigned AlignmentVal = 0;
  157. if (Alignment) {
  158. llvm::APSInt Val;
  159. // pack(0) is like pack(), which just works out since that is what
  160. // we use 0 for in PackAttr.
  161. if (Alignment->isTypeDependent() ||
  162. Alignment->isValueDependent() ||
  163. !Alignment->isIntegerConstantExpr(Val, Context) ||
  164. !(Val == 0 || Val.isPowerOf2()) ||
  165. Val.getZExtValue() > 16) {
  166. Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
  167. return; // Ignore
  168. }
  169. AlignmentVal = (unsigned) Val.getZExtValue();
  170. }
  171. if (Action == Sema::PSK_Show) {
  172. // Show the current alignment, making sure to show the right value
  173. // for the default.
  174. // FIXME: This should come from the target.
  175. AlignmentVal = PackStack.CurrentValue;
  176. if (AlignmentVal == 0)
  177. AlignmentVal = 8;
  178. if (AlignmentVal == Sema::kMac68kAlignmentSentinel)
  179. Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
  180. else
  181. Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
  182. }
  183. // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
  184. // "#pragma pack(pop, identifier, n) is undefined"
  185. if (Action & Sema::PSK_Pop) {
  186. if (Alignment && !SlotLabel.empty())
  187. Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
  188. if (PackStack.Stack.empty())
  189. Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
  190. }
  191. PackStack.Act(PragmaLoc, Action, SlotLabel, AlignmentVal);
  192. }
  193. void Sema::DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
  194. SourceLocation IncludeLoc) {
  195. if (Kind == PragmaPackDiagnoseKind::NonDefaultStateAtInclude) {
  196. SourceLocation PrevLocation = PackStack.CurrentPragmaLocation;
  197. // Warn about non-default alignment at #includes (without redundant
  198. // warnings for the same directive in nested includes).
  199. // The warning is delayed until the end of the file to avoid warnings
  200. // for files that don't have any records that are affected by the modified
  201. // alignment.
  202. bool HasNonDefaultValue =
  203. PackStack.hasValue() &&
  204. (PackIncludeStack.empty() ||
  205. PackIncludeStack.back().CurrentPragmaLocation != PrevLocation);
  206. PackIncludeStack.push_back(
  207. {PackStack.CurrentValue,
  208. PackStack.hasValue() ? PrevLocation : SourceLocation(),
  209. HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
  210. return;
  211. }
  212. assert(Kind == PragmaPackDiagnoseKind::ChangedStateAtExit && "invalid kind");
  213. PackIncludeState PrevPackState = PackIncludeStack.pop_back_val();
  214. if (PrevPackState.ShouldWarnOnInclude) {
  215. // Emit the delayed non-default alignment at #include warning.
  216. Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);
  217. Diag(PrevPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);
  218. }
  219. // Warn about modified alignment after #includes.
  220. if (PrevPackState.CurrentValue != PackStack.CurrentValue) {
  221. Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);
  222. Diag(PackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);
  223. }
  224. }
  225. void Sema::DiagnoseUnterminatedPragmaPack() {
  226. if (PackStack.Stack.empty())
  227. return;
  228. bool IsInnermost = true;
  229. for (const auto &StackSlot : llvm::reverse(PackStack.Stack)) {
  230. Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);
  231. // The user might have already reset the alignment, so suggest replacing
  232. // the reset with a pop.
  233. if (IsInnermost && PackStack.CurrentValue == PackStack.DefaultValue) {
  234. DiagnosticBuilder DB = Diag(PackStack.CurrentPragmaLocation,
  235. diag::note_pragma_pack_pop_instead_reset);
  236. SourceLocation FixItLoc = Lexer::findLocationAfterToken(
  237. PackStack.CurrentPragmaLocation, tok::l_paren, SourceMgr, LangOpts,
  238. /*SkipTrailing=*/false);
  239. if (FixItLoc.isValid())
  240. DB << FixItHint::CreateInsertion(FixItLoc, "pop");
  241. }
  242. IsInnermost = false;
  243. }
  244. }
  245. void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
  246. MSStructPragmaOn = (Kind == PMSST_ON);
  247. }
  248. void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
  249. PragmaMSCommentKind Kind, StringRef Arg) {
  250. auto *PCD = PragmaCommentDecl::Create(
  251. Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
  252. Context.getTranslationUnitDecl()->addDecl(PCD);
  253. Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
  254. }
  255. void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
  256. StringRef Value) {
  257. auto *PDMD = PragmaDetectMismatchDecl::Create(
  258. Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
  259. Context.getTranslationUnitDecl()->addDecl(PDMD);
  260. Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
  261. }
  262. void Sema::ActOnPragmaMSPointersToMembers(
  263. LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
  264. SourceLocation PragmaLoc) {
  265. MSPointerToMemberRepresentationMethod = RepresentationMethod;
  266. ImplicitMSInheritanceAttrLoc = PragmaLoc;
  267. }
  268. void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
  269. SourceLocation PragmaLoc,
  270. MSVtorDispAttr::Mode Mode) {
  271. if (Action & PSK_Pop && VtorDispStack.Stack.empty())
  272. Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
  273. << "stack empty";
  274. VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
  275. }
  276. template<typename ValueType>
  277. void Sema::PragmaStack<ValueType>::Act(SourceLocation PragmaLocation,
  278. PragmaMsStackAction Action,
  279. llvm::StringRef StackSlotLabel,
  280. ValueType Value) {
  281. if (Action == PSK_Reset) {
  282. CurrentValue = DefaultValue;
  283. CurrentPragmaLocation = PragmaLocation;
  284. return;
  285. }
  286. if (Action & PSK_Push)
  287. Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
  288. PragmaLocation);
  289. else if (Action & PSK_Pop) {
  290. if (!StackSlotLabel.empty()) {
  291. // If we've got a label, try to find it and jump there.
  292. auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
  293. return x.StackSlotLabel == StackSlotLabel;
  294. });
  295. // If we found the label so pop from there.
  296. if (I != Stack.rend()) {
  297. CurrentValue = I->Value;
  298. CurrentPragmaLocation = I->PragmaLocation;
  299. Stack.erase(std::prev(I.base()), Stack.end());
  300. }
  301. } else if (!Stack.empty()) {
  302. // We do not have a label, just pop the last entry.
  303. CurrentValue = Stack.back().Value;
  304. CurrentPragmaLocation = Stack.back().PragmaLocation;
  305. Stack.pop_back();
  306. }
  307. }
  308. if (Action & PSK_Set) {
  309. CurrentValue = Value;
  310. CurrentPragmaLocation = PragmaLocation;
  311. }
  312. }
  313. bool Sema::UnifySection(StringRef SectionName,
  314. int SectionFlags,
  315. DeclaratorDecl *Decl) {
  316. auto Section = Context.SectionInfos.find(SectionName);
  317. if (Section == Context.SectionInfos.end()) {
  318. Context.SectionInfos[SectionName] =
  319. ASTContext::SectionInfo(Decl, SourceLocation(), SectionFlags);
  320. return false;
  321. }
  322. // A pre-declared section takes precedence w/o diagnostic.
  323. if (Section->second.SectionFlags == SectionFlags ||
  324. !(Section->second.SectionFlags & ASTContext::PSF_Implicit))
  325. return false;
  326. auto OtherDecl = Section->second.Decl;
  327. Diag(Decl->getLocation(), diag::err_section_conflict)
  328. << Decl << OtherDecl;
  329. Diag(OtherDecl->getLocation(), diag::note_declared_at)
  330. << OtherDecl->getName();
  331. if (auto A = Decl->getAttr<SectionAttr>())
  332. if (A->isImplicit())
  333. Diag(A->getLocation(), diag::note_pragma_entered_here);
  334. if (auto A = OtherDecl->getAttr<SectionAttr>())
  335. if (A->isImplicit())
  336. Diag(A->getLocation(), diag::note_pragma_entered_here);
  337. return true;
  338. }
  339. bool Sema::UnifySection(StringRef SectionName,
  340. int SectionFlags,
  341. SourceLocation PragmaSectionLocation) {
  342. auto Section = Context.SectionInfos.find(SectionName);
  343. if (Section != Context.SectionInfos.end()) {
  344. if (Section->second.SectionFlags == SectionFlags)
  345. return false;
  346. if (!(Section->second.SectionFlags & ASTContext::PSF_Implicit)) {
  347. Diag(PragmaSectionLocation, diag::err_section_conflict)
  348. << "this" << "a prior #pragma section";
  349. Diag(Section->second.PragmaSectionLocation,
  350. diag::note_pragma_entered_here);
  351. return true;
  352. }
  353. }
  354. Context.SectionInfos[SectionName] =
  355. ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
  356. return false;
  357. }
  358. /// Called on well formed \#pragma bss_seg().
  359. void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
  360. PragmaMsStackAction Action,
  361. llvm::StringRef StackSlotLabel,
  362. StringLiteral *SegmentName,
  363. llvm::StringRef PragmaName) {
  364. PragmaStack<StringLiteral *> *Stack =
  365. llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
  366. .Case("data_seg", &DataSegStack)
  367. .Case("bss_seg", &BSSSegStack)
  368. .Case("const_seg", &ConstSegStack)
  369. .Case("code_seg", &CodeSegStack);
  370. if (Action & PSK_Pop && Stack->Stack.empty())
  371. Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
  372. << "stack empty";
  373. if (SegmentName) {
  374. if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
  375. return;
  376. if (SegmentName->getString() == ".drectve" &&
  377. Context.getTargetInfo().getCXXABI().isMicrosoft())
  378. Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
  379. }
  380. Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
  381. }
  382. /// Called on well formed \#pragma bss_seg().
  383. void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
  384. int SectionFlags, StringLiteral *SegmentName) {
  385. UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
  386. }
  387. void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
  388. StringLiteral *SegmentName) {
  389. // There's no stack to maintain, so we just have a current section. When we
  390. // see the default section, reset our current section back to null so we stop
  391. // tacking on unnecessary attributes.
  392. CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
  393. CurInitSegLoc = PragmaLocation;
  394. }
  395. void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
  396. SourceLocation PragmaLoc) {
  397. IdentifierInfo *Name = IdTok.getIdentifierInfo();
  398. LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
  399. LookupParsedName(Lookup, curScope, nullptr, true);
  400. if (Lookup.empty()) {
  401. Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
  402. << Name << SourceRange(IdTok.getLocation());
  403. return;
  404. }
  405. VarDecl *VD = Lookup.getAsSingle<VarDecl>();
  406. if (!VD) {
  407. Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
  408. << Name << SourceRange(IdTok.getLocation());
  409. return;
  410. }
  411. // Warn if this was used before being marked unused.
  412. if (VD->isUsed())
  413. Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
  414. VD->addAttr(UnusedAttr::CreateImplicit(Context, UnusedAttr::GNU_unused,
  415. IdTok.getLocation()));
  416. }
  417. void Sema::AddCFAuditedAttribute(Decl *D) {
  418. SourceLocation Loc = PP.getPragmaARCCFCodeAuditedLoc();
  419. if (!Loc.isValid()) return;
  420. // Don't add a redundant or conflicting attribute.
  421. if (D->hasAttr<CFAuditedTransferAttr>() ||
  422. D->hasAttr<CFUnknownTransferAttr>())
  423. return;
  424. D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Loc));
  425. }
  426. namespace {
  427. Optional<attr::SubjectMatchRule>
  428. getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
  429. using namespace attr;
  430. switch (Rule) {
  431. default:
  432. return None;
  433. #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
  434. #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
  435. case Value: \
  436. return Parent;
  437. #include "clang/Basic/AttrSubMatchRulesList.inc"
  438. }
  439. }
  440. bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
  441. using namespace attr;
  442. switch (Rule) {
  443. default:
  444. return false;
  445. #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
  446. #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
  447. case Value: \
  448. return IsNegated;
  449. #include "clang/Basic/AttrSubMatchRulesList.inc"
  450. }
  451. }
  452. CharSourceRange replacementRangeForListElement(const Sema &S,
  453. SourceRange Range) {
  454. // Make sure that the ',' is removed as well.
  455. SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
  456. Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
  457. /*SkipTrailingWhitespaceAndNewLine=*/false);
  458. if (AfterCommaLoc.isValid())
  459. return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
  460. else
  461. return CharSourceRange::getTokenRange(Range);
  462. }
  463. std::string
  464. attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
  465. std::string Result;
  466. llvm::raw_string_ostream OS(Result);
  467. for (const auto &I : llvm::enumerate(Rules)) {
  468. if (I.index())
  469. OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");
  470. OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
  471. }
  472. return OS.str();
  473. }
  474. } // end anonymous namespace
  475. void Sema::ActOnPragmaAttributeAttribute(
  476. ParsedAttr &Attribute, SourceLocation PragmaLoc,
  477. attr::ParsedSubjectMatchRuleSet Rules) {
  478. Attribute.setIsPragmaClangAttribute();
  479. SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;
  480. // Gather the subject match rules that are supported by the attribute.
  481. SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>
  482. StrictSubjectMatchRuleSet;
  483. Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);
  484. // Figure out which subject matching rules are valid.
  485. if (StrictSubjectMatchRuleSet.empty()) {
  486. // Check for contradicting match rules. Contradicting match rules are
  487. // either:
  488. // - a top-level rule and one of its sub-rules. E.g. variable and
  489. // variable(is_parameter).
  490. // - a sub-rule and a sibling that's negated. E.g.
  491. // variable(is_thread_local) and variable(unless(is_parameter))
  492. llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
  493. RulesToFirstSpecifiedNegatedSubRule;
  494. for (const auto &Rule : Rules) {
  495. attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
  496. Optional<attr::SubjectMatchRule> ParentRule =
  497. getParentAttrMatcherRule(MatchRule);
  498. if (!ParentRule)
  499. continue;
  500. auto It = Rules.find(*ParentRule);
  501. if (It != Rules.end()) {
  502. // A sub-rule contradicts a parent rule.
  503. Diag(Rule.second.getBegin(),
  504. diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
  505. << attr::getSubjectMatchRuleSpelling(MatchRule)
  506. << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
  507. << FixItHint::CreateRemoval(
  508. replacementRangeForListElement(*this, Rule.second));
  509. // Keep going without removing this rule as it won't change the set of
  510. // declarations that receive the attribute.
  511. continue;
  512. }
  513. if (isNegatedAttrMatcherSubRule(MatchRule))
  514. RulesToFirstSpecifiedNegatedSubRule.insert(
  515. std::make_pair(*ParentRule, Rule));
  516. }
  517. bool IgnoreNegatedSubRules = false;
  518. for (const auto &Rule : Rules) {
  519. attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
  520. Optional<attr::SubjectMatchRule> ParentRule =
  521. getParentAttrMatcherRule(MatchRule);
  522. if (!ParentRule)
  523. continue;
  524. auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
  525. if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
  526. It->second != Rule) {
  527. // Negated sub-rule contradicts another sub-rule.
  528. Diag(
  529. It->second.second.getBegin(),
  530. diag::
  531. err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
  532. << attr::getSubjectMatchRuleSpelling(
  533. attr::SubjectMatchRule(It->second.first))
  534. << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
  535. << FixItHint::CreateRemoval(
  536. replacementRangeForListElement(*this, It->second.second));
  537. // Keep going but ignore all of the negated sub-rules.
  538. IgnoreNegatedSubRules = true;
  539. RulesToFirstSpecifiedNegatedSubRule.erase(It);
  540. }
  541. }
  542. if (!IgnoreNegatedSubRules) {
  543. for (const auto &Rule : Rules)
  544. SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
  545. } else {
  546. for (const auto &Rule : Rules) {
  547. if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
  548. SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
  549. }
  550. }
  551. Rules.clear();
  552. } else {
  553. for (const auto &Rule : StrictSubjectMatchRuleSet) {
  554. if (Rules.erase(Rule.first)) {
  555. // Add the rule to the set of attribute receivers only if it's supported
  556. // in the current language mode.
  557. if (Rule.second)
  558. SubjectMatchRules.push_back(Rule.first);
  559. }
  560. }
  561. }
  562. if (!Rules.empty()) {
  563. auto Diagnostic =
  564. Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
  565. << Attribute.getName();
  566. SmallVector<attr::SubjectMatchRule, 2> ExtraRules;
  567. for (const auto &Rule : Rules) {
  568. ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
  569. Diagnostic << FixItHint::CreateRemoval(
  570. replacementRangeForListElement(*this, Rule.second));
  571. }
  572. Diagnostic << attrMatcherRuleListToString(ExtraRules);
  573. }
  574. if (PragmaAttributeStack.empty()) {
  575. Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
  576. return;
  577. }
  578. PragmaAttributeStack.back().Entries.push_back(
  579. {PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});
  580. }
  581. void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
  582. const IdentifierInfo *Namespace) {
  583. PragmaAttributeStack.emplace_back();
  584. PragmaAttributeStack.back().Loc = PragmaLoc;
  585. PragmaAttributeStack.back().Namespace = Namespace;
  586. }
  587. void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,
  588. const IdentifierInfo *Namespace) {
  589. if (PragmaAttributeStack.empty()) {
  590. Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
  591. return;
  592. }
  593. // Dig back through the stack trying to find the most recently pushed group
  594. // that in Namespace. Note that this works fine if no namespace is present,
  595. // think of push/pops without namespaces as having an implicit "nullptr"
  596. // namespace.
  597. for (size_t Index = PragmaAttributeStack.size(); Index;) {
  598. --Index;
  599. if (PragmaAttributeStack[Index].Namespace == Namespace) {
  600. for (const PragmaAttributeEntry &Entry :
  601. PragmaAttributeStack[Index].Entries) {
  602. if (!Entry.IsUsed) {
  603. assert(Entry.Attribute && "Expected an attribute");
  604. Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
  605. << *Entry.Attribute;
  606. Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
  607. }
  608. }
  609. PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);
  610. return;
  611. }
  612. }
  613. if (Namespace)
  614. Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
  615. << 0 << Namespace->getName();
  616. else
  617. Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
  618. }
  619. void Sema::AddPragmaAttributes(Scope *S, Decl *D) {
  620. if (PragmaAttributeStack.empty())
  621. return;
  622. for (auto &Group : PragmaAttributeStack) {
  623. for (auto &Entry : Group.Entries) {
  624. ParsedAttr *Attribute = Entry.Attribute;
  625. assert(Attribute && "Expected an attribute");
  626. assert(Attribute->isPragmaClangAttribute() &&
  627. "expected #pragma clang attribute");
  628. // Ensure that the attribute can be applied to the given declaration.
  629. bool Applies = false;
  630. for (const auto &Rule : Entry.MatchRules) {
  631. if (Attribute->appliesToDecl(D, Rule)) {
  632. Applies = true;
  633. break;
  634. }
  635. }
  636. if (!Applies)
  637. continue;
  638. Entry.IsUsed = true;
  639. PragmaAttributeCurrentTargetDecl = D;
  640. ParsedAttributesView Attrs;
  641. Attrs.addAtEnd(Attribute);
  642. ProcessDeclAttributeList(S, D, Attrs);
  643. PragmaAttributeCurrentTargetDecl = nullptr;
  644. }
  645. }
  646. }
  647. void Sema::PrintPragmaAttributeInstantiationPoint() {
  648. assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
  649. Diags.Report(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
  650. diag::note_pragma_attribute_applied_decl_here);
  651. }
  652. void Sema::DiagnoseUnterminatedPragmaAttribute() {
  653. if (PragmaAttributeStack.empty())
  654. return;
  655. Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
  656. }
  657. void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
  658. if(On)
  659. OptimizeOffPragmaLocation = SourceLocation();
  660. else
  661. OptimizeOffPragmaLocation = PragmaLoc;
  662. }
  663. void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
  664. // In the future, check other pragmas if they're implemented (e.g. pragma
  665. // optimize 0 will probably map to this functionality too).
  666. if(OptimizeOffPragmaLocation.isValid())
  667. AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
  668. }
  669. void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
  670. SourceLocation Loc) {
  671. // Don't add a conflicting attribute. No diagnostic is needed.
  672. if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
  673. return;
  674. // Add attributes only if required. Optnone requires noinline as well, but if
  675. // either is already present then don't bother adding them.
  676. if (!FD->hasAttr<OptimizeNoneAttr>())
  677. FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
  678. if (!FD->hasAttr<NoInlineAttr>())
  679. FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
  680. }
  681. typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
  682. enum : unsigned { NoVisibility = ~0U };
  683. void Sema::AddPushedVisibilityAttribute(Decl *D) {
  684. if (!VisContext)
  685. return;
  686. NamedDecl *ND = dyn_cast<NamedDecl>(D);
  687. if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
  688. return;
  689. VisStack *Stack = static_cast<VisStack*>(VisContext);
  690. unsigned rawType = Stack->back().first;
  691. if (rawType == NoVisibility) return;
  692. VisibilityAttr::VisibilityType type
  693. = (VisibilityAttr::VisibilityType) rawType;
  694. SourceLocation loc = Stack->back().second;
  695. D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
  696. }
  697. /// FreeVisContext - Deallocate and null out VisContext.
  698. void Sema::FreeVisContext() {
  699. delete static_cast<VisStack*>(VisContext);
  700. VisContext = nullptr;
  701. }
  702. static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
  703. // Put visibility on stack.
  704. if (!S.VisContext)
  705. S.VisContext = new VisStack;
  706. VisStack *Stack = static_cast<VisStack*>(S.VisContext);
  707. Stack->push_back(std::make_pair(type, loc));
  708. }
  709. void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
  710. SourceLocation PragmaLoc) {
  711. if (VisType) {
  712. // Compute visibility to use.
  713. VisibilityAttr::VisibilityType T;
  714. if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
  715. Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
  716. return;
  717. }
  718. PushPragmaVisibility(*this, T, PragmaLoc);
  719. } else {
  720. PopPragmaVisibility(false, PragmaLoc);
  721. }
  722. }
  723. void Sema::ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC) {
  724. switch (FPC) {
  725. case LangOptions::FPC_On:
  726. FPFeatures.setAllowFPContractWithinStatement();
  727. break;
  728. case LangOptions::FPC_Fast:
  729. FPFeatures.setAllowFPContractAcrossStatement();
  730. break;
  731. case LangOptions::FPC_Off:
  732. FPFeatures.setDisallowFPContract();
  733. break;
  734. }
  735. }
  736. void Sema::ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC) {
  737. switch (FPC) {
  738. case LangOptions::FEA_On:
  739. FPFeatures.setAllowFEnvAccess();
  740. break;
  741. case LangOptions::FEA_Off:
  742. FPFeatures.setDisallowFEnvAccess();
  743. break;
  744. }
  745. }
  746. void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
  747. SourceLocation Loc) {
  748. // Visibility calculations will consider the namespace's visibility.
  749. // Here we just want to note that we're in a visibility context
  750. // which overrides any enclosing #pragma context, but doesn't itself
  751. // contribute visibility.
  752. PushPragmaVisibility(*this, NoVisibility, Loc);
  753. }
  754. void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
  755. if (!VisContext) {
  756. Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
  757. return;
  758. }
  759. // Pop visibility from stack
  760. VisStack *Stack = static_cast<VisStack*>(VisContext);
  761. const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
  762. bool StartsWithPragma = Back->first != NoVisibility;
  763. if (StartsWithPragma && IsNamespaceEnd) {
  764. Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
  765. Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
  766. // For better error recovery, eat all pushes inside the namespace.
  767. do {
  768. Stack->pop_back();
  769. Back = &Stack->back();
  770. StartsWithPragma = Back->first != NoVisibility;
  771. } while (StartsWithPragma);
  772. } else if (!StartsWithPragma && !IsNamespaceEnd) {
  773. Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
  774. Diag(Back->second, diag::note_surrounding_namespace_starts_here);
  775. return;
  776. }
  777. Stack->pop_back();
  778. // To simplify the implementation, never keep around an empty stack.
  779. if (Stack->empty())
  780. FreeVisContext();
  781. }