SemaAttr.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  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. AlignPackInfo InfoVal = AlignPackStack.CurrentValue;
  47. AlignPackInfo::Mode M = InfoVal.getAlignMode();
  48. bool IsPackSet = InfoVal.IsPackSet();
  49. bool IsXLPragma = getLangOpts().XLPragmaPack;
  50. // If we are not under mac68k/natural alignment mode and also there is no pack
  51. // value, we don't need any attributes.
  52. if (!IsPackSet && M != AlignPackInfo::Mac68k && M != AlignPackInfo::Natural)
  53. return;
  54. if (M == AlignPackInfo::Mac68k && (IsXLPragma || InfoVal.IsAlignAttr())) {
  55. RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
  56. } else if (IsPackSet) {
  57. // Check to see if we need a max field alignment attribute.
  58. RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(
  59. Context, InfoVal.getPackNumber() * 8));
  60. }
  61. if (IsXLPragma && M == AlignPackInfo::Natural)
  62. RD->addAttr(AlignNaturalAttr::CreateImplicit(Context));
  63. if (AlignPackIncludeStack.empty())
  64. return;
  65. // The #pragma align/pack affected a record in an included file, so Clang
  66. // should warn when that pragma was written in a file that included the
  67. // included file.
  68. for (auto &AlignPackedInclude : llvm::reverse(AlignPackIncludeStack)) {
  69. if (AlignPackedInclude.CurrentPragmaLocation !=
  70. AlignPackStack.CurrentPragmaLocation)
  71. break;
  72. if (AlignPackedInclude.HasNonDefaultValue)
  73. AlignPackedInclude.ShouldWarnOnInclude = true;
  74. }
  75. }
  76. void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
  77. if (MSStructPragmaOn)
  78. RD->addAttr(MSStructAttr::CreateImplicit(Context));
  79. // FIXME: We should merge AddAlignmentAttributesForRecord with
  80. // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
  81. // all active pragmas and applies them as attributes to class definitions.
  82. if (VtorDispStack.CurrentValue != getLangOpts().getVtorDispMode())
  83. RD->addAttr(MSVtorDispAttr::CreateImplicit(
  84. Context, unsigned(VtorDispStack.CurrentValue)));
  85. }
  86. template <typename Attribute>
  87. static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
  88. CXXRecordDecl *Record) {
  89. if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
  90. return;
  91. for (Decl *Redecl : Record->redecls())
  92. Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
  93. }
  94. void Sema::inferGslPointerAttribute(NamedDecl *ND,
  95. CXXRecordDecl *UnderlyingRecord) {
  96. if (!UnderlyingRecord)
  97. return;
  98. const auto *Parent = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
  99. if (!Parent)
  100. return;
  101. static llvm::StringSet<> Containers{
  102. "array",
  103. "basic_string",
  104. "deque",
  105. "forward_list",
  106. "vector",
  107. "list",
  108. "map",
  109. "multiset",
  110. "multimap",
  111. "priority_queue",
  112. "queue",
  113. "set",
  114. "stack",
  115. "unordered_set",
  116. "unordered_map",
  117. "unordered_multiset",
  118. "unordered_multimap",
  119. };
  120. static llvm::StringSet<> Iterators{"iterator", "const_iterator",
  121. "reverse_iterator",
  122. "const_reverse_iterator"};
  123. if (Parent->isInStdNamespace() && Iterators.count(ND->getName()) &&
  124. Containers.count(Parent->getName()))
  125. addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context,
  126. UnderlyingRecord);
  127. }
  128. void Sema::inferGslPointerAttribute(TypedefNameDecl *TD) {
  129. QualType Canonical = TD->getUnderlyingType().getCanonicalType();
  130. CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();
  131. if (!RD) {
  132. if (auto *TST =
  133. dyn_cast<TemplateSpecializationType>(Canonical.getTypePtr())) {
  134. RD = dyn_cast_or_null<CXXRecordDecl>(
  135. TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl());
  136. }
  137. }
  138. inferGslPointerAttribute(TD, RD);
  139. }
  140. void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {
  141. static llvm::StringSet<> StdOwners{
  142. "any",
  143. "array",
  144. "basic_regex",
  145. "basic_string",
  146. "deque",
  147. "forward_list",
  148. "vector",
  149. "list",
  150. "map",
  151. "multiset",
  152. "multimap",
  153. "optional",
  154. "priority_queue",
  155. "queue",
  156. "set",
  157. "stack",
  158. "unique_ptr",
  159. "unordered_set",
  160. "unordered_map",
  161. "unordered_multiset",
  162. "unordered_multimap",
  163. "variant",
  164. };
  165. static llvm::StringSet<> StdPointers{
  166. "basic_string_view",
  167. "reference_wrapper",
  168. "regex_iterator",
  169. };
  170. if (!Record->getIdentifier())
  171. return;
  172. // Handle classes that directly appear in std namespace.
  173. if (Record->isInStdNamespace()) {
  174. if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
  175. return;
  176. if (StdOwners.count(Record->getName()))
  177. addGslOwnerPointerAttributeIfNotExisting<OwnerAttr>(Context, Record);
  178. else if (StdPointers.count(Record->getName()))
  179. addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context, Record);
  180. return;
  181. }
  182. // Handle nested classes that could be a gsl::Pointer.
  183. inferGslPointerAttribute(Record, Record);
  184. }
  185. void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
  186. SourceLocation PragmaLoc) {
  187. PragmaMsStackAction Action = Sema::PSK_Reset;
  188. AlignPackInfo::Mode ModeVal = AlignPackInfo::Native;
  189. switch (Kind) {
  190. // For most of the platforms we support, native and natural are the same.
  191. // With XL, native is the same as power, natural means something else.
  192. //
  193. // FIXME: This is not true on Darwin/PPC.
  194. case POAK_Native:
  195. case POAK_Power:
  196. Action = Sema::PSK_Push_Set;
  197. break;
  198. case POAK_Natural:
  199. Action = Sema::PSK_Push_Set;
  200. ModeVal = AlignPackInfo::Natural;
  201. break;
  202. // Note that '#pragma options align=packed' is not equivalent to attribute
  203. // packed, it has a different precedence relative to attribute aligned.
  204. case POAK_Packed:
  205. Action = Sema::PSK_Push_Set;
  206. ModeVal = AlignPackInfo::Packed;
  207. break;
  208. case POAK_Mac68k:
  209. // Check if the target supports this.
  210. if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
  211. Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
  212. return;
  213. }
  214. Action = Sema::PSK_Push_Set;
  215. ModeVal = AlignPackInfo::Mac68k;
  216. break;
  217. case POAK_Reset:
  218. // Reset just pops the top of the stack, or resets the current alignment to
  219. // default.
  220. Action = Sema::PSK_Pop;
  221. if (AlignPackStack.Stack.empty()) {
  222. if (AlignPackStack.CurrentValue.getAlignMode() != AlignPackInfo::Native ||
  223. AlignPackStack.CurrentValue.IsPackAttr()) {
  224. Action = Sema::PSK_Reset;
  225. } else {
  226. Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
  227. << "stack empty";
  228. return;
  229. }
  230. }
  231. break;
  232. }
  233. AlignPackInfo Info(ModeVal, getLangOpts().XLPragmaPack);
  234. AlignPackStack.Act(PragmaLoc, Action, StringRef(), Info);
  235. }
  236. void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc,
  237. PragmaClangSectionAction Action,
  238. PragmaClangSectionKind SecKind,
  239. StringRef SecName) {
  240. PragmaClangSection *CSec;
  241. int SectionFlags = ASTContext::PSF_Read;
  242. switch (SecKind) {
  243. case PragmaClangSectionKind::PCSK_BSS:
  244. CSec = &PragmaClangBSSSection;
  245. SectionFlags |= ASTContext::PSF_Write | ASTContext::PSF_ZeroInit;
  246. break;
  247. case PragmaClangSectionKind::PCSK_Data:
  248. CSec = &PragmaClangDataSection;
  249. SectionFlags |= ASTContext::PSF_Write;
  250. break;
  251. case PragmaClangSectionKind::PCSK_Rodata:
  252. CSec = &PragmaClangRodataSection;
  253. break;
  254. case PragmaClangSectionKind::PCSK_Relro:
  255. CSec = &PragmaClangRelroSection;
  256. break;
  257. case PragmaClangSectionKind::PCSK_Text:
  258. CSec = &PragmaClangTextSection;
  259. SectionFlags |= ASTContext::PSF_Execute;
  260. break;
  261. default:
  262. llvm_unreachable("invalid clang section kind");
  263. }
  264. if (Action == PragmaClangSectionAction::PCSA_Clear) {
  265. CSec->Valid = false;
  266. return;
  267. }
  268. if (llvm::Error E = isValidSectionSpecifier(SecName)) {
  269. Diag(PragmaLoc, diag::err_pragma_section_invalid_for_target)
  270. << toString(std::move(E));
  271. CSec->Valid = false;
  272. return;
  273. }
  274. if (UnifySection(SecName, SectionFlags, PragmaLoc))
  275. return;
  276. CSec->Valid = true;
  277. CSec->SectionName = std::string(SecName);
  278. CSec->PragmaLocation = PragmaLoc;
  279. }
  280. void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
  281. StringRef SlotLabel, Expr *alignment) {
  282. bool IsXLPragma = getLangOpts().XLPragmaPack;
  283. // XL pragma pack does not support identifier syntax.
  284. if (IsXLPragma && !SlotLabel.empty()) {
  285. Diag(PragmaLoc, diag::err_pragma_pack_identifer_not_supported);
  286. return;
  287. }
  288. const AlignPackInfo CurVal = AlignPackStack.CurrentValue;
  289. Expr *Alignment = static_cast<Expr *>(alignment);
  290. // If specified then alignment must be a "small" power of two.
  291. unsigned AlignmentVal = 0;
  292. AlignPackInfo::Mode ModeVal = CurVal.getAlignMode();
  293. if (Alignment) {
  294. Optional<llvm::APSInt> Val;
  295. Val = Alignment->getIntegerConstantExpr(Context);
  296. // pack(0) is like pack(), which just works out since that is what
  297. // we use 0 for in PackAttr.
  298. if (Alignment->isTypeDependent() || !Val ||
  299. !(*Val == 0 || Val->isPowerOf2()) || Val->getZExtValue() > 16) {
  300. Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
  301. return; // Ignore
  302. }
  303. if (IsXLPragma && *Val == 0) {
  304. // pack(0) does not work out with XL.
  305. Diag(PragmaLoc, diag::err_pragma_pack_invalid_alignment);
  306. return; // Ignore
  307. }
  308. AlignmentVal = (unsigned)Val->getZExtValue();
  309. }
  310. if (Action == Sema::PSK_Show) {
  311. // Show the current alignment, making sure to show the right value
  312. // for the default.
  313. // FIXME: This should come from the target.
  314. AlignmentVal = CurVal.IsPackSet() ? CurVal.getPackNumber() : 8;
  315. if (ModeVal == AlignPackInfo::Mac68k &&
  316. (IsXLPragma || CurVal.IsAlignAttr()))
  317. Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
  318. else
  319. Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
  320. }
  321. // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
  322. // "#pragma pack(pop, identifier, n) is undefined"
  323. if (Action & Sema::PSK_Pop) {
  324. if (Alignment && !SlotLabel.empty())
  325. Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
  326. if (AlignPackStack.Stack.empty()) {
  327. assert(CurVal.getAlignMode() == AlignPackInfo::Native &&
  328. "Empty pack stack can only be at Native alignment mode.");
  329. Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
  330. }
  331. }
  332. AlignPackInfo Info(ModeVal, AlignmentVal, IsXLPragma);
  333. AlignPackStack.Act(PragmaLoc, Action, SlotLabel, Info);
  334. }
  335. void Sema::DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
  336. SourceLocation IncludeLoc) {
  337. if (Kind == PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude) {
  338. SourceLocation PrevLocation = AlignPackStack.CurrentPragmaLocation;
  339. // Warn about non-default alignment at #includes (without redundant
  340. // warnings for the same directive in nested includes).
  341. // The warning is delayed until the end of the file to avoid warnings
  342. // for files that don't have any records that are affected by the modified
  343. // alignment.
  344. bool HasNonDefaultValue =
  345. AlignPackStack.hasValue() &&
  346. (AlignPackIncludeStack.empty() ||
  347. AlignPackIncludeStack.back().CurrentPragmaLocation != PrevLocation);
  348. AlignPackIncludeStack.push_back(
  349. {AlignPackStack.CurrentValue,
  350. AlignPackStack.hasValue() ? PrevLocation : SourceLocation(),
  351. HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
  352. return;
  353. }
  354. assert(Kind == PragmaAlignPackDiagnoseKind::ChangedStateAtExit &&
  355. "invalid kind");
  356. AlignPackIncludeState PrevAlignPackState =
  357. AlignPackIncludeStack.pop_back_val();
  358. // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
  359. // information, diagnostics below might not be accurate if we have mixed
  360. // pragmas.
  361. if (PrevAlignPackState.ShouldWarnOnInclude) {
  362. // Emit the delayed non-default alignment at #include warning.
  363. Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);
  364. Diag(PrevAlignPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);
  365. }
  366. // Warn about modified alignment after #includes.
  367. if (PrevAlignPackState.CurrentValue != AlignPackStack.CurrentValue) {
  368. Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);
  369. Diag(AlignPackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);
  370. }
  371. }
  372. void Sema::DiagnoseUnterminatedPragmaAlignPack() {
  373. if (AlignPackStack.Stack.empty())
  374. return;
  375. bool IsInnermost = true;
  376. // FIXME: AlignPackStack may contain both #pragma align and #pragma pack
  377. // information, diagnostics below might not be accurate if we have mixed
  378. // pragmas.
  379. for (const auto &StackSlot : llvm::reverse(AlignPackStack.Stack)) {
  380. Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);
  381. // The user might have already reset the alignment, so suggest replacing
  382. // the reset with a pop.
  383. if (IsInnermost &&
  384. AlignPackStack.CurrentValue == AlignPackStack.DefaultValue) {
  385. auto DB = Diag(AlignPackStack.CurrentPragmaLocation,
  386. diag::note_pragma_pack_pop_instead_reset);
  387. SourceLocation FixItLoc =
  388. Lexer::findLocationAfterToken(AlignPackStack.CurrentPragmaLocation,
  389. tok::l_paren, SourceMgr, LangOpts,
  390. /*SkipTrailing=*/false);
  391. if (FixItLoc.isValid())
  392. DB << FixItHint::CreateInsertion(FixItLoc, "pop");
  393. }
  394. IsInnermost = false;
  395. }
  396. }
  397. void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
  398. MSStructPragmaOn = (Kind == PMSST_ON);
  399. }
  400. void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
  401. PragmaMSCommentKind Kind, StringRef Arg) {
  402. auto *PCD = PragmaCommentDecl::Create(
  403. Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
  404. Context.getTranslationUnitDecl()->addDecl(PCD);
  405. Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
  406. }
  407. void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
  408. StringRef Value) {
  409. auto *PDMD = PragmaDetectMismatchDecl::Create(
  410. Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
  411. Context.getTranslationUnitDecl()->addDecl(PDMD);
  412. Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
  413. }
  414. void Sema::ActOnPragmaFloatControl(SourceLocation Loc,
  415. PragmaMsStackAction Action,
  416. PragmaFloatControlKind Value) {
  417. FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
  418. if ((Action == PSK_Push_Set || Action == PSK_Push || Action == PSK_Pop) &&
  419. !CurContext->getRedeclContext()->isFileContext()) {
  420. // Push and pop can only occur at file or namespace scope, or within a
  421. // language linkage declaration.
  422. Diag(Loc, diag::err_pragma_fc_pp_scope);
  423. return;
  424. }
  425. switch (Value) {
  426. default:
  427. llvm_unreachable("invalid pragma float_control kind");
  428. case PFC_Precise:
  429. NewFPFeatures.setFPPreciseEnabled(true);
  430. FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
  431. break;
  432. case PFC_NoPrecise:
  433. if (CurFPFeatures.getFPExceptionMode() == LangOptions::FPE_Strict)
  434. Diag(Loc, diag::err_pragma_fc_noprecise_requires_noexcept);
  435. else if (CurFPFeatures.getAllowFEnvAccess())
  436. Diag(Loc, diag::err_pragma_fc_noprecise_requires_nofenv);
  437. else
  438. NewFPFeatures.setFPPreciseEnabled(false);
  439. FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
  440. break;
  441. case PFC_Except:
  442. if (!isPreciseFPEnabled())
  443. Diag(Loc, diag::err_pragma_fc_except_requires_precise);
  444. else
  445. NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Strict);
  446. FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
  447. break;
  448. case PFC_NoExcept:
  449. NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Ignore);
  450. FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
  451. break;
  452. case PFC_Push:
  453. FpPragmaStack.Act(Loc, Sema::PSK_Push_Set, StringRef(), NewFPFeatures);
  454. break;
  455. case PFC_Pop:
  456. if (FpPragmaStack.Stack.empty()) {
  457. Diag(Loc, diag::warn_pragma_pop_failed) << "float_control"
  458. << "stack empty";
  459. return;
  460. }
  461. FpPragmaStack.Act(Loc, Action, StringRef(), NewFPFeatures);
  462. NewFPFeatures = FpPragmaStack.CurrentValue;
  463. break;
  464. }
  465. CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
  466. }
  467. void Sema::ActOnPragmaMSPointersToMembers(
  468. LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
  469. SourceLocation PragmaLoc) {
  470. MSPointerToMemberRepresentationMethod = RepresentationMethod;
  471. ImplicitMSInheritanceAttrLoc = PragmaLoc;
  472. }
  473. void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
  474. SourceLocation PragmaLoc,
  475. MSVtorDispMode Mode) {
  476. if (Action & PSK_Pop && VtorDispStack.Stack.empty())
  477. Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
  478. << "stack empty";
  479. VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
  480. }
  481. template <>
  482. void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
  483. PragmaMsStackAction Action,
  484. llvm::StringRef StackSlotLabel,
  485. AlignPackInfo Value) {
  486. if (Action == PSK_Reset) {
  487. CurrentValue = DefaultValue;
  488. CurrentPragmaLocation = PragmaLocation;
  489. return;
  490. }
  491. if (Action & PSK_Push)
  492. Stack.emplace_back(Slot(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
  493. PragmaLocation));
  494. else if (Action & PSK_Pop) {
  495. if (!StackSlotLabel.empty()) {
  496. // If we've got a label, try to find it and jump there.
  497. auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
  498. return x.StackSlotLabel == StackSlotLabel;
  499. });
  500. // We found the label, so pop from there.
  501. if (I != Stack.rend()) {
  502. CurrentValue = I->Value;
  503. CurrentPragmaLocation = I->PragmaLocation;
  504. Stack.erase(std::prev(I.base()), Stack.end());
  505. }
  506. } else if (Value.IsXLStack() && Value.IsAlignAttr() &&
  507. CurrentValue.IsPackAttr()) {
  508. // XL '#pragma align(reset)' would pop the stack until
  509. // a current in effect pragma align is popped.
  510. auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
  511. return x.Value.IsAlignAttr();
  512. });
  513. // If we found pragma align so pop from there.
  514. if (I != Stack.rend()) {
  515. Stack.erase(std::prev(I.base()), Stack.end());
  516. if (Stack.empty()) {
  517. CurrentValue = DefaultValue;
  518. CurrentPragmaLocation = PragmaLocation;
  519. } else {
  520. CurrentValue = Stack.back().Value;
  521. CurrentPragmaLocation = Stack.back().PragmaLocation;
  522. Stack.pop_back();
  523. }
  524. }
  525. } else if (!Stack.empty()) {
  526. // xl '#pragma align' sets the baseline, and `#pragma pack` cannot pop
  527. // over the baseline.
  528. if (Value.IsXLStack() && Value.IsPackAttr() && CurrentValue.IsAlignAttr())
  529. return;
  530. // We don't have a label, just pop the last entry.
  531. CurrentValue = Stack.back().Value;
  532. CurrentPragmaLocation = Stack.back().PragmaLocation;
  533. Stack.pop_back();
  534. }
  535. }
  536. if (Action & PSK_Set) {
  537. CurrentValue = Value;
  538. CurrentPragmaLocation = PragmaLocation;
  539. }
  540. }
  541. bool Sema::UnifySection(StringRef SectionName, int SectionFlags,
  542. NamedDecl *Decl) {
  543. SourceLocation PragmaLocation;
  544. if (auto A = Decl->getAttr<SectionAttr>())
  545. if (A->isImplicit())
  546. PragmaLocation = A->getLocation();
  547. auto SectionIt = Context.SectionInfos.find(SectionName);
  548. if (SectionIt == Context.SectionInfos.end()) {
  549. Context.SectionInfos[SectionName] =
  550. ASTContext::SectionInfo(Decl, PragmaLocation, SectionFlags);
  551. return false;
  552. }
  553. // A pre-declared section takes precedence w/o diagnostic.
  554. const auto &Section = SectionIt->second;
  555. if (Section.SectionFlags == SectionFlags ||
  556. ((SectionFlags & ASTContext::PSF_Implicit) &&
  557. !(Section.SectionFlags & ASTContext::PSF_Implicit)))
  558. return false;
  559. Diag(Decl->getLocation(), diag::err_section_conflict) << Decl << Section;
  560. if (Section.Decl)
  561. Diag(Section.Decl->getLocation(), diag::note_declared_at)
  562. << Section.Decl->getName();
  563. if (PragmaLocation.isValid())
  564. Diag(PragmaLocation, diag::note_pragma_entered_here);
  565. if (Section.PragmaSectionLocation.isValid())
  566. Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
  567. return true;
  568. }
  569. bool Sema::UnifySection(StringRef SectionName,
  570. int SectionFlags,
  571. SourceLocation PragmaSectionLocation) {
  572. auto SectionIt = Context.SectionInfos.find(SectionName);
  573. if (SectionIt != Context.SectionInfos.end()) {
  574. const auto &Section = SectionIt->second;
  575. if (Section.SectionFlags == SectionFlags)
  576. return false;
  577. if (!(Section.SectionFlags & ASTContext::PSF_Implicit)) {
  578. Diag(PragmaSectionLocation, diag::err_section_conflict)
  579. << "this" << Section;
  580. if (Section.Decl)
  581. Diag(Section.Decl->getLocation(), diag::note_declared_at)
  582. << Section.Decl->getName();
  583. if (Section.PragmaSectionLocation.isValid())
  584. Diag(Section.PragmaSectionLocation, diag::note_pragma_entered_here);
  585. return true;
  586. }
  587. }
  588. Context.SectionInfos[SectionName] =
  589. ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
  590. return false;
  591. }
  592. /// Called on well formed \#pragma bss_seg().
  593. void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
  594. PragmaMsStackAction Action,
  595. llvm::StringRef StackSlotLabel,
  596. StringLiteral *SegmentName,
  597. llvm::StringRef PragmaName) {
  598. PragmaStack<StringLiteral *> *Stack =
  599. llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
  600. .Case("data_seg", &DataSegStack)
  601. .Case("bss_seg", &BSSSegStack)
  602. .Case("const_seg", &ConstSegStack)
  603. .Case("code_seg", &CodeSegStack);
  604. if (Action & PSK_Pop && Stack->Stack.empty())
  605. Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
  606. << "stack empty";
  607. if (SegmentName) {
  608. if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
  609. return;
  610. if (SegmentName->getString() == ".drectve" &&
  611. Context.getTargetInfo().getCXXABI().isMicrosoft())
  612. Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
  613. }
  614. Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
  615. }
  616. /// Called on well formed \#pragma bss_seg().
  617. void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
  618. int SectionFlags, StringLiteral *SegmentName) {
  619. UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
  620. }
  621. void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
  622. StringLiteral *SegmentName) {
  623. // There's no stack to maintain, so we just have a current section. When we
  624. // see the default section, reset our current section back to null so we stop
  625. // tacking on unnecessary attributes.
  626. CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
  627. CurInitSegLoc = PragmaLocation;
  628. }
  629. void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
  630. SourceLocation PragmaLoc) {
  631. IdentifierInfo *Name = IdTok.getIdentifierInfo();
  632. LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
  633. LookupParsedName(Lookup, curScope, nullptr, true);
  634. if (Lookup.empty()) {
  635. Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
  636. << Name << SourceRange(IdTok.getLocation());
  637. return;
  638. }
  639. VarDecl *VD = Lookup.getAsSingle<VarDecl>();
  640. if (!VD) {
  641. Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
  642. << Name << SourceRange(IdTok.getLocation());
  643. return;
  644. }
  645. // Warn if this was used before being marked unused.
  646. if (VD->isUsed())
  647. Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
  648. VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),
  649. AttributeCommonInfo::AS_Pragma,
  650. UnusedAttr::GNU_unused));
  651. }
  652. void Sema::AddCFAuditedAttribute(Decl *D) {
  653. IdentifierInfo *Ident;
  654. SourceLocation Loc;
  655. std::tie(Ident, Loc) = PP.getPragmaARCCFCodeAuditedInfo();
  656. if (!Loc.isValid()) return;
  657. // Don't add a redundant or conflicting attribute.
  658. if (D->hasAttr<CFAuditedTransferAttr>() ||
  659. D->hasAttr<CFUnknownTransferAttr>())
  660. return;
  661. AttributeCommonInfo Info(Ident, SourceRange(Loc),
  662. AttributeCommonInfo::AS_Pragma);
  663. D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Info));
  664. }
  665. namespace {
  666. Optional<attr::SubjectMatchRule>
  667. getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
  668. using namespace attr;
  669. switch (Rule) {
  670. default:
  671. return None;
  672. #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
  673. #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
  674. case Value: \
  675. return Parent;
  676. #include "clang/Basic/AttrSubMatchRulesList.inc"
  677. }
  678. }
  679. bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
  680. using namespace attr;
  681. switch (Rule) {
  682. default:
  683. return false;
  684. #define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
  685. #define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
  686. case Value: \
  687. return IsNegated;
  688. #include "clang/Basic/AttrSubMatchRulesList.inc"
  689. }
  690. }
  691. CharSourceRange replacementRangeForListElement(const Sema &S,
  692. SourceRange Range) {
  693. // Make sure that the ',' is removed as well.
  694. SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
  695. Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
  696. /*SkipTrailingWhitespaceAndNewLine=*/false);
  697. if (AfterCommaLoc.isValid())
  698. return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
  699. else
  700. return CharSourceRange::getTokenRange(Range);
  701. }
  702. std::string
  703. attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
  704. std::string Result;
  705. llvm::raw_string_ostream OS(Result);
  706. for (const auto &I : llvm::enumerate(Rules)) {
  707. if (I.index())
  708. OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");
  709. OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
  710. }
  711. return Result;
  712. }
  713. } // end anonymous namespace
  714. void Sema::ActOnPragmaAttributeAttribute(
  715. ParsedAttr &Attribute, SourceLocation PragmaLoc,
  716. attr::ParsedSubjectMatchRuleSet Rules) {
  717. Attribute.setIsPragmaClangAttribute();
  718. SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;
  719. // Gather the subject match rules that are supported by the attribute.
  720. SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>
  721. StrictSubjectMatchRuleSet;
  722. Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);
  723. // Figure out which subject matching rules are valid.
  724. if (StrictSubjectMatchRuleSet.empty()) {
  725. // Check for contradicting match rules. Contradicting match rules are
  726. // either:
  727. // - a top-level rule and one of its sub-rules. E.g. variable and
  728. // variable(is_parameter).
  729. // - a sub-rule and a sibling that's negated. E.g.
  730. // variable(is_thread_local) and variable(unless(is_parameter))
  731. llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
  732. RulesToFirstSpecifiedNegatedSubRule;
  733. for (const auto &Rule : Rules) {
  734. attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
  735. Optional<attr::SubjectMatchRule> ParentRule =
  736. getParentAttrMatcherRule(MatchRule);
  737. if (!ParentRule)
  738. continue;
  739. auto It = Rules.find(*ParentRule);
  740. if (It != Rules.end()) {
  741. // A sub-rule contradicts a parent rule.
  742. Diag(Rule.second.getBegin(),
  743. diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
  744. << attr::getSubjectMatchRuleSpelling(MatchRule)
  745. << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
  746. << FixItHint::CreateRemoval(
  747. replacementRangeForListElement(*this, Rule.second));
  748. // Keep going without removing this rule as it won't change the set of
  749. // declarations that receive the attribute.
  750. continue;
  751. }
  752. if (isNegatedAttrMatcherSubRule(MatchRule))
  753. RulesToFirstSpecifiedNegatedSubRule.insert(
  754. std::make_pair(*ParentRule, Rule));
  755. }
  756. bool IgnoreNegatedSubRules = false;
  757. for (const auto &Rule : Rules) {
  758. attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
  759. Optional<attr::SubjectMatchRule> ParentRule =
  760. getParentAttrMatcherRule(MatchRule);
  761. if (!ParentRule)
  762. continue;
  763. auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
  764. if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
  765. It->second != Rule) {
  766. // Negated sub-rule contradicts another sub-rule.
  767. Diag(
  768. It->second.second.getBegin(),
  769. diag::
  770. err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
  771. << attr::getSubjectMatchRuleSpelling(
  772. attr::SubjectMatchRule(It->second.first))
  773. << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
  774. << FixItHint::CreateRemoval(
  775. replacementRangeForListElement(*this, It->second.second));
  776. // Keep going but ignore all of the negated sub-rules.
  777. IgnoreNegatedSubRules = true;
  778. RulesToFirstSpecifiedNegatedSubRule.erase(It);
  779. }
  780. }
  781. if (!IgnoreNegatedSubRules) {
  782. for (const auto &Rule : Rules)
  783. SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
  784. } else {
  785. for (const auto &Rule : Rules) {
  786. if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
  787. SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
  788. }
  789. }
  790. Rules.clear();
  791. } else {
  792. // Each rule in Rules must be a strict subset of the attribute's
  793. // SubjectMatch rules. I.e. we're allowed to use
  794. // `apply_to=variables(is_global)` on an attrubute with SubjectList<[Var]>,
  795. // but should not allow `apply_to=variables` on an attribute which has
  796. // `SubjectList<[GlobalVar]>`.
  797. for (const auto &StrictRule : StrictSubjectMatchRuleSet) {
  798. // First, check for exact match.
  799. if (Rules.erase(StrictRule.first)) {
  800. // Add the rule to the set of attribute receivers only if it's supported
  801. // in the current language mode.
  802. if (StrictRule.second)
  803. SubjectMatchRules.push_back(StrictRule.first);
  804. }
  805. }
  806. // Check remaining rules for subset matches.
  807. auto RulesToCheck = Rules;
  808. for (const auto &Rule : RulesToCheck) {
  809. attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
  810. if (auto ParentRule = getParentAttrMatcherRule(MatchRule)) {
  811. if (llvm::any_of(StrictSubjectMatchRuleSet,
  812. [ParentRule](const auto &StrictRule) {
  813. return StrictRule.first == *ParentRule &&
  814. StrictRule.second; // IsEnabled
  815. })) {
  816. SubjectMatchRules.push_back(MatchRule);
  817. Rules.erase(MatchRule);
  818. }
  819. }
  820. }
  821. }
  822. if (!Rules.empty()) {
  823. auto Diagnostic =
  824. Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
  825. << Attribute;
  826. SmallVector<attr::SubjectMatchRule, 2> ExtraRules;
  827. for (const auto &Rule : Rules) {
  828. ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
  829. Diagnostic << FixItHint::CreateRemoval(
  830. replacementRangeForListElement(*this, Rule.second));
  831. }
  832. Diagnostic << attrMatcherRuleListToString(ExtraRules);
  833. }
  834. if (PragmaAttributeStack.empty()) {
  835. Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
  836. return;
  837. }
  838. PragmaAttributeStack.back().Entries.push_back(
  839. {PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});
  840. }
  841. void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
  842. const IdentifierInfo *Namespace) {
  843. PragmaAttributeStack.emplace_back();
  844. PragmaAttributeStack.back().Loc = PragmaLoc;
  845. PragmaAttributeStack.back().Namespace = Namespace;
  846. }
  847. void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,
  848. const IdentifierInfo *Namespace) {
  849. if (PragmaAttributeStack.empty()) {
  850. Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
  851. return;
  852. }
  853. // Dig back through the stack trying to find the most recently pushed group
  854. // that in Namespace. Note that this works fine if no namespace is present,
  855. // think of push/pops without namespaces as having an implicit "nullptr"
  856. // namespace.
  857. for (size_t Index = PragmaAttributeStack.size(); Index;) {
  858. --Index;
  859. if (PragmaAttributeStack[Index].Namespace == Namespace) {
  860. for (const PragmaAttributeEntry &Entry :
  861. PragmaAttributeStack[Index].Entries) {
  862. if (!Entry.IsUsed) {
  863. assert(Entry.Attribute && "Expected an attribute");
  864. Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
  865. << *Entry.Attribute;
  866. Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
  867. }
  868. }
  869. PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);
  870. return;
  871. }
  872. }
  873. if (Namespace)
  874. Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
  875. << 0 << Namespace->getName();
  876. else
  877. Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
  878. }
  879. void Sema::AddPragmaAttributes(Scope *S, Decl *D) {
  880. if (PragmaAttributeStack.empty())
  881. return;
  882. for (auto &Group : PragmaAttributeStack) {
  883. for (auto &Entry : Group.Entries) {
  884. ParsedAttr *Attribute = Entry.Attribute;
  885. assert(Attribute && "Expected an attribute");
  886. assert(Attribute->isPragmaClangAttribute() &&
  887. "expected #pragma clang attribute");
  888. // Ensure that the attribute can be applied to the given declaration.
  889. bool Applies = false;
  890. for (const auto &Rule : Entry.MatchRules) {
  891. if (Attribute->appliesToDecl(D, Rule)) {
  892. Applies = true;
  893. break;
  894. }
  895. }
  896. if (!Applies)
  897. continue;
  898. Entry.IsUsed = true;
  899. PragmaAttributeCurrentTargetDecl = D;
  900. ParsedAttributesView Attrs;
  901. Attrs.addAtEnd(Attribute);
  902. ProcessDeclAttributeList(S, D, Attrs);
  903. PragmaAttributeCurrentTargetDecl = nullptr;
  904. }
  905. }
  906. }
  907. void Sema::PrintPragmaAttributeInstantiationPoint() {
  908. assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
  909. Diags.Report(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
  910. diag::note_pragma_attribute_applied_decl_here);
  911. }
  912. void Sema::DiagnoseUnterminatedPragmaAttribute() {
  913. if (PragmaAttributeStack.empty())
  914. return;
  915. Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
  916. }
  917. void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
  918. if(On)
  919. OptimizeOffPragmaLocation = SourceLocation();
  920. else
  921. OptimizeOffPragmaLocation = PragmaLoc;
  922. }
  923. void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
  924. // In the future, check other pragmas if they're implemented (e.g. pragma
  925. // optimize 0 will probably map to this functionality too).
  926. if(OptimizeOffPragmaLocation.isValid())
  927. AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
  928. }
  929. void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
  930. SourceLocation Loc) {
  931. // Don't add a conflicting attribute. No diagnostic is needed.
  932. if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
  933. return;
  934. // Add attributes only if required. Optnone requires noinline as well, but if
  935. // either is already present then don't bother adding them.
  936. if (!FD->hasAttr<OptimizeNoneAttr>())
  937. FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
  938. if (!FD->hasAttr<NoInlineAttr>())
  939. FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
  940. }
  941. typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
  942. enum : unsigned { NoVisibility = ~0U };
  943. void Sema::AddPushedVisibilityAttribute(Decl *D) {
  944. if (!VisContext)
  945. return;
  946. NamedDecl *ND = dyn_cast<NamedDecl>(D);
  947. if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
  948. return;
  949. VisStack *Stack = static_cast<VisStack*>(VisContext);
  950. unsigned rawType = Stack->back().first;
  951. if (rawType == NoVisibility) return;
  952. VisibilityAttr::VisibilityType type
  953. = (VisibilityAttr::VisibilityType) rawType;
  954. SourceLocation loc = Stack->back().second;
  955. D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
  956. }
  957. /// FreeVisContext - Deallocate and null out VisContext.
  958. void Sema::FreeVisContext() {
  959. delete static_cast<VisStack*>(VisContext);
  960. VisContext = nullptr;
  961. }
  962. static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
  963. // Put visibility on stack.
  964. if (!S.VisContext)
  965. S.VisContext = new VisStack;
  966. VisStack *Stack = static_cast<VisStack*>(S.VisContext);
  967. Stack->push_back(std::make_pair(type, loc));
  968. }
  969. void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
  970. SourceLocation PragmaLoc) {
  971. if (VisType) {
  972. // Compute visibility to use.
  973. VisibilityAttr::VisibilityType T;
  974. if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
  975. Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
  976. return;
  977. }
  978. PushPragmaVisibility(*this, T, PragmaLoc);
  979. } else {
  980. PopPragmaVisibility(false, PragmaLoc);
  981. }
  982. }
  983. void Sema::ActOnPragmaFPContract(SourceLocation Loc,
  984. LangOptions::FPModeKind FPC) {
  985. FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
  986. switch (FPC) {
  987. case LangOptions::FPM_On:
  988. NewFPFeatures.setAllowFPContractWithinStatement();
  989. break;
  990. case LangOptions::FPM_Fast:
  991. NewFPFeatures.setAllowFPContractAcrossStatement();
  992. break;
  993. case LangOptions::FPM_Off:
  994. NewFPFeatures.setDisallowFPContract();
  995. break;
  996. case LangOptions::FPM_FastHonorPragmas:
  997. llvm_unreachable("Should not happen");
  998. }
  999. FpPragmaStack.Act(Loc, Sema::PSK_Set, StringRef(), NewFPFeatures);
  1000. CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
  1001. }
  1002. void Sema::ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled) {
  1003. FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
  1004. NewFPFeatures.setAllowFPReassociateOverride(IsEnabled);
  1005. FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
  1006. CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
  1007. }
  1008. void Sema::setRoundingMode(SourceLocation Loc, llvm::RoundingMode FPR) {
  1009. // C2x: 7.6.2p3 If the FE_DYNAMIC mode is specified and FENV_ACCESS is "off",
  1010. // the translator may assume that the default rounding mode is in effect.
  1011. if (FPR == llvm::RoundingMode::Dynamic &&
  1012. !CurFPFeatures.getAllowFEnvAccess() &&
  1013. CurFPFeatures.getFPExceptionMode() == LangOptions::FPE_Ignore)
  1014. FPR = llvm::RoundingMode::NearestTiesToEven;
  1015. FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
  1016. NewFPFeatures.setRoundingModeOverride(FPR);
  1017. FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
  1018. CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
  1019. }
  1020. void Sema::setExceptionMode(SourceLocation Loc,
  1021. LangOptions::FPExceptionModeKind FPE) {
  1022. FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
  1023. NewFPFeatures.setFPExceptionModeOverride(FPE);
  1024. FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
  1025. CurFPFeatures = NewFPFeatures.applyOverrides(getLangOpts());
  1026. }
  1027. void Sema::ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled) {
  1028. FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
  1029. auto LO = getLangOpts();
  1030. if (IsEnabled) {
  1031. // Verify Microsoft restriction:
  1032. // You can't enable fenv_access unless precise semantics are enabled.
  1033. // Precise semantics can be enabled either by the float_control
  1034. // pragma, or by using the /fp:precise or /fp:strict compiler options
  1035. if (!isPreciseFPEnabled())
  1036. Diag(Loc, diag::err_pragma_fenv_requires_precise);
  1037. NewFPFeatures.setAllowFEnvAccessOverride(true);
  1038. // Enabling FENV access sets the RoundingMode to Dynamic.
  1039. // and ExceptionBehavior to Strict
  1040. NewFPFeatures.setRoundingModeOverride(llvm::RoundingMode::Dynamic);
  1041. NewFPFeatures.setFPExceptionModeOverride(LangOptions::FPE_Strict);
  1042. } else {
  1043. NewFPFeatures.setAllowFEnvAccessOverride(false);
  1044. }
  1045. FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
  1046. CurFPFeatures = NewFPFeatures.applyOverrides(LO);
  1047. }
  1048. void Sema::ActOnPragmaFPExceptions(SourceLocation Loc,
  1049. LangOptions::FPExceptionModeKind FPE) {
  1050. setExceptionMode(Loc, FPE);
  1051. }
  1052. void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
  1053. SourceLocation Loc) {
  1054. // Visibility calculations will consider the namespace's visibility.
  1055. // Here we just want to note that we're in a visibility context
  1056. // which overrides any enclosing #pragma context, but doesn't itself
  1057. // contribute visibility.
  1058. PushPragmaVisibility(*this, NoVisibility, Loc);
  1059. }
  1060. void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
  1061. if (!VisContext) {
  1062. Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
  1063. return;
  1064. }
  1065. // Pop visibility from stack
  1066. VisStack *Stack = static_cast<VisStack*>(VisContext);
  1067. const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
  1068. bool StartsWithPragma = Back->first != NoVisibility;
  1069. if (StartsWithPragma && IsNamespaceEnd) {
  1070. Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
  1071. Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
  1072. // For better error recovery, eat all pushes inside the namespace.
  1073. do {
  1074. Stack->pop_back();
  1075. Back = &Stack->back();
  1076. StartsWithPragma = Back->first != NoVisibility;
  1077. } while (StartsWithPragma);
  1078. } else if (!StartsWithPragma && !IsNamespaceEnd) {
  1079. Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
  1080. Diag(Back->second, diag::note_surrounding_namespace_starts_here);
  1081. return;
  1082. }
  1083. Stack->pop_back();
  1084. // To simplify the implementation, never keep around an empty stack.
  1085. if (Stack->empty())
  1086. FreeVisContext();
  1087. }
  1088. template <typename Ty>
  1089. static bool checkCommonAttributeFeatures(Sema& S, const Ty *Node,
  1090. const ParsedAttr& A) {
  1091. // Several attributes carry different semantics than the parsing requires, so
  1092. // those are opted out of the common argument checks.
  1093. //
  1094. // We also bail on unknown and ignored attributes because those are handled
  1095. // as part of the target-specific handling logic.
  1096. if (A.getKind() == ParsedAttr::UnknownAttribute)
  1097. return false;
  1098. // Check whether the attribute requires specific language extensions to be
  1099. // enabled.
  1100. if (!A.diagnoseLangOpts(S))
  1101. return true;
  1102. // Check whether the attribute appertains to the given subject.
  1103. if (!A.diagnoseAppertainsTo(S, Node))
  1104. return true;
  1105. // Check whether the attribute is mutually exclusive with other attributes
  1106. // that have already been applied to the declaration.
  1107. if (!A.diagnoseMutualExclusion(S, Node))
  1108. return true;
  1109. // Check whether the attribute exists in the target architecture.
  1110. if (S.CheckAttrTarget(A))
  1111. return true;
  1112. if (A.hasCustomParsing())
  1113. return false;
  1114. if (A.getMinArgs() == A.getMaxArgs()) {
  1115. // If there are no optional arguments, then checking for the argument count
  1116. // is trivial.
  1117. if (!A.checkExactlyNumArgs(S, A.getMinArgs()))
  1118. return true;
  1119. } else {
  1120. // There are optional arguments, so checking is slightly more involved.
  1121. if (A.getMinArgs() && !A.checkAtLeastNumArgs(S, A.getMinArgs()))
  1122. return true;
  1123. else if (!A.hasVariadicArg() && A.getMaxArgs() &&
  1124. !A.checkAtMostNumArgs(S, A.getMaxArgs()))
  1125. return true;
  1126. }
  1127. return false;
  1128. }
  1129. bool Sema::checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A) {
  1130. return ::checkCommonAttributeFeatures(*this, D, A);
  1131. }
  1132. bool Sema::checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A) {
  1133. return ::checkCommonAttributeFeatures(*this, S, A);
  1134. }