Coverage Report

Created: 2020-09-22 08:39

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