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