Sema.cpp 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632
  1. //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
  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 the actions class which performs semantic analysis and
  10. // builds an AST out of a parse stream.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "UsedDeclVisitor.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTDiagnostic.h"
  16. #include "clang/AST/Decl.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/DeclFriend.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/PrettyDeclStackTrace.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/Basic/DarwinSDKInfo.h"
  25. #include "clang/Basic/DiagnosticOptions.h"
  26. #include "clang/Basic/PartialDiagnostic.h"
  27. #include "clang/Basic/SourceManager.h"
  28. #include "clang/Basic/Stack.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Lex/HeaderSearch.h"
  31. #include "clang/Lex/HeaderSearchOptions.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "clang/Sema/CXXFieldCollector.h"
  34. #include "clang/Sema/DelayedDiagnostic.h"
  35. #include "clang/Sema/ExternalSemaSource.h"
  36. #include "clang/Sema/Initialization.h"
  37. #include "clang/Sema/MultiplexExternalSemaSource.h"
  38. #include "clang/Sema/ObjCMethodList.h"
  39. #include "clang/Sema/Scope.h"
  40. #include "clang/Sema/ScopeInfo.h"
  41. #include "clang/Sema/SemaConsumer.h"
  42. #include "clang/Sema/SemaInternal.h"
  43. #include "clang/Sema/TemplateDeduction.h"
  44. #include "clang/Sema/TemplateInstCallback.h"
  45. #include "clang/Sema/TypoCorrection.h"
  46. #include "llvm/ADT/DenseMap.h"
  47. #include "llvm/ADT/SmallPtrSet.h"
  48. #include "llvm/Support/TimeProfiler.h"
  49. using namespace clang;
  50. using namespace sema;
  51. SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
  52. return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
  53. }
  54. ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
  55. DarwinSDKInfo *
  56. Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
  57. StringRef Platform) {
  58. auto *SDKInfo = getDarwinSDKInfoForAvailabilityChecking();
  59. if (!SDKInfo && !WarnedDarwinSDKInfoMissing) {
  60. Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)
  61. << Platform;
  62. WarnedDarwinSDKInfoMissing = true;
  63. }
  64. return SDKInfo;
  65. }
  66. DarwinSDKInfo *Sema::getDarwinSDKInfoForAvailabilityChecking() {
  67. if (CachedDarwinSDKInfo)
  68. return CachedDarwinSDKInfo->get();
  69. auto SDKInfo = parseDarwinSDKInfo(
  70. PP.getFileManager().getVirtualFileSystem(),
  71. PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot);
  72. if (SDKInfo && *SDKInfo) {
  73. CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));
  74. return CachedDarwinSDKInfo->get();
  75. }
  76. if (!SDKInfo)
  77. llvm::consumeError(SDKInfo.takeError());
  78. CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
  79. return nullptr;
  80. }
  81. IdentifierInfo *
  82. Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
  83. unsigned int Index) {
  84. std::string InventedName;
  85. llvm::raw_string_ostream OS(InventedName);
  86. if (!ParamName)
  87. OS << "auto:" << Index + 1;
  88. else
  89. OS << ParamName->getName() << ":auto";
  90. OS.flush();
  91. return &Context.Idents.get(OS.str());
  92. }
  93. PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
  94. const Preprocessor &PP) {
  95. PrintingPolicy Policy = Context.getPrintingPolicy();
  96. // In diagnostics, we print _Bool as bool if the latter is defined as the
  97. // former.
  98. Policy.Bool = Context.getLangOpts().Bool;
  99. if (!Policy.Bool) {
  100. if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
  101. Policy.Bool = BoolMacro->isObjectLike() &&
  102. BoolMacro->getNumTokens() == 1 &&
  103. BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
  104. }
  105. }
  106. return Policy;
  107. }
  108. void Sema::ActOnTranslationUnitScope(Scope *S) {
  109. TUScope = S;
  110. PushDeclContext(S, Context.getTranslationUnitDecl());
  111. }
  112. namespace clang {
  113. namespace sema {
  114. class SemaPPCallbacks : public PPCallbacks {
  115. Sema *S = nullptr;
  116. llvm::SmallVector<SourceLocation, 8> IncludeStack;
  117. public:
  118. void set(Sema &S) { this->S = &S; }
  119. void reset() { S = nullptr; }
  120. virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  121. SrcMgr::CharacteristicKind FileType,
  122. FileID PrevFID) override {
  123. if (!S)
  124. return;
  125. switch (Reason) {
  126. case EnterFile: {
  127. SourceManager &SM = S->getSourceManager();
  128. SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
  129. if (IncludeLoc.isValid()) {
  130. if (llvm::timeTraceProfilerEnabled()) {
  131. const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
  132. llvm::timeTraceProfilerBegin(
  133. "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>"));
  134. }
  135. IncludeStack.push_back(IncludeLoc);
  136. S->DiagnoseNonDefaultPragmaAlignPack(
  137. Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude,
  138. IncludeLoc);
  139. }
  140. break;
  141. }
  142. case ExitFile:
  143. if (!IncludeStack.empty()) {
  144. if (llvm::timeTraceProfilerEnabled())
  145. llvm::timeTraceProfilerEnd();
  146. S->DiagnoseNonDefaultPragmaAlignPack(
  147. Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit,
  148. IncludeStack.pop_back_val());
  149. }
  150. break;
  151. default:
  152. break;
  153. }
  154. }
  155. };
  156. } // end namespace sema
  157. } // end namespace clang
  158. const unsigned Sema::MaxAlignmentExponent;
  159. const uint64_t Sema::MaximumAlignment;
  160. Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
  161. TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
  162. : ExternalSource(nullptr), isMultiplexExternalSource(false),
  163. CurFPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
  164. Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
  165. SourceMgr(PP.getSourceManager()), CollectStats(false),
  166. CodeCompleter(CodeCompleter), CurContext(nullptr),
  167. OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
  168. MSPointerToMemberRepresentationMethod(
  169. LangOpts.getMSPointerToMemberRepresentationMethod()),
  170. VtorDispStack(LangOpts.getVtorDispMode()),
  171. AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),
  172. DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
  173. CodeSegStack(nullptr), FpPragmaStack(FPOptionsOverride()),
  174. CurInitSeg(nullptr), VisContext(nullptr),
  175. PragmaAttributeCurrentTargetDecl(nullptr),
  176. IsBuildingRecoveryCallExpr(false), LateTemplateParser(nullptr),
  177. LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
  178. StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
  179. StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr),
  180. MSVCGuidDecl(nullptr), NSNumberDecl(nullptr), NSValueDecl(nullptr),
  181. NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
  182. ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
  183. ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
  184. DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
  185. TUKind(TUKind), NumSFINAEErrors(0),
  186. FullyCheckedComparisonCategories(
  187. static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
  188. SatisfactionCache(Context), AccessCheckingSFINAE(false),
  189. InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
  190. ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
  191. DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
  192. ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
  193. CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
  194. assert(pp.TUKind == TUKind);
  195. TUScope = nullptr;
  196. isConstantEvaluatedOverride = false;
  197. LoadedExternalKnownNamespaces = false;
  198. for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
  199. NSNumberLiteralMethods[I] = nullptr;
  200. if (getLangOpts().ObjC)
  201. NSAPIObj.reset(new NSAPI(Context));
  202. if (getLangOpts().CPlusPlus)
  203. FieldCollector.reset(new CXXFieldCollector());
  204. // Tell diagnostics how to render things from the AST library.
  205. Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
  206. ExprEvalContexts.emplace_back(
  207. ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
  208. nullptr, ExpressionEvaluationContextRecord::EK_Other);
  209. // Initialization of data sharing attributes stack for OpenMP
  210. InitDataSharingAttributesStack();
  211. std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
  212. std::make_unique<sema::SemaPPCallbacks>();
  213. SemaPPCallbackHandler = Callbacks.get();
  214. PP.addPPCallbacks(std::move(Callbacks));
  215. SemaPPCallbackHandler->set(*this);
  216. }
  217. // Anchor Sema's type info to this TU.
  218. void Sema::anchor() {}
  219. void Sema::addImplicitTypedef(StringRef Name, QualType T) {
  220. DeclarationName DN = &Context.Idents.get(Name);
  221. if (IdResolver.begin(DN) == IdResolver.end())
  222. PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
  223. }
  224. void Sema::Initialize() {
  225. if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
  226. SC->InitializeSema(*this);
  227. // Tell the external Sema source about this Sema object.
  228. if (ExternalSemaSource *ExternalSema
  229. = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
  230. ExternalSema->InitializeSema(*this);
  231. // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
  232. // will not be able to merge any duplicate __va_list_tag decls correctly.
  233. VAListTagName = PP.getIdentifierInfo("__va_list_tag");
  234. if (!TUScope)
  235. return;
  236. // Initialize predefined 128-bit integer types, if needed.
  237. if (Context.getTargetInfo().hasInt128Type() ||
  238. (Context.getAuxTargetInfo() &&
  239. Context.getAuxTargetInfo()->hasInt128Type())) {
  240. // If either of the 128-bit integer types are unavailable to name lookup,
  241. // define them now.
  242. DeclarationName Int128 = &Context.Idents.get("__int128_t");
  243. if (IdResolver.begin(Int128) == IdResolver.end())
  244. PushOnScopeChains(Context.getInt128Decl(), TUScope);
  245. DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
  246. if (IdResolver.begin(UInt128) == IdResolver.end())
  247. PushOnScopeChains(Context.getUInt128Decl(), TUScope);
  248. }
  249. // Initialize predefined Objective-C types:
  250. if (getLangOpts().ObjC) {
  251. // If 'SEL' does not yet refer to any declarations, make it refer to the
  252. // predefined 'SEL'.
  253. DeclarationName SEL = &Context.Idents.get("SEL");
  254. if (IdResolver.begin(SEL) == IdResolver.end())
  255. PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
  256. // If 'id' does not yet refer to any declarations, make it refer to the
  257. // predefined 'id'.
  258. DeclarationName Id = &Context.Idents.get("id");
  259. if (IdResolver.begin(Id) == IdResolver.end())
  260. PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
  261. // Create the built-in typedef for 'Class'.
  262. DeclarationName Class = &Context.Idents.get("Class");
  263. if (IdResolver.begin(Class) == IdResolver.end())
  264. PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
  265. // Create the built-in forward declaratino for 'Protocol'.
  266. DeclarationName Protocol = &Context.Idents.get("Protocol");
  267. if (IdResolver.begin(Protocol) == IdResolver.end())
  268. PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
  269. }
  270. // Create the internal type for the *StringMakeConstantString builtins.
  271. DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
  272. if (IdResolver.begin(ConstantString) == IdResolver.end())
  273. PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
  274. // Initialize Microsoft "predefined C++ types".
  275. if (getLangOpts().MSVCCompat) {
  276. if (getLangOpts().CPlusPlus &&
  277. IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
  278. PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
  279. TUScope);
  280. addImplicitTypedef("size_t", Context.getSizeType());
  281. }
  282. // Initialize predefined OpenCL types and supported extensions and (optional)
  283. // core features.
  284. if (getLangOpts().OpenCL) {
  285. getOpenCLOptions().addSupport(
  286. Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());
  287. addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
  288. addImplicitTypedef("event_t", Context.OCLEventTy);
  289. auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();
  290. if (OCLCompatibleVersion >= 200) {
  291. if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) {
  292. addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
  293. addImplicitTypedef("queue_t", Context.OCLQueueTy);
  294. }
  295. if (getLangOpts().OpenCLPipes)
  296. addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
  297. addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
  298. addImplicitTypedef("atomic_uint",
  299. Context.getAtomicType(Context.UnsignedIntTy));
  300. addImplicitTypedef("atomic_float",
  301. Context.getAtomicType(Context.FloatTy));
  302. // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
  303. // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
  304. addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
  305. // OpenCL v2.0 s6.13.11.6:
  306. // - The atomic_long and atomic_ulong types are supported if the
  307. // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
  308. // extensions are supported.
  309. // - The atomic_double type is only supported if double precision
  310. // is supported and the cl_khr_int64_base_atomics and
  311. // cl_khr_int64_extended_atomics extensions are supported.
  312. // - If the device address space is 64-bits, the data types
  313. // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
  314. // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
  315. // cl_khr_int64_extended_atomics extensions are supported.
  316. auto AddPointerSizeDependentTypes = [&]() {
  317. auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
  318. auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
  319. auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
  320. auto AtomicPtrDiffT =
  321. Context.getAtomicType(Context.getPointerDiffType());
  322. addImplicitTypedef("atomic_size_t", AtomicSizeT);
  323. addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
  324. addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
  325. addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
  326. };
  327. if (Context.getTypeSize(Context.getSizeType()) == 32) {
  328. AddPointerSizeDependentTypes();
  329. }
  330. if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
  331. auto AtomicHalfT = Context.getAtomicType(Context.HalfTy);
  332. addImplicitTypedef("atomic_half", AtomicHalfT);
  333. }
  334. std::vector<QualType> Atomic64BitTypes;
  335. if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
  336. getLangOpts()) &&
  337. getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
  338. getLangOpts())) {
  339. if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
  340. auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
  341. addImplicitTypedef("atomic_double", AtomicDoubleT);
  342. Atomic64BitTypes.push_back(AtomicDoubleT);
  343. }
  344. auto AtomicLongT = Context.getAtomicType(Context.LongTy);
  345. auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
  346. addImplicitTypedef("atomic_long", AtomicLongT);
  347. addImplicitTypedef("atomic_ulong", AtomicULongT);
  348. if (Context.getTypeSize(Context.getSizeType()) == 64) {
  349. AddPointerSizeDependentTypes();
  350. }
  351. }
  352. }
  353. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  354. if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \
  355. addImplicitTypedef(#ExtType, Context.Id##Ty); \
  356. }
  357. #include "clang/Basic/OpenCLExtensionTypes.def"
  358. }
  359. if (Context.getTargetInfo().hasAArch64SVETypes()) {
  360. #define SVE_TYPE(Name, Id, SingletonId) \
  361. addImplicitTypedef(Name, Context.SingletonId);
  362. #include "clang/Basic/AArch64SVEACLETypes.def"
  363. }
  364. if (Context.getTargetInfo().getTriple().isPPC64()) {
  365. #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
  366. addImplicitTypedef(#Name, Context.Id##Ty);
  367. #include "clang/Basic/PPCTypes.def"
  368. #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
  369. addImplicitTypedef(#Name, Context.Id##Ty);
  370. #include "clang/Basic/PPCTypes.def"
  371. }
  372. if (Context.getTargetInfo().hasRISCVVTypes()) {
  373. #define RVV_TYPE(Name, Id, SingletonId) \
  374. addImplicitTypedef(Name, Context.SingletonId);
  375. #include "clang/Basic/RISCVVTypes.def"
  376. }
  377. if (Context.getTargetInfo().hasBuiltinMSVaList()) {
  378. DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
  379. if (IdResolver.begin(MSVaList) == IdResolver.end())
  380. PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
  381. }
  382. DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
  383. if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
  384. PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
  385. }
  386. Sema::~Sema() {
  387. assert(InstantiatingSpecializations.empty() &&
  388. "failed to clean up an InstantiatingTemplate?");
  389. if (VisContext) FreeVisContext();
  390. // Kill all the active scopes.
  391. for (sema::FunctionScopeInfo *FSI : FunctionScopes)
  392. delete FSI;
  393. // Tell the SemaConsumer to forget about us; we're going out of scope.
  394. if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
  395. SC->ForgetSema();
  396. // Detach from the external Sema source.
  397. if (ExternalSemaSource *ExternalSema
  398. = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
  399. ExternalSema->ForgetSema();
  400. // If Sema's ExternalSource is the multiplexer - we own it.
  401. if (isMultiplexExternalSource)
  402. delete ExternalSource;
  403. // Delete cached satisfactions.
  404. std::vector<ConstraintSatisfaction *> Satisfactions;
  405. Satisfactions.reserve(Satisfactions.size());
  406. for (auto &Node : SatisfactionCache)
  407. Satisfactions.push_back(&Node);
  408. for (auto *Node : Satisfactions)
  409. delete Node;
  410. threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
  411. // Destroys data sharing attributes stack for OpenMP
  412. DestroyDataSharingAttributesStack();
  413. // Detach from the PP callback handler which outlives Sema since it's owned
  414. // by the preprocessor.
  415. SemaPPCallbackHandler->reset();
  416. }
  417. void Sema::warnStackExhausted(SourceLocation Loc) {
  418. // Only warn about this once.
  419. if (!WarnedStackExhausted) {
  420. Diag(Loc, diag::warn_stack_exhausted);
  421. WarnedStackExhausted = true;
  422. }
  423. }
  424. void Sema::runWithSufficientStackSpace(SourceLocation Loc,
  425. llvm::function_ref<void()> Fn) {
  426. clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc); }, Fn);
  427. }
  428. /// makeUnavailableInSystemHeader - There is an error in the current
  429. /// context. If we're still in a system header, and we can plausibly
  430. /// make the relevant declaration unavailable instead of erroring, do
  431. /// so and return true.
  432. bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
  433. UnavailableAttr::ImplicitReason reason) {
  434. // If we're not in a function, it's an error.
  435. FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
  436. if (!fn) return false;
  437. // If we're in template instantiation, it's an error.
  438. if (inTemplateInstantiation())
  439. return false;
  440. // If that function's not in a system header, it's an error.
  441. if (!Context.getSourceManager().isInSystemHeader(loc))
  442. return false;
  443. // If the function is already unavailable, it's not an error.
  444. if (fn->hasAttr<UnavailableAttr>()) return true;
  445. fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
  446. return true;
  447. }
  448. ASTMutationListener *Sema::getASTMutationListener() const {
  449. return getASTConsumer().GetASTMutationListener();
  450. }
  451. ///Registers an external source. If an external source already exists,
  452. /// creates a multiplex external source and appends to it.
  453. ///
  454. ///\param[in] E - A non-null external sema source.
  455. ///
  456. void Sema::addExternalSource(ExternalSemaSource *E) {
  457. assert(E && "Cannot use with NULL ptr");
  458. if (!ExternalSource) {
  459. ExternalSource = E;
  460. return;
  461. }
  462. if (isMultiplexExternalSource)
  463. static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
  464. else {
  465. ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
  466. isMultiplexExternalSource = true;
  467. }
  468. }
  469. /// Print out statistics about the semantic analysis.
  470. void Sema::PrintStats() const {
  471. llvm::errs() << "\n*** Semantic Analysis Stats:\n";
  472. llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
  473. BumpAlloc.PrintStats();
  474. AnalysisWarnings.PrintStats();
  475. }
  476. void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
  477. QualType SrcType,
  478. SourceLocation Loc) {
  479. Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
  480. if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable &&
  481. *ExprNullability != NullabilityKind::NullableResult))
  482. return;
  483. Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
  484. if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
  485. return;
  486. Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
  487. }
  488. void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) {
  489. if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
  490. E->getBeginLoc()))
  491. return;
  492. // nullptr only exists from C++11 on, so don't warn on its absence earlier.
  493. if (!getLangOpts().CPlusPlus11)
  494. return;
  495. if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
  496. return;
  497. if (E->IgnoreParenImpCasts()->getType()->isNullPtrType())
  498. return;
  499. // Don't diagnose the conversion from a 0 literal to a null pointer argument
  500. // in a synthesized call to operator<=>.
  501. if (!CodeSynthesisContexts.empty() &&
  502. CodeSynthesisContexts.back().Kind ==
  503. CodeSynthesisContext::RewritingOperatorAsSpaceship)
  504. return;
  505. // If it is a macro from system header, and if the macro name is not "NULL",
  506. // do not warn.
  507. SourceLocation MaybeMacroLoc = E->getBeginLoc();
  508. if (Diags.getSuppressSystemWarnings() &&
  509. SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
  510. !findMacroSpelling(MaybeMacroLoc, "NULL"))
  511. return;
  512. Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
  513. << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
  514. }
  515. /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
  516. /// If there is already an implicit cast, merge into the existing one.
  517. /// The result is of the given category.
  518. ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
  519. CastKind Kind, ExprValueKind VK,
  520. const CXXCastPath *BasePath,
  521. CheckedConversionKind CCK) {
  522. #ifndef NDEBUG
  523. if (VK == VK_PRValue && !E->isPRValue()) {
  524. switch (Kind) {
  525. default:
  526. llvm_unreachable(
  527. ("can't implicitly cast glvalue to prvalue with this cast "
  528. "kind: " +
  529. std::string(CastExpr::getCastKindName(Kind)))
  530. .c_str());
  531. case CK_Dependent:
  532. case CK_LValueToRValue:
  533. case CK_ArrayToPointerDecay:
  534. case CK_FunctionToPointerDecay:
  535. case CK_ToVoid:
  536. case CK_NonAtomicToAtomic:
  537. break;
  538. }
  539. }
  540. assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) &&
  541. "can't cast prvalue to glvalue");
  542. #endif
  543. diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
  544. diagnoseZeroToNullptrConversion(Kind, E);
  545. QualType ExprTy = Context.getCanonicalType(E->getType());
  546. QualType TypeTy = Context.getCanonicalType(Ty);
  547. if (ExprTy == TypeTy)
  548. return E;
  549. if (Kind == CK_ArrayToPointerDecay) {
  550. // C++1z [conv.array]: The temporary materialization conversion is applied.
  551. // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
  552. if (getLangOpts().CPlusPlus && E->isPRValue()) {
  553. // The temporary is an lvalue in C++98 and an xvalue otherwise.
  554. ExprResult Materialized = CreateMaterializeTemporaryExpr(
  555. E->getType(), E, !getLangOpts().CPlusPlus11);
  556. if (Materialized.isInvalid())
  557. return ExprError();
  558. E = Materialized.get();
  559. }
  560. // C17 6.7.1p6 footnote 124: The implementation can treat any register
  561. // declaration simply as an auto declaration. However, whether or not
  562. // addressable storage is actually used, the address of any part of an
  563. // object declared with storage-class specifier register cannot be
  564. // computed, either explicitly(by use of the unary & operator as discussed
  565. // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
  566. // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
  567. // array declared with storage-class specifier register is sizeof.
  568. if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) {
  569. if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  570. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  571. if (VD->getStorageClass() == SC_Register) {
  572. Diag(E->getExprLoc(), diag::err_typecheck_address_of)
  573. << /*register variable*/ 3 << E->getSourceRange();
  574. return ExprError();
  575. }
  576. }
  577. }
  578. }
  579. }
  580. if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
  581. if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
  582. ImpCast->setType(Ty);
  583. ImpCast->setValueKind(VK);
  584. return E;
  585. }
  586. }
  587. return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
  588. CurFPFeatureOverrides());
  589. }
  590. /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
  591. /// to the conversion from scalar type ScalarTy to the Boolean type.
  592. CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
  593. switch (ScalarTy->getScalarTypeKind()) {
  594. case Type::STK_Bool: return CK_NoOp;
  595. case Type::STK_CPointer: return CK_PointerToBoolean;
  596. case Type::STK_BlockPointer: return CK_PointerToBoolean;
  597. case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
  598. case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
  599. case Type::STK_Integral: return CK_IntegralToBoolean;
  600. case Type::STK_Floating: return CK_FloatingToBoolean;
  601. case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
  602. case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
  603. case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
  604. }
  605. llvm_unreachable("unknown scalar type kind");
  606. }
  607. /// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
  608. static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
  609. if (D->getMostRecentDecl()->isUsed())
  610. return true;
  611. if (D->isExternallyVisible())
  612. return true;
  613. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  614. // If this is a function template and none of its specializations is used,
  615. // we should warn.
  616. if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
  617. for (const auto *Spec : Template->specializations())
  618. if (ShouldRemoveFromUnused(SemaRef, Spec))
  619. return true;
  620. // UnusedFileScopedDecls stores the first declaration.
  621. // The declaration may have become definition so check again.
  622. const FunctionDecl *DeclToCheck;
  623. if (FD->hasBody(DeclToCheck))
  624. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  625. // Later redecls may add new information resulting in not having to warn,
  626. // so check again.
  627. DeclToCheck = FD->getMostRecentDecl();
  628. if (DeclToCheck != FD)
  629. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  630. }
  631. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  632. // If a variable usable in constant expressions is referenced,
  633. // don't warn if it isn't used: if the value of a variable is required
  634. // for the computation of a constant expression, it doesn't make sense to
  635. // warn even if the variable isn't odr-used. (isReferenced doesn't
  636. // precisely reflect that, but it's a decent approximation.)
  637. if (VD->isReferenced() &&
  638. VD->mightBeUsableInConstantExpressions(SemaRef->Context))
  639. return true;
  640. if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
  641. // If this is a variable template and none of its specializations is used,
  642. // we should warn.
  643. for (const auto *Spec : Template->specializations())
  644. if (ShouldRemoveFromUnused(SemaRef, Spec))
  645. return true;
  646. // UnusedFileScopedDecls stores the first declaration.
  647. // The declaration may have become definition so check again.
  648. const VarDecl *DeclToCheck = VD->getDefinition();
  649. if (DeclToCheck)
  650. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  651. // Later redecls may add new information resulting in not having to warn,
  652. // so check again.
  653. DeclToCheck = VD->getMostRecentDecl();
  654. if (DeclToCheck != VD)
  655. return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
  656. }
  657. return false;
  658. }
  659. static bool isFunctionOrVarDeclExternC(NamedDecl *ND) {
  660. if (auto *FD = dyn_cast<FunctionDecl>(ND))
  661. return FD->isExternC();
  662. return cast<VarDecl>(ND)->isExternC();
  663. }
  664. /// Determine whether ND is an external-linkage function or variable whose
  665. /// type has no linkage.
  666. bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) {
  667. // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
  668. // because we also want to catch the case where its type has VisibleNoLinkage,
  669. // which does not affect the linkage of VD.
  670. return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
  671. !isExternalFormalLinkage(VD->getType()->getLinkage()) &&
  672. !isFunctionOrVarDeclExternC(VD);
  673. }
  674. /// Obtains a sorted list of functions and variables that are undefined but
  675. /// ODR-used.
  676. void Sema::getUndefinedButUsed(
  677. SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
  678. for (const auto &UndefinedUse : UndefinedButUsed) {
  679. NamedDecl *ND = UndefinedUse.first;
  680. // Ignore attributes that have become invalid.
  681. if (ND->isInvalidDecl()) continue;
  682. // __attribute__((weakref)) is basically a definition.
  683. if (ND->hasAttr<WeakRefAttr>()) continue;
  684. if (isa<CXXDeductionGuideDecl>(ND))
  685. continue;
  686. if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
  687. // An exported function will always be emitted when defined, so even if
  688. // the function is inline, it doesn't have to be emitted in this TU. An
  689. // imported function implies that it has been exported somewhere else.
  690. continue;
  691. }
  692. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  693. if (FD->isDefined())
  694. continue;
  695. if (FD->isExternallyVisible() &&
  696. !isExternalWithNoLinkageType(FD) &&
  697. !FD->getMostRecentDecl()->isInlined() &&
  698. !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  699. continue;
  700. if (FD->getBuiltinID())
  701. continue;
  702. } else {
  703. auto *VD = cast<VarDecl>(ND);
  704. if (VD->hasDefinition() != VarDecl::DeclarationOnly)
  705. continue;
  706. if (VD->isExternallyVisible() &&
  707. !isExternalWithNoLinkageType(VD) &&
  708. !VD->getMostRecentDecl()->isInline() &&
  709. !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
  710. continue;
  711. // Skip VarDecls that lack formal definitions but which we know are in
  712. // fact defined somewhere.
  713. if (VD->isKnownToBeDefined())
  714. continue;
  715. }
  716. Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
  717. }
  718. }
  719. /// checkUndefinedButUsed - Check for undefined objects with internal linkage
  720. /// or that are inline.
  721. static void checkUndefinedButUsed(Sema &S) {
  722. if (S.UndefinedButUsed.empty()) return;
  723. // Collect all the still-undefined entities with internal linkage.
  724. SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
  725. S.getUndefinedButUsed(Undefined);
  726. if (Undefined.empty()) return;
  727. for (auto Undef : Undefined) {
  728. ValueDecl *VD = cast<ValueDecl>(Undef.first);
  729. SourceLocation UseLoc = Undef.second;
  730. if (S.isExternalWithNoLinkageType(VD)) {
  731. // C++ [basic.link]p8:
  732. // A type without linkage shall not be used as the type of a variable
  733. // or function with external linkage unless
  734. // -- the entity has C language linkage
  735. // -- the entity is not odr-used or is defined in the same TU
  736. //
  737. // As an extension, accept this in cases where the type is externally
  738. // visible, since the function or variable actually can be defined in
  739. // another translation unit in that case.
  740. S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
  741. ? diag::ext_undefined_internal_type
  742. : diag::err_undefined_internal_type)
  743. << isa<VarDecl>(VD) << VD;
  744. } else if (!VD->isExternallyVisible()) {
  745. // FIXME: We can promote this to an error. The function or variable can't
  746. // be defined anywhere else, so the program must necessarily violate the
  747. // one definition rule.
  748. bool IsImplicitBase = false;
  749. if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) {
  750. auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
  751. if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
  752. llvm::omp::TraitProperty::
  753. implementation_extension_disable_implicit_base)) {
  754. const auto *Func = cast<FunctionDecl>(
  755. cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());
  756. IsImplicitBase = BaseD->isImplicit() &&
  757. Func->getIdentifier()->isMangledOpenMPVariantName();
  758. }
  759. }
  760. if (!S.getLangOpts().OpenMP || !IsImplicitBase)
  761. S.Diag(VD->getLocation(), diag::warn_undefined_internal)
  762. << isa<VarDecl>(VD) << VD;
  763. } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
  764. (void)FD;
  765. assert(FD->getMostRecentDecl()->isInlined() &&
  766. "used object requires definition but isn't inline or internal?");
  767. // FIXME: This is ill-formed; we should reject.
  768. S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
  769. } else {
  770. assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
  771. "used var requires definition but isn't inline or internal?");
  772. S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
  773. }
  774. if (UseLoc.isValid())
  775. S.Diag(UseLoc, diag::note_used_here);
  776. }
  777. S.UndefinedButUsed.clear();
  778. }
  779. void Sema::LoadExternalWeakUndeclaredIdentifiers() {
  780. if (!ExternalSource)
  781. return;
  782. SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
  783. ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
  784. for (auto &WeakID : WeakIDs)
  785. WeakUndeclaredIdentifiers.insert(WeakID);
  786. }
  787. typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
  788. /// Returns true, if all methods and nested classes of the given
  789. /// CXXRecordDecl are defined in this translation unit.
  790. ///
  791. /// Should only be called from ActOnEndOfTranslationUnit so that all
  792. /// definitions are actually read.
  793. static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
  794. RecordCompleteMap &MNCComplete) {
  795. RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
  796. if (Cache != MNCComplete.end())
  797. return Cache->second;
  798. if (!RD->isCompleteDefinition())
  799. return false;
  800. bool Complete = true;
  801. for (DeclContext::decl_iterator I = RD->decls_begin(),
  802. E = RD->decls_end();
  803. I != E && Complete; ++I) {
  804. if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
  805. Complete = M->isDefined() || M->isDefaulted() ||
  806. (M->isPure() && !isa<CXXDestructorDecl>(M));
  807. else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
  808. // If the template function is marked as late template parsed at this
  809. // point, it has not been instantiated and therefore we have not
  810. // performed semantic analysis on it yet, so we cannot know if the type
  811. // can be considered complete.
  812. Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
  813. F->getTemplatedDecl()->isDefined();
  814. else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
  815. if (R->isInjectedClassName())
  816. continue;
  817. if (R->hasDefinition())
  818. Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
  819. MNCComplete);
  820. else
  821. Complete = false;
  822. }
  823. }
  824. MNCComplete[RD] = Complete;
  825. return Complete;
  826. }
  827. /// Returns true, if the given CXXRecordDecl is fully defined in this
  828. /// translation unit, i.e. all methods are defined or pure virtual and all
  829. /// friends, friend functions and nested classes are fully defined in this
  830. /// translation unit.
  831. ///
  832. /// Should only be called from ActOnEndOfTranslationUnit so that all
  833. /// definitions are actually read.
  834. static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
  835. RecordCompleteMap &RecordsComplete,
  836. RecordCompleteMap &MNCComplete) {
  837. RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
  838. if (Cache != RecordsComplete.end())
  839. return Cache->second;
  840. bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
  841. for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
  842. E = RD->friend_end();
  843. I != E && Complete; ++I) {
  844. // Check if friend classes and methods are complete.
  845. if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
  846. // Friend classes are available as the TypeSourceInfo of the FriendDecl.
  847. if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
  848. Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
  849. else
  850. Complete = false;
  851. } else {
  852. // Friend functions are available through the NamedDecl of FriendDecl.
  853. if (const FunctionDecl *FD =
  854. dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
  855. Complete = FD->isDefined();
  856. else
  857. // This is a template friend, give up.
  858. Complete = false;
  859. }
  860. }
  861. RecordsComplete[RD] = Complete;
  862. return Complete;
  863. }
  864. void Sema::emitAndClearUnusedLocalTypedefWarnings() {
  865. if (ExternalSource)
  866. ExternalSource->ReadUnusedLocalTypedefNameCandidates(
  867. UnusedLocalTypedefNameCandidates);
  868. for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
  869. if (TD->isReferenced())
  870. continue;
  871. Diag(TD->getLocation(), diag::warn_unused_local_typedef)
  872. << isa<TypeAliasDecl>(TD) << TD->getDeclName();
  873. }
  874. UnusedLocalTypedefNameCandidates.clear();
  875. }
  876. /// This is called before the very first declaration in the translation unit
  877. /// is parsed. Note that the ASTContext may have already injected some
  878. /// declarations.
  879. void Sema::ActOnStartOfTranslationUnit() {
  880. if (getLangOpts().ModulesTS &&
  881. (getLangOpts().getCompilingModule() == LangOptions::CMK_ModuleInterface ||
  882. getLangOpts().getCompilingModule() == LangOptions::CMK_None)) {
  883. // We start in an implied global module fragment.
  884. SourceLocation StartOfTU =
  885. SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
  886. ActOnGlobalModuleFragmentDecl(StartOfTU);
  887. ModuleScopes.back().ImplicitGlobalModuleFragment = true;
  888. }
  889. }
  890. void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
  891. // No explicit actions are required at the end of the global module fragment.
  892. if (Kind == TUFragmentKind::Global)
  893. return;
  894. // Transfer late parsed template instantiations over to the pending template
  895. // instantiation list. During normal compilation, the late template parser
  896. // will be installed and instantiating these templates will succeed.
  897. //
  898. // If we are building a TU prefix for serialization, it is also safe to
  899. // transfer these over, even though they are not parsed. The end of the TU
  900. // should be outside of any eager template instantiation scope, so when this
  901. // AST is deserialized, these templates will not be parsed until the end of
  902. // the combined TU.
  903. PendingInstantiations.insert(PendingInstantiations.end(),
  904. LateParsedInstantiations.begin(),
  905. LateParsedInstantiations.end());
  906. LateParsedInstantiations.clear();
  907. // If DefinedUsedVTables ends up marking any virtual member functions it
  908. // might lead to more pending template instantiations, which we then need
  909. // to instantiate.
  910. DefineUsedVTables();
  911. // C++: Perform implicit template instantiations.
  912. //
  913. // FIXME: When we perform these implicit instantiations, we do not
  914. // carefully keep track of the point of instantiation (C++ [temp.point]).
  915. // This means that name lookup that occurs within the template
  916. // instantiation will always happen at the end of the translation unit,
  917. // so it will find some names that are not required to be found. This is
  918. // valid, but we could do better by diagnosing if an instantiation uses a
  919. // name that was not visible at its first point of instantiation.
  920. if (ExternalSource) {
  921. // Load pending instantiations from the external source.
  922. SmallVector<PendingImplicitInstantiation, 4> Pending;
  923. ExternalSource->ReadPendingInstantiations(Pending);
  924. for (auto PII : Pending)
  925. if (auto Func = dyn_cast<FunctionDecl>(PII.first))
  926. Func->setInstantiationIsPending(true);
  927. PendingInstantiations.insert(PendingInstantiations.begin(),
  928. Pending.begin(), Pending.end());
  929. }
  930. {
  931. llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
  932. PerformPendingInstantiations();
  933. }
  934. emitDeferredDiags();
  935. assert(LateParsedInstantiations.empty() &&
  936. "end of TU template instantiation should not create more "
  937. "late-parsed templates");
  938. // Report diagnostics for uncorrected delayed typos. Ideally all of them
  939. // should have been corrected by that time, but it is very hard to cover all
  940. // cases in practice.
  941. for (const auto &Typo : DelayedTypos) {
  942. // We pass an empty TypoCorrection to indicate no correction was performed.
  943. Typo.second.DiagHandler(TypoCorrection());
  944. }
  945. DelayedTypos.clear();
  946. }
  947. /// ActOnEndOfTranslationUnit - This is called at the very end of the
  948. /// translation unit when EOF is reached and all but the top-level scope is
  949. /// popped.
  950. void Sema::ActOnEndOfTranslationUnit() {
  951. assert(DelayedDiagnostics.getCurrentPool() == nullptr
  952. && "reached end of translation unit with a pool attached?");
  953. // If code completion is enabled, don't perform any end-of-translation-unit
  954. // work.
  955. if (PP.isCodeCompletionEnabled())
  956. return;
  957. // Complete translation units and modules define vtables and perform implicit
  958. // instantiations. PCH files do not.
  959. if (TUKind != TU_Prefix) {
  960. DiagnoseUseOfUnimplementedSelectors();
  961. ActOnEndOfTranslationUnitFragment(
  962. !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
  963. Module::PrivateModuleFragment
  964. ? TUFragmentKind::Private
  965. : TUFragmentKind::Normal);
  966. if (LateTemplateParserCleanup)
  967. LateTemplateParserCleanup(OpaqueParser);
  968. CheckDelayedMemberExceptionSpecs();
  969. } else {
  970. // If we are building a TU prefix for serialization, it is safe to transfer
  971. // these over, even though they are not parsed. The end of the TU should be
  972. // outside of any eager template instantiation scope, so when this AST is
  973. // deserialized, these templates will not be parsed until the end of the
  974. // combined TU.
  975. PendingInstantiations.insert(PendingInstantiations.end(),
  976. LateParsedInstantiations.begin(),
  977. LateParsedInstantiations.end());
  978. LateParsedInstantiations.clear();
  979. if (LangOpts.PCHInstantiateTemplates) {
  980. llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
  981. PerformPendingInstantiations();
  982. }
  983. }
  984. DiagnoseUnterminatedPragmaAlignPack();
  985. DiagnoseUnterminatedPragmaAttribute();
  986. // All delayed member exception specs should be checked or we end up accepting
  987. // incompatible declarations.
  988. assert(DelayedOverridingExceptionSpecChecks.empty());
  989. assert(DelayedEquivalentExceptionSpecChecks.empty());
  990. // All dllexport classes should have been processed already.
  991. assert(DelayedDllExportClasses.empty());
  992. assert(DelayedDllExportMemberFunctions.empty());
  993. // Remove file scoped decls that turned out to be used.
  994. UnusedFileScopedDecls.erase(
  995. std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
  996. UnusedFileScopedDecls.end(),
  997. [this](const DeclaratorDecl *DD) {
  998. return ShouldRemoveFromUnused(this, DD);
  999. }),
  1000. UnusedFileScopedDecls.end());
  1001. if (TUKind == TU_Prefix) {
  1002. // Translation unit prefixes don't need any of the checking below.
  1003. if (!PP.isIncrementalProcessingEnabled())
  1004. TUScope = nullptr;
  1005. return;
  1006. }
  1007. // Check for #pragma weak identifiers that were never declared
  1008. LoadExternalWeakUndeclaredIdentifiers();
  1009. for (auto WeakID : WeakUndeclaredIdentifiers) {
  1010. if (WeakID.second.getUsed())
  1011. continue;
  1012. Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
  1013. LookupOrdinaryName);
  1014. if (PrevDecl != nullptr &&
  1015. !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
  1016. Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
  1017. << "'weak'" << ExpectedVariableOrFunction;
  1018. else
  1019. Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
  1020. << WeakID.first;
  1021. }
  1022. if (LangOpts.CPlusPlus11 &&
  1023. !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
  1024. CheckDelegatingCtorCycles();
  1025. if (!Diags.hasErrorOccurred()) {
  1026. if (ExternalSource)
  1027. ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
  1028. checkUndefinedButUsed(*this);
  1029. }
  1030. // A global-module-fragment is only permitted within a module unit.
  1031. bool DiagnosedMissingModuleDeclaration = false;
  1032. if (!ModuleScopes.empty() &&
  1033. ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment &&
  1034. !ModuleScopes.back().ImplicitGlobalModuleFragment) {
  1035. Diag(ModuleScopes.back().BeginLoc,
  1036. diag::err_module_declaration_missing_after_global_module_introducer);
  1037. DiagnosedMissingModuleDeclaration = true;
  1038. }
  1039. if (TUKind == TU_Module) {
  1040. // If we are building a module interface unit, we need to have seen the
  1041. // module declaration by now.
  1042. if (getLangOpts().getCompilingModule() ==
  1043. LangOptions::CMK_ModuleInterface &&
  1044. (ModuleScopes.empty() ||
  1045. !ModuleScopes.back().Module->isModulePurview()) &&
  1046. !DiagnosedMissingModuleDeclaration) {
  1047. // FIXME: Make a better guess as to where to put the module declaration.
  1048. Diag(getSourceManager().getLocForStartOfFile(
  1049. getSourceManager().getMainFileID()),
  1050. diag::err_module_declaration_missing);
  1051. }
  1052. // If we are building a module, resolve all of the exported declarations
  1053. // now.
  1054. if (Module *CurrentModule = PP.getCurrentModule()) {
  1055. ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
  1056. SmallVector<Module *, 2> Stack;
  1057. Stack.push_back(CurrentModule);
  1058. while (!Stack.empty()) {
  1059. Module *Mod = Stack.pop_back_val();
  1060. // Resolve the exported declarations and conflicts.
  1061. // FIXME: Actually complain, once we figure out how to teach the
  1062. // diagnostic client to deal with complaints in the module map at this
  1063. // point.
  1064. ModMap.resolveExports(Mod, /*Complain=*/false);
  1065. ModMap.resolveUses(Mod, /*Complain=*/false);
  1066. ModMap.resolveConflicts(Mod, /*Complain=*/false);
  1067. // Queue the submodules, so their exports will also be resolved.
  1068. Stack.append(Mod->submodule_begin(), Mod->submodule_end());
  1069. }
  1070. }
  1071. // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
  1072. // modules when they are built, not every time they are used.
  1073. emitAndClearUnusedLocalTypedefWarnings();
  1074. }
  1075. // C99 6.9.2p2:
  1076. // A declaration of an identifier for an object that has file
  1077. // scope without an initializer, and without a storage-class
  1078. // specifier or with the storage-class specifier static,
  1079. // constitutes a tentative definition. If a translation unit
  1080. // contains one or more tentative definitions for an identifier,
  1081. // and the translation unit contains no external definition for
  1082. // that identifier, then the behavior is exactly as if the
  1083. // translation unit contains a file scope declaration of that
  1084. // identifier, with the composite type as of the end of the
  1085. // translation unit, with an initializer equal to 0.
  1086. llvm::SmallSet<VarDecl *, 32> Seen;
  1087. for (TentativeDefinitionsType::iterator
  1088. T = TentativeDefinitions.begin(ExternalSource),
  1089. TEnd = TentativeDefinitions.end();
  1090. T != TEnd; ++T) {
  1091. VarDecl *VD = (*T)->getActingDefinition();
  1092. // If the tentative definition was completed, getActingDefinition() returns
  1093. // null. If we've already seen this variable before, insert()'s second
  1094. // return value is false.
  1095. if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
  1096. continue;
  1097. if (const IncompleteArrayType *ArrayT
  1098. = Context.getAsIncompleteArrayType(VD->getType())) {
  1099. // Set the length of the array to 1 (C99 6.9.2p5).
  1100. Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
  1101. llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
  1102. QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One,
  1103. nullptr, ArrayType::Normal, 0);
  1104. VD->setType(T);
  1105. } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
  1106. diag::err_tentative_def_incomplete_type))
  1107. VD->setInvalidDecl();
  1108. // No initialization is performed for a tentative definition.
  1109. CheckCompleteVariableDeclaration(VD);
  1110. // Notify the consumer that we've completed a tentative definition.
  1111. if (!VD->isInvalidDecl())
  1112. Consumer.CompleteTentativeDefinition(VD);
  1113. }
  1114. for (auto D : ExternalDeclarations) {
  1115. if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
  1116. continue;
  1117. Consumer.CompleteExternalDeclaration(D);
  1118. }
  1119. // If there were errors, disable 'unused' warnings since they will mostly be
  1120. // noise. Don't warn for a use from a module: either we should warn on all
  1121. // file-scope declarations in modules or not at all, but whether the
  1122. // declaration is used is immaterial.
  1123. if (!Diags.hasErrorOccurred() && TUKind != TU_Module) {
  1124. // Output warning for unused file scoped decls.
  1125. for (UnusedFileScopedDeclsType::iterator
  1126. I = UnusedFileScopedDecls.begin(ExternalSource),
  1127. E = UnusedFileScopedDecls.end(); I != E; ++I) {
  1128. if (ShouldRemoveFromUnused(this, *I))
  1129. continue;
  1130. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  1131. const FunctionDecl *DiagD;
  1132. if (!FD->hasBody(DiagD))
  1133. DiagD = FD;
  1134. if (DiagD->isDeleted())
  1135. continue; // Deleted functions are supposed to be unused.
  1136. if (DiagD->isReferenced()) {
  1137. if (isa<CXXMethodDecl>(DiagD))
  1138. Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
  1139. << DiagD;
  1140. else {
  1141. if (FD->getStorageClass() == SC_Static &&
  1142. !FD->isInlineSpecified() &&
  1143. !SourceMgr.isInMainFile(
  1144. SourceMgr.getExpansionLoc(FD->getLocation())))
  1145. Diag(DiagD->getLocation(),
  1146. diag::warn_unneeded_static_internal_decl)
  1147. << DiagD;
  1148. else
  1149. Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
  1150. << /*function*/ 0 << DiagD;
  1151. }
  1152. } else {
  1153. if (FD->getDescribedFunctionTemplate())
  1154. Diag(DiagD->getLocation(), diag::warn_unused_template)
  1155. << /*function*/ 0 << DiagD;
  1156. else
  1157. Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
  1158. ? diag::warn_unused_member_function
  1159. : diag::warn_unused_function)
  1160. << DiagD;
  1161. }
  1162. } else {
  1163. const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
  1164. if (!DiagD)
  1165. DiagD = cast<VarDecl>(*I);
  1166. if (DiagD->isReferenced()) {
  1167. Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
  1168. << /*variable*/ 1 << DiagD;
  1169. } else if (DiagD->getType().isConstQualified()) {
  1170. const SourceManager &SM = SourceMgr;
  1171. if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
  1172. !PP.getLangOpts().IsHeaderFile)
  1173. Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
  1174. << DiagD;
  1175. } else {
  1176. if (DiagD->getDescribedVarTemplate())
  1177. Diag(DiagD->getLocation(), diag::warn_unused_template)
  1178. << /*variable*/ 1 << DiagD;
  1179. else
  1180. Diag(DiagD->getLocation(), diag::warn_unused_variable) << DiagD;
  1181. }
  1182. }
  1183. }
  1184. emitAndClearUnusedLocalTypedefWarnings();
  1185. }
  1186. if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
  1187. // FIXME: Load additional unused private field candidates from the external
  1188. // source.
  1189. RecordCompleteMap RecordsComplete;
  1190. RecordCompleteMap MNCComplete;
  1191. for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
  1192. E = UnusedPrivateFields.end(); I != E; ++I) {
  1193. const NamedDecl *D = *I;
  1194. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
  1195. if (RD && !RD->isUnion() &&
  1196. IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
  1197. Diag(D->getLocation(), diag::warn_unused_private_field)
  1198. << D->getDeclName();
  1199. }
  1200. }
  1201. }
  1202. if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
  1203. if (ExternalSource)
  1204. ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
  1205. for (const auto &DeletedFieldInfo : DeleteExprs) {
  1206. for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
  1207. AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
  1208. DeleteExprLoc.second);
  1209. }
  1210. }
  1211. }
  1212. // Check we've noticed that we're no longer parsing the initializer for every
  1213. // variable. If we miss cases, then at best we have a performance issue and
  1214. // at worst a rejects-valid bug.
  1215. assert(ParsingInitForAutoVars.empty() &&
  1216. "Didn't unmark var as having its initializer parsed");
  1217. if (!PP.isIncrementalProcessingEnabled())
  1218. TUScope = nullptr;
  1219. }
  1220. //===----------------------------------------------------------------------===//
  1221. // Helper functions.
  1222. //===----------------------------------------------------------------------===//
  1223. DeclContext *Sema::getFunctionLevelDeclContext() {
  1224. DeclContext *DC = CurContext;
  1225. while (true) {
  1226. if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||
  1227. isa<RequiresExprBodyDecl>(DC)) {
  1228. DC = DC->getParent();
  1229. } else if (isa<CXXMethodDecl>(DC) &&
  1230. cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
  1231. cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
  1232. DC = DC->getParent()->getParent();
  1233. }
  1234. else break;
  1235. }
  1236. return DC;
  1237. }
  1238. /// getCurFunctionDecl - If inside of a function body, this returns a pointer
  1239. /// to the function decl for the function being parsed. If we're currently
  1240. /// in a 'block', this returns the containing context.
  1241. FunctionDecl *Sema::getCurFunctionDecl() {
  1242. DeclContext *DC = getFunctionLevelDeclContext();
  1243. return dyn_cast<FunctionDecl>(DC);
  1244. }
  1245. ObjCMethodDecl *Sema::getCurMethodDecl() {
  1246. DeclContext *DC = getFunctionLevelDeclContext();
  1247. while (isa<RecordDecl>(DC))
  1248. DC = DC->getParent();
  1249. return dyn_cast<ObjCMethodDecl>(DC);
  1250. }
  1251. NamedDecl *Sema::getCurFunctionOrMethodDecl() {
  1252. DeclContext *DC = getFunctionLevelDeclContext();
  1253. if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
  1254. return cast<NamedDecl>(DC);
  1255. return nullptr;
  1256. }
  1257. LangAS Sema::getDefaultCXXMethodAddrSpace() const {
  1258. if (getLangOpts().OpenCL)
  1259. return getASTContext().getDefaultOpenCLPointeeAddrSpace();
  1260. return LangAS::Default;
  1261. }
  1262. void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
  1263. // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
  1264. // and yet we also use the current diag ID on the DiagnosticsEngine. This has
  1265. // been made more painfully obvious by the refactor that introduced this
  1266. // function, but it is possible that the incoming argument can be
  1267. // eliminated. If it truly cannot be (for example, there is some reentrancy
  1268. // issue I am not seeing yet), then there should at least be a clarifying
  1269. // comment somewhere.
  1270. if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
  1271. switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
  1272. Diags.getCurrentDiagID())) {
  1273. case DiagnosticIDs::SFINAE_Report:
  1274. // We'll report the diagnostic below.
  1275. break;
  1276. case DiagnosticIDs::SFINAE_SubstitutionFailure:
  1277. // Count this failure so that we know that template argument deduction
  1278. // has failed.
  1279. ++NumSFINAEErrors;
  1280. // Make a copy of this suppressed diagnostic and store it with the
  1281. // template-deduction information.
  1282. if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
  1283. Diagnostic DiagInfo(&Diags);
  1284. (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
  1285. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  1286. }
  1287. Diags.setLastDiagnosticIgnored(true);
  1288. Diags.Clear();
  1289. return;
  1290. case DiagnosticIDs::SFINAE_AccessControl: {
  1291. // Per C++ Core Issue 1170, access control is part of SFINAE.
  1292. // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
  1293. // make access control a part of SFINAE for the purposes of checking
  1294. // type traits.
  1295. if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
  1296. break;
  1297. SourceLocation Loc = Diags.getCurrentDiagLoc();
  1298. // Suppress this diagnostic.
  1299. ++NumSFINAEErrors;
  1300. // Make a copy of this suppressed diagnostic and store it with the
  1301. // template-deduction information.
  1302. if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
  1303. Diagnostic DiagInfo(&Diags);
  1304. (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
  1305. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  1306. }
  1307. Diags.setLastDiagnosticIgnored(true);
  1308. Diags.Clear();
  1309. // Now the diagnostic state is clear, produce a C++98 compatibility
  1310. // warning.
  1311. Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
  1312. // The last diagnostic which Sema produced was ignored. Suppress any
  1313. // notes attached to it.
  1314. Diags.setLastDiagnosticIgnored(true);
  1315. return;
  1316. }
  1317. case DiagnosticIDs::SFINAE_Suppress:
  1318. // Make a copy of this suppressed diagnostic and store it with the
  1319. // template-deduction information;
  1320. if (*Info) {
  1321. Diagnostic DiagInfo(&Diags);
  1322. (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
  1323. PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
  1324. }
  1325. // Suppress this diagnostic.
  1326. Diags.setLastDiagnosticIgnored(true);
  1327. Diags.Clear();
  1328. return;
  1329. }
  1330. }
  1331. // Copy the diagnostic printing policy over the ASTContext printing policy.
  1332. // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
  1333. Context.setPrintingPolicy(getPrintingPolicy());
  1334. // Emit the diagnostic.
  1335. if (!Diags.EmitCurrentDiagnostic())
  1336. return;
  1337. // If this is not a note, and we're in a template instantiation
  1338. // that is different from the last template instantiation where
  1339. // we emitted an error, print a template instantiation
  1340. // backtrace.
  1341. if (!DiagnosticIDs::isBuiltinNote(DiagID))
  1342. PrintContextStack();
  1343. }
  1344. Sema::SemaDiagnosticBuilder
  1345. Sema::Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint) {
  1346. return Diag(Loc, PD.getDiagID(), DeferHint) << PD;
  1347. }
  1348. bool Sema::hasUncompilableErrorOccurred() const {
  1349. if (getDiagnostics().hasUncompilableErrorOccurred())
  1350. return true;
  1351. auto *FD = dyn_cast<FunctionDecl>(CurContext);
  1352. if (!FD)
  1353. return false;
  1354. auto Loc = DeviceDeferredDiags.find(FD);
  1355. if (Loc == DeviceDeferredDiags.end())
  1356. return false;
  1357. for (auto PDAt : Loc->second) {
  1358. if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID()))
  1359. return true;
  1360. }
  1361. return false;
  1362. }
  1363. // Print notes showing how we can reach FD starting from an a priori
  1364. // known-callable function.
  1365. static void emitCallStackNotes(Sema &S, FunctionDecl *FD) {
  1366. auto FnIt = S.DeviceKnownEmittedFns.find(FD);
  1367. while (FnIt != S.DeviceKnownEmittedFns.end()) {
  1368. // Respect error limit.
  1369. if (S.Diags.hasFatalErrorOccurred())
  1370. return;
  1371. DiagnosticBuilder Builder(
  1372. S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
  1373. Builder << FnIt->second.FD;
  1374. FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
  1375. }
  1376. }
  1377. namespace {
  1378. /// Helper class that emits deferred diagnostic messages if an entity directly
  1379. /// or indirectly using the function that causes the deferred diagnostic
  1380. /// messages is known to be emitted.
  1381. ///
  1382. /// During parsing of AST, certain diagnostic messages are recorded as deferred
  1383. /// diagnostics since it is unknown whether the functions containing such
  1384. /// diagnostics will be emitted. A list of potentially emitted functions and
  1385. /// variables that may potentially trigger emission of functions are also
  1386. /// recorded. DeferredDiagnosticsEmitter recursively visits used functions
  1387. /// by each function to emit deferred diagnostics.
  1388. ///
  1389. /// During the visit, certain OpenMP directives or initializer of variables
  1390. /// with certain OpenMP attributes will cause subsequent visiting of any
  1391. /// functions enter a state which is called OpenMP device context in this
  1392. /// implementation. The state is exited when the directive or initializer is
  1393. /// exited. This state can change the emission states of subsequent uses
  1394. /// of functions.
  1395. ///
  1396. /// Conceptually the functions or variables to be visited form a use graph
  1397. /// where the parent node uses the child node. At any point of the visit,
  1398. /// the tree nodes traversed from the tree root to the current node form a use
  1399. /// stack. The emission state of the current node depends on two factors:
  1400. /// 1. the emission state of the root node
  1401. /// 2. whether the current node is in OpenMP device context
  1402. /// If the function is decided to be emitted, its contained deferred diagnostics
  1403. /// are emitted, together with the information about the use stack.
  1404. ///
  1405. class DeferredDiagnosticsEmitter
  1406. : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
  1407. public:
  1408. typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
  1409. // Whether the function is already in the current use-path.
  1410. llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
  1411. // The current use-path.
  1412. llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
  1413. // Whether the visiting of the function has been done. Done[0] is for the
  1414. // case not in OpenMP device context. Done[1] is for the case in OpenMP
  1415. // device context. We need two sets because diagnostics emission may be
  1416. // different depending on whether it is in OpenMP device context.
  1417. llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
  1418. // Emission state of the root node of the current use graph.
  1419. bool ShouldEmitRootNode;
  1420. // Current OpenMP device context level. It is initialized to 0 and each
  1421. // entering of device context increases it by 1 and each exit decreases
  1422. // it by 1. Non-zero value indicates it is currently in device context.
  1423. unsigned InOMPDeviceContext;
  1424. DeferredDiagnosticsEmitter(Sema &S)
  1425. : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
  1426. bool shouldVisitDiscardedStmt() const { return false; }
  1427. void VisitOMPTargetDirective(OMPTargetDirective *Node) {
  1428. ++InOMPDeviceContext;
  1429. Inherited::VisitOMPTargetDirective(Node);
  1430. --InOMPDeviceContext;
  1431. }
  1432. void visitUsedDecl(SourceLocation Loc, Decl *D) {
  1433. if (isa<VarDecl>(D))
  1434. return;
  1435. if (auto *FD = dyn_cast<FunctionDecl>(D))
  1436. checkFunc(Loc, FD);
  1437. else
  1438. Inherited::visitUsedDecl(Loc, D);
  1439. }
  1440. void checkVar(VarDecl *VD) {
  1441. assert(VD->isFileVarDecl() &&
  1442. "Should only check file-scope variables");
  1443. if (auto *Init = VD->getInit()) {
  1444. auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
  1445. bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
  1446. *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
  1447. if (IsDev)
  1448. ++InOMPDeviceContext;
  1449. this->Visit(Init);
  1450. if (IsDev)
  1451. --InOMPDeviceContext;
  1452. }
  1453. }
  1454. void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
  1455. auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
  1456. FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
  1457. if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
  1458. S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
  1459. return;
  1460. // Finalize analysis of OpenMP-specific constructs.
  1461. if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
  1462. (ShouldEmitRootNode || InOMPDeviceContext))
  1463. S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
  1464. if (Caller)
  1465. S.DeviceKnownEmittedFns[FD] = {Caller, Loc};
  1466. // Always emit deferred diagnostics for the direct users. This does not
  1467. // lead to explosion of diagnostics since each user is visited at most
  1468. // twice.
  1469. if (ShouldEmitRootNode || InOMPDeviceContext)
  1470. emitDeferredDiags(FD, Caller);
  1471. // Do not revisit a function if the function body has been completely
  1472. // visited before.
  1473. if (!Done.insert(FD).second)
  1474. return;
  1475. InUsePath.insert(FD);
  1476. UsePath.push_back(FD);
  1477. if (auto *S = FD->getBody()) {
  1478. this->Visit(S);
  1479. }
  1480. UsePath.pop_back();
  1481. InUsePath.erase(FD);
  1482. }
  1483. void checkRecordedDecl(Decl *D) {
  1484. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  1485. ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
  1486. Sema::FunctionEmissionStatus::Emitted;
  1487. checkFunc(SourceLocation(), FD);
  1488. } else
  1489. checkVar(cast<VarDecl>(D));
  1490. }
  1491. // Emit any deferred diagnostics for FD
  1492. void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
  1493. auto It = S.DeviceDeferredDiags.find(FD);
  1494. if (It == S.DeviceDeferredDiags.end())
  1495. return;
  1496. bool HasWarningOrError = false;
  1497. bool FirstDiag = true;
  1498. for (PartialDiagnosticAt &PDAt : It->second) {
  1499. // Respect error limit.
  1500. if (S.Diags.hasFatalErrorOccurred())
  1501. return;
  1502. const SourceLocation &Loc = PDAt.first;
  1503. const PartialDiagnostic &PD = PDAt.second;
  1504. HasWarningOrError |=
  1505. S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >=
  1506. DiagnosticsEngine::Warning;
  1507. {
  1508. DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
  1509. PD.Emit(Builder);
  1510. }
  1511. // Emit the note on the first diagnostic in case too many diagnostics
  1512. // cause the note not emitted.
  1513. if (FirstDiag && HasWarningOrError && ShowCallStack) {
  1514. emitCallStackNotes(S, FD);
  1515. FirstDiag = false;
  1516. }
  1517. }
  1518. }
  1519. };
  1520. } // namespace
  1521. void Sema::emitDeferredDiags() {
  1522. if (ExternalSource)
  1523. ExternalSource->ReadDeclsToCheckForDeferredDiags(
  1524. DeclsToCheckForDeferredDiags);
  1525. if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
  1526. DeclsToCheckForDeferredDiags.empty())
  1527. return;
  1528. DeferredDiagnosticsEmitter DDE(*this);
  1529. for (auto D : DeclsToCheckForDeferredDiags)
  1530. DDE.checkRecordedDecl(D);
  1531. }
  1532. // In CUDA, there are some constructs which may appear in semantically-valid
  1533. // code, but trigger errors if we ever generate code for the function in which
  1534. // they appear. Essentially every construct you're not allowed to use on the
  1535. // device falls into this category, because you are allowed to use these
  1536. // constructs in a __host__ __device__ function, but only if that function is
  1537. // never codegen'ed on the device.
  1538. //
  1539. // To handle semantic checking for these constructs, we keep track of the set of
  1540. // functions we know will be emitted, either because we could tell a priori that
  1541. // they would be emitted, or because they were transitively called by a
  1542. // known-emitted function.
  1543. //
  1544. // We also keep a partial call graph of which not-known-emitted functions call
  1545. // which other not-known-emitted functions.
  1546. //
  1547. // When we see something which is illegal if the current function is emitted
  1548. // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
  1549. // CheckCUDACall), we first check if the current function is known-emitted. If
  1550. // so, we immediately output the diagnostic.
  1551. //
  1552. // Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
  1553. // until we discover that the function is known-emitted, at which point we take
  1554. // it out of this map and emit the diagnostic.
  1555. Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,
  1556. unsigned DiagID,
  1557. FunctionDecl *Fn, Sema &S)
  1558. : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
  1559. ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
  1560. switch (K) {
  1561. case K_Nop:
  1562. break;
  1563. case K_Immediate:
  1564. case K_ImmediateWithCallStack:
  1565. ImmediateDiag.emplace(
  1566. ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
  1567. break;
  1568. case K_Deferred:
  1569. assert(Fn && "Must have a function to attach the deferred diag to.");
  1570. auto &Diags = S.DeviceDeferredDiags[Fn];
  1571. PartialDiagId.emplace(Diags.size());
  1572. Diags.emplace_back(Loc, S.PDiag(DiagID));
  1573. break;
  1574. }
  1575. }
  1576. Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
  1577. : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
  1578. ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
  1579. PartialDiagId(D.PartialDiagId) {
  1580. // Clean the previous diagnostics.
  1581. D.ShowCallStack = false;
  1582. D.ImmediateDiag.reset();
  1583. D.PartialDiagId.reset();
  1584. }
  1585. Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
  1586. if (ImmediateDiag) {
  1587. // Emit our diagnostic and, if it was a warning or error, output a callstack
  1588. // if Fn isn't a priori known-emitted.
  1589. bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
  1590. DiagID, Loc) >= DiagnosticsEngine::Warning;
  1591. ImmediateDiag.reset(); // Emit the immediate diag.
  1592. if (IsWarningOrError && ShowCallStack)
  1593. emitCallStackNotes(S, Fn);
  1594. } else {
  1595. assert((!PartialDiagId || ShowCallStack) &&
  1596. "Must always show call stack for deferred diags.");
  1597. }
  1598. }
  1599. Sema::SemaDiagnosticBuilder
  1600. Sema::targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD) {
  1601. FD = FD ? FD : getCurFunctionDecl();
  1602. if (LangOpts.OpenMP)
  1603. return LangOpts.OpenMPIsDevice ? diagIfOpenMPDeviceCode(Loc, DiagID, FD)
  1604. : diagIfOpenMPHostCode(Loc, DiagID, FD);
  1605. if (getLangOpts().CUDA)
  1606. return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID)
  1607. : CUDADiagIfHostCode(Loc, DiagID);
  1608. if (getLangOpts().SYCLIsDevice)
  1609. return SYCLDiagIfDeviceCode(Loc, DiagID);
  1610. return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID,
  1611. FD, *this);
  1612. }
  1613. Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID,
  1614. bool DeferHint) {
  1615. bool IsError = Diags.getDiagnosticIDs()->isDefaultMappingAsError(DiagID);
  1616. bool ShouldDefer = getLangOpts().CUDA && LangOpts.GPUDeferDiag &&
  1617. DiagnosticIDs::isDeferrable(DiagID) &&
  1618. (DeferHint || DeferDiags || !IsError);
  1619. auto SetIsLastErrorImmediate = [&](bool Flag) {
  1620. if (IsError)
  1621. IsLastErrorImmediate = Flag;
  1622. };
  1623. if (!ShouldDefer) {
  1624. SetIsLastErrorImmediate(true);
  1625. return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc,
  1626. DiagID, getCurFunctionDecl(), *this);
  1627. }
  1628. SemaDiagnosticBuilder DB = getLangOpts().CUDAIsDevice
  1629. ? CUDADiagIfDeviceCode(Loc, DiagID)
  1630. : CUDADiagIfHostCode(Loc, DiagID);
  1631. SetIsLastErrorImmediate(DB.isImmediate());
  1632. return DB;
  1633. }
  1634. void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) {
  1635. if (isUnevaluatedContext() || Ty.isNull())
  1636. return;
  1637. // The original idea behind checkTypeSupport function is that unused
  1638. // declarations can be replaced with an array of bytes of the same size during
  1639. // codegen, such replacement doesn't seem to be possible for types without
  1640. // constant byte size like zero length arrays. So, do a deep check for SYCL.
  1641. if (D && LangOpts.SYCLIsDevice) {
  1642. llvm::DenseSet<QualType> Visited;
  1643. deepTypeCheckForSYCLDevice(Loc, Visited, D);
  1644. }
  1645. Decl *C = cast<Decl>(getCurLexicalContext());
  1646. // Memcpy operations for structs containing a member with unsupported type
  1647. // are ok, though.
  1648. if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
  1649. if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
  1650. MD->isTrivial())
  1651. return;
  1652. if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
  1653. if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
  1654. return;
  1655. }
  1656. // Try to associate errors with the lexical context, if that is a function, or
  1657. // the value declaration otherwise.
  1658. FunctionDecl *FD = isa<FunctionDecl>(C) ? cast<FunctionDecl>(C)
  1659. : dyn_cast_or_null<FunctionDecl>(D);
  1660. auto CheckDeviceType = [&](QualType Ty) {
  1661. if (Ty->isDependentType())
  1662. return;
  1663. if (Ty->isBitIntType()) {
  1664. if (!Context.getTargetInfo().hasBitIntType()) {
  1665. PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
  1666. if (D)
  1667. PD << D;
  1668. else
  1669. PD << "expression";
  1670. targetDiag(Loc, PD, FD)
  1671. << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
  1672. << Ty << Context.getTargetInfo().getTriple().str();
  1673. }
  1674. return;
  1675. }
  1676. // Check if we are dealing with two 'long double' but with different
  1677. // semantics.
  1678. bool LongDoubleMismatched = false;
  1679. if (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128) {
  1680. const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty);
  1681. if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
  1682. !Context.getTargetInfo().hasFloat128Type()) ||
  1683. (&Sem == &llvm::APFloat::PPCDoubleDouble() &&
  1684. !Context.getTargetInfo().hasIbm128Type()))
  1685. LongDoubleMismatched = true;
  1686. }
  1687. if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
  1688. (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
  1689. (Ty->isIbm128Type() && !Context.getTargetInfo().hasIbm128Type()) ||
  1690. (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
  1691. !Context.getTargetInfo().hasInt128Type()) ||
  1692. LongDoubleMismatched) {
  1693. PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
  1694. if (D)
  1695. PD << D;
  1696. else
  1697. PD << "expression";
  1698. if (targetDiag(Loc, PD, FD)
  1699. << true /*show bit size*/
  1700. << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
  1701. << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
  1702. if (D)
  1703. D->setInvalidDecl();
  1704. }
  1705. if (D)
  1706. targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
  1707. }
  1708. };
  1709. auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
  1710. if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice) ||
  1711. LangOpts.CUDAIsDevice)
  1712. CheckDeviceType(Ty);
  1713. QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType();
  1714. const TargetInfo &TI = Context.getTargetInfo();
  1715. if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) {
  1716. PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
  1717. if (D)
  1718. PD << D;
  1719. else
  1720. PD << "expression";
  1721. if (Diag(Loc, PD, FD)
  1722. << false /*show bit size*/ << 0 << Ty << false /*return*/
  1723. << Context.getTargetInfo().getTriple().str()) {
  1724. if (D)
  1725. D->setInvalidDecl();
  1726. }
  1727. if (D)
  1728. targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
  1729. }
  1730. bool IsDouble = UnqualTy == Context.DoubleTy;
  1731. bool IsFloat = UnqualTy == Context.FloatTy;
  1732. if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) {
  1733. PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
  1734. if (D)
  1735. PD << D;
  1736. else
  1737. PD << "expression";
  1738. if (Diag(Loc, PD, FD)
  1739. << false /*show bit size*/ << 0 << Ty << true /*return*/
  1740. << Context.getTargetInfo().getTriple().str()) {
  1741. if (D)
  1742. D->setInvalidDecl();
  1743. }
  1744. if (D)
  1745. targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
  1746. }
  1747. };
  1748. CheckType(Ty);
  1749. if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
  1750. for (const auto &ParamTy : FPTy->param_types())
  1751. CheckType(ParamTy);
  1752. CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);
  1753. }
  1754. if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
  1755. CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
  1756. }
  1757. /// Looks through the macro-expansion chain for the given
  1758. /// location, looking for a macro expansion with the given name.
  1759. /// If one is found, returns true and sets the location to that
  1760. /// expansion loc.
  1761. bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
  1762. SourceLocation loc = locref;
  1763. if (!loc.isMacroID()) return false;
  1764. // There's no good way right now to look at the intermediate
  1765. // expansions, so just jump to the expansion location.
  1766. loc = getSourceManager().getExpansionLoc(loc);
  1767. // If that's written with the name, stop here.
  1768. SmallString<16> buffer;
  1769. if (getPreprocessor().getSpelling(loc, buffer) == name) {
  1770. locref = loc;
  1771. return true;
  1772. }
  1773. return false;
  1774. }
  1775. /// Determines the active Scope associated with the given declaration
  1776. /// context.
  1777. ///
  1778. /// This routine maps a declaration context to the active Scope object that
  1779. /// represents that declaration context in the parser. It is typically used
  1780. /// from "scope-less" code (e.g., template instantiation, lazy creation of
  1781. /// declarations) that injects a name for name-lookup purposes and, therefore,
  1782. /// must update the Scope.
  1783. ///
  1784. /// \returns The scope corresponding to the given declaraion context, or NULL
  1785. /// if no such scope is open.
  1786. Scope *Sema::getScopeForContext(DeclContext *Ctx) {
  1787. if (!Ctx)
  1788. return nullptr;
  1789. Ctx = Ctx->getPrimaryContext();
  1790. for (Scope *S = getCurScope(); S; S = S->getParent()) {
  1791. // Ignore scopes that cannot have declarations. This is important for
  1792. // out-of-line definitions of static class members.
  1793. if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
  1794. if (DeclContext *Entity = S->getEntity())
  1795. if (Ctx == Entity->getPrimaryContext())
  1796. return S;
  1797. }
  1798. return nullptr;
  1799. }
  1800. /// Enter a new function scope
  1801. void Sema::PushFunctionScope() {
  1802. if (FunctionScopes.empty() && CachedFunctionScope) {
  1803. // Use CachedFunctionScope to avoid allocating memory when possible.
  1804. CachedFunctionScope->Clear();
  1805. FunctionScopes.push_back(CachedFunctionScope.release());
  1806. } else {
  1807. FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
  1808. }
  1809. if (LangOpts.OpenMP)
  1810. pushOpenMPFunctionRegion();
  1811. }
  1812. void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
  1813. FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
  1814. BlockScope, Block));
  1815. }
  1816. LambdaScopeInfo *Sema::PushLambdaScope() {
  1817. LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
  1818. FunctionScopes.push_back(LSI);
  1819. return LSI;
  1820. }
  1821. void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
  1822. if (LambdaScopeInfo *const LSI = getCurLambda()) {
  1823. LSI->AutoTemplateParameterDepth = Depth;
  1824. return;
  1825. }
  1826. llvm_unreachable(
  1827. "Remove assertion if intentionally called in a non-lambda context.");
  1828. }
  1829. // Check that the type of the VarDecl has an accessible copy constructor and
  1830. // resolve its destructor's exception specification.
  1831. // This also performs initialization of block variables when they are moved
  1832. // to the heap. It uses the same rules as applicable for implicit moves
  1833. // according to the C++ standard in effect ([class.copy.elision]p3).
  1834. static void checkEscapingByref(VarDecl *VD, Sema &S) {
  1835. QualType T = VD->getType();
  1836. EnterExpressionEvaluationContext scope(
  1837. S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  1838. SourceLocation Loc = VD->getLocation();
  1839. Expr *VarRef =
  1840. new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
  1841. ExprResult Result;
  1842. auto IE = InitializedEntity::InitializeBlock(Loc, T);
  1843. if (S.getLangOpts().CPlusPlus2b) {
  1844. auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
  1845. VK_XValue, FPOptionsOverride());
  1846. Result = S.PerformCopyInitialization(IE, SourceLocation(), E);
  1847. } else {
  1848. Result = S.PerformMoveOrCopyInitialization(
  1849. IE, Sema::NamedReturnInfo{VD, Sema::NamedReturnInfo::MoveEligible},
  1850. VarRef);
  1851. }
  1852. if (!Result.isInvalid()) {
  1853. Result = S.MaybeCreateExprWithCleanups(Result);
  1854. Expr *Init = Result.getAs<Expr>();
  1855. S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
  1856. }
  1857. // The destructor's exception specification is needed when IRGen generates
  1858. // block copy/destroy functions. Resolve it here.
  1859. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  1860. if (CXXDestructorDecl *DD = RD->getDestructor()) {
  1861. auto *FPT = DD->getType()->getAs<FunctionProtoType>();
  1862. S.ResolveExceptionSpec(Loc, FPT);
  1863. }
  1864. }
  1865. static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
  1866. // Set the EscapingByref flag of __block variables captured by
  1867. // escaping blocks.
  1868. for (const BlockDecl *BD : FSI.Blocks) {
  1869. for (const BlockDecl::Capture &BC : BD->captures()) {
  1870. VarDecl *VD = BC.getVariable();
  1871. if (VD->hasAttr<BlocksAttr>()) {
  1872. // Nothing to do if this is a __block variable captured by a
  1873. // non-escaping block.
  1874. if (BD->doesNotEscape())
  1875. continue;
  1876. VD->setEscapingByref();
  1877. }
  1878. // Check whether the captured variable is or contains an object of
  1879. // non-trivial C union type.
  1880. QualType CapType = BC.getVariable()->getType();
  1881. if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
  1882. CapType.hasNonTrivialToPrimitiveCopyCUnion())
  1883. S.checkNonTrivialCUnion(BC.getVariable()->getType(),
  1884. BD->getCaretLocation(),
  1885. Sema::NTCUC_BlockCapture,
  1886. Sema::NTCUK_Destruct|Sema::NTCUK_Copy);
  1887. }
  1888. }
  1889. for (VarDecl *VD : FSI.ByrefBlockVars) {
  1890. // __block variables might require us to capture a copy-initializer.
  1891. if (!VD->isEscapingByref())
  1892. continue;
  1893. // It's currently invalid to ever have a __block variable with an
  1894. // array type; should we diagnose that here?
  1895. // Regardless, we don't want to ignore array nesting when
  1896. // constructing this copy.
  1897. if (VD->getType()->isStructureOrClassType())
  1898. checkEscapingByref(VD, S);
  1899. }
  1900. }
  1901. /// Pop a function (or block or lambda or captured region) scope from the stack.
  1902. ///
  1903. /// \param WP The warning policy to use for CFG-based warnings, or null if such
  1904. /// warnings should not be produced.
  1905. /// \param D The declaration corresponding to this function scope, if producing
  1906. /// CFG-based warnings.
  1907. /// \param BlockType The type of the block expression, if D is a BlockDecl.
  1908. Sema::PoppedFunctionScopePtr
  1909. Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
  1910. const Decl *D, QualType BlockType) {
  1911. assert(!FunctionScopes.empty() && "mismatched push/pop!");
  1912. markEscapingByrefs(*FunctionScopes.back(), *this);
  1913. PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
  1914. PoppedFunctionScopeDeleter(this));
  1915. if (LangOpts.OpenMP)
  1916. popOpenMPFunctionRegion(Scope.get());
  1917. // Issue any analysis-based warnings.
  1918. if (WP && D)
  1919. AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
  1920. else
  1921. for (const auto &PUD : Scope->PossiblyUnreachableDiags)
  1922. Diag(PUD.Loc, PUD.PD);
  1923. return Scope;
  1924. }
  1925. void Sema::PoppedFunctionScopeDeleter::
  1926. operator()(sema::FunctionScopeInfo *Scope) const {
  1927. // Stash the function scope for later reuse if it's for a normal function.
  1928. if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
  1929. Self->CachedFunctionScope.reset(Scope);
  1930. else
  1931. delete Scope;
  1932. }
  1933. void Sema::PushCompoundScope(bool IsStmtExpr) {
  1934. getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo(IsStmtExpr));
  1935. }
  1936. void Sema::PopCompoundScope() {
  1937. FunctionScopeInfo *CurFunction = getCurFunction();
  1938. assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
  1939. CurFunction->CompoundScopes.pop_back();
  1940. }
  1941. /// Determine whether any errors occurred within this function/method/
  1942. /// block.
  1943. bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
  1944. return getCurFunction()->hasUnrecoverableErrorOccurred();
  1945. }
  1946. void Sema::setFunctionHasBranchIntoScope() {
  1947. if (!FunctionScopes.empty())
  1948. FunctionScopes.back()->setHasBranchIntoScope();
  1949. }
  1950. void Sema::setFunctionHasBranchProtectedScope() {
  1951. if (!FunctionScopes.empty())
  1952. FunctionScopes.back()->setHasBranchProtectedScope();
  1953. }
  1954. void Sema::setFunctionHasIndirectGoto() {
  1955. if (!FunctionScopes.empty())
  1956. FunctionScopes.back()->setHasIndirectGoto();
  1957. }
  1958. void Sema::setFunctionHasMustTail() {
  1959. if (!FunctionScopes.empty())
  1960. FunctionScopes.back()->setHasMustTail();
  1961. }
  1962. BlockScopeInfo *Sema::getCurBlock() {
  1963. if (FunctionScopes.empty())
  1964. return nullptr;
  1965. auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
  1966. if (CurBSI && CurBSI->TheDecl &&
  1967. !CurBSI->TheDecl->Encloses(CurContext)) {
  1968. // We have switched contexts due to template instantiation.
  1969. assert(!CodeSynthesisContexts.empty());
  1970. return nullptr;
  1971. }
  1972. return CurBSI;
  1973. }
  1974. FunctionScopeInfo *Sema::getEnclosingFunction() const {
  1975. if (FunctionScopes.empty())
  1976. return nullptr;
  1977. for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
  1978. if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
  1979. continue;
  1980. return FunctionScopes[e];
  1981. }
  1982. return nullptr;
  1983. }
  1984. LambdaScopeInfo *Sema::getEnclosingLambda() const {
  1985. for (auto *Scope : llvm::reverse(FunctionScopes)) {
  1986. if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {
  1987. if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext)) {
  1988. // We have switched contexts due to template instantiation.
  1989. // FIXME: We should swap out the FunctionScopes during code synthesis
  1990. // so that we don't need to check for this.
  1991. assert(!CodeSynthesisContexts.empty());
  1992. return nullptr;
  1993. }
  1994. return LSI;
  1995. }
  1996. }
  1997. return nullptr;
  1998. }
  1999. LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
  2000. if (FunctionScopes.empty())
  2001. return nullptr;
  2002. auto I = FunctionScopes.rbegin();
  2003. if (IgnoreNonLambdaCapturingScope) {
  2004. auto E = FunctionScopes.rend();
  2005. while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
  2006. ++I;
  2007. if (I == E)
  2008. return nullptr;
  2009. }
  2010. auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
  2011. if (CurLSI && CurLSI->Lambda &&
  2012. !CurLSI->Lambda->Encloses(CurContext)) {
  2013. // We have switched contexts due to template instantiation.
  2014. assert(!CodeSynthesisContexts.empty());
  2015. return nullptr;
  2016. }
  2017. return CurLSI;
  2018. }
  2019. // We have a generic lambda if we parsed auto parameters, or we have
  2020. // an associated template parameter list.
  2021. LambdaScopeInfo *Sema::getCurGenericLambda() {
  2022. if (LambdaScopeInfo *LSI = getCurLambda()) {
  2023. return (LSI->TemplateParams.size() ||
  2024. LSI->GLTemplateParameterList) ? LSI : nullptr;
  2025. }
  2026. return nullptr;
  2027. }
  2028. void Sema::ActOnComment(SourceRange Comment) {
  2029. if (!LangOpts.RetainCommentsFromSystemHeaders &&
  2030. SourceMgr.isInSystemHeader(Comment.getBegin()))
  2031. return;
  2032. RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
  2033. if (RC.isAlmostTrailingComment()) {
  2034. SourceRange MagicMarkerRange(Comment.getBegin(),
  2035. Comment.getBegin().getLocWithOffset(3));
  2036. StringRef MagicMarkerText;
  2037. switch (RC.getKind()) {
  2038. case RawComment::RCK_OrdinaryBCPL:
  2039. MagicMarkerText = "///<";
  2040. break;
  2041. case RawComment::RCK_OrdinaryC:
  2042. MagicMarkerText = "/**<";
  2043. break;
  2044. default:
  2045. llvm_unreachable("if this is an almost Doxygen comment, "
  2046. "it should be ordinary");
  2047. }
  2048. Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
  2049. FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
  2050. }
  2051. Context.addComment(RC);
  2052. }
  2053. // Pin this vtable to this file.
  2054. ExternalSemaSource::~ExternalSemaSource() {}
  2055. char ExternalSemaSource::ID;
  2056. void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
  2057. void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
  2058. void ExternalSemaSource::ReadKnownNamespaces(
  2059. SmallVectorImpl<NamespaceDecl *> &Namespaces) {
  2060. }
  2061. void ExternalSemaSource::ReadUndefinedButUsed(
  2062. llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
  2063. void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
  2064. FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
  2065. /// Figure out if an expression could be turned into a call.
  2066. ///
  2067. /// Use this when trying to recover from an error where the programmer may have
  2068. /// written just the name of a function instead of actually calling it.
  2069. ///
  2070. /// \param E - The expression to examine.
  2071. /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
  2072. /// with no arguments, this parameter is set to the type returned by such a
  2073. /// call; otherwise, it is set to an empty QualType.
  2074. /// \param OverloadSet - If the expression is an overloaded function
  2075. /// name, this parameter is populated with the decls of the various overloads.
  2076. bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
  2077. UnresolvedSetImpl &OverloadSet) {
  2078. ZeroArgCallReturnTy = QualType();
  2079. OverloadSet.clear();
  2080. const OverloadExpr *Overloads = nullptr;
  2081. bool IsMemExpr = false;
  2082. if (E.getType() == Context.OverloadTy) {
  2083. OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
  2084. // Ignore overloads that are pointer-to-member constants.
  2085. if (FR.HasFormOfMemberPointer)
  2086. return false;
  2087. Overloads = FR.Expression;
  2088. } else if (E.getType() == Context.BoundMemberTy) {
  2089. Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
  2090. IsMemExpr = true;
  2091. }
  2092. bool Ambiguous = false;
  2093. bool IsMV = false;
  2094. if (Overloads) {
  2095. for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
  2096. DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
  2097. OverloadSet.addDecl(*it);
  2098. // Check whether the function is a non-template, non-member which takes no
  2099. // arguments.
  2100. if (IsMemExpr)
  2101. continue;
  2102. if (const FunctionDecl *OverloadDecl
  2103. = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
  2104. if (OverloadDecl->getMinRequiredArguments() == 0) {
  2105. if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
  2106. (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
  2107. OverloadDecl->isCPUSpecificMultiVersion()))) {
  2108. ZeroArgCallReturnTy = QualType();
  2109. Ambiguous = true;
  2110. } else {
  2111. ZeroArgCallReturnTy = OverloadDecl->getReturnType();
  2112. IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
  2113. OverloadDecl->isCPUSpecificMultiVersion();
  2114. }
  2115. }
  2116. }
  2117. }
  2118. // If it's not a member, use better machinery to try to resolve the call
  2119. if (!IsMemExpr)
  2120. return !ZeroArgCallReturnTy.isNull();
  2121. }
  2122. // Attempt to call the member with no arguments - this will correctly handle
  2123. // member templates with defaults/deduction of template arguments, overloads
  2124. // with default arguments, etc.
  2125. if (IsMemExpr && !E.isTypeDependent()) {
  2126. Sema::TentativeAnalysisScope Trap(*this);
  2127. ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
  2128. None, SourceLocation());
  2129. if (R.isUsable()) {
  2130. ZeroArgCallReturnTy = R.get()->getType();
  2131. return true;
  2132. }
  2133. return false;
  2134. }
  2135. if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
  2136. if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
  2137. if (Fun->getMinRequiredArguments() == 0)
  2138. ZeroArgCallReturnTy = Fun->getReturnType();
  2139. return true;
  2140. }
  2141. }
  2142. // We don't have an expression that's convenient to get a FunctionDecl from,
  2143. // but we can at least check if the type is "function of 0 arguments".
  2144. QualType ExprTy = E.getType();
  2145. const FunctionType *FunTy = nullptr;
  2146. QualType PointeeTy = ExprTy->getPointeeType();
  2147. if (!PointeeTy.isNull())
  2148. FunTy = PointeeTy->getAs<FunctionType>();
  2149. if (!FunTy)
  2150. FunTy = ExprTy->getAs<FunctionType>();
  2151. if (const FunctionProtoType *FPT =
  2152. dyn_cast_or_null<FunctionProtoType>(FunTy)) {
  2153. if (FPT->getNumParams() == 0)
  2154. ZeroArgCallReturnTy = FunTy->getReturnType();
  2155. return true;
  2156. }
  2157. return false;
  2158. }
  2159. /// Give notes for a set of overloads.
  2160. ///
  2161. /// A companion to tryExprAsCall. In cases when the name that the programmer
  2162. /// wrote was an overloaded function, we may be able to make some guesses about
  2163. /// plausible overloads based on their return types; such guesses can be handed
  2164. /// off to this method to be emitted as notes.
  2165. ///
  2166. /// \param Overloads - The overloads to note.
  2167. /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
  2168. /// -fshow-overloads=best, this is the location to attach to the note about too
  2169. /// many candidates. Typically this will be the location of the original
  2170. /// ill-formed expression.
  2171. static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
  2172. const SourceLocation FinalNoteLoc) {
  2173. unsigned ShownOverloads = 0;
  2174. unsigned SuppressedOverloads = 0;
  2175. for (UnresolvedSetImpl::iterator It = Overloads.begin(),
  2176. DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
  2177. if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
  2178. ++SuppressedOverloads;
  2179. continue;
  2180. }
  2181. NamedDecl *Fn = (*It)->getUnderlyingDecl();
  2182. // Don't print overloads for non-default multiversioned functions.
  2183. if (const auto *FD = Fn->getAsFunction()) {
  2184. if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
  2185. !FD->getAttr<TargetAttr>()->isDefaultVersion())
  2186. continue;
  2187. }
  2188. S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
  2189. ++ShownOverloads;
  2190. }
  2191. S.Diags.overloadCandidatesShown(ShownOverloads);
  2192. if (SuppressedOverloads)
  2193. S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
  2194. << SuppressedOverloads;
  2195. }
  2196. static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
  2197. const UnresolvedSetImpl &Overloads,
  2198. bool (*IsPlausibleResult)(QualType)) {
  2199. if (!IsPlausibleResult)
  2200. return noteOverloads(S, Overloads, Loc);
  2201. UnresolvedSet<2> PlausibleOverloads;
  2202. for (OverloadExpr::decls_iterator It = Overloads.begin(),
  2203. DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
  2204. const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
  2205. QualType OverloadResultTy = OverloadDecl->getReturnType();
  2206. if (IsPlausibleResult(OverloadResultTy))
  2207. PlausibleOverloads.addDecl(It.getDecl());
  2208. }
  2209. noteOverloads(S, PlausibleOverloads, Loc);
  2210. }
  2211. /// Determine whether the given expression can be called by just
  2212. /// putting parentheses after it. Notably, expressions with unary
  2213. /// operators can't be because the unary operator will start parsing
  2214. /// outside the call.
  2215. static bool IsCallableWithAppend(Expr *E) {
  2216. E = E->IgnoreImplicit();
  2217. return (!isa<CStyleCastExpr>(E) &&
  2218. !isa<UnaryOperator>(E) &&
  2219. !isa<BinaryOperator>(E) &&
  2220. !isa<CXXOperatorCallExpr>(E));
  2221. }
  2222. static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
  2223. if (const auto *UO = dyn_cast<UnaryOperator>(E))
  2224. E = UO->getSubExpr();
  2225. if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  2226. if (ULE->getNumDecls() == 0)
  2227. return false;
  2228. const NamedDecl *ND = *ULE->decls_begin();
  2229. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  2230. return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
  2231. }
  2232. return false;
  2233. }
  2234. bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
  2235. bool ForceComplain,
  2236. bool (*IsPlausibleResult)(QualType)) {
  2237. SourceLocation Loc = E.get()->getExprLoc();
  2238. SourceRange Range = E.get()->getSourceRange();
  2239. UnresolvedSet<4> Overloads;
  2240. // If this is a SFINAE context, don't try anything that might trigger ADL
  2241. // prematurely.
  2242. if (!isSFINAEContext()) {
  2243. QualType ZeroArgCallTy;
  2244. if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
  2245. !ZeroArgCallTy.isNull() &&
  2246. (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
  2247. // At this point, we know E is potentially callable with 0
  2248. // arguments and that it returns something of a reasonable type,
  2249. // so we can emit a fixit and carry on pretending that E was
  2250. // actually a CallExpr.
  2251. SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
  2252. bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
  2253. Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
  2254. << (IsCallableWithAppend(E.get())
  2255. ? FixItHint::CreateInsertion(ParenInsertionLoc,
  2256. "()")
  2257. : FixItHint());
  2258. if (!IsMV)
  2259. notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
  2260. // FIXME: Try this before emitting the fixit, and suppress diagnostics
  2261. // while doing so.
  2262. E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), None,
  2263. Range.getEnd().getLocWithOffset(1));
  2264. return true;
  2265. }
  2266. }
  2267. if (!ForceComplain) return false;
  2268. bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
  2269. Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
  2270. if (!IsMV)
  2271. notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
  2272. E = ExprError();
  2273. return true;
  2274. }
  2275. IdentifierInfo *Sema::getSuperIdentifier() const {
  2276. if (!Ident_super)
  2277. Ident_super = &Context.Idents.get("super");
  2278. return Ident_super;
  2279. }
  2280. IdentifierInfo *Sema::getFloat128Identifier() const {
  2281. if (!Ident___float128)
  2282. Ident___float128 = &Context.Idents.get("__float128");
  2283. return Ident___float128;
  2284. }
  2285. void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
  2286. CapturedRegionKind K,
  2287. unsigned OpenMPCaptureLevel) {
  2288. auto *CSI = new CapturedRegionScopeInfo(
  2289. getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
  2290. (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0,
  2291. OpenMPCaptureLevel);
  2292. CSI->ReturnType = Context.VoidTy;
  2293. FunctionScopes.push_back(CSI);
  2294. }
  2295. CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
  2296. if (FunctionScopes.empty())
  2297. return nullptr;
  2298. return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
  2299. }
  2300. const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
  2301. Sema::getMismatchingDeleteExpressions() const {
  2302. return DeleteExprs;
  2303. }