SemaAttr.cpp 35 KB

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