blob: 6a2f74479c481bc7bcbb17339772cca32e352ac7 [file] [log] [blame]
Bill Wendling44426052012-12-20 19:22:21 +00001//===--- SemaAttr.cpp - Semantic Analysis for Attributes ------------------===//
Chris Lattner2eccbc12009-02-17 00:57:29 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattner2eccbc12009-02-17 00:57:29 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattner31180bb2009-02-17 01:09:29 +00009// This file implements semantic analysis for non-trivial attributes and
10// pragmas.
Chris Lattner2eccbc12009-02-17 00:57:29 +000011//
12//===----------------------------------------------------------------------===//
13
Reid Klecknere43f0fe2013-05-08 13:44:39 +000014#include "clang/AST/ASTConsumer.h"
Alexis Huntdcfba7b2010-08-18 23:23:40 +000015#include "clang/AST/Attr.h"
Chris Lattner2eccbc12009-02-17 00:57:29 +000016#include "clang/AST/Expr.h"
Daniel Dunbarbd606522010-05-27 00:35:16 +000017#include "clang/Basic/TargetInfo.h"
18#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Sema/Lookup.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000020#include "clang/Sema/SemaInternal.h"
Chris Lattner2eccbc12009-02-17 00:57:29 +000021using namespace clang;
22
Chris Lattner31180bb2009-02-17 01:09:29 +000023//===----------------------------------------------------------------------===//
Daniel Dunbar69dac582010-05-27 00:04:40 +000024// Pragma 'pack' and 'options align'
Chris Lattner31180bb2009-02-17 01:09:29 +000025//===----------------------------------------------------------------------===//
26
Denis Zobnin2290dac2016-04-29 11:27:00 +000027Sema::PragmaStackSentinelRAII::PragmaStackSentinelRAII(Sema &S,
28 StringRef SlotLabel,
29 bool ShouldAct)
30 : S(S), SlotLabel(SlotLabel), ShouldAct(ShouldAct) {
31 if (ShouldAct) {
32 S.VtorDispStack.SentinelAction(PSK_Push, SlotLabel);
33 S.DataSegStack.SentinelAction(PSK_Push, SlotLabel);
34 S.BSSSegStack.SentinelAction(PSK_Push, SlotLabel);
35 S.ConstSegStack.SentinelAction(PSK_Push, SlotLabel);
36 S.CodeSegStack.SentinelAction(PSK_Push, SlotLabel);
37 }
38}
39
40Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {
41 if (ShouldAct) {
42 S.VtorDispStack.SentinelAction(PSK_Pop, SlotLabel);
43 S.DataSegStack.SentinelAction(PSK_Pop, SlotLabel);
44 S.BSSSegStack.SentinelAction(PSK_Pop, SlotLabel);
45 S.ConstSegStack.SentinelAction(PSK_Pop, SlotLabel);
46 S.CodeSegStack.SentinelAction(PSK_Pop, SlotLabel);
47 }
48}
Chris Lattner31180bb2009-02-17 01:09:29 +000049
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000050void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
Denis Zobnin10c4f452016-04-29 18:17:40 +000051 // If there is no pack value, we don't need any attributes.
52 if (!PackStack.CurrentValue)
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000053 return;
54
Daniel Dunbar8804f2e2010-05-27 01:53:40 +000055 // Otherwise, check to see if we need a max field alignment attribute.
Denis Zobnin10c4f452016-04-29 18:17:40 +000056 if (unsigned Alignment = PackStack.CurrentValue) {
57 if (Alignment == Sema::kMac68kAlignmentSentinel)
Aaron Ballman36a53502014-01-16 13:03:14 +000058 RD->addAttr(AlignMac68kAttr::CreateImplicit(Context));
Daniel Dunbar6da10982010-05-27 05:45:51 +000059 else
Aaron Ballman36a53502014-01-16 13:03:14 +000060 RD->addAttr(MaxFieldAlignmentAttr::CreateImplicit(Context,
Alexis Huntdcfba7b2010-08-18 23:23:40 +000061 Alignment * 8));
Daniel Dunbar6da10982010-05-27 05:45:51 +000062 }
Alex Lorenz45b40142017-07-28 14:41:21 +000063 if (PackIncludeStack.empty())
64 return;
65 // The #pragma pack affected a record in an included file, so Clang should
66 // warn when that pragma was written in a file that included the included
67 // file.
68 for (auto &PackedInclude : llvm::reverse(PackIncludeStack)) {
69 if (PackedInclude.CurrentPragmaLocation != PackStack.CurrentPragmaLocation)
70 break;
71 if (PackedInclude.HasNonDefaultValue)
72 PackedInclude.ShouldWarnOnInclude = true;
73 }
Chris Lattner31180bb2009-02-17 01:09:29 +000074}
75
Fariborz Jahanian6b4e26b2011-04-26 17:54:40 +000076void Sema::AddMsStructLayoutForRecord(RecordDecl *RD) {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +000077 if (MSStructPragmaOn)
David Majnemer8ab003a2015-02-02 19:30:52 +000078 RD->addAttr(MSStructAttr::CreateImplicit(Context));
Reid Klecknerc0dca6d2014-02-12 23:50:26 +000079
80 // FIXME: We should merge AddAlignmentAttributesForRecord with
81 // AddMsStructLayoutForRecord into AddPragmaAttributesForRecord, which takes
82 // all active pragmas and applies them as attributes to class definitions.
Reid Kleckner2692eb02019-11-22 14:55:49 -080083 if (VtorDispStack.CurrentValue != getLangOpts().getVtorDispMode())
84 RD->addAttr(MSVtorDispAttr::CreateImplicit(
85 Context, unsigned(VtorDispStack.CurrentValue)));
Fariborz Jahanian6b4e26b2011-04-26 17:54:40 +000086}
87
Matthias Gehre23092ca2019-08-07 10:45:36 +000088template <typename Attribute>
89static void addGslOwnerPointerAttributeIfNotExisting(ASTContext &Context,
90 CXXRecordDecl *Record) {
Matthias Gehref64f4882019-09-06 08:56:30 +000091 if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
Matthias Gehre23092ca2019-08-07 10:45:36 +000092 return;
93
Matthias Gehref64f4882019-09-06 08:56:30 +000094 for (Decl *Redecl : Record->redecls())
95 Redecl->addAttr(Attribute::CreateImplicit(Context, /*DerefType=*/nullptr));
Matthias Gehre23092ca2019-08-07 10:45:36 +000096}
97
98void Sema::inferGslPointerAttribute(NamedDecl *ND,
99 CXXRecordDecl *UnderlyingRecord) {
100 if (!UnderlyingRecord)
101 return;
102
103 const auto *Parent = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
104 if (!Parent)
105 return;
106
107 static llvm::StringSet<> Containers{
108 "array",
109 "basic_string",
110 "deque",
111 "forward_list",
112 "vector",
113 "list",
114 "map",
115 "multiset",
116 "multimap",
117 "priority_queue",
118 "queue",
119 "set",
120 "stack",
121 "unordered_set",
122 "unordered_map",
123 "unordered_multiset",
124 "unordered_multimap",
125 };
126
127 static llvm::StringSet<> Iterators{"iterator", "const_iterator",
128 "reverse_iterator",
129 "const_reverse_iterator"};
130
131 if (Parent->isInStdNamespace() && Iterators.count(ND->getName()) &&
132 Containers.count(Parent->getName()))
133 addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context,
134 UnderlyingRecord);
135}
136
137void Sema::inferGslPointerAttribute(TypedefNameDecl *TD) {
138
139 QualType Canonical = TD->getUnderlyingType().getCanonicalType();
140
141 CXXRecordDecl *RD = Canonical->getAsCXXRecordDecl();
142 if (!RD) {
143 if (auto *TST =
144 dyn_cast<TemplateSpecializationType>(Canonical.getTypePtr())) {
145
146 RD = dyn_cast_or_null<CXXRecordDecl>(
147 TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl());
148 }
149 }
150
151 inferGslPointerAttribute(TD, RD);
152}
153
154void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl *Record) {
155 static llvm::StringSet<> StdOwners{
156 "any",
157 "array",
158 "basic_regex",
159 "basic_string",
160 "deque",
161 "forward_list",
162 "vector",
163 "list",
164 "map",
165 "multiset",
166 "multimap",
167 "optional",
168 "priority_queue",
169 "queue",
170 "set",
171 "stack",
172 "unique_ptr",
173 "unordered_set",
174 "unordered_map",
175 "unordered_multiset",
176 "unordered_multimap",
177 "variant",
178 };
179 static llvm::StringSet<> StdPointers{
180 "basic_string_view",
181 "reference_wrapper",
182 "regex_iterator",
183 };
184
185 if (!Record->getIdentifier())
186 return;
187
188 // Handle classes that directly appear in std namespace.
189 if (Record->isInStdNamespace()) {
Matthias Gehref64f4882019-09-06 08:56:30 +0000190 if (Record->hasAttr<OwnerAttr>() || Record->hasAttr<PointerAttr>())
Matthias Gehre23092ca2019-08-07 10:45:36 +0000191 return;
192
193 if (StdOwners.count(Record->getName()))
194 addGslOwnerPointerAttributeIfNotExisting<OwnerAttr>(Context, Record);
195 else if (StdPointers.count(Record->getName()))
196 addGslOwnerPointerAttributeIfNotExisting<PointerAttr>(Context, Record);
197
198 return;
199 }
200
201 // Handle nested classes that could be a gsl::Pointer.
202 inferGslPointerAttribute(Record, Record);
203}
204
Daniel Dunbar69dac582010-05-27 00:04:40 +0000205void Sema::ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
Eli Friedman68be1642012-10-04 02:36:51 +0000206 SourceLocation PragmaLoc) {
Denis Zobnin10c4f452016-04-29 18:17:40 +0000207 PragmaMsStackAction Action = Sema::PSK_Reset;
Denis Zobnin3f287c22016-04-29 22:50:16 +0000208 unsigned Alignment = 0;
Daniel Dunbar69dac582010-05-27 00:04:40 +0000209 switch (Kind) {
Daniel Dunbar663e8092010-05-27 18:42:09 +0000210 // For all targets we support native and natural are the same.
211 //
212 // FIXME: This is not true on Darwin/PPC.
213 case POAK_Native:
Daniel Dunbar5794c6f2010-05-28 19:43:33 +0000214 case POAK_Power:
Daniel Dunbara6885662010-05-28 20:08:00 +0000215 case POAK_Natural:
Denis Zobnin10c4f452016-04-29 18:17:40 +0000216 Action = Sema::PSK_Push_Set;
217 Alignment = 0;
Daniel Dunbar5794c6f2010-05-28 19:43:33 +0000218 break;
219
Daniel Dunbar9c84d4a2010-05-27 18:42:17 +0000220 // Note that '#pragma options align=packed' is not equivalent to attribute
221 // packed, it has a different precedence relative to attribute aligned.
222 case POAK_Packed:
Denis Zobnin10c4f452016-04-29 18:17:40 +0000223 Action = Sema::PSK_Push_Set;
224 Alignment = 1;
Daniel Dunbar9c84d4a2010-05-27 18:42:17 +0000225 break;
226
Daniel Dunbarbd606522010-05-27 00:35:16 +0000227 case POAK_Mac68k:
228 // Check if the target supports this.
Alp Tokerb6cc5922014-05-03 03:45:55 +0000229 if (!this->Context.getTargetInfo().hasAlignMac68kSupport()) {
Daniel Dunbarbd606522010-05-27 00:35:16 +0000230 Diag(PragmaLoc, diag::err_pragma_options_align_mac68k_target_unsupported);
231 return;
Daniel Dunbarbd606522010-05-27 00:35:16 +0000232 }
Denis Zobnin10c4f452016-04-29 18:17:40 +0000233 Action = Sema::PSK_Push_Set;
234 Alignment = Sema::kMac68kAlignmentSentinel;
Daniel Dunbarbd606522010-05-27 00:35:16 +0000235 break;
236
Eli Friedman68be1642012-10-04 02:36:51 +0000237 case POAK_Reset:
238 // Reset just pops the top of the stack, or resets the current alignment to
239 // default.
Denis Zobnin10c4f452016-04-29 18:17:40 +0000240 Action = Sema::PSK_Pop;
241 if (PackStack.Stack.empty()) {
242 if (PackStack.CurrentValue) {
243 Action = Sema::PSK_Reset;
244 } else {
245 Diag(PragmaLoc, diag::warn_pragma_options_align_reset_failed)
246 << "stack empty";
247 return;
248 }
Eli Friedman68be1642012-10-04 02:36:51 +0000249 }
Daniel Dunbar69dac582010-05-27 00:04:40 +0000250 break;
251 }
Denis Zobnin10c4f452016-04-29 18:17:40 +0000252
253 PackStack.Act(PragmaLoc, Action, StringRef(), Alignment);
Daniel Dunbar69dac582010-05-27 00:04:40 +0000254}
255
Javed Absar2a67c9e2017-06-05 10:11:57 +0000256void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action,
257 PragmaClangSectionKind SecKind, StringRef SecName) {
258 PragmaClangSection *CSec;
259 switch (SecKind) {
260 case PragmaClangSectionKind::PCSK_BSS:
261 CSec = &PragmaClangBSSSection;
262 break;
263 case PragmaClangSectionKind::PCSK_Data:
264 CSec = &PragmaClangDataSection;
265 break;
266 case PragmaClangSectionKind::PCSK_Rodata:
267 CSec = &PragmaClangRodataSection;
268 break;
Dmitry Mikulinf14642f2019-10-15 18:31:10 +0000269 case PragmaClangSectionKind::PCSK_Relro:
270 CSec = &PragmaClangRelroSection;
271 break;
Javed Absar2a67c9e2017-06-05 10:11:57 +0000272 case PragmaClangSectionKind::PCSK_Text:
273 CSec = &PragmaClangTextSection;
274 break;
275 default:
276 llvm_unreachable("invalid clang section kind");
277 }
278
279 if (Action == PragmaClangSectionAction::PCSA_Clear) {
280 CSec->Valid = false;
281 return;
282 }
283
284 CSec->Valid = true;
Benjamin Krameradcd0262020-01-28 20:23:46 +0100285 CSec->SectionName = std::string(SecName);
Javed Absar2a67c9e2017-06-05 10:11:57 +0000286 CSec->PragmaLocation = PragmaLoc;
287}
288
Denis Zobnin10c4f452016-04-29 18:17:40 +0000289void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
290 StringRef SlotLabel, Expr *alignment) {
Chris Lattner2eccbc12009-02-17 00:57:29 +0000291 Expr *Alignment = static_cast<Expr *>(alignment);
292
293 // If specified then alignment must be a "small" power of two.
294 unsigned AlignmentVal = 0;
295 if (Alignment) {
296 llvm::APSInt Val;
Mike Stump11289f42009-09-09 15:08:12 +0000297
Daniel Dunbare03c6102009-03-06 20:45:54 +0000298 // pack(0) is like pack(), which just works out since that is what
299 // we use 0 for in PackAttr.
Douglas Gregorbdb604a2010-05-18 23:01:22 +0000300 if (Alignment->isTypeDependent() ||
301 Alignment->isValueDependent() ||
302 !Alignment->isIntegerConstantExpr(Val, Context) ||
Daniel Dunbare03c6102009-03-06 20:45:54 +0000303 !(Val == 0 || Val.isPowerOf2()) ||
Chris Lattner2eccbc12009-02-17 00:57:29 +0000304 Val.getZExtValue() > 16) {
305 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
Chris Lattner2eccbc12009-02-17 00:57:29 +0000306 return; // Ignore
307 }
308
309 AlignmentVal = (unsigned) Val.getZExtValue();
310 }
Denis Zobnin10c4f452016-04-29 18:17:40 +0000311 if (Action == Sema::PSK_Show) {
Chris Lattner2eccbc12009-02-17 00:57:29 +0000312 // Show the current alignment, making sure to show the right value
313 // for the default.
Chris Lattner2eccbc12009-02-17 00:57:29 +0000314 // FIXME: This should come from the target.
Denis Zobnin10c4f452016-04-29 18:17:40 +0000315 AlignmentVal = PackStack.CurrentValue;
Chris Lattner2eccbc12009-02-17 00:57:29 +0000316 if (AlignmentVal == 0)
317 AlignmentVal = 8;
Denis Zobnin10c4f452016-04-29 18:17:40 +0000318 if (AlignmentVal == Sema::kMac68kAlignmentSentinel)
Daniel Dunbar6da10982010-05-27 05:45:51 +0000319 Diag(PragmaLoc, diag::warn_pragma_pack_show) << "mac68k";
320 else
321 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Chris Lattner2eccbc12009-02-17 00:57:29 +0000322 }
Denis Zobnin10c4f452016-04-29 18:17:40 +0000323 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
324 // "#pragma pack(pop, identifier, n) is undefined"
325 if (Action & Sema::PSK_Pop) {
326 if (Alignment && !SlotLabel.empty())
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000327 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifier_and_alignment);
Denis Zobnin10c4f452016-04-29 18:17:40 +0000328 if (PackStack.Stack.empty())
329 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "pack" << "stack empty";
330 }
331
332 PackStack.Act(PragmaLoc, Action, SlotLabel, AlignmentVal);
Chris Lattner2eccbc12009-02-17 00:57:29 +0000333}
334
Alex Lorenz45b40142017-07-28 14:41:21 +0000335void Sema::DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
336 SourceLocation IncludeLoc) {
337 if (Kind == PragmaPackDiagnoseKind::NonDefaultStateAtInclude) {
338 SourceLocation PrevLocation = PackStack.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 PackStack.hasValue() &&
346 (PackIncludeStack.empty() ||
347 PackIncludeStack.back().CurrentPragmaLocation != PrevLocation);
348 PackIncludeStack.push_back(
349 {PackStack.CurrentValue,
350 PackStack.hasValue() ? PrevLocation : SourceLocation(),
351 HasNonDefaultValue, /*ShouldWarnOnInclude*/ false});
352 return;
353 }
354
355 assert(Kind == PragmaPackDiagnoseKind::ChangedStateAtExit && "invalid kind");
356 PackIncludeState PrevPackState = PackIncludeStack.pop_back_val();
357 if (PrevPackState.ShouldWarnOnInclude) {
358 // Emit the delayed non-default alignment at #include warning.
359 Diag(IncludeLoc, diag::warn_pragma_pack_non_default_at_include);
360 Diag(PrevPackState.CurrentPragmaLocation, diag::note_pragma_pack_here);
361 }
362 // Warn about modified alignment after #includes.
363 if (PrevPackState.CurrentValue != PackStack.CurrentValue) {
364 Diag(IncludeLoc, diag::warn_pragma_pack_modified_after_include);
365 Diag(PackStack.CurrentPragmaLocation, diag::note_pragma_pack_here);
366 }
367}
368
369void Sema::DiagnoseUnterminatedPragmaPack() {
370 if (PackStack.Stack.empty())
371 return;
Alex Lorenza1479d72017-07-31 13:37:50 +0000372 bool IsInnermost = true;
373 for (const auto &StackSlot : llvm::reverse(PackStack.Stack)) {
Alex Lorenz45b40142017-07-28 14:41:21 +0000374 Diag(StackSlot.PragmaPushLocation, diag::warn_pragma_pack_no_pop_eof);
Alex Lorenza1479d72017-07-31 13:37:50 +0000375 // The user might have already reset the alignment, so suggest replacing
376 // the reset with a pop.
377 if (IsInnermost && PackStack.CurrentValue == PackStack.DefaultValue) {
378 DiagnosticBuilder DB = Diag(PackStack.CurrentPragmaLocation,
379 diag::note_pragma_pack_pop_instead_reset);
380 SourceLocation FixItLoc = Lexer::findLocationAfterToken(
381 PackStack.CurrentPragmaLocation, tok::l_paren, SourceMgr, LangOpts,
382 /*SkipTrailing=*/false);
383 if (FixItLoc.isValid())
384 DB << FixItHint::CreateInsertion(FixItLoc, "pop");
385 }
386 IsInnermost = false;
387 }
Alex Lorenz45b40142017-07-28 14:41:21 +0000388}
389
Fangrui Song6907ce22018-07-30 19:24:48 +0000390void Sema::ActOnPragmaMSStruct(PragmaMSStructKind Kind) {
Fariborz Jahanian743dda42011-04-25 18:49:15 +0000391 MSStructPragmaOn = (Kind == PMSST_ON);
392}
393
Nico Weber66220292016-03-02 17:28:48 +0000394void Sema::ActOnPragmaMSComment(SourceLocation CommentLoc,
395 PragmaMSCommentKind Kind, StringRef Arg) {
396 auto *PCD = PragmaCommentDecl::Create(
397 Context, Context.getTranslationUnitDecl(), CommentLoc, Kind, Arg);
398 Context.getTranslationUnitDecl()->addDecl(PCD);
399 Consumer.HandleTopLevelDecl(DeclGroupRef(PCD));
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000400}
401
Nico Webercbbaeb12016-03-02 19:28:54 +0000402void Sema::ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
403 StringRef Value) {
404 auto *PDMD = PragmaDetectMismatchDecl::Create(
405 Context, Context.getTranslationUnitDecl(), Loc, Name, Value);
406 Context.getTranslationUnitDecl()->addDecl(PDMD);
407 Consumer.HandleTopLevelDecl(DeclGroupRef(PDMD));
Aaron Ballman5d041be2013-06-04 02:07:14 +0000408}
409
David Majnemer4bb09802014-02-10 19:50:15 +0000410void Sema::ActOnPragmaMSPointersToMembers(
David Majnemer86c318f2014-02-11 21:05:00 +0000411 LangOptions::PragmaMSPointersToMembersKind RepresentationMethod,
David Majnemer4bb09802014-02-10 19:50:15 +0000412 SourceLocation PragmaLoc) {
413 MSPointerToMemberRepresentationMethod = RepresentationMethod;
414 ImplicitMSInheritanceAttrLoc = PragmaLoc;
415}
416
Denis Zobnin2290dac2016-04-29 11:27:00 +0000417void Sema::ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000418 SourceLocation PragmaLoc,
Reid Kleckner2692eb02019-11-22 14:55:49 -0800419 MSVtorDispMode Mode) {
Denis Zobnin2290dac2016-04-29 11:27:00 +0000420 if (Action & PSK_Pop && VtorDispStack.Stack.empty())
421 Diag(PragmaLoc, diag::warn_pragma_pop_failed) << "vtordisp"
422 << "stack empty";
423 VtorDispStack.Act(PragmaLoc, Action, StringRef(), Mode);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000424}
425
Warren Huntc3b18962014-04-08 22:30:47 +0000426template<typename ValueType>
427void Sema::PragmaStack<ValueType>::Act(SourceLocation PragmaLocation,
428 PragmaMsStackAction Action,
429 llvm::StringRef StackSlotLabel,
430 ValueType Value) {
431 if (Action == PSK_Reset) {
Denis Zobnin2290dac2016-04-29 11:27:00 +0000432 CurrentValue = DefaultValue;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +0000433 CurrentPragmaLocation = PragmaLocation;
Warren Huntc3b18962014-04-08 22:30:47 +0000434 return;
435 }
436 if (Action & PSK_Push)
Alex Lorenz45b40142017-07-28 14:41:21 +0000437 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
438 PragmaLocation);
Warren Huntc3b18962014-04-08 22:30:47 +0000439 else if (Action & PSK_Pop) {
440 if (!StackSlotLabel.empty()) {
441 // If we've got a label, try to find it and jump there.
David Majnemerf7e36092016-06-23 00:15:04 +0000442 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
443 return x.StackSlotLabel == StackSlotLabel;
444 });
Warren Huntc3b18962014-04-08 22:30:47 +0000445 // If we found the label so pop from there.
446 if (I != Stack.rend()) {
447 CurrentValue = I->Value;
448 CurrentPragmaLocation = I->PragmaLocation;
449 Stack.erase(std::prev(I.base()), Stack.end());
450 }
451 } else if (!Stack.empty()) {
George Burgess IVa75c71d2018-05-26 02:29:14 +0000452 // We do not have a label, just pop the last entry.
Warren Huntc3b18962014-04-08 22:30:47 +0000453 CurrentValue = Stack.back().Value;
454 CurrentPragmaLocation = Stack.back().PragmaLocation;
455 Stack.pop_back();
456 }
457 }
458 if (Action & PSK_Set) {
459 CurrentValue = Value;
460 CurrentPragmaLocation = PragmaLocation;
461 }
462}
463
Craig Topperbf3e3272014-08-30 16:55:52 +0000464bool Sema::UnifySection(StringRef SectionName,
Warren Huntc3b18962014-04-08 22:30:47 +0000465 int SectionFlags,
466 DeclaratorDecl *Decl) {
Hans Wennborg899ded92014-10-16 20:52:46 +0000467 auto Section = Context.SectionInfos.find(SectionName);
468 if (Section == Context.SectionInfos.end()) {
469 Context.SectionInfos[SectionName] =
470 ASTContext::SectionInfo(Decl, SourceLocation(), SectionFlags);
Warren Huntc3b18962014-04-08 22:30:47 +0000471 return false;
472 }
473 // A pre-declared section takes precedence w/o diagnostic.
474 if (Section->second.SectionFlags == SectionFlags ||
Hans Wennborg899ded92014-10-16 20:52:46 +0000475 !(Section->second.SectionFlags & ASTContext::PSF_Implicit))
Warren Huntc3b18962014-04-08 22:30:47 +0000476 return false;
477 auto OtherDecl = Section->second.Decl;
478 Diag(Decl->getLocation(), diag::err_section_conflict)
479 << Decl << OtherDecl;
480 Diag(OtherDecl->getLocation(), diag::note_declared_at)
481 << OtherDecl->getName();
482 if (auto A = Decl->getAttr<SectionAttr>())
483 if (A->isImplicit())
484 Diag(A->getLocation(), diag::note_pragma_entered_here);
485 if (auto A = OtherDecl->getAttr<SectionAttr>())
486 if (A->isImplicit())
487 Diag(A->getLocation(), diag::note_pragma_entered_here);
Ehsan Akhgari0b510602014-09-22 19:46:39 +0000488 return true;
Warren Huntc3b18962014-04-08 22:30:47 +0000489}
490
Craig Topperbf3e3272014-08-30 16:55:52 +0000491bool Sema::UnifySection(StringRef SectionName,
Warren Huntc3b18962014-04-08 22:30:47 +0000492 int SectionFlags,
493 SourceLocation PragmaSectionLocation) {
Hans Wennborg899ded92014-10-16 20:52:46 +0000494 auto Section = Context.SectionInfos.find(SectionName);
495 if (Section != Context.SectionInfos.end()) {
Warren Huntc3b18962014-04-08 22:30:47 +0000496 if (Section->second.SectionFlags == SectionFlags)
497 return false;
Hans Wennborg899ded92014-10-16 20:52:46 +0000498 if (!(Section->second.SectionFlags & ASTContext::PSF_Implicit)) {
Warren Huntc3b18962014-04-08 22:30:47 +0000499 Diag(PragmaSectionLocation, diag::err_section_conflict)
500 << "this" << "a prior #pragma section";
501 Diag(Section->second.PragmaSectionLocation,
502 diag::note_pragma_entered_here);
503 return true;
504 }
505 }
Hans Wennborg899ded92014-10-16 20:52:46 +0000506 Context.SectionInfos[SectionName] =
507 ASTContext::SectionInfo(nullptr, PragmaSectionLocation, SectionFlags);
Warren Huntc3b18962014-04-08 22:30:47 +0000508 return false;
509}
510
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000511/// Called on well formed \#pragma bss_seg().
Warren Huntc3b18962014-04-08 22:30:47 +0000512void Sema::ActOnPragmaMSSeg(SourceLocation PragmaLocation,
513 PragmaMsStackAction Action,
514 llvm::StringRef StackSlotLabel,
515 StringLiteral *SegmentName,
516 llvm::StringRef PragmaName) {
517 PragmaStack<StringLiteral *> *Stack =
518 llvm::StringSwitch<PragmaStack<StringLiteral *> *>(PragmaName)
519 .Case("data_seg", &DataSegStack)
520 .Case("bss_seg", &BSSSegStack)
521 .Case("const_seg", &ConstSegStack)
522 .Case("code_seg", &CodeSegStack);
523 if (Action & PSK_Pop && Stack->Stack.empty())
524 Diag(PragmaLocation, diag::warn_pragma_pop_failed) << PragmaName
525 << "stack empty";
Nico Weber98016212019-07-09 00:02:23 +0000526 if (SegmentName) {
527 if (!checkSectionName(SegmentName->getBeginLoc(), SegmentName->getString()))
528 return;
529
530 if (SegmentName->getString() == ".drectve" &&
531 Context.getTargetInfo().getCXXABI().isMicrosoft())
532 Diag(PragmaLocation, diag::warn_attribute_section_drectve) << PragmaName;
533 }
534
Warren Huntc3b18962014-04-08 22:30:47 +0000535 Stack->Act(PragmaLocation, Action, StackSlotLabel, SegmentName);
536}
537
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000538/// Called on well formed \#pragma bss_seg().
Warren Huntc3b18962014-04-08 22:30:47 +0000539void Sema::ActOnPragmaMSSection(SourceLocation PragmaLocation,
540 int SectionFlags, StringLiteral *SegmentName) {
541 UnifySection(SegmentName->getString(), SectionFlags, PragmaLocation);
542}
543
Reid Kleckner1a711b12014-07-22 00:53:05 +0000544void Sema::ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
545 StringLiteral *SegmentName) {
546 // There's no stack to maintain, so we just have a current section. When we
547 // see the default section, reset our current section back to null so we stop
548 // tacking on unnecessary attributes.
549 CurInitSeg = SegmentName->getString() == ".CRT$XCU" ? nullptr : SegmentName;
550 CurInitSegLoc = PragmaLocation;
551}
552
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000553void Sema::ActOnPragmaUnused(const Token &IdTok, Scope *curScope,
554 SourceLocation PragmaLoc) {
Ted Kremenekfd14fad2009-03-23 22:28:25 +0000555
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000556 IdentifierInfo *Name = IdTok.getIdentifierInfo();
557 LookupResult Lookup(*this, Name, IdTok.getLocation(), LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +0000558 LookupParsedName(Lookup, curScope, nullptr, true);
Ted Kremenekfd14fad2009-03-23 22:28:25 +0000559
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000560 if (Lookup.empty()) {
561 Diag(PragmaLoc, diag::warn_pragma_unused_undeclared_var)
562 << Name << SourceRange(IdTok.getLocation());
563 return;
Ted Kremenekfd14fad2009-03-23 22:28:25 +0000564 }
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000565
566 VarDecl *VD = Lookup.getAsSingle<VarDecl>();
Argyrios Kyrtzidisff115a22011-01-27 18:16:48 +0000567 if (!VD) {
568 Diag(PragmaLoc, diag::warn_pragma_unused_expected_var_arg)
Argyrios Kyrtzidisee569622011-01-17 18:58:44 +0000569 << Name << SourceRange(IdTok.getLocation());
570 return;
571 }
572
573 // Warn if this was used before being marked unused.
574 if (VD->isUsed())
575 Diag(PragmaLoc, diag::warn_used_but_marked_unused) << Name;
576
Erich Keane6a24e802019-09-13 17:39:31 +0000577 VD->addAttr(UnusedAttr::CreateImplicit(Context, IdTok.getLocation(),
578 AttributeCommonInfo::AS_Pragma,
579 UnusedAttr::GNU_unused));
Ted Kremenekfd14fad2009-03-23 22:28:25 +0000580}
Eli Friedman570024a2010-08-05 06:57:20 +0000581
John McCall32f5fe12011-09-30 05:12:12 +0000582void Sema::AddCFAuditedAttribute(Decl *D) {
Erich Keane6a24e802019-09-13 17:39:31 +0000583 IdentifierInfo *Ident;
584 SourceLocation Loc;
585 std::tie(Ident, Loc) = PP.getPragmaARCCFCodeAuditedInfo();
John McCall32f5fe12011-09-30 05:12:12 +0000586 if (!Loc.isValid()) return;
587
588 // Don't add a redundant or conflicting attribute.
589 if (D->hasAttr<CFAuditedTransferAttr>() ||
590 D->hasAttr<CFUnknownTransferAttr>())
591 return;
592
Erich Keane6a24e802019-09-13 17:39:31 +0000593 AttributeCommonInfo Info(Ident, SourceRange(Loc),
594 AttributeCommonInfo::AS_Pragma);
595 D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Info));
John McCall32f5fe12011-09-30 05:12:12 +0000596}
597
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000598namespace {
599
600Optional<attr::SubjectMatchRule>
601getParentAttrMatcherRule(attr::SubjectMatchRule Rule) {
602 using namespace attr;
603 switch (Rule) {
604 default:
605 return None;
606#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
607#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
608 case Value: \
609 return Parent;
610#include "clang/Basic/AttrSubMatchRulesList.inc"
611 }
612}
613
614bool isNegatedAttrMatcherSubRule(attr::SubjectMatchRule Rule) {
615 using namespace attr;
616 switch (Rule) {
617 default:
618 return false;
619#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract)
620#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, IsNegated) \
621 case Value: \
622 return IsNegated;
623#include "clang/Basic/AttrSubMatchRulesList.inc"
624 }
625}
626
627CharSourceRange replacementRangeForListElement(const Sema &S,
628 SourceRange Range) {
629 // Make sure that the ',' is removed as well.
630 SourceLocation AfterCommaLoc = Lexer::findLocationAfterToken(
631 Range.getEnd(), tok::comma, S.getSourceManager(), S.getLangOpts(),
632 /*SkipTrailingWhitespaceAndNewLine=*/false);
633 if (AfterCommaLoc.isValid())
634 return CharSourceRange::getCharRange(Range.getBegin(), AfterCommaLoc);
635 else
636 return CharSourceRange::getTokenRange(Range);
637}
638
639std::string
640attrMatcherRuleListToString(ArrayRef<attr::SubjectMatchRule> Rules) {
641 std::string Result;
642 llvm::raw_string_ostream OS(Result);
643 for (const auto &I : llvm::enumerate(Rules)) {
644 if (I.index())
645 OS << (I.index() == Rules.size() - 1 ? ", and " : ", ");
646 OS << "'" << attr::getSubjectMatchRuleSpelling(I.value()) << "'";
647 }
648 return OS.str();
649}
650
651} // end anonymous namespace
652
Erik Pilkington7d180942018-10-29 17:38:42 +0000653void Sema::ActOnPragmaAttributeAttribute(
654 ParsedAttr &Attribute, SourceLocation PragmaLoc,
655 attr::ParsedSubjectMatchRuleSet Rules) {
Alex Lorenz3cfe9d52019-01-24 19:14:39 +0000656 Attribute.setIsPragmaClangAttribute();
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000657 SmallVector<attr::SubjectMatchRule, 4> SubjectMatchRules;
658 // Gather the subject match rules that are supported by the attribute.
659 SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4>
660 StrictSubjectMatchRuleSet;
661 Attribute.getMatchRules(LangOpts, StrictSubjectMatchRuleSet);
662
663 // Figure out which subject matching rules are valid.
664 if (StrictSubjectMatchRuleSet.empty()) {
665 // Check for contradicting match rules. Contradicting match rules are
666 // either:
667 // - a top-level rule and one of its sub-rules. E.g. variable and
668 // variable(is_parameter).
669 // - a sub-rule and a sibling that's negated. E.g.
670 // variable(is_thread_local) and variable(unless(is_parameter))
Alex Lorenz26b47652017-04-18 20:54:23 +0000671 llvm::SmallDenseMap<int, std::pair<int, SourceRange>, 2>
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000672 RulesToFirstSpecifiedNegatedSubRule;
673 for (const auto &Rule : Rules) {
Alex Lorenz26b47652017-04-18 20:54:23 +0000674 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000675 Optional<attr::SubjectMatchRule> ParentRule =
Alex Lorenz26b47652017-04-18 20:54:23 +0000676 getParentAttrMatcherRule(MatchRule);
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000677 if (!ParentRule)
678 continue;
679 auto It = Rules.find(*ParentRule);
680 if (It != Rules.end()) {
681 // A sub-rule contradicts a parent rule.
682 Diag(Rule.second.getBegin(),
683 diag::err_pragma_attribute_matcher_subrule_contradicts_rule)
Alex Lorenz26b47652017-04-18 20:54:23 +0000684 << attr::getSubjectMatchRuleSpelling(MatchRule)
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000685 << attr::getSubjectMatchRuleSpelling(*ParentRule) << It->second
686 << FixItHint::CreateRemoval(
687 replacementRangeForListElement(*this, Rule.second));
688 // Keep going without removing this rule as it won't change the set of
689 // declarations that receive the attribute.
690 continue;
691 }
Alex Lorenz26b47652017-04-18 20:54:23 +0000692 if (isNegatedAttrMatcherSubRule(MatchRule))
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000693 RulesToFirstSpecifiedNegatedSubRule.insert(
694 std::make_pair(*ParentRule, Rule));
695 }
696 bool IgnoreNegatedSubRules = false;
697 for (const auto &Rule : Rules) {
Alex Lorenz26b47652017-04-18 20:54:23 +0000698 attr::SubjectMatchRule MatchRule = attr::SubjectMatchRule(Rule.first);
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000699 Optional<attr::SubjectMatchRule> ParentRule =
Alex Lorenz26b47652017-04-18 20:54:23 +0000700 getParentAttrMatcherRule(MatchRule);
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000701 if (!ParentRule)
702 continue;
703 auto It = RulesToFirstSpecifiedNegatedSubRule.find(*ParentRule);
704 if (It != RulesToFirstSpecifiedNegatedSubRule.end() &&
705 It->second != Rule) {
706 // Negated sub-rule contradicts another sub-rule.
707 Diag(
708 It->second.second.getBegin(),
709 diag::
710 err_pragma_attribute_matcher_negated_subrule_contradicts_subrule)
Alex Lorenz26b47652017-04-18 20:54:23 +0000711 << attr::getSubjectMatchRuleSpelling(
712 attr::SubjectMatchRule(It->second.first))
713 << attr::getSubjectMatchRuleSpelling(MatchRule) << Rule.second
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000714 << FixItHint::CreateRemoval(
715 replacementRangeForListElement(*this, It->second.second));
716 // Keep going but ignore all of the negated sub-rules.
717 IgnoreNegatedSubRules = true;
718 RulesToFirstSpecifiedNegatedSubRule.erase(It);
719 }
720 }
721
722 if (!IgnoreNegatedSubRules) {
723 for (const auto &Rule : Rules)
Alex Lorenz26b47652017-04-18 20:54:23 +0000724 SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000725 } else {
726 for (const auto &Rule : Rules) {
Alex Lorenz26b47652017-04-18 20:54:23 +0000727 if (!isNegatedAttrMatcherSubRule(attr::SubjectMatchRule(Rule.first)))
728 SubjectMatchRules.push_back(attr::SubjectMatchRule(Rule.first));
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000729 }
730 }
731 Rules.clear();
732 } else {
733 for (const auto &Rule : StrictSubjectMatchRuleSet) {
734 if (Rules.erase(Rule.first)) {
735 // Add the rule to the set of attribute receivers only if it's supported
736 // in the current language mode.
737 if (Rule.second)
738 SubjectMatchRules.push_back(Rule.first);
739 }
740 }
741 }
742
743 if (!Rules.empty()) {
744 auto Diagnostic =
745 Diag(PragmaLoc, diag::err_pragma_attribute_invalid_matchers)
Erich Keane6a24e802019-09-13 17:39:31 +0000746 << Attribute;
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000747 SmallVector<attr::SubjectMatchRule, 2> ExtraRules;
748 for (const auto &Rule : Rules) {
Alex Lorenz26b47652017-04-18 20:54:23 +0000749 ExtraRules.push_back(attr::SubjectMatchRule(Rule.first));
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000750 Diagnostic << FixItHint::CreateRemoval(
751 replacementRangeForListElement(*this, Rule.second));
752 }
753 Diagnostic << attrMatcherRuleListToString(ExtraRules);
754 }
755
Erik Pilkington7d180942018-10-29 17:38:42 +0000756 if (PragmaAttributeStack.empty()) {
757 Diag(PragmaLoc, diag::err_pragma_attr_attr_no_push);
758 return;
759 }
760
761 PragmaAttributeStack.back().Entries.push_back(
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000762 {PragmaLoc, &Attribute, std::move(SubjectMatchRules), /*IsUsed=*/false});
763}
764
Erik Pilkington0876cae2018-12-20 22:32:04 +0000765void Sema::ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
766 const IdentifierInfo *Namespace) {
Erik Pilkington7d180942018-10-29 17:38:42 +0000767 PragmaAttributeStack.emplace_back();
768 PragmaAttributeStack.back().Loc = PragmaLoc;
Erik Pilkington0876cae2018-12-20 22:32:04 +0000769 PragmaAttributeStack.back().Namespace = Namespace;
Erik Pilkington7d180942018-10-29 17:38:42 +0000770}
771
Erik Pilkington0876cae2018-12-20 22:32:04 +0000772void Sema::ActOnPragmaAttributePop(SourceLocation PragmaLoc,
773 const IdentifierInfo *Namespace) {
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000774 if (PragmaAttributeStack.empty()) {
Erik Pilkington0876cae2018-12-20 22:32:04 +0000775 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000776 return;
777 }
Erik Pilkington7d180942018-10-29 17:38:42 +0000778
Erik Pilkington0876cae2018-12-20 22:32:04 +0000779 // Dig back through the stack trying to find the most recently pushed group
780 // that in Namespace. Note that this works fine if no namespace is present,
781 // think of push/pops without namespaces as having an implicit "nullptr"
782 // namespace.
783 for (size_t Index = PragmaAttributeStack.size(); Index;) {
784 --Index;
785 if (PragmaAttributeStack[Index].Namespace == Namespace) {
786 for (const PragmaAttributeEntry &Entry :
787 PragmaAttributeStack[Index].Entries) {
788 if (!Entry.IsUsed) {
789 assert(Entry.Attribute && "Expected an attribute");
790 Diag(Entry.Attribute->getLoc(), diag::warn_pragma_attribute_unused)
791 << *Entry.Attribute;
792 Diag(PragmaLoc, diag::note_pragma_attribute_region_ends_here);
793 }
794 }
795 PragmaAttributeStack.erase(PragmaAttributeStack.begin() + Index);
796 return;
Erik Pilkington7d180942018-10-29 17:38:42 +0000797 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000798 }
Erik Pilkington7d180942018-10-29 17:38:42 +0000799
Erik Pilkington0876cae2018-12-20 22:32:04 +0000800 if (Namespace)
801 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch)
802 << 0 << Namespace->getName();
803 else
804 Diag(PragmaLoc, diag::err_pragma_attribute_stack_mismatch) << 1;
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000805}
806
807void Sema::AddPragmaAttributes(Scope *S, Decl *D) {
808 if (PragmaAttributeStack.empty())
809 return;
Erik Pilkington7d180942018-10-29 17:38:42 +0000810 for (auto &Group : PragmaAttributeStack) {
811 for (auto &Entry : Group.Entries) {
812 ParsedAttr *Attribute = Entry.Attribute;
813 assert(Attribute && "Expected an attribute");
Alex Lorenz3cfe9d52019-01-24 19:14:39 +0000814 assert(Attribute->isPragmaClangAttribute() &&
815 "expected #pragma clang attribute");
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000816
Erik Pilkington7d180942018-10-29 17:38:42 +0000817 // Ensure that the attribute can be applied to the given declaration.
818 bool Applies = false;
819 for (const auto &Rule : Entry.MatchRules) {
820 if (Attribute->appliesToDecl(D, Rule)) {
821 Applies = true;
822 break;
823 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000824 }
Erik Pilkington7d180942018-10-29 17:38:42 +0000825 if (!Applies)
826 continue;
827 Entry.IsUsed = true;
828 PragmaAttributeCurrentTargetDecl = D;
829 ParsedAttributesView Attrs;
830 Attrs.addAtEnd(Attribute);
831 ProcessDeclAttributeList(S, D, Attrs);
832 PragmaAttributeCurrentTargetDecl = nullptr;
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000833 }
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000834 }
835}
836
837void Sema::PrintPragmaAttributeInstantiationPoint() {
838 assert(PragmaAttributeCurrentTargetDecl && "Expected an active declaration");
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000839 Diags.Report(PragmaAttributeCurrentTargetDecl->getBeginLoc(),
Alex Lorenz9e7bf162017-04-18 14:33:39 +0000840 diag::note_pragma_attribute_applied_decl_here);
841}
842
843void Sema::DiagnoseUnterminatedPragmaAttribute() {
844 if (PragmaAttributeStack.empty())
845 return;
846 Diag(PragmaAttributeStack.back().Loc, diag::err_pragma_attribute_no_pop_eof);
847}
848
Dario Domizioli13a0a382014-05-23 12:13:25 +0000849void Sema::ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc) {
850 if(On)
851 OptimizeOffPragmaLocation = SourceLocation();
852 else
853 OptimizeOffPragmaLocation = PragmaLoc;
854}
855
856void Sema::AddRangeBasedOptnone(FunctionDecl *FD) {
857 // In the future, check other pragmas if they're implemented (e.g. pragma
858 // optimize 0 will probably map to this functionality too).
859 if(OptimizeOffPragmaLocation.isValid())
860 AddOptnoneAttributeIfNoConflicts(FD, OptimizeOffPragmaLocation);
861}
862
Fangrui Song6907ce22018-07-30 19:24:48 +0000863void Sema::AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD,
Dario Domizioli13a0a382014-05-23 12:13:25 +0000864 SourceLocation Loc) {
865 // Don't add a conflicting attribute. No diagnostic is needed.
866 if (FD->hasAttr<MinSizeAttr>() || FD->hasAttr<AlwaysInlineAttr>())
867 return;
868
869 // Add attributes only if required. Optnone requires noinline as well, but if
870 // either is already present then don't bother adding them.
871 if (!FD->hasAttr<OptimizeNoneAttr>())
872 FD->addAttr(OptimizeNoneAttr::CreateImplicit(Context, Loc));
873 if (!FD->hasAttr<NoInlineAttr>())
874 FD->addAttr(NoInlineAttr::CreateImplicit(Context, Loc));
875}
876
John McCall2faf32c2010-12-10 02:59:44 +0000877typedef std::vector<std::pair<unsigned, SourceLocation> > VisStack;
Alp Tokerceb95c42014-03-02 03:20:16 +0000878enum : unsigned { NoVisibility = ~0U };
Eli Friedman570024a2010-08-05 06:57:20 +0000879
880void Sema::AddPushedVisibilityAttribute(Decl *D) {
881 if (!VisContext)
882 return;
883
Rafael Espindola54606d52012-12-25 07:31:49 +0000884 NamedDecl *ND = dyn_cast<NamedDecl>(D);
John McCalld041a9b2013-02-20 01:54:26 +0000885 if (ND && ND->getExplicitVisibility(NamedDecl::VisibilityForValue))
Eli Friedman570024a2010-08-05 06:57:20 +0000886 return;
887
888 VisStack *Stack = static_cast<VisStack*>(VisContext);
John McCall2faf32c2010-12-10 02:59:44 +0000889 unsigned rawType = Stack->back().first;
890 if (rawType == NoVisibility) return;
891
892 VisibilityAttr::VisibilityType type
893 = (VisibilityAttr::VisibilityType) rawType;
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000894 SourceLocation loc = Stack->back().second;
Eli Friedman570024a2010-08-05 06:57:20 +0000895
Aaron Ballman36a53502014-01-16 13:03:14 +0000896 D->addAttr(VisibilityAttr::CreateImplicit(Context, type, loc));
Eli Friedman570024a2010-08-05 06:57:20 +0000897}
898
899/// FreeVisContext - Deallocate and null out VisContext.
900void Sema::FreeVisContext() {
901 delete static_cast<VisStack*>(VisContext);
Craig Topperc3ec1492014-05-26 06:22:03 +0000902 VisContext = nullptr;
Eli Friedman570024a2010-08-05 06:57:20 +0000903}
904
John McCall2faf32c2010-12-10 02:59:44 +0000905static void PushPragmaVisibility(Sema &S, unsigned type, SourceLocation loc) {
John McCallb1be5232010-08-26 09:15:37 +0000906 // Put visibility on stack.
907 if (!S.VisContext)
908 S.VisContext = new VisStack;
909
910 VisStack *Stack = static_cast<VisStack*>(S.VisContext);
911 Stack->push_back(std::make_pair(type, loc));
912}
913
Rafael Espindolade15baf2012-01-21 05:43:40 +0000914void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
Eli Friedman570024a2010-08-05 06:57:20 +0000915 SourceLocation PragmaLoc) {
Rafael Espindolade15baf2012-01-21 05:43:40 +0000916 if (VisType) {
Eli Friedman570024a2010-08-05 06:57:20 +0000917 // Compute visibility to use.
Aaron Ballman682ee422013-09-11 19:47:58 +0000918 VisibilityAttr::VisibilityType T;
919 if (!VisibilityAttr::ConvertStrToVisibilityType(VisType->getName(), T)) {
920 Diag(PragmaLoc, diag::warn_attribute_unknown_visibility) << VisType;
Eli Friedman570024a2010-08-05 06:57:20 +0000921 return;
922 }
Aaron Ballman682ee422013-09-11 19:47:58 +0000923 PushPragmaVisibility(*this, T, PragmaLoc);
Eli Friedman570024a2010-08-05 06:57:20 +0000924 } else {
Rafael Espindola6d65d7b2012-02-01 23:24:59 +0000925 PopPragmaVisibility(false, PragmaLoc);
Eli Friedman570024a2010-08-05 06:57:20 +0000926 }
927}
928
Adam Nemet60d32642017-04-04 21:18:36 +0000929void Sema::ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC) {
930 switch (FPC) {
931 case LangOptions::FPC_On:
Adam Nemet049a31d2017-03-29 21:54:24 +0000932 FPFeatures.setAllowFPContractWithinStatement();
Peter Collingbourne564c0fa2011-02-14 01:42:35 +0000933 break;
Adam Nemet60d32642017-04-04 21:18:36 +0000934 case LangOptions::FPC_Fast:
935 FPFeatures.setAllowFPContractAcrossStatement();
Peter Collingbourne564c0fa2011-02-14 01:42:35 +0000936 break;
Adam Nemet60d32642017-04-04 21:18:36 +0000937 case LangOptions::FPC_Off:
938 FPFeatures.setDisallowFPContract();
Peter Collingbourne564c0fa2011-02-14 01:42:35 +0000939 break;
940 }
941}
942
Serge Pavlov4aea70e2019-08-07 23:31:26 +0700943void Sema::setRoundingMode(LangOptions::FPRoundingModeKind FPR) {
944 FPFeatures.setRoundingMode(FPR);
945}
946
947void Sema::setExceptionMode(LangOptions::FPExceptionModeKind FPE) {
948 FPFeatures.setExceptionMode(FPE);
949}
950
Kevin P. Neal2c0bc8b2018-08-14 17:06:56 +0000951void Sema::ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC) {
952 switch (FPC) {
953 case LangOptions::FEA_On:
954 FPFeatures.setAllowFEnvAccess();
955 break;
956 case LangOptions::FEA_Off:
957 FPFeatures.setDisallowFEnvAccess();
958 break;
959 }
960}
961
962
Rafael Espindola6d65d7b2012-02-01 23:24:59 +0000963void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
964 SourceLocation Loc) {
John McCall2faf32c2010-12-10 02:59:44 +0000965 // Visibility calculations will consider the namespace's visibility.
966 // Here we just want to note that we're in a visibility context
967 // which overrides any enclosing #pragma context, but doesn't itself
968 // contribute visibility.
Rafael Espindola6d65d7b2012-02-01 23:24:59 +0000969 PushPragmaVisibility(*this, NoVisibility, Loc);
Eli Friedman570024a2010-08-05 06:57:20 +0000970}
971
Rafael Espindola6d65d7b2012-02-01 23:24:59 +0000972void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc) {
973 if (!VisContext) {
974 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
975 return;
Eli Friedman570024a2010-08-05 06:57:20 +0000976 }
Rafael Espindola6d65d7b2012-02-01 23:24:59 +0000977
978 // Pop visibility from stack
979 VisStack *Stack = static_cast<VisStack*>(VisContext);
980
981 const std::pair<unsigned, SourceLocation> *Back = &Stack->back();
982 bool StartsWithPragma = Back->first != NoVisibility;
983 if (StartsWithPragma && IsNamespaceEnd) {
984 Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
985 Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
986
987 // For better error recovery, eat all pushes inside the namespace.
988 do {
989 Stack->pop_back();
990 Back = &Stack->back();
991 StartsWithPragma = Back->first != NoVisibility;
992 } while (StartsWithPragma);
993 } else if (!StartsWithPragma && !IsNamespaceEnd) {
994 Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
995 Diag(Back->second, diag::note_surrounding_namespace_starts_here);
996 return;
997 }
998
999 Stack->pop_back();
1000 // To simplify the implementation, never keep around an empty stack.
1001 if (Stack->empty())
1002 FreeVisContext();
Eli Friedman570024a2010-08-05 06:57:20 +00001003}