Decl.h 181 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- Decl.h - Classes for representing declarations -----------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the Decl subclasses.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_CLANG_AST_DECL_H
  18. #define LLVM_CLANG_AST_DECL_H
  19. #include "clang/AST/APValue.h"
  20. #include "clang/AST/ASTContextAllocate.h"
  21. #include "clang/AST/DeclAccessPair.h"
  22. #include "clang/AST/DeclBase.h"
  23. #include "clang/AST/DeclarationName.h"
  24. #include "clang/AST/ExternalASTSource.h"
  25. #include "clang/AST/NestedNameSpecifier.h"
  26. #include "clang/AST/Redeclarable.h"
  27. #include "clang/AST/Type.h"
  28. #include "clang/Basic/AddressSpaces.h"
  29. #include "clang/Basic/Diagnostic.h"
  30. #include "clang/Basic/IdentifierTable.h"
  31. #include "clang/Basic/LLVM.h"
  32. #include "clang/Basic/Linkage.h"
  33. #include "clang/Basic/OperatorKinds.h"
  34. #include "clang/Basic/PartialDiagnostic.h"
  35. #include "clang/Basic/PragmaKinds.h"
  36. #include "clang/Basic/SourceLocation.h"
  37. #include "clang/Basic/Specifiers.h"
  38. #include "clang/Basic/Visibility.h"
  39. #include "llvm/ADT/APSInt.h"
  40. #include "llvm/ADT/ArrayRef.h"
  41. #include "llvm/ADT/PointerIntPair.h"
  42. #include "llvm/ADT/PointerUnion.h"
  43. #include "llvm/ADT/StringRef.h"
  44. #include "llvm/ADT/iterator_range.h"
  45. #include "llvm/Support/Casting.h"
  46. #include "llvm/Support/Compiler.h"
  47. #include "llvm/Support/TrailingObjects.h"
  48. #include <cassert>
  49. #include <cstddef>
  50. #include <cstdint>
  51. #include <optional>
  52. #include <string>
  53. #include <utility>
  54. namespace clang {
  55. class ASTContext;
  56. struct ASTTemplateArgumentListInfo;
  57. class CompoundStmt;
  58. class DependentFunctionTemplateSpecializationInfo;
  59. class EnumDecl;
  60. class Expr;
  61. class FunctionTemplateDecl;
  62. class FunctionTemplateSpecializationInfo;
  63. class FunctionTypeLoc;
  64. class LabelStmt;
  65. class MemberSpecializationInfo;
  66. class Module;
  67. class NamespaceDecl;
  68. class ParmVarDecl;
  69. class RecordDecl;
  70. class Stmt;
  71. class StringLiteral;
  72. class TagDecl;
  73. class TemplateArgumentList;
  74. class TemplateArgumentListInfo;
  75. class TemplateParameterList;
  76. class TypeAliasTemplateDecl;
  77. class UnresolvedSetImpl;
  78. class VarTemplateDecl;
  79. /// The top declaration context.
  80. class TranslationUnitDecl : public Decl,
  81. public DeclContext,
  82. public Redeclarable<TranslationUnitDecl> {
  83. using redeclarable_base = Redeclarable<TranslationUnitDecl>;
  84. TranslationUnitDecl *getNextRedeclarationImpl() override {
  85. return getNextRedeclaration();
  86. }
  87. TranslationUnitDecl *getPreviousDeclImpl() override {
  88. return getPreviousDecl();
  89. }
  90. TranslationUnitDecl *getMostRecentDeclImpl() override {
  91. return getMostRecentDecl();
  92. }
  93. ASTContext &Ctx;
  94. /// The (most recently entered) anonymous namespace for this
  95. /// translation unit, if one has been created.
  96. NamespaceDecl *AnonymousNamespace = nullptr;
  97. explicit TranslationUnitDecl(ASTContext &ctx);
  98. virtual void anchor();
  99. public:
  100. using redecl_range = redeclarable_base::redecl_range;
  101. using redecl_iterator = redeclarable_base::redecl_iterator;
  102. using redeclarable_base::getMostRecentDecl;
  103. using redeclarable_base::getPreviousDecl;
  104. using redeclarable_base::isFirstDecl;
  105. using redeclarable_base::redecls;
  106. using redeclarable_base::redecls_begin;
  107. using redeclarable_base::redecls_end;
  108. ASTContext &getASTContext() const { return Ctx; }
  109. NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
  110. void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
  111. static TranslationUnitDecl *Create(ASTContext &C);
  112. // Implement isa/cast/dyncast/etc.
  113. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  114. static bool classofKind(Kind K) { return K == TranslationUnit; }
  115. static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
  116. return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
  117. }
  118. static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
  119. return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
  120. }
  121. };
  122. /// Represents a `#pragma comment` line. Always a child of
  123. /// TranslationUnitDecl.
  124. class PragmaCommentDecl final
  125. : public Decl,
  126. private llvm::TrailingObjects<PragmaCommentDecl, char> {
  127. friend class ASTDeclReader;
  128. friend class ASTDeclWriter;
  129. friend TrailingObjects;
  130. PragmaMSCommentKind CommentKind;
  131. PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
  132. PragmaMSCommentKind CommentKind)
  133. : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
  134. virtual void anchor();
  135. public:
  136. static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
  137. SourceLocation CommentLoc,
  138. PragmaMSCommentKind CommentKind,
  139. StringRef Arg);
  140. static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
  141. unsigned ArgSize);
  142. PragmaMSCommentKind getCommentKind() const { return CommentKind; }
  143. StringRef getArg() const { return getTrailingObjects<char>(); }
  144. // Implement isa/cast/dyncast/etc.
  145. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  146. static bool classofKind(Kind K) { return K == PragmaComment; }
  147. };
  148. /// Represents a `#pragma detect_mismatch` line. Always a child of
  149. /// TranslationUnitDecl.
  150. class PragmaDetectMismatchDecl final
  151. : public Decl,
  152. private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
  153. friend class ASTDeclReader;
  154. friend class ASTDeclWriter;
  155. friend TrailingObjects;
  156. size_t ValueStart;
  157. PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
  158. size_t ValueStart)
  159. : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
  160. virtual void anchor();
  161. public:
  162. static PragmaDetectMismatchDecl *Create(const ASTContext &C,
  163. TranslationUnitDecl *DC,
  164. SourceLocation Loc, StringRef Name,
  165. StringRef Value);
  166. static PragmaDetectMismatchDecl *
  167. CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
  168. StringRef getName() const { return getTrailingObjects<char>(); }
  169. StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
  170. // Implement isa/cast/dyncast/etc.
  171. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  172. static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
  173. };
  174. /// Declaration context for names declared as extern "C" in C++. This
  175. /// is neither the semantic nor lexical context for such declarations, but is
  176. /// used to check for conflicts with other extern "C" declarations. Example:
  177. ///
  178. /// \code
  179. /// namespace N { extern "C" void f(); } // #1
  180. /// void N::f() {} // #2
  181. /// namespace M { extern "C" void f(); } // #3
  182. /// \endcode
  183. ///
  184. /// The semantic context of #1 is namespace N and its lexical context is the
  185. /// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
  186. /// context is the TU. However, both declarations are also visible in the
  187. /// extern "C" context.
  188. ///
  189. /// The declaration at #3 finds it is a redeclaration of \c N::f through
  190. /// lookup in the extern "C" context.
  191. class ExternCContextDecl : public Decl, public DeclContext {
  192. explicit ExternCContextDecl(TranslationUnitDecl *TU)
  193. : Decl(ExternCContext, TU, SourceLocation()),
  194. DeclContext(ExternCContext) {}
  195. virtual void anchor();
  196. public:
  197. static ExternCContextDecl *Create(const ASTContext &C,
  198. TranslationUnitDecl *TU);
  199. // Implement isa/cast/dyncast/etc.
  200. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  201. static bool classofKind(Kind K) { return K == ExternCContext; }
  202. static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
  203. return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
  204. }
  205. static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
  206. return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
  207. }
  208. };
  209. /// This represents a decl that may have a name. Many decls have names such
  210. /// as ObjCMethodDecl, but not \@class, etc.
  211. ///
  212. /// Note that not every NamedDecl is actually named (e.g., a struct might
  213. /// be anonymous), and not every name is an identifier.
  214. class NamedDecl : public Decl {
  215. /// The name of this declaration, which is typically a normal
  216. /// identifier but may also be a special kind of name (C++
  217. /// constructor, Objective-C selector, etc.)
  218. DeclarationName Name;
  219. virtual void anchor();
  220. private:
  221. NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY;
  222. protected:
  223. NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
  224. : Decl(DK, DC, L), Name(N) {}
  225. public:
  226. /// Get the identifier that names this declaration, if there is one.
  227. ///
  228. /// This will return NULL if this declaration has no name (e.g., for
  229. /// an unnamed class) or if the name is a special name (C++ constructor,
  230. /// Objective-C selector, etc.).
  231. IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
  232. /// Get the name of identifier for this declaration as a StringRef.
  233. ///
  234. /// This requires that the declaration have a name and that it be a simple
  235. /// identifier.
  236. StringRef getName() const {
  237. assert(Name.isIdentifier() && "Name is not a simple identifier");
  238. return getIdentifier() ? getIdentifier()->getName() : "";
  239. }
  240. /// Get a human-readable name for the declaration, even if it is one of the
  241. /// special kinds of names (C++ constructor, Objective-C selector, etc).
  242. ///
  243. /// Creating this name requires expensive string manipulation, so it should
  244. /// be called only when performance doesn't matter. For simple declarations,
  245. /// getNameAsCString() should suffice.
  246. //
  247. // FIXME: This function should be renamed to indicate that it is not just an
  248. // alternate form of getName(), and clients should move as appropriate.
  249. //
  250. // FIXME: Deprecated, move clients to getName().
  251. std::string getNameAsString() const { return Name.getAsString(); }
  252. /// Pretty-print the unqualified name of this declaration. Can be overloaded
  253. /// by derived classes to provide a more user-friendly name when appropriate.
  254. virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const;
  255. /// Calls printName() with the ASTContext printing policy from the decl.
  256. void printName(raw_ostream &OS) const;
  257. /// Get the actual, stored name of the declaration, which may be a special
  258. /// name.
  259. ///
  260. /// Note that generally in diagnostics, the non-null \p NamedDecl* itself
  261. /// should be sent into the diagnostic instead of using the result of
  262. /// \p getDeclName().
  263. ///
  264. /// A \p DeclarationName in a diagnostic will just be streamed to the output,
  265. /// which will directly result in a call to \p DeclarationName::print.
  266. ///
  267. /// A \p NamedDecl* in a diagnostic will also ultimately result in a call to
  268. /// \p DeclarationName::print, but with two customisation points along the
  269. /// way (\p getNameForDiagnostic and \p printName). These are used to print
  270. /// the template arguments if any, and to provide a user-friendly name for
  271. /// some entities (such as unnamed variables and anonymous records).
  272. DeclarationName getDeclName() const { return Name; }
  273. /// Set the name of this declaration.
  274. void setDeclName(DeclarationName N) { Name = N; }
  275. /// Returns a human-readable qualified name for this declaration, like
  276. /// A::B::i, for i being member of namespace A::B.
  277. ///
  278. /// If the declaration is not a member of context which can be named (record,
  279. /// namespace), it will return the same result as printName().
  280. ///
  281. /// Creating this name is expensive, so it should be called only when
  282. /// performance doesn't matter.
  283. void printQualifiedName(raw_ostream &OS) const;
  284. void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
  285. /// Print only the nested name specifier part of a fully-qualified name,
  286. /// including the '::' at the end. E.g.
  287. /// when `printQualifiedName(D)` prints "A::B::i",
  288. /// this function prints "A::B::".
  289. void printNestedNameSpecifier(raw_ostream &OS) const;
  290. void printNestedNameSpecifier(raw_ostream &OS,
  291. const PrintingPolicy &Policy) const;
  292. // FIXME: Remove string version.
  293. std::string getQualifiedNameAsString() const;
  294. /// Appends a human-readable name for this declaration into the given stream.
  295. ///
  296. /// This is the method invoked by Sema when displaying a NamedDecl
  297. /// in a diagnostic. It does not necessarily produce the same
  298. /// result as printName(); for example, class template
  299. /// specializations are printed with their template arguments.
  300. virtual void getNameForDiagnostic(raw_ostream &OS,
  301. const PrintingPolicy &Policy,
  302. bool Qualified) const;
  303. /// Determine whether this declaration, if known to be well-formed within
  304. /// its context, will replace the declaration OldD if introduced into scope.
  305. ///
  306. /// A declaration will replace another declaration if, for example, it is
  307. /// a redeclaration of the same variable or function, but not if it is a
  308. /// declaration of a different kind (function vs. class) or an overloaded
  309. /// function.
  310. ///
  311. /// \param IsKnownNewer \c true if this declaration is known to be newer
  312. /// than \p OldD (for instance, if this declaration is newly-created).
  313. bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
  314. /// Determine whether this declaration has linkage.
  315. bool hasLinkage() const;
  316. using Decl::isModulePrivate;
  317. using Decl::setModulePrivate;
  318. /// Determine whether this declaration is a C++ class member.
  319. bool isCXXClassMember() const {
  320. const DeclContext *DC = getDeclContext();
  321. // C++0x [class.mem]p1:
  322. // The enumerators of an unscoped enumeration defined in
  323. // the class are members of the class.
  324. if (isa<EnumDecl>(DC))
  325. DC = DC->getRedeclContext();
  326. return DC->isRecord();
  327. }
  328. /// Determine whether the given declaration is an instance member of
  329. /// a C++ class.
  330. bool isCXXInstanceMember() const;
  331. /// Determine if the declaration obeys the reserved identifier rules of the
  332. /// given language.
  333. ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const;
  334. /// Determine what kind of linkage this entity has.
  335. ///
  336. /// This is not the linkage as defined by the standard or the codegen notion
  337. /// of linkage. It is just an implementation detail that is used to compute
  338. /// those.
  339. Linkage getLinkageInternal() const;
  340. /// Get the linkage from a semantic point of view. Entities in
  341. /// anonymous namespaces are external (in c++98).
  342. Linkage getFormalLinkage() const {
  343. return clang::getFormalLinkage(getLinkageInternal());
  344. }
  345. /// True if this decl has external linkage.
  346. bool hasExternalFormalLinkage() const {
  347. return isExternalFormalLinkage(getLinkageInternal());
  348. }
  349. bool isExternallyVisible() const {
  350. return clang::isExternallyVisible(getLinkageInternal());
  351. }
  352. /// Determine whether this declaration can be redeclared in a
  353. /// different translation unit.
  354. bool isExternallyDeclarable() const {
  355. return isExternallyVisible() && !getOwningModuleForLinkage();
  356. }
  357. /// Determines the visibility of this entity.
  358. Visibility getVisibility() const {
  359. return getLinkageAndVisibility().getVisibility();
  360. }
  361. /// Determines the linkage and visibility of this entity.
  362. LinkageInfo getLinkageAndVisibility() const;
  363. /// Kinds of explicit visibility.
  364. enum ExplicitVisibilityKind {
  365. /// Do an LV computation for, ultimately, a type.
  366. /// Visibility may be restricted by type visibility settings and
  367. /// the visibility of template arguments.
  368. VisibilityForType,
  369. /// Do an LV computation for, ultimately, a non-type declaration.
  370. /// Visibility may be restricted by value visibility settings and
  371. /// the visibility of template arguments.
  372. VisibilityForValue
  373. };
  374. /// If visibility was explicitly specified for this
  375. /// declaration, return that visibility.
  376. std::optional<Visibility>
  377. getExplicitVisibility(ExplicitVisibilityKind kind) const;
  378. /// True if the computed linkage is valid. Used for consistency
  379. /// checking. Should always return true.
  380. bool isLinkageValid() const;
  381. /// True if something has required us to compute the linkage
  382. /// of this declaration.
  383. ///
  384. /// Language features which can retroactively change linkage (like a
  385. /// typedef name for linkage purposes) may need to consider this,
  386. /// but hopefully only in transitory ways during parsing.
  387. bool hasLinkageBeenComputed() const {
  388. return hasCachedLinkage();
  389. }
  390. /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
  391. /// the underlying named decl.
  392. NamedDecl *getUnderlyingDecl() {
  393. // Fast-path the common case.
  394. if (this->getKind() != UsingShadow &&
  395. this->getKind() != ConstructorUsingShadow &&
  396. this->getKind() != ObjCCompatibleAlias &&
  397. this->getKind() != NamespaceAlias)
  398. return this;
  399. return getUnderlyingDeclImpl();
  400. }
  401. const NamedDecl *getUnderlyingDecl() const {
  402. return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
  403. }
  404. NamedDecl *getMostRecentDecl() {
  405. return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
  406. }
  407. const NamedDecl *getMostRecentDecl() const {
  408. return const_cast<NamedDecl*>(this)->getMostRecentDecl();
  409. }
  410. ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
  411. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  412. static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
  413. };
  414. inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
  415. ND.printName(OS);
  416. return OS;
  417. }
  418. /// Represents the declaration of a label. Labels also have a
  419. /// corresponding LabelStmt, which indicates the position that the label was
  420. /// defined at. For normal labels, the location of the decl is the same as the
  421. /// location of the statement. For GNU local labels (__label__), the decl
  422. /// location is where the __label__ is.
  423. class LabelDecl : public NamedDecl {
  424. LabelStmt *TheStmt;
  425. StringRef MSAsmName;
  426. bool MSAsmNameResolved = false;
  427. /// For normal labels, this is the same as the main declaration
  428. /// label, i.e., the location of the identifier; for GNU local labels,
  429. /// this is the location of the __label__ keyword.
  430. SourceLocation LocStart;
  431. LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
  432. LabelStmt *S, SourceLocation StartL)
  433. : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
  434. void anchor() override;
  435. public:
  436. static LabelDecl *Create(ASTContext &C, DeclContext *DC,
  437. SourceLocation IdentL, IdentifierInfo *II);
  438. static LabelDecl *Create(ASTContext &C, DeclContext *DC,
  439. SourceLocation IdentL, IdentifierInfo *II,
  440. SourceLocation GnuLabelL);
  441. static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  442. LabelStmt *getStmt() const { return TheStmt; }
  443. void setStmt(LabelStmt *T) { TheStmt = T; }
  444. bool isGnuLocal() const { return LocStart != getLocation(); }
  445. void setLocStart(SourceLocation L) { LocStart = L; }
  446. SourceRange getSourceRange() const override LLVM_READONLY {
  447. return SourceRange(LocStart, getLocation());
  448. }
  449. bool isMSAsmLabel() const { return !MSAsmName.empty(); }
  450. bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
  451. void setMSAsmLabel(StringRef Name);
  452. StringRef getMSAsmLabel() const { return MSAsmName; }
  453. void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
  454. // Implement isa/cast/dyncast/etc.
  455. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  456. static bool classofKind(Kind K) { return K == Label; }
  457. };
  458. /// Represent a C++ namespace.
  459. class NamespaceDecl : public NamedDecl, public DeclContext,
  460. public Redeclarable<NamespaceDecl>
  461. {
  462. enum Flags : unsigned { F_Inline = 1 << 0, F_Nested = 1 << 1 };
  463. /// The starting location of the source range, pointing
  464. /// to either the namespace or the inline keyword.
  465. SourceLocation LocStart;
  466. /// The ending location of the source range.
  467. SourceLocation RBraceLoc;
  468. /// A pointer to either the anonymous namespace that lives just inside
  469. /// this namespace or to the first namespace in the chain (the latter case
  470. /// only when this is not the first in the chain), along with a
  471. /// boolean value indicating whether this is an inline namespace.
  472. llvm::PointerIntPair<NamespaceDecl *, 2, unsigned>
  473. AnonOrFirstNamespaceAndFlags;
  474. NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
  475. SourceLocation StartLoc, SourceLocation IdLoc,
  476. IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested);
  477. using redeclarable_base = Redeclarable<NamespaceDecl>;
  478. NamespaceDecl *getNextRedeclarationImpl() override;
  479. NamespaceDecl *getPreviousDeclImpl() override;
  480. NamespaceDecl *getMostRecentDeclImpl() override;
  481. public:
  482. friend class ASTDeclReader;
  483. friend class ASTDeclWriter;
  484. static NamespaceDecl *Create(ASTContext &C, DeclContext *DC, bool Inline,
  485. SourceLocation StartLoc, SourceLocation IdLoc,
  486. IdentifierInfo *Id, NamespaceDecl *PrevDecl,
  487. bool Nested);
  488. static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  489. using redecl_range = redeclarable_base::redecl_range;
  490. using redecl_iterator = redeclarable_base::redecl_iterator;
  491. using redeclarable_base::redecls_begin;
  492. using redeclarable_base::redecls_end;
  493. using redeclarable_base::redecls;
  494. using redeclarable_base::getPreviousDecl;
  495. using redeclarable_base::getMostRecentDecl;
  496. using redeclarable_base::isFirstDecl;
  497. /// Returns true if this is an anonymous namespace declaration.
  498. ///
  499. /// For example:
  500. /// \code
  501. /// namespace {
  502. /// ...
  503. /// };
  504. /// \endcode
  505. /// q.v. C++ [namespace.unnamed]
  506. bool isAnonymousNamespace() const {
  507. return !getIdentifier();
  508. }
  509. /// Returns true if this is an inline namespace declaration.
  510. bool isInline() const {
  511. return AnonOrFirstNamespaceAndFlags.getInt() & F_Inline;
  512. }
  513. /// Set whether this is an inline namespace declaration.
  514. void setInline(bool Inline) {
  515. unsigned F = AnonOrFirstNamespaceAndFlags.getInt();
  516. if (Inline)
  517. AnonOrFirstNamespaceAndFlags.setInt(F | F_Inline);
  518. else
  519. AnonOrFirstNamespaceAndFlags.setInt(F & ~F_Inline);
  520. }
  521. /// Returns true if this is a nested namespace declaration.
  522. /// \code
  523. /// namespace outer::nested { }
  524. /// \endcode
  525. bool isNested() const {
  526. return AnonOrFirstNamespaceAndFlags.getInt() & F_Nested;
  527. }
  528. /// Set whether this is a nested namespace declaration.
  529. void setNested(bool Nested) {
  530. unsigned F = AnonOrFirstNamespaceAndFlags.getInt();
  531. if (Nested)
  532. AnonOrFirstNamespaceAndFlags.setInt(F | F_Nested);
  533. else
  534. AnonOrFirstNamespaceAndFlags.setInt(F & ~F_Nested);
  535. }
  536. /// Returns true if the inline qualifier for \c Name is redundant.
  537. bool isRedundantInlineQualifierFor(DeclarationName Name) const {
  538. if (!isInline())
  539. return false;
  540. auto X = lookup(Name);
  541. // We should not perform a lookup within a transparent context, so find a
  542. // non-transparent parent context.
  543. auto Y = getParent()->getNonTransparentContext()->lookup(Name);
  544. return std::distance(X.begin(), X.end()) ==
  545. std::distance(Y.begin(), Y.end());
  546. }
  547. /// Get the original (first) namespace declaration.
  548. NamespaceDecl *getOriginalNamespace();
  549. /// Get the original (first) namespace declaration.
  550. const NamespaceDecl *getOriginalNamespace() const;
  551. /// Return true if this declaration is an original (first) declaration
  552. /// of the namespace. This is false for non-original (subsequent) namespace
  553. /// declarations and anonymous namespaces.
  554. bool isOriginalNamespace() const;
  555. /// Retrieve the anonymous namespace nested inside this namespace,
  556. /// if any.
  557. NamespaceDecl *getAnonymousNamespace() const {
  558. return getOriginalNamespace()->AnonOrFirstNamespaceAndFlags.getPointer();
  559. }
  560. void setAnonymousNamespace(NamespaceDecl *D) {
  561. getOriginalNamespace()->AnonOrFirstNamespaceAndFlags.setPointer(D);
  562. }
  563. /// Retrieves the canonical declaration of this namespace.
  564. NamespaceDecl *getCanonicalDecl() override {
  565. return getOriginalNamespace();
  566. }
  567. const NamespaceDecl *getCanonicalDecl() const {
  568. return getOriginalNamespace();
  569. }
  570. SourceRange getSourceRange() const override LLVM_READONLY {
  571. return SourceRange(LocStart, RBraceLoc);
  572. }
  573. SourceLocation getBeginLoc() const LLVM_READONLY { return LocStart; }
  574. SourceLocation getRBraceLoc() const { return RBraceLoc; }
  575. void setLocStart(SourceLocation L) { LocStart = L; }
  576. void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
  577. // Implement isa/cast/dyncast/etc.
  578. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  579. static bool classofKind(Kind K) { return K == Namespace; }
  580. static DeclContext *castToDeclContext(const NamespaceDecl *D) {
  581. return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
  582. }
  583. static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
  584. return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
  585. }
  586. };
  587. class VarDecl;
  588. /// Represent the declaration of a variable (in which case it is
  589. /// an lvalue) a function (in which case it is a function designator) or
  590. /// an enum constant.
  591. class ValueDecl : public NamedDecl {
  592. QualType DeclType;
  593. void anchor() override;
  594. protected:
  595. ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
  596. DeclarationName N, QualType T)
  597. : NamedDecl(DK, DC, L, N), DeclType(T) {}
  598. public:
  599. QualType getType() const { return DeclType; }
  600. void setType(QualType newType) { DeclType = newType; }
  601. /// Determine whether this symbol is weakly-imported,
  602. /// or declared with the weak or weak-ref attr.
  603. bool isWeak() const;
  604. /// Whether this variable is the implicit variable for a lambda init-capture.
  605. /// Only VarDecl can be init captures, but both VarDecl and BindingDecl
  606. /// can be captured.
  607. bool isInitCapture() const;
  608. // If this is a VarDecl, or a BindindDecl with an
  609. // associated decomposed VarDecl, return that VarDecl.
  610. VarDecl *getPotentiallyDecomposedVarDecl();
  611. const VarDecl *getPotentiallyDecomposedVarDecl() const {
  612. return const_cast<ValueDecl *>(this)->getPotentiallyDecomposedVarDecl();
  613. }
  614. // Implement isa/cast/dyncast/etc.
  615. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  616. static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
  617. };
  618. /// A struct with extended info about a syntactic
  619. /// name qualifier, to be used for the case of out-of-line declarations.
  620. struct QualifierInfo {
  621. NestedNameSpecifierLoc QualifierLoc;
  622. /// The number of "outer" template parameter lists.
  623. /// The count includes all of the template parameter lists that were matched
  624. /// against the template-ids occurring into the NNS and possibly (in the
  625. /// case of an explicit specialization) a final "template <>".
  626. unsigned NumTemplParamLists = 0;
  627. /// A new-allocated array of size NumTemplParamLists,
  628. /// containing pointers to the "outer" template parameter lists.
  629. /// It includes all of the template parameter lists that were matched
  630. /// against the template-ids occurring into the NNS and possibly (in the
  631. /// case of an explicit specialization) a final "template <>".
  632. TemplateParameterList** TemplParamLists = nullptr;
  633. QualifierInfo() = default;
  634. QualifierInfo(const QualifierInfo &) = delete;
  635. QualifierInfo& operator=(const QualifierInfo &) = delete;
  636. /// Sets info about "outer" template parameter lists.
  637. void setTemplateParameterListsInfo(ASTContext &Context,
  638. ArrayRef<TemplateParameterList *> TPLists);
  639. };
  640. /// Represents a ValueDecl that came out of a declarator.
  641. /// Contains type source information through TypeSourceInfo.
  642. class DeclaratorDecl : public ValueDecl {
  643. // A struct representing a TInfo, a trailing requires-clause and a syntactic
  644. // qualifier, to be used for the (uncommon) case of out-of-line declarations
  645. // and constrained function decls.
  646. struct ExtInfo : public QualifierInfo {
  647. TypeSourceInfo *TInfo;
  648. Expr *TrailingRequiresClause = nullptr;
  649. };
  650. llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
  651. /// The start of the source range for this declaration,
  652. /// ignoring outer template declarations.
  653. SourceLocation InnerLocStart;
  654. bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
  655. ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
  656. const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
  657. protected:
  658. DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
  659. DeclarationName N, QualType T, TypeSourceInfo *TInfo,
  660. SourceLocation StartL)
  661. : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
  662. public:
  663. friend class ASTDeclReader;
  664. friend class ASTDeclWriter;
  665. TypeSourceInfo *getTypeSourceInfo() const {
  666. return hasExtInfo()
  667. ? getExtInfo()->TInfo
  668. : DeclInfo.get<TypeSourceInfo*>();
  669. }
  670. void setTypeSourceInfo(TypeSourceInfo *TI) {
  671. if (hasExtInfo())
  672. getExtInfo()->TInfo = TI;
  673. else
  674. DeclInfo = TI;
  675. }
  676. /// Return start of source range ignoring outer template declarations.
  677. SourceLocation getInnerLocStart() const { return InnerLocStart; }
  678. void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
  679. /// Return start of source range taking into account any outer template
  680. /// declarations.
  681. SourceLocation getOuterLocStart() const;
  682. SourceRange getSourceRange() const override LLVM_READONLY;
  683. SourceLocation getBeginLoc() const LLVM_READONLY {
  684. return getOuterLocStart();
  685. }
  686. /// Retrieve the nested-name-specifier that qualifies the name of this
  687. /// declaration, if it was present in the source.
  688. NestedNameSpecifier *getQualifier() const {
  689. return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
  690. : nullptr;
  691. }
  692. /// Retrieve the nested-name-specifier (with source-location
  693. /// information) that qualifies the name of this declaration, if it was
  694. /// present in the source.
  695. NestedNameSpecifierLoc getQualifierLoc() const {
  696. return hasExtInfo() ? getExtInfo()->QualifierLoc
  697. : NestedNameSpecifierLoc();
  698. }
  699. void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
  700. /// \brief Get the constraint-expression introduced by the trailing
  701. /// requires-clause in the function/member declaration, or null if no
  702. /// requires-clause was provided.
  703. Expr *getTrailingRequiresClause() {
  704. return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
  705. : nullptr;
  706. }
  707. const Expr *getTrailingRequiresClause() const {
  708. return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
  709. : nullptr;
  710. }
  711. void setTrailingRequiresClause(Expr *TrailingRequiresClause);
  712. unsigned getNumTemplateParameterLists() const {
  713. return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
  714. }
  715. TemplateParameterList *getTemplateParameterList(unsigned index) const {
  716. assert(index < getNumTemplateParameterLists());
  717. return getExtInfo()->TemplParamLists[index];
  718. }
  719. void setTemplateParameterListsInfo(ASTContext &Context,
  720. ArrayRef<TemplateParameterList *> TPLists);
  721. SourceLocation getTypeSpecStartLoc() const;
  722. SourceLocation getTypeSpecEndLoc() const;
  723. // Implement isa/cast/dyncast/etc.
  724. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  725. static bool classofKind(Kind K) {
  726. return K >= firstDeclarator && K <= lastDeclarator;
  727. }
  728. };
  729. /// Structure used to store a statement, the constant value to
  730. /// which it was evaluated (if any), and whether or not the statement
  731. /// is an integral constant expression (if known).
  732. struct EvaluatedStmt {
  733. /// Whether this statement was already evaluated.
  734. bool WasEvaluated : 1;
  735. /// Whether this statement is being evaluated.
  736. bool IsEvaluating : 1;
  737. /// Whether this variable is known to have constant initialization. This is
  738. /// currently only computed in C++, for static / thread storage duration
  739. /// variables that might have constant initialization and for variables that
  740. /// are usable in constant expressions.
  741. bool HasConstantInitialization : 1;
  742. /// Whether this variable is known to have constant destruction. That is,
  743. /// whether running the destructor on the initial value is a side-effect
  744. /// (and doesn't inspect any state that might have changed during program
  745. /// execution). This is currently only computed if the destructor is
  746. /// non-trivial.
  747. bool HasConstantDestruction : 1;
  748. /// In C++98, whether the initializer is an ICE. This affects whether the
  749. /// variable is usable in constant expressions.
  750. bool HasICEInit : 1;
  751. bool CheckedForICEInit : 1;
  752. Stmt *Value;
  753. APValue Evaluated;
  754. EvaluatedStmt()
  755. : WasEvaluated(false), IsEvaluating(false),
  756. HasConstantInitialization(false), HasConstantDestruction(false),
  757. HasICEInit(false), CheckedForICEInit(false) {}
  758. };
  759. /// Represents a variable declaration or definition.
  760. class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
  761. public:
  762. /// Initialization styles.
  763. enum InitializationStyle {
  764. /// C-style initialization with assignment
  765. CInit,
  766. /// Call-style initialization (C++98)
  767. CallInit,
  768. /// Direct list-initialization (C++11)
  769. ListInit,
  770. /// Parenthesized list-initialization (C++20)
  771. ParenListInit
  772. };
  773. /// Kinds of thread-local storage.
  774. enum TLSKind {
  775. /// Not a TLS variable.
  776. TLS_None,
  777. /// TLS with a known-constant initializer.
  778. TLS_Static,
  779. /// TLS with a dynamic initializer.
  780. TLS_Dynamic
  781. };
  782. /// Return the string used to specify the storage class \p SC.
  783. ///
  784. /// It is illegal to call this function with SC == None.
  785. static const char *getStorageClassSpecifierString(StorageClass SC);
  786. protected:
  787. // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
  788. // have allocated the auxiliary struct of information there.
  789. //
  790. // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
  791. // this as *many* VarDecls are ParmVarDecls that don't have default
  792. // arguments. We could save some space by moving this pointer union to be
  793. // allocated in trailing space when necessary.
  794. using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
  795. /// The initializer for this variable or, for a ParmVarDecl, the
  796. /// C++ default argument.
  797. mutable InitType Init;
  798. private:
  799. friend class ASTDeclReader;
  800. friend class ASTNodeImporter;
  801. friend class StmtIteratorBase;
  802. class VarDeclBitfields {
  803. friend class ASTDeclReader;
  804. friend class VarDecl;
  805. unsigned SClass : 3;
  806. unsigned TSCSpec : 2;
  807. unsigned InitStyle : 2;
  808. /// Whether this variable is an ARC pseudo-__strong variable; see
  809. /// isARCPseudoStrong() for details.
  810. unsigned ARCPseudoStrong : 1;
  811. };
  812. enum { NumVarDeclBits = 8 };
  813. protected:
  814. enum { NumParameterIndexBits = 8 };
  815. enum DefaultArgKind {
  816. DAK_None,
  817. DAK_Unparsed,
  818. DAK_Uninstantiated,
  819. DAK_Normal
  820. };
  821. enum { NumScopeDepthOrObjCQualsBits = 7 };
  822. class ParmVarDeclBitfields {
  823. friend class ASTDeclReader;
  824. friend class ParmVarDecl;
  825. unsigned : NumVarDeclBits;
  826. /// Whether this parameter inherits a default argument from a
  827. /// prior declaration.
  828. unsigned HasInheritedDefaultArg : 1;
  829. /// Describes the kind of default argument for this parameter. By default
  830. /// this is none. If this is normal, then the default argument is stored in
  831. /// the \c VarDecl initializer expression unless we were unable to parse
  832. /// (even an invalid) expression for the default argument.
  833. unsigned DefaultArgKind : 2;
  834. /// Whether this parameter undergoes K&R argument promotion.
  835. unsigned IsKNRPromoted : 1;
  836. /// Whether this parameter is an ObjC method parameter or not.
  837. unsigned IsObjCMethodParam : 1;
  838. /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
  839. /// Otherwise, the number of function parameter scopes enclosing
  840. /// the function parameter scope in which this parameter was
  841. /// declared.
  842. unsigned ScopeDepthOrObjCQuals : NumScopeDepthOrObjCQualsBits;
  843. /// The number of parameters preceding this parameter in the
  844. /// function parameter scope in which it was declared.
  845. unsigned ParameterIndex : NumParameterIndexBits;
  846. };
  847. class NonParmVarDeclBitfields {
  848. friend class ASTDeclReader;
  849. friend class ImplicitParamDecl;
  850. friend class VarDecl;
  851. unsigned : NumVarDeclBits;
  852. // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
  853. /// Whether this variable is a definition which was demoted due to
  854. /// module merge.
  855. unsigned IsThisDeclarationADemotedDefinition : 1;
  856. /// Whether this variable is the exception variable in a C++ catch
  857. /// or an Objective-C @catch statement.
  858. unsigned ExceptionVar : 1;
  859. /// Whether this local variable could be allocated in the return
  860. /// slot of its function, enabling the named return value optimization
  861. /// (NRVO).
  862. unsigned NRVOVariable : 1;
  863. /// Whether this variable is the for-range-declaration in a C++0x
  864. /// for-range statement.
  865. unsigned CXXForRangeDecl : 1;
  866. /// Whether this variable is the for-in loop declaration in Objective-C.
  867. unsigned ObjCForDecl : 1;
  868. /// Whether this variable is (C++1z) inline.
  869. unsigned IsInline : 1;
  870. /// Whether this variable has (C++1z) inline explicitly specified.
  871. unsigned IsInlineSpecified : 1;
  872. /// Whether this variable is (C++0x) constexpr.
  873. unsigned IsConstexpr : 1;
  874. /// Whether this variable is the implicit variable for a lambda
  875. /// init-capture.
  876. unsigned IsInitCapture : 1;
  877. /// Whether this local extern variable's previous declaration was
  878. /// declared in the same block scope. This controls whether we should merge
  879. /// the type of this declaration with its previous declaration.
  880. unsigned PreviousDeclInSameBlockScope : 1;
  881. /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
  882. /// something else.
  883. unsigned ImplicitParamKind : 3;
  884. unsigned EscapingByref : 1;
  885. };
  886. union {
  887. unsigned AllBits;
  888. VarDeclBitfields VarDeclBits;
  889. ParmVarDeclBitfields ParmVarDeclBits;
  890. NonParmVarDeclBitfields NonParmVarDeclBits;
  891. };
  892. VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  893. SourceLocation IdLoc, const IdentifierInfo *Id, QualType T,
  894. TypeSourceInfo *TInfo, StorageClass SC);
  895. using redeclarable_base = Redeclarable<VarDecl>;
  896. VarDecl *getNextRedeclarationImpl() override {
  897. return getNextRedeclaration();
  898. }
  899. VarDecl *getPreviousDeclImpl() override {
  900. return getPreviousDecl();
  901. }
  902. VarDecl *getMostRecentDeclImpl() override {
  903. return getMostRecentDecl();
  904. }
  905. public:
  906. using redecl_range = redeclarable_base::redecl_range;
  907. using redecl_iterator = redeclarable_base::redecl_iterator;
  908. using redeclarable_base::redecls_begin;
  909. using redeclarable_base::redecls_end;
  910. using redeclarable_base::redecls;
  911. using redeclarable_base::getPreviousDecl;
  912. using redeclarable_base::getMostRecentDecl;
  913. using redeclarable_base::isFirstDecl;
  914. static VarDecl *Create(ASTContext &C, DeclContext *DC,
  915. SourceLocation StartLoc, SourceLocation IdLoc,
  916. const IdentifierInfo *Id, QualType T,
  917. TypeSourceInfo *TInfo, StorageClass S);
  918. static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  919. SourceRange getSourceRange() const override LLVM_READONLY;
  920. /// Returns the storage class as written in the source. For the
  921. /// computed linkage of symbol, see getLinkage.
  922. StorageClass getStorageClass() const {
  923. return (StorageClass) VarDeclBits.SClass;
  924. }
  925. void setStorageClass(StorageClass SC);
  926. void setTSCSpec(ThreadStorageClassSpecifier TSC) {
  927. VarDeclBits.TSCSpec = TSC;
  928. assert(VarDeclBits.TSCSpec == TSC && "truncation");
  929. }
  930. ThreadStorageClassSpecifier getTSCSpec() const {
  931. return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
  932. }
  933. TLSKind getTLSKind() const;
  934. /// Returns true if a variable with function scope is a non-static local
  935. /// variable.
  936. bool hasLocalStorage() const {
  937. if (getStorageClass() == SC_None) {
  938. // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
  939. // used to describe variables allocated in global memory and which are
  940. // accessed inside a kernel(s) as read-only variables. As such, variables
  941. // in constant address space cannot have local storage.
  942. if (getType().getAddressSpace() == LangAS::opencl_constant)
  943. return false;
  944. // Second check is for C++11 [dcl.stc]p4.
  945. return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
  946. }
  947. // Global Named Register (GNU extension)
  948. if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
  949. return false;
  950. // Return true for: Auto, Register.
  951. // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
  952. return getStorageClass() >= SC_Auto;
  953. }
  954. /// Returns true if a variable with function scope is a static local
  955. /// variable.
  956. bool isStaticLocal() const {
  957. return (getStorageClass() == SC_Static ||
  958. // C++11 [dcl.stc]p4
  959. (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
  960. && !isFileVarDecl();
  961. }
  962. /// Returns true if a variable has extern or __private_extern__
  963. /// storage.
  964. bool hasExternalStorage() const {
  965. return getStorageClass() == SC_Extern ||
  966. getStorageClass() == SC_PrivateExtern;
  967. }
  968. /// Returns true for all variables that do not have local storage.
  969. ///
  970. /// This includes all global variables as well as static variables declared
  971. /// within a function.
  972. bool hasGlobalStorage() const { return !hasLocalStorage(); }
  973. /// Get the storage duration of this variable, per C++ [basic.stc].
  974. StorageDuration getStorageDuration() const {
  975. return hasLocalStorage() ? SD_Automatic :
  976. getTSCSpec() ? SD_Thread : SD_Static;
  977. }
  978. /// Compute the language linkage.
  979. LanguageLinkage getLanguageLinkage() const;
  980. /// Determines whether this variable is a variable with external, C linkage.
  981. bool isExternC() const;
  982. /// Determines whether this variable's context is, or is nested within,
  983. /// a C++ extern "C" linkage spec.
  984. bool isInExternCContext() const;
  985. /// Determines whether this variable's context is, or is nested within,
  986. /// a C++ extern "C++" linkage spec.
  987. bool isInExternCXXContext() const;
  988. /// Returns true for local variable declarations other than parameters.
  989. /// Note that this includes static variables inside of functions. It also
  990. /// includes variables inside blocks.
  991. ///
  992. /// void foo() { int x; static int y; extern int z; }
  993. bool isLocalVarDecl() const {
  994. if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
  995. return false;
  996. if (const DeclContext *DC = getLexicalDeclContext())
  997. return DC->getRedeclContext()->isFunctionOrMethod();
  998. return false;
  999. }
  1000. /// Similar to isLocalVarDecl but also includes parameters.
  1001. bool isLocalVarDeclOrParm() const {
  1002. return isLocalVarDecl() || getKind() == Decl::ParmVar;
  1003. }
  1004. /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
  1005. bool isFunctionOrMethodVarDecl() const {
  1006. if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
  1007. return false;
  1008. const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
  1009. return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
  1010. }
  1011. /// Determines whether this is a static data member.
  1012. ///
  1013. /// This will only be true in C++, and applies to, e.g., the
  1014. /// variable 'x' in:
  1015. /// \code
  1016. /// struct S {
  1017. /// static int x;
  1018. /// };
  1019. /// \endcode
  1020. bool isStaticDataMember() const {
  1021. // If it wasn't static, it would be a FieldDecl.
  1022. return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
  1023. }
  1024. VarDecl *getCanonicalDecl() override;
  1025. const VarDecl *getCanonicalDecl() const {
  1026. return const_cast<VarDecl*>(this)->getCanonicalDecl();
  1027. }
  1028. enum DefinitionKind {
  1029. /// This declaration is only a declaration.
  1030. DeclarationOnly,
  1031. /// This declaration is a tentative definition.
  1032. TentativeDefinition,
  1033. /// This declaration is definitely a definition.
  1034. Definition
  1035. };
  1036. /// Check whether this declaration is a definition. If this could be
  1037. /// a tentative definition (in C), don't check whether there's an overriding
  1038. /// definition.
  1039. DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
  1040. DefinitionKind isThisDeclarationADefinition() const {
  1041. return isThisDeclarationADefinition(getASTContext());
  1042. }
  1043. /// Check whether this variable is defined in this translation unit.
  1044. DefinitionKind hasDefinition(ASTContext &) const;
  1045. DefinitionKind hasDefinition() const {
  1046. return hasDefinition(getASTContext());
  1047. }
  1048. /// Get the tentative definition that acts as the real definition in a TU.
  1049. /// Returns null if there is a proper definition available.
  1050. VarDecl *getActingDefinition();
  1051. const VarDecl *getActingDefinition() const {
  1052. return const_cast<VarDecl*>(this)->getActingDefinition();
  1053. }
  1054. /// Get the real (not just tentative) definition for this declaration.
  1055. VarDecl *getDefinition(ASTContext &);
  1056. const VarDecl *getDefinition(ASTContext &C) const {
  1057. return const_cast<VarDecl*>(this)->getDefinition(C);
  1058. }
  1059. VarDecl *getDefinition() {
  1060. return getDefinition(getASTContext());
  1061. }
  1062. const VarDecl *getDefinition() const {
  1063. return const_cast<VarDecl*>(this)->getDefinition();
  1064. }
  1065. /// Determine whether this is or was instantiated from an out-of-line
  1066. /// definition of a static data member.
  1067. bool isOutOfLine() const override;
  1068. /// Returns true for file scoped variable declaration.
  1069. bool isFileVarDecl() const {
  1070. Kind K = getKind();
  1071. if (K == ParmVar || K == ImplicitParam)
  1072. return false;
  1073. if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
  1074. return true;
  1075. if (isStaticDataMember())
  1076. return true;
  1077. return false;
  1078. }
  1079. /// Get the initializer for this variable, no matter which
  1080. /// declaration it is attached to.
  1081. const Expr *getAnyInitializer() const {
  1082. const VarDecl *D;
  1083. return getAnyInitializer(D);
  1084. }
  1085. /// Get the initializer for this variable, no matter which
  1086. /// declaration it is attached to. Also get that declaration.
  1087. const Expr *getAnyInitializer(const VarDecl *&D) const;
  1088. bool hasInit() const;
  1089. const Expr *getInit() const {
  1090. return const_cast<VarDecl *>(this)->getInit();
  1091. }
  1092. Expr *getInit();
  1093. /// Retrieve the address of the initializer expression.
  1094. Stmt **getInitAddress();
  1095. void setInit(Expr *I);
  1096. /// Get the initializing declaration of this variable, if any. This is
  1097. /// usually the definition, except that for a static data member it can be
  1098. /// the in-class declaration.
  1099. VarDecl *getInitializingDeclaration();
  1100. const VarDecl *getInitializingDeclaration() const {
  1101. return const_cast<VarDecl *>(this)->getInitializingDeclaration();
  1102. }
  1103. /// Determine whether this variable's value might be usable in a
  1104. /// constant expression, according to the relevant language standard.
  1105. /// This only checks properties of the declaration, and does not check
  1106. /// whether the initializer is in fact a constant expression.
  1107. ///
  1108. /// This corresponds to C++20 [expr.const]p3's notion of a
  1109. /// "potentially-constant" variable.
  1110. bool mightBeUsableInConstantExpressions(const ASTContext &C) const;
  1111. /// Determine whether this variable's value can be used in a
  1112. /// constant expression, according to the relevant language standard,
  1113. /// including checking whether it was initialized by a constant expression.
  1114. bool isUsableInConstantExpressions(const ASTContext &C) const;
  1115. EvaluatedStmt *ensureEvaluatedStmt() const;
  1116. EvaluatedStmt *getEvaluatedStmt() const;
  1117. /// Attempt to evaluate the value of the initializer attached to this
  1118. /// declaration, and produce notes explaining why it cannot be evaluated.
  1119. /// Returns a pointer to the value if evaluation succeeded, 0 otherwise.
  1120. APValue *evaluateValue() const;
  1121. private:
  1122. APValue *evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
  1123. bool IsConstantInitialization) const;
  1124. public:
  1125. /// Return the already-evaluated value of this variable's
  1126. /// initializer, or NULL if the value is not yet known. Returns pointer
  1127. /// to untyped APValue if the value could not be evaluated.
  1128. APValue *getEvaluatedValue() const;
  1129. /// Evaluate the destruction of this variable to determine if it constitutes
  1130. /// constant destruction.
  1131. ///
  1132. /// \pre hasConstantInitialization()
  1133. /// \return \c true if this variable has constant destruction, \c false if
  1134. /// not.
  1135. bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
  1136. /// Determine whether this variable has constant initialization.
  1137. ///
  1138. /// This is only set in two cases: when the language semantics require
  1139. /// constant initialization (globals in C and some globals in C++), and when
  1140. /// the variable is usable in constant expressions (constexpr, const int, and
  1141. /// reference variables in C++).
  1142. bool hasConstantInitialization() const;
  1143. /// Determine whether the initializer of this variable is an integer constant
  1144. /// expression. For use in C++98, where this affects whether the variable is
  1145. /// usable in constant expressions.
  1146. bool hasICEInitializer(const ASTContext &Context) const;
  1147. /// Evaluate the initializer of this variable to determine whether it's a
  1148. /// constant initializer. Should only be called once, after completing the
  1149. /// definition of the variable.
  1150. bool checkForConstantInitialization(
  1151. SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
  1152. void setInitStyle(InitializationStyle Style) {
  1153. VarDeclBits.InitStyle = Style;
  1154. }
  1155. /// The style of initialization for this declaration.
  1156. ///
  1157. /// C-style initialization is "int x = 1;". Call-style initialization is
  1158. /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
  1159. /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
  1160. /// expression for class types. List-style initialization is C++11 syntax,
  1161. /// e.g. "int x{1};". Clients can distinguish between different forms of
  1162. /// initialization by checking this value. In particular, "int x = {1};" is
  1163. /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
  1164. /// Init expression in all three cases is an InitListExpr.
  1165. InitializationStyle getInitStyle() const {
  1166. return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
  1167. }
  1168. /// Whether the initializer is a direct-initializer (list or call).
  1169. bool isDirectInit() const {
  1170. return getInitStyle() != CInit;
  1171. }
  1172. /// If this definition should pretend to be a declaration.
  1173. bool isThisDeclarationADemotedDefinition() const {
  1174. return isa<ParmVarDecl>(this) ? false :
  1175. NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
  1176. }
  1177. /// This is a definition which should be demoted to a declaration.
  1178. ///
  1179. /// In some cases (mostly module merging) we can end up with two visible
  1180. /// definitions one of which needs to be demoted to a declaration to keep
  1181. /// the AST invariants.
  1182. void demoteThisDefinitionToDeclaration() {
  1183. assert(isThisDeclarationADefinition() && "Not a definition!");
  1184. assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!");
  1185. NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
  1186. }
  1187. /// Determine whether this variable is the exception variable in a
  1188. /// C++ catch statememt or an Objective-C \@catch statement.
  1189. bool isExceptionVariable() const {
  1190. return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
  1191. }
  1192. void setExceptionVariable(bool EV) {
  1193. assert(!isa<ParmVarDecl>(this));
  1194. NonParmVarDeclBits.ExceptionVar = EV;
  1195. }
  1196. /// Determine whether this local variable can be used with the named
  1197. /// return value optimization (NRVO).
  1198. ///
  1199. /// The named return value optimization (NRVO) works by marking certain
  1200. /// non-volatile local variables of class type as NRVO objects. These
  1201. /// locals can be allocated within the return slot of their containing
  1202. /// function, in which case there is no need to copy the object to the
  1203. /// return slot when returning from the function. Within the function body,
  1204. /// each return that returns the NRVO object will have this variable as its
  1205. /// NRVO candidate.
  1206. bool isNRVOVariable() const {
  1207. return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
  1208. }
  1209. void setNRVOVariable(bool NRVO) {
  1210. assert(!isa<ParmVarDecl>(this));
  1211. NonParmVarDeclBits.NRVOVariable = NRVO;
  1212. }
  1213. /// Determine whether this variable is the for-range-declaration in
  1214. /// a C++0x for-range statement.
  1215. bool isCXXForRangeDecl() const {
  1216. return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
  1217. }
  1218. void setCXXForRangeDecl(bool FRD) {
  1219. assert(!isa<ParmVarDecl>(this));
  1220. NonParmVarDeclBits.CXXForRangeDecl = FRD;
  1221. }
  1222. /// Determine whether this variable is a for-loop declaration for a
  1223. /// for-in statement in Objective-C.
  1224. bool isObjCForDecl() const {
  1225. return NonParmVarDeclBits.ObjCForDecl;
  1226. }
  1227. void setObjCForDecl(bool FRD) {
  1228. NonParmVarDeclBits.ObjCForDecl = FRD;
  1229. }
  1230. /// Determine whether this variable is an ARC pseudo-__strong variable. A
  1231. /// pseudo-__strong variable has a __strong-qualified type but does not
  1232. /// actually retain the object written into it. Generally such variables are
  1233. /// also 'const' for safety. There are 3 cases where this will be set, 1) if
  1234. /// the variable is annotated with the objc_externally_retained attribute, 2)
  1235. /// if its 'self' in a non-init method, or 3) if its the variable in an for-in
  1236. /// loop.
  1237. bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
  1238. void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; }
  1239. /// Whether this variable is (C++1z) inline.
  1240. bool isInline() const {
  1241. return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
  1242. }
  1243. bool isInlineSpecified() const {
  1244. return isa<ParmVarDecl>(this) ? false
  1245. : NonParmVarDeclBits.IsInlineSpecified;
  1246. }
  1247. void setInlineSpecified() {
  1248. assert(!isa<ParmVarDecl>(this));
  1249. NonParmVarDeclBits.IsInline = true;
  1250. NonParmVarDeclBits.IsInlineSpecified = true;
  1251. }
  1252. void setImplicitlyInline() {
  1253. assert(!isa<ParmVarDecl>(this));
  1254. NonParmVarDeclBits.IsInline = true;
  1255. }
  1256. /// Whether this variable is (C++11) constexpr.
  1257. bool isConstexpr() const {
  1258. return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
  1259. }
  1260. void setConstexpr(bool IC) {
  1261. assert(!isa<ParmVarDecl>(this));
  1262. NonParmVarDeclBits.IsConstexpr = IC;
  1263. }
  1264. /// Whether this variable is the implicit variable for a lambda init-capture.
  1265. bool isInitCapture() const {
  1266. return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
  1267. }
  1268. void setInitCapture(bool IC) {
  1269. assert(!isa<ParmVarDecl>(this));
  1270. NonParmVarDeclBits.IsInitCapture = IC;
  1271. }
  1272. /// Determine whether this variable is actually a function parameter pack or
  1273. /// init-capture pack.
  1274. bool isParameterPack() const;
  1275. /// Whether this local extern variable declaration's previous declaration
  1276. /// was declared in the same block scope. Only correct in C++.
  1277. bool isPreviousDeclInSameBlockScope() const {
  1278. return isa<ParmVarDecl>(this)
  1279. ? false
  1280. : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
  1281. }
  1282. void setPreviousDeclInSameBlockScope(bool Same) {
  1283. assert(!isa<ParmVarDecl>(this));
  1284. NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
  1285. }
  1286. /// Indicates the capture is a __block variable that is captured by a block
  1287. /// that can potentially escape (a block for which BlockDecl::doesNotEscape
  1288. /// returns false).
  1289. bool isEscapingByref() const;
  1290. /// Indicates the capture is a __block variable that is never captured by an
  1291. /// escaping block.
  1292. bool isNonEscapingByref() const;
  1293. void setEscapingByref() {
  1294. NonParmVarDeclBits.EscapingByref = true;
  1295. }
  1296. /// Determines if this variable's alignment is dependent.
  1297. bool hasDependentAlignment() const;
  1298. /// Retrieve the variable declaration from which this variable could
  1299. /// be instantiated, if it is an instantiation (rather than a non-template).
  1300. VarDecl *getTemplateInstantiationPattern() const;
  1301. /// If this variable is an instantiated static data member of a
  1302. /// class template specialization, returns the templated static data member
  1303. /// from which it was instantiated.
  1304. VarDecl *getInstantiatedFromStaticDataMember() const;
  1305. /// If this variable is an instantiation of a variable template or a
  1306. /// static data member of a class template, determine what kind of
  1307. /// template specialization or instantiation this is.
  1308. TemplateSpecializationKind getTemplateSpecializationKind() const;
  1309. /// Get the template specialization kind of this variable for the purposes of
  1310. /// template instantiation. This differs from getTemplateSpecializationKind()
  1311. /// for an instantiation of a class-scope explicit specialization.
  1312. TemplateSpecializationKind
  1313. getTemplateSpecializationKindForInstantiation() const;
  1314. /// If this variable is an instantiation of a variable template or a
  1315. /// static data member of a class template, determine its point of
  1316. /// instantiation.
  1317. SourceLocation getPointOfInstantiation() const;
  1318. /// If this variable is an instantiation of a static data member of a
  1319. /// class template specialization, retrieves the member specialization
  1320. /// information.
  1321. MemberSpecializationInfo *getMemberSpecializationInfo() const;
  1322. /// For a static data member that was instantiated from a static
  1323. /// data member of a class template, set the template specialiation kind.
  1324. void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  1325. SourceLocation PointOfInstantiation = SourceLocation());
  1326. /// Specify that this variable is an instantiation of the
  1327. /// static data member VD.
  1328. void setInstantiationOfStaticDataMember(VarDecl *VD,
  1329. TemplateSpecializationKind TSK);
  1330. /// Retrieves the variable template that is described by this
  1331. /// variable declaration.
  1332. ///
  1333. /// Every variable template is represented as a VarTemplateDecl and a
  1334. /// VarDecl. The former contains template properties (such as
  1335. /// the template parameter lists) while the latter contains the
  1336. /// actual description of the template's
  1337. /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
  1338. /// VarDecl that from a VarTemplateDecl, while
  1339. /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
  1340. /// a VarDecl.
  1341. VarTemplateDecl *getDescribedVarTemplate() const;
  1342. void setDescribedVarTemplate(VarTemplateDecl *Template);
  1343. // Is this variable known to have a definition somewhere in the complete
  1344. // program? This may be true even if the declaration has internal linkage and
  1345. // has no definition within this source file.
  1346. bool isKnownToBeDefined() const;
  1347. /// Is destruction of this variable entirely suppressed? If so, the variable
  1348. /// need not have a usable destructor at all.
  1349. bool isNoDestroy(const ASTContext &) const;
  1350. /// Would the destruction of this variable have any effect, and if so, what
  1351. /// kind?
  1352. QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const;
  1353. /// Whether this variable has a flexible array member initialized with one
  1354. /// or more elements. This can only be called for declarations where
  1355. /// hasInit() is true.
  1356. ///
  1357. /// (The standard doesn't allow initializing flexible array members; this is
  1358. /// a gcc/msvc extension.)
  1359. bool hasFlexibleArrayInit(const ASTContext &Ctx) const;
  1360. /// If hasFlexibleArrayInit is true, compute the number of additional bytes
  1361. /// necessary to store those elements. Otherwise, returns zero.
  1362. ///
  1363. /// This can only be called for declarations where hasInit() is true.
  1364. CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const;
  1365. // Implement isa/cast/dyncast/etc.
  1366. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  1367. static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
  1368. };
  1369. class ImplicitParamDecl : public VarDecl {
  1370. void anchor() override;
  1371. public:
  1372. /// Defines the kind of the implicit parameter: is this an implicit parameter
  1373. /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
  1374. /// context or something else.
  1375. enum ImplicitParamKind : unsigned {
  1376. /// Parameter for Objective-C 'self' argument
  1377. ObjCSelf,
  1378. /// Parameter for Objective-C '_cmd' argument
  1379. ObjCCmd,
  1380. /// Parameter for C++ 'this' argument
  1381. CXXThis,
  1382. /// Parameter for C++ virtual table pointers
  1383. CXXVTT,
  1384. /// Parameter for captured context
  1385. CapturedContext,
  1386. /// Parameter for Thread private variable
  1387. ThreadPrivateVar,
  1388. /// Other implicit parameter
  1389. Other,
  1390. };
  1391. /// Create implicit parameter.
  1392. static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
  1393. SourceLocation IdLoc, IdentifierInfo *Id,
  1394. QualType T, ImplicitParamKind ParamKind);
  1395. static ImplicitParamDecl *Create(ASTContext &C, QualType T,
  1396. ImplicitParamKind ParamKind);
  1397. static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  1398. ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
  1399. IdentifierInfo *Id, QualType Type,
  1400. ImplicitParamKind ParamKind)
  1401. : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
  1402. /*TInfo=*/nullptr, SC_None) {
  1403. NonParmVarDeclBits.ImplicitParamKind = ParamKind;
  1404. setImplicit();
  1405. }
  1406. ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
  1407. : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
  1408. SourceLocation(), /*Id=*/nullptr, Type,
  1409. /*TInfo=*/nullptr, SC_None) {
  1410. NonParmVarDeclBits.ImplicitParamKind = ParamKind;
  1411. setImplicit();
  1412. }
  1413. /// Returns the implicit parameter kind.
  1414. ImplicitParamKind getParameterKind() const {
  1415. return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
  1416. }
  1417. // Implement isa/cast/dyncast/etc.
  1418. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  1419. static bool classofKind(Kind K) { return K == ImplicitParam; }
  1420. };
  1421. /// Represents a parameter to a function.
  1422. class ParmVarDecl : public VarDecl {
  1423. public:
  1424. enum { MaxFunctionScopeDepth = 255 };
  1425. enum { MaxFunctionScopeIndex = 255 };
  1426. protected:
  1427. ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  1428. SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
  1429. TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
  1430. : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
  1431. assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
  1432. assert(ParmVarDeclBits.DefaultArgKind == DAK_None);
  1433. assert(ParmVarDeclBits.IsKNRPromoted == false);
  1434. assert(ParmVarDeclBits.IsObjCMethodParam == false);
  1435. setDefaultArg(DefArg);
  1436. }
  1437. public:
  1438. static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
  1439. SourceLocation StartLoc,
  1440. SourceLocation IdLoc, IdentifierInfo *Id,
  1441. QualType T, TypeSourceInfo *TInfo,
  1442. StorageClass S, Expr *DefArg);
  1443. static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  1444. SourceRange getSourceRange() const override LLVM_READONLY;
  1445. void setObjCMethodScopeInfo(unsigned parameterIndex) {
  1446. ParmVarDeclBits.IsObjCMethodParam = true;
  1447. setParameterIndex(parameterIndex);
  1448. }
  1449. void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
  1450. assert(!ParmVarDeclBits.IsObjCMethodParam);
  1451. ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
  1452. assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
  1453. && "truncation!");
  1454. setParameterIndex(parameterIndex);
  1455. }
  1456. bool isObjCMethodParameter() const {
  1457. return ParmVarDeclBits.IsObjCMethodParam;
  1458. }
  1459. /// Determines whether this parameter is destroyed in the callee function.
  1460. bool isDestroyedInCallee() const;
  1461. unsigned getFunctionScopeDepth() const {
  1462. if (ParmVarDeclBits.IsObjCMethodParam) return 0;
  1463. return ParmVarDeclBits.ScopeDepthOrObjCQuals;
  1464. }
  1465. static constexpr unsigned getMaxFunctionScopeDepth() {
  1466. return (1u << NumScopeDepthOrObjCQualsBits) - 1;
  1467. }
  1468. /// Returns the index of this parameter in its prototype or method scope.
  1469. unsigned getFunctionScopeIndex() const {
  1470. return getParameterIndex();
  1471. }
  1472. ObjCDeclQualifier getObjCDeclQualifier() const {
  1473. if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
  1474. return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
  1475. }
  1476. void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
  1477. assert(ParmVarDeclBits.IsObjCMethodParam);
  1478. ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
  1479. }
  1480. /// True if the value passed to this parameter must undergo
  1481. /// K&R-style default argument promotion:
  1482. ///
  1483. /// C99 6.5.2.2.
  1484. /// If the expression that denotes the called function has a type
  1485. /// that does not include a prototype, the integer promotions are
  1486. /// performed on each argument, and arguments that have type float
  1487. /// are promoted to double.
  1488. bool isKNRPromoted() const {
  1489. return ParmVarDeclBits.IsKNRPromoted;
  1490. }
  1491. void setKNRPromoted(bool promoted) {
  1492. ParmVarDeclBits.IsKNRPromoted = promoted;
  1493. }
  1494. Expr *getDefaultArg();
  1495. const Expr *getDefaultArg() const {
  1496. return const_cast<ParmVarDecl *>(this)->getDefaultArg();
  1497. }
  1498. void setDefaultArg(Expr *defarg);
  1499. /// Retrieve the source range that covers the entire default
  1500. /// argument.
  1501. SourceRange getDefaultArgRange() const;
  1502. void setUninstantiatedDefaultArg(Expr *arg);
  1503. Expr *getUninstantiatedDefaultArg();
  1504. const Expr *getUninstantiatedDefaultArg() const {
  1505. return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
  1506. }
  1507. /// Determines whether this parameter has a default argument,
  1508. /// either parsed or not.
  1509. bool hasDefaultArg() const;
  1510. /// Determines whether this parameter has a default argument that has not
  1511. /// yet been parsed. This will occur during the processing of a C++ class
  1512. /// whose member functions have default arguments, e.g.,
  1513. /// @code
  1514. /// class X {
  1515. /// public:
  1516. /// void f(int x = 17); // x has an unparsed default argument now
  1517. /// }; // x has a regular default argument now
  1518. /// @endcode
  1519. bool hasUnparsedDefaultArg() const {
  1520. return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
  1521. }
  1522. bool hasUninstantiatedDefaultArg() const {
  1523. return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
  1524. }
  1525. /// Specify that this parameter has an unparsed default argument.
  1526. /// The argument will be replaced with a real default argument via
  1527. /// setDefaultArg when the class definition enclosing the function
  1528. /// declaration that owns this default argument is completed.
  1529. void setUnparsedDefaultArg() {
  1530. ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
  1531. }
  1532. bool hasInheritedDefaultArg() const {
  1533. return ParmVarDeclBits.HasInheritedDefaultArg;
  1534. }
  1535. void setHasInheritedDefaultArg(bool I = true) {
  1536. ParmVarDeclBits.HasInheritedDefaultArg = I;
  1537. }
  1538. QualType getOriginalType() const;
  1539. /// Sets the function declaration that owns this
  1540. /// ParmVarDecl. Since ParmVarDecls are often created before the
  1541. /// FunctionDecls that own them, this routine is required to update
  1542. /// the DeclContext appropriately.
  1543. void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
  1544. // Implement isa/cast/dyncast/etc.
  1545. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  1546. static bool classofKind(Kind K) { return K == ParmVar; }
  1547. private:
  1548. enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
  1549. void setParameterIndex(unsigned parameterIndex) {
  1550. if (parameterIndex >= ParameterIndexSentinel) {
  1551. setParameterIndexLarge(parameterIndex);
  1552. return;
  1553. }
  1554. ParmVarDeclBits.ParameterIndex = parameterIndex;
  1555. assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
  1556. }
  1557. unsigned getParameterIndex() const {
  1558. unsigned d = ParmVarDeclBits.ParameterIndex;
  1559. return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
  1560. }
  1561. void setParameterIndexLarge(unsigned parameterIndex);
  1562. unsigned getParameterIndexLarge() const;
  1563. };
  1564. enum class MultiVersionKind {
  1565. None,
  1566. Target,
  1567. CPUSpecific,
  1568. CPUDispatch,
  1569. TargetClones,
  1570. TargetVersion
  1571. };
  1572. /// Represents a function declaration or definition.
  1573. ///
  1574. /// Since a given function can be declared several times in a program,
  1575. /// there may be several FunctionDecls that correspond to that
  1576. /// function. Only one of those FunctionDecls will be found when
  1577. /// traversing the list of declarations in the context of the
  1578. /// FunctionDecl (e.g., the translation unit); this FunctionDecl
  1579. /// contains all of the information known about the function. Other,
  1580. /// previous declarations of the function are available via the
  1581. /// getPreviousDecl() chain.
  1582. class FunctionDecl : public DeclaratorDecl,
  1583. public DeclContext,
  1584. public Redeclarable<FunctionDecl> {
  1585. // This class stores some data in DeclContext::FunctionDeclBits
  1586. // to save some space. Use the provided accessors to access it.
  1587. public:
  1588. /// The kind of templated function a FunctionDecl can be.
  1589. enum TemplatedKind {
  1590. // Not templated.
  1591. TK_NonTemplate,
  1592. // The pattern in a function template declaration.
  1593. TK_FunctionTemplate,
  1594. // A non-template function that is an instantiation or explicit
  1595. // specialization of a member of a templated class.
  1596. TK_MemberSpecialization,
  1597. // An instantiation or explicit specialization of a function template.
  1598. // Note: this might have been instantiated from a templated class if it
  1599. // is a class-scope explicit specialization.
  1600. TK_FunctionTemplateSpecialization,
  1601. // A function template specialization that hasn't yet been resolved to a
  1602. // particular specialized function template.
  1603. TK_DependentFunctionTemplateSpecialization,
  1604. // A non-template function which is in a dependent scope.
  1605. TK_DependentNonTemplate
  1606. };
  1607. /// Stashed information about a defaulted function definition whose body has
  1608. /// not yet been lazily generated.
  1609. class DefaultedFunctionInfo final
  1610. : llvm::TrailingObjects<DefaultedFunctionInfo, DeclAccessPair> {
  1611. friend TrailingObjects;
  1612. unsigned NumLookups;
  1613. public:
  1614. static DefaultedFunctionInfo *Create(ASTContext &Context,
  1615. ArrayRef<DeclAccessPair> Lookups);
  1616. /// Get the unqualified lookup results that should be used in this
  1617. /// defaulted function definition.
  1618. ArrayRef<DeclAccessPair> getUnqualifiedLookups() const {
  1619. return {getTrailingObjects<DeclAccessPair>(), NumLookups};
  1620. }
  1621. };
  1622. private:
  1623. /// A new[]'d array of pointers to VarDecls for the formal
  1624. /// parameters of this function. This is null if a prototype or if there are
  1625. /// no formals.
  1626. ParmVarDecl **ParamInfo = nullptr;
  1627. /// The active member of this union is determined by
  1628. /// FunctionDeclBits.HasDefaultedFunctionInfo.
  1629. union {
  1630. /// The body of the function.
  1631. LazyDeclStmtPtr Body;
  1632. /// Information about a future defaulted function definition.
  1633. DefaultedFunctionInfo *DefaultedInfo;
  1634. };
  1635. unsigned ODRHash;
  1636. /// End part of this FunctionDecl's source range.
  1637. ///
  1638. /// We could compute the full range in getSourceRange(). However, when we're
  1639. /// dealing with a function definition deserialized from a PCH/AST file,
  1640. /// we can only compute the full range once the function body has been
  1641. /// de-serialized, so it's far better to have the (sometimes-redundant)
  1642. /// EndRangeLoc.
  1643. SourceLocation EndRangeLoc;
  1644. SourceLocation DefaultKWLoc;
  1645. /// The template or declaration that this declaration
  1646. /// describes or was instantiated from, respectively.
  1647. ///
  1648. /// For non-templates this value will be NULL, unless this declaration was
  1649. /// declared directly inside of a function template, in which case it will
  1650. /// have a pointer to a FunctionDecl, stored in the NamedDecl. For function
  1651. /// declarations that describe a function template, this will be a pointer to
  1652. /// a FunctionTemplateDecl, stored in the NamedDecl. For member functions of
  1653. /// class template specializations, this will be a MemberSpecializationInfo
  1654. /// pointer containing information about the specialization.
  1655. /// For function template specializations, this will be a
  1656. /// FunctionTemplateSpecializationInfo, which contains information about
  1657. /// the template being specialized and the template arguments involved in
  1658. /// that specialization.
  1659. llvm::PointerUnion<NamedDecl *, MemberSpecializationInfo *,
  1660. FunctionTemplateSpecializationInfo *,
  1661. DependentFunctionTemplateSpecializationInfo *>
  1662. TemplateOrSpecialization;
  1663. /// Provides source/type location info for the declaration name embedded in
  1664. /// the DeclaratorDecl base class.
  1665. DeclarationNameLoc DNLoc;
  1666. /// Specify that this function declaration is actually a function
  1667. /// template specialization.
  1668. ///
  1669. /// \param C the ASTContext.
  1670. ///
  1671. /// \param Template the function template that this function template
  1672. /// specialization specializes.
  1673. ///
  1674. /// \param TemplateArgs the template arguments that produced this
  1675. /// function template specialization from the template.
  1676. ///
  1677. /// \param InsertPos If non-NULL, the position in the function template
  1678. /// specialization set where the function template specialization data will
  1679. /// be inserted.
  1680. ///
  1681. /// \param TSK the kind of template specialization this is.
  1682. ///
  1683. /// \param TemplateArgsAsWritten location info of template arguments.
  1684. ///
  1685. /// \param PointOfInstantiation point at which the function template
  1686. /// specialization was first instantiated.
  1687. void setFunctionTemplateSpecialization(ASTContext &C,
  1688. FunctionTemplateDecl *Template,
  1689. const TemplateArgumentList *TemplateArgs,
  1690. void *InsertPos,
  1691. TemplateSpecializationKind TSK,
  1692. const TemplateArgumentListInfo *TemplateArgsAsWritten,
  1693. SourceLocation PointOfInstantiation);
  1694. /// Specify that this record is an instantiation of the
  1695. /// member function FD.
  1696. void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
  1697. TemplateSpecializationKind TSK);
  1698. void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
  1699. // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl
  1700. // need to access this bit but we want to avoid making ASTDeclWriter
  1701. // a friend of FunctionDeclBitfields just for this.
  1702. bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; }
  1703. /// Whether an ODRHash has been stored.
  1704. bool hasODRHash() const { return FunctionDeclBits.HasODRHash; }
  1705. /// State that an ODRHash has been stored.
  1706. void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; }
  1707. protected:
  1708. FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  1709. const DeclarationNameInfo &NameInfo, QualType T,
  1710. TypeSourceInfo *TInfo, StorageClass S, bool UsesFPIntrin,
  1711. bool isInlineSpecified, ConstexprSpecKind ConstexprKind,
  1712. Expr *TrailingRequiresClause = nullptr);
  1713. using redeclarable_base = Redeclarable<FunctionDecl>;
  1714. FunctionDecl *getNextRedeclarationImpl() override {
  1715. return getNextRedeclaration();
  1716. }
  1717. FunctionDecl *getPreviousDeclImpl() override {
  1718. return getPreviousDecl();
  1719. }
  1720. FunctionDecl *getMostRecentDeclImpl() override {
  1721. return getMostRecentDecl();
  1722. }
  1723. public:
  1724. friend class ASTDeclReader;
  1725. friend class ASTDeclWriter;
  1726. using redecl_range = redeclarable_base::redecl_range;
  1727. using redecl_iterator = redeclarable_base::redecl_iterator;
  1728. using redeclarable_base::redecls_begin;
  1729. using redeclarable_base::redecls_end;
  1730. using redeclarable_base::redecls;
  1731. using redeclarable_base::getPreviousDecl;
  1732. using redeclarable_base::getMostRecentDecl;
  1733. using redeclarable_base::isFirstDecl;
  1734. static FunctionDecl *
  1735. Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  1736. SourceLocation NLoc, DeclarationName N, QualType T,
  1737. TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin = false,
  1738. bool isInlineSpecified = false, bool hasWrittenPrototype = true,
  1739. ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified,
  1740. Expr *TrailingRequiresClause = nullptr) {
  1741. DeclarationNameInfo NameInfo(N, NLoc);
  1742. return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC,
  1743. UsesFPIntrin, isInlineSpecified,
  1744. hasWrittenPrototype, ConstexprKind,
  1745. TrailingRequiresClause);
  1746. }
  1747. static FunctionDecl *
  1748. Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  1749. const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
  1750. StorageClass SC, bool UsesFPIntrin, bool isInlineSpecified,
  1751. bool hasWrittenPrototype, ConstexprSpecKind ConstexprKind,
  1752. Expr *TrailingRequiresClause);
  1753. static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  1754. DeclarationNameInfo getNameInfo() const {
  1755. return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
  1756. }
  1757. void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
  1758. bool Qualified) const override;
  1759. void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
  1760. /// Returns the location of the ellipsis of a variadic function.
  1761. SourceLocation getEllipsisLoc() const {
  1762. const auto *FPT = getType()->getAs<FunctionProtoType>();
  1763. if (FPT && FPT->isVariadic())
  1764. return FPT->getEllipsisLoc();
  1765. return SourceLocation();
  1766. }
  1767. SourceRange getSourceRange() const override LLVM_READONLY;
  1768. // Function definitions.
  1769. //
  1770. // A function declaration may be:
  1771. // - a non defining declaration,
  1772. // - a definition. A function may be defined because:
  1773. // - it has a body, or will have it in the case of late parsing.
  1774. // - it has an uninstantiated body. The body does not exist because the
  1775. // function is not used yet, but the declaration is considered a
  1776. // definition and does not allow other definition of this function.
  1777. // - it does not have a user specified body, but it does not allow
  1778. // redefinition, because it is deleted/defaulted or is defined through
  1779. // some other mechanism (alias, ifunc).
  1780. /// Returns true if the function has a body.
  1781. ///
  1782. /// The function body might be in any of the (re-)declarations of this
  1783. /// function. The variant that accepts a FunctionDecl pointer will set that
  1784. /// function declaration to the actual declaration containing the body (if
  1785. /// there is one).
  1786. bool hasBody(const FunctionDecl *&Definition) const;
  1787. bool hasBody() const override {
  1788. const FunctionDecl* Definition;
  1789. return hasBody(Definition);
  1790. }
  1791. /// Returns whether the function has a trivial body that does not require any
  1792. /// specific codegen.
  1793. bool hasTrivialBody() const;
  1794. /// Returns true if the function has a definition that does not need to be
  1795. /// instantiated.
  1796. ///
  1797. /// The variant that accepts a FunctionDecl pointer will set that function
  1798. /// declaration to the declaration that is a definition (if there is one).
  1799. ///
  1800. /// \param CheckForPendingFriendDefinition If \c true, also check for friend
  1801. /// declarations that were instantiataed from function definitions.
  1802. /// Such a declaration behaves as if it is a definition for the
  1803. /// purpose of redefinition checking, but isn't actually a "real"
  1804. /// definition until its body is instantiated.
  1805. bool isDefined(const FunctionDecl *&Definition,
  1806. bool CheckForPendingFriendDefinition = false) const;
  1807. bool isDefined() const {
  1808. const FunctionDecl* Definition;
  1809. return isDefined(Definition);
  1810. }
  1811. /// Get the definition for this declaration.
  1812. FunctionDecl *getDefinition() {
  1813. const FunctionDecl *Definition;
  1814. if (isDefined(Definition))
  1815. return const_cast<FunctionDecl *>(Definition);
  1816. return nullptr;
  1817. }
  1818. const FunctionDecl *getDefinition() const {
  1819. return const_cast<FunctionDecl *>(this)->getDefinition();
  1820. }
  1821. /// Retrieve the body (definition) of the function. The function body might be
  1822. /// in any of the (re-)declarations of this function. The variant that accepts
  1823. /// a FunctionDecl pointer will set that function declaration to the actual
  1824. /// declaration containing the body (if there is one).
  1825. /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
  1826. /// unnecessary AST de-serialization of the body.
  1827. Stmt *getBody(const FunctionDecl *&Definition) const;
  1828. Stmt *getBody() const override {
  1829. const FunctionDecl* Definition;
  1830. return getBody(Definition);
  1831. }
  1832. /// Returns whether this specific declaration of the function is also a
  1833. /// definition that does not contain uninstantiated body.
  1834. ///
  1835. /// This does not determine whether the function has been defined (e.g., in a
  1836. /// previous definition); for that information, use isDefined.
  1837. ///
  1838. /// Note: the function declaration does not become a definition until the
  1839. /// parser reaches the definition, if called before, this function will return
  1840. /// `false`.
  1841. bool isThisDeclarationADefinition() const {
  1842. return isDeletedAsWritten() || isDefaulted() ||
  1843. doesThisDeclarationHaveABody() || hasSkippedBody() ||
  1844. willHaveBody() || hasDefiningAttr();
  1845. }
  1846. /// Determine whether this specific declaration of the function is a friend
  1847. /// declaration that was instantiated from a function definition. Such
  1848. /// declarations behave like definitions in some contexts.
  1849. bool isThisDeclarationInstantiatedFromAFriendDefinition() const;
  1850. /// Returns whether this specific declaration of the function has a body.
  1851. bool doesThisDeclarationHaveABody() const {
  1852. return (!FunctionDeclBits.HasDefaultedFunctionInfo && Body) ||
  1853. isLateTemplateParsed();
  1854. }
  1855. void setBody(Stmt *B);
  1856. void setLazyBody(uint64_t Offset) {
  1857. FunctionDeclBits.HasDefaultedFunctionInfo = false;
  1858. Body = LazyDeclStmtPtr(Offset);
  1859. }
  1860. void setDefaultedFunctionInfo(DefaultedFunctionInfo *Info);
  1861. DefaultedFunctionInfo *getDefaultedFunctionInfo() const;
  1862. /// Whether this function is variadic.
  1863. bool isVariadic() const;
  1864. /// Whether this function is marked as virtual explicitly.
  1865. bool isVirtualAsWritten() const {
  1866. return FunctionDeclBits.IsVirtualAsWritten;
  1867. }
  1868. /// State that this function is marked as virtual explicitly.
  1869. void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; }
  1870. /// Whether this virtual function is pure, i.e. makes the containing class
  1871. /// abstract.
  1872. bool isPure() const { return FunctionDeclBits.IsPure; }
  1873. void setPure(bool P = true);
  1874. /// Whether this templated function will be late parsed.
  1875. bool isLateTemplateParsed() const {
  1876. return FunctionDeclBits.IsLateTemplateParsed;
  1877. }
  1878. /// State that this templated function will be late parsed.
  1879. void setLateTemplateParsed(bool ILT = true) {
  1880. FunctionDeclBits.IsLateTemplateParsed = ILT;
  1881. }
  1882. /// Whether this function is "trivial" in some specialized C++ senses.
  1883. /// Can only be true for default constructors, copy constructors,
  1884. /// copy assignment operators, and destructors. Not meaningful until
  1885. /// the class has been fully built by Sema.
  1886. bool isTrivial() const { return FunctionDeclBits.IsTrivial; }
  1887. void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; }
  1888. bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; }
  1889. void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; }
  1890. /// Whether this function is defaulted. Valid for e.g.
  1891. /// special member functions, defaulted comparisions (not methods!).
  1892. bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; }
  1893. void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; }
  1894. /// Whether this function is explicitly defaulted.
  1895. bool isExplicitlyDefaulted() const {
  1896. return FunctionDeclBits.IsExplicitlyDefaulted;
  1897. }
  1898. /// State that this function is explicitly defaulted.
  1899. void setExplicitlyDefaulted(bool ED = true) {
  1900. FunctionDeclBits.IsExplicitlyDefaulted = ED;
  1901. }
  1902. SourceLocation getDefaultLoc() const {
  1903. return isExplicitlyDefaulted() ? DefaultKWLoc : SourceLocation();
  1904. }
  1905. void setDefaultLoc(SourceLocation NewLoc) {
  1906. assert((NewLoc.isInvalid() || isExplicitlyDefaulted()) &&
  1907. "Can't set default loc is function isn't explicitly defaulted");
  1908. DefaultKWLoc = NewLoc;
  1909. }
  1910. /// True if this method is user-declared and was not
  1911. /// deleted or defaulted on its first declaration.
  1912. bool isUserProvided() const {
  1913. auto *DeclAsWritten = this;
  1914. if (FunctionDecl *Pattern = getTemplateInstantiationPattern())
  1915. DeclAsWritten = Pattern;
  1916. return !(DeclAsWritten->isDeleted() ||
  1917. DeclAsWritten->getCanonicalDecl()->isDefaulted());
  1918. }
  1919. bool isIneligibleOrNotSelected() const {
  1920. return FunctionDeclBits.IsIneligibleOrNotSelected;
  1921. }
  1922. void setIneligibleOrNotSelected(bool II) {
  1923. FunctionDeclBits.IsIneligibleOrNotSelected = II;
  1924. }
  1925. /// Whether falling off this function implicitly returns null/zero.
  1926. /// If a more specific implicit return value is required, front-ends
  1927. /// should synthesize the appropriate return statements.
  1928. bool hasImplicitReturnZero() const {
  1929. return FunctionDeclBits.HasImplicitReturnZero;
  1930. }
  1931. /// State that falling off this function implicitly returns null/zero.
  1932. /// If a more specific implicit return value is required, front-ends
  1933. /// should synthesize the appropriate return statements.
  1934. void setHasImplicitReturnZero(bool IRZ) {
  1935. FunctionDeclBits.HasImplicitReturnZero = IRZ;
  1936. }
  1937. /// Whether this function has a prototype, either because one
  1938. /// was explicitly written or because it was "inherited" by merging
  1939. /// a declaration without a prototype with a declaration that has a
  1940. /// prototype.
  1941. bool hasPrototype() const {
  1942. return hasWrittenPrototype() || hasInheritedPrototype();
  1943. }
  1944. /// Whether this function has a written prototype.
  1945. bool hasWrittenPrototype() const {
  1946. return FunctionDeclBits.HasWrittenPrototype;
  1947. }
  1948. /// State that this function has a written prototype.
  1949. void setHasWrittenPrototype(bool P = true) {
  1950. FunctionDeclBits.HasWrittenPrototype = P;
  1951. }
  1952. /// Whether this function inherited its prototype from a
  1953. /// previous declaration.
  1954. bool hasInheritedPrototype() const {
  1955. return FunctionDeclBits.HasInheritedPrototype;
  1956. }
  1957. /// State that this function inherited its prototype from a
  1958. /// previous declaration.
  1959. void setHasInheritedPrototype(bool P = true) {
  1960. FunctionDeclBits.HasInheritedPrototype = P;
  1961. }
  1962. /// Whether this is a (C++11) constexpr function or constexpr constructor.
  1963. bool isConstexpr() const {
  1964. return getConstexprKind() != ConstexprSpecKind::Unspecified;
  1965. }
  1966. void setConstexprKind(ConstexprSpecKind CSK) {
  1967. FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(CSK);
  1968. }
  1969. ConstexprSpecKind getConstexprKind() const {
  1970. return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind);
  1971. }
  1972. bool isConstexprSpecified() const {
  1973. return getConstexprKind() == ConstexprSpecKind::Constexpr;
  1974. }
  1975. bool isConsteval() const {
  1976. return getConstexprKind() == ConstexprSpecKind::Consteval;
  1977. }
  1978. /// Whether the instantiation of this function is pending.
  1979. /// This bit is set when the decision to instantiate this function is made
  1980. /// and unset if and when the function body is created. That leaves out
  1981. /// cases where instantiation did not happen because the template definition
  1982. /// was not seen in this TU. This bit remains set in those cases, under the
  1983. /// assumption that the instantiation will happen in some other TU.
  1984. bool instantiationIsPending() const {
  1985. return FunctionDeclBits.InstantiationIsPending;
  1986. }
  1987. /// State that the instantiation of this function is pending.
  1988. /// (see instantiationIsPending)
  1989. void setInstantiationIsPending(bool IC) {
  1990. FunctionDeclBits.InstantiationIsPending = IC;
  1991. }
  1992. /// Indicates the function uses __try.
  1993. bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
  1994. void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
  1995. /// Whether this function has been deleted.
  1996. ///
  1997. /// A function that is "deleted" (via the C++0x "= delete" syntax)
  1998. /// acts like a normal function, except that it cannot actually be
  1999. /// called or have its address taken. Deleted functions are
  2000. /// typically used in C++ overload resolution to attract arguments
  2001. /// whose type or lvalue/rvalue-ness would permit the use of a
  2002. /// different overload that would behave incorrectly. For example,
  2003. /// one might use deleted functions to ban implicit conversion from
  2004. /// a floating-point number to an Integer type:
  2005. ///
  2006. /// @code
  2007. /// struct Integer {
  2008. /// Integer(long); // construct from a long
  2009. /// Integer(double) = delete; // no construction from float or double
  2010. /// Integer(long double) = delete; // no construction from long double
  2011. /// };
  2012. /// @endcode
  2013. // If a function is deleted, its first declaration must be.
  2014. bool isDeleted() const {
  2015. return getCanonicalDecl()->FunctionDeclBits.IsDeleted;
  2016. }
  2017. bool isDeletedAsWritten() const {
  2018. return FunctionDeclBits.IsDeleted && !isDefaulted();
  2019. }
  2020. void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; }
  2021. /// Determines whether this function is "main", which is the
  2022. /// entry point into an executable program.
  2023. bool isMain() const;
  2024. /// Determines whether this function is a MSVCRT user defined entry
  2025. /// point.
  2026. bool isMSVCRTEntryPoint() const;
  2027. /// Determines whether this operator new or delete is one
  2028. /// of the reserved global placement operators:
  2029. /// void *operator new(size_t, void *);
  2030. /// void *operator new[](size_t, void *);
  2031. /// void operator delete(void *, void *);
  2032. /// void operator delete[](void *, void *);
  2033. /// These functions have special behavior under [new.delete.placement]:
  2034. /// These functions are reserved, a C++ program may not define
  2035. /// functions that displace the versions in the Standard C++ library.
  2036. /// The provisions of [basic.stc.dynamic] do not apply to these
  2037. /// reserved placement forms of operator new and operator delete.
  2038. ///
  2039. /// This function must be an allocation or deallocation function.
  2040. bool isReservedGlobalPlacementOperator() const;
  2041. /// Determines whether this function is one of the replaceable
  2042. /// global allocation functions:
  2043. /// void *operator new(size_t);
  2044. /// void *operator new(size_t, const std::nothrow_t &) noexcept;
  2045. /// void *operator new[](size_t);
  2046. /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
  2047. /// void operator delete(void *) noexcept;
  2048. /// void operator delete(void *, std::size_t) noexcept; [C++1y]
  2049. /// void operator delete(void *, const std::nothrow_t &) noexcept;
  2050. /// void operator delete[](void *) noexcept;
  2051. /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
  2052. /// void operator delete[](void *, const std::nothrow_t &) noexcept;
  2053. /// These functions have special behavior under C++1y [expr.new]:
  2054. /// An implementation is allowed to omit a call to a replaceable global
  2055. /// allocation function. [...]
  2056. ///
  2057. /// If this function is an aligned allocation/deallocation function, return
  2058. /// the parameter number of the requested alignment through AlignmentParam.
  2059. ///
  2060. /// If this function is an allocation/deallocation function that takes
  2061. /// the `std::nothrow_t` tag, return true through IsNothrow,
  2062. bool isReplaceableGlobalAllocationFunction(
  2063. std::optional<unsigned> *AlignmentParam = nullptr,
  2064. bool *IsNothrow = nullptr) const;
  2065. /// Determine if this function provides an inline implementation of a builtin.
  2066. bool isInlineBuiltinDeclaration() const;
  2067. /// Determine whether this is a destroying operator delete.
  2068. bool isDestroyingOperatorDelete() const;
  2069. /// Compute the language linkage.
  2070. LanguageLinkage getLanguageLinkage() const;
  2071. /// Determines whether this function is a function with
  2072. /// external, C linkage.
  2073. bool isExternC() const;
  2074. /// Determines whether this function's context is, or is nested within,
  2075. /// a C++ extern "C" linkage spec.
  2076. bool isInExternCContext() const;
  2077. /// Determines whether this function's context is, or is nested within,
  2078. /// a C++ extern "C++" linkage spec.
  2079. bool isInExternCXXContext() const;
  2080. /// Determines whether this is a global function.
  2081. bool isGlobal() const;
  2082. /// Determines whether this function is known to be 'noreturn', through
  2083. /// an attribute on its declaration or its type.
  2084. bool isNoReturn() const;
  2085. /// True if the function was a definition but its body was skipped.
  2086. bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
  2087. void setHasSkippedBody(bool Skipped = true) {
  2088. FunctionDeclBits.HasSkippedBody = Skipped;
  2089. }
  2090. /// True if this function will eventually have a body, once it's fully parsed.
  2091. bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; }
  2092. void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; }
  2093. /// True if this function is considered a multiversioned function.
  2094. bool isMultiVersion() const {
  2095. return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion;
  2096. }
  2097. /// Sets the multiversion state for this declaration and all of its
  2098. /// redeclarations.
  2099. void setIsMultiVersion(bool V = true) {
  2100. getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V;
  2101. }
  2102. // Sets that this is a constrained friend where the constraint refers to an
  2103. // enclosing template.
  2104. void setFriendConstraintRefersToEnclosingTemplate(bool V = true) {
  2105. getCanonicalDecl()
  2106. ->FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = V;
  2107. }
  2108. // Indicates this function is a constrained friend, where the constraint
  2109. // refers to an enclosing template for hte purposes of [temp.friend]p9.
  2110. bool FriendConstraintRefersToEnclosingTemplate() const {
  2111. return getCanonicalDecl()
  2112. ->FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate;
  2113. }
  2114. /// Gets the kind of multiversioning attribute this declaration has. Note that
  2115. /// this can return a value even if the function is not multiversion, such as
  2116. /// the case of 'target'.
  2117. MultiVersionKind getMultiVersionKind() const;
  2118. /// True if this function is a multiversioned dispatch function as a part of
  2119. /// the cpu_specific/cpu_dispatch functionality.
  2120. bool isCPUDispatchMultiVersion() const;
  2121. /// True if this function is a multiversioned processor specific function as a
  2122. /// part of the cpu_specific/cpu_dispatch functionality.
  2123. bool isCPUSpecificMultiVersion() const;
  2124. /// True if this function is a multiversioned dispatch function as a part of
  2125. /// the target functionality.
  2126. bool isTargetMultiVersion() const;
  2127. /// True if this function is a multiversioned dispatch function as a part of
  2128. /// the target-clones functionality.
  2129. bool isTargetClonesMultiVersion() const;
  2130. /// \brief Get the associated-constraints of this function declaration.
  2131. /// Currently, this will either be a vector of size 1 containing the
  2132. /// trailing-requires-clause or an empty vector.
  2133. ///
  2134. /// Use this instead of getTrailingRequiresClause for concepts APIs that
  2135. /// accept an ArrayRef of constraint expressions.
  2136. void getAssociatedConstraints(SmallVectorImpl<const Expr *> &AC) const {
  2137. if (auto *TRC = getTrailingRequiresClause())
  2138. AC.push_back(TRC);
  2139. }
  2140. void setPreviousDeclaration(FunctionDecl * PrevDecl);
  2141. FunctionDecl *getCanonicalDecl() override;
  2142. const FunctionDecl *getCanonicalDecl() const {
  2143. return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
  2144. }
  2145. unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const;
  2146. // ArrayRef interface to parameters.
  2147. ArrayRef<ParmVarDecl *> parameters() const {
  2148. return {ParamInfo, getNumParams()};
  2149. }
  2150. MutableArrayRef<ParmVarDecl *> parameters() {
  2151. return {ParamInfo, getNumParams()};
  2152. }
  2153. // Iterator access to formal parameters.
  2154. using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
  2155. using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
  2156. bool param_empty() const { return parameters().empty(); }
  2157. param_iterator param_begin() { return parameters().begin(); }
  2158. param_iterator param_end() { return parameters().end(); }
  2159. param_const_iterator param_begin() const { return parameters().begin(); }
  2160. param_const_iterator param_end() const { return parameters().end(); }
  2161. size_t param_size() const { return parameters().size(); }
  2162. /// Return the number of parameters this function must have based on its
  2163. /// FunctionType. This is the length of the ParamInfo array after it has been
  2164. /// created.
  2165. unsigned getNumParams() const;
  2166. const ParmVarDecl *getParamDecl(unsigned i) const {
  2167. assert(i < getNumParams() && "Illegal param #");
  2168. return ParamInfo[i];
  2169. }
  2170. ParmVarDecl *getParamDecl(unsigned i) {
  2171. assert(i < getNumParams() && "Illegal param #");
  2172. return ParamInfo[i];
  2173. }
  2174. void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
  2175. setParams(getASTContext(), NewParamInfo);
  2176. }
  2177. /// Returns the minimum number of arguments needed to call this function. This
  2178. /// may be fewer than the number of function parameters, if some of the
  2179. /// parameters have default arguments (in C++).
  2180. unsigned getMinRequiredArguments() const;
  2181. /// Determine whether this function has a single parameter, or multiple
  2182. /// parameters where all but the first have default arguments.
  2183. ///
  2184. /// This notion is used in the definition of copy/move constructors and
  2185. /// initializer list constructors. Note that, unlike getMinRequiredArguments,
  2186. /// parameter packs are not treated specially here.
  2187. bool hasOneParamOrDefaultArgs() const;
  2188. /// Find the source location information for how the type of this function
  2189. /// was written. May be absent (for example if the function was declared via
  2190. /// a typedef) and may contain a different type from that of the function
  2191. /// (for example if the function type was adjusted by an attribute).
  2192. FunctionTypeLoc getFunctionTypeLoc() const;
  2193. QualType getReturnType() const {
  2194. return getType()->castAs<FunctionType>()->getReturnType();
  2195. }
  2196. /// Attempt to compute an informative source range covering the
  2197. /// function return type. This may omit qualifiers and other information with
  2198. /// limited representation in the AST.
  2199. SourceRange getReturnTypeSourceRange() const;
  2200. /// Attempt to compute an informative source range covering the
  2201. /// function parameters, including the ellipsis of a variadic function.
  2202. /// The source range excludes the parentheses, and is invalid if there are
  2203. /// no parameters and no ellipsis.
  2204. SourceRange getParametersSourceRange() const;
  2205. /// Get the declared return type, which may differ from the actual return
  2206. /// type if the return type is deduced.
  2207. QualType getDeclaredReturnType() const {
  2208. auto *TSI = getTypeSourceInfo();
  2209. QualType T = TSI ? TSI->getType() : getType();
  2210. return T->castAs<FunctionType>()->getReturnType();
  2211. }
  2212. /// Gets the ExceptionSpecificationType as declared.
  2213. ExceptionSpecificationType getExceptionSpecType() const {
  2214. auto *TSI = getTypeSourceInfo();
  2215. QualType T = TSI ? TSI->getType() : getType();
  2216. const auto *FPT = T->getAs<FunctionProtoType>();
  2217. return FPT ? FPT->getExceptionSpecType() : EST_None;
  2218. }
  2219. /// Attempt to compute an informative source range covering the
  2220. /// function exception specification, if any.
  2221. SourceRange getExceptionSpecSourceRange() const;
  2222. /// Determine the type of an expression that calls this function.
  2223. QualType getCallResultType() const {
  2224. return getType()->castAs<FunctionType>()->getCallResultType(
  2225. getASTContext());
  2226. }
  2227. /// Returns the storage class as written in the source. For the
  2228. /// computed linkage of symbol, see getLinkage.
  2229. StorageClass getStorageClass() const {
  2230. return static_cast<StorageClass>(FunctionDeclBits.SClass);
  2231. }
  2232. /// Sets the storage class as written in the source.
  2233. void setStorageClass(StorageClass SClass) {
  2234. FunctionDeclBits.SClass = SClass;
  2235. }
  2236. /// Determine whether the "inline" keyword was specified for this
  2237. /// function.
  2238. bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; }
  2239. /// Set whether the "inline" keyword was specified for this function.
  2240. void setInlineSpecified(bool I) {
  2241. FunctionDeclBits.IsInlineSpecified = I;
  2242. FunctionDeclBits.IsInline = I;
  2243. }
  2244. /// Determine whether the function was declared in source context
  2245. /// that requires constrained FP intrinsics
  2246. bool UsesFPIntrin() const { return FunctionDeclBits.UsesFPIntrin; }
  2247. /// Set whether the function was declared in source context
  2248. /// that requires constrained FP intrinsics
  2249. void setUsesFPIntrin(bool I) { FunctionDeclBits.UsesFPIntrin = I; }
  2250. /// Flag that this function is implicitly inline.
  2251. void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; }
  2252. /// Determine whether this function should be inlined, because it is
  2253. /// either marked "inline" or "constexpr" or is a member function of a class
  2254. /// that was defined in the class body.
  2255. bool isInlined() const { return FunctionDeclBits.IsInline; }
  2256. bool isInlineDefinitionExternallyVisible() const;
  2257. bool isMSExternInline() const;
  2258. bool doesDeclarationForceExternallyVisibleDefinition() const;
  2259. bool isStatic() const { return getStorageClass() == SC_Static; }
  2260. /// Whether this function declaration represents an C++ overloaded
  2261. /// operator, e.g., "operator+".
  2262. bool isOverloadedOperator() const {
  2263. return getOverloadedOperator() != OO_None;
  2264. }
  2265. OverloadedOperatorKind getOverloadedOperator() const;
  2266. const IdentifierInfo *getLiteralIdentifier() const;
  2267. /// If this function is an instantiation of a member function
  2268. /// of a class template specialization, retrieves the function from
  2269. /// which it was instantiated.
  2270. ///
  2271. /// This routine will return non-NULL for (non-templated) member
  2272. /// functions of class templates and for instantiations of function
  2273. /// templates. For example, given:
  2274. ///
  2275. /// \code
  2276. /// template<typename T>
  2277. /// struct X {
  2278. /// void f(T);
  2279. /// };
  2280. /// \endcode
  2281. ///
  2282. /// The declaration for X<int>::f is a (non-templated) FunctionDecl
  2283. /// whose parent is the class template specialization X<int>. For
  2284. /// this declaration, getInstantiatedFromFunction() will return
  2285. /// the FunctionDecl X<T>::A. When a complete definition of
  2286. /// X<int>::A is required, it will be instantiated from the
  2287. /// declaration returned by getInstantiatedFromMemberFunction().
  2288. FunctionDecl *getInstantiatedFromMemberFunction() const;
  2289. /// What kind of templated function this is.
  2290. TemplatedKind getTemplatedKind() const;
  2291. /// If this function is an instantiation of a member function of a
  2292. /// class template specialization, retrieves the member specialization
  2293. /// information.
  2294. MemberSpecializationInfo *getMemberSpecializationInfo() const;
  2295. /// Specify that this record is an instantiation of the
  2296. /// member function FD.
  2297. void setInstantiationOfMemberFunction(FunctionDecl *FD,
  2298. TemplateSpecializationKind TSK) {
  2299. setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
  2300. }
  2301. /// Specify that this function declaration was instantiated from a
  2302. /// FunctionDecl FD. This is only used if this is a function declaration
  2303. /// declared locally inside of a function template.
  2304. void setInstantiatedFromDecl(FunctionDecl *FD);
  2305. FunctionDecl *getInstantiatedFromDecl() const;
  2306. /// Retrieves the function template that is described by this
  2307. /// function declaration.
  2308. ///
  2309. /// Every function template is represented as a FunctionTemplateDecl
  2310. /// and a FunctionDecl (or something derived from FunctionDecl). The
  2311. /// former contains template properties (such as the template
  2312. /// parameter lists) while the latter contains the actual
  2313. /// description of the template's
  2314. /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
  2315. /// FunctionDecl that describes the function template,
  2316. /// getDescribedFunctionTemplate() retrieves the
  2317. /// FunctionTemplateDecl from a FunctionDecl.
  2318. FunctionTemplateDecl *getDescribedFunctionTemplate() const;
  2319. void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
  2320. /// Determine whether this function is a function template
  2321. /// specialization.
  2322. bool isFunctionTemplateSpecialization() const {
  2323. return getPrimaryTemplate() != nullptr;
  2324. }
  2325. /// If this function is actually a function template specialization,
  2326. /// retrieve information about this function template specialization.
  2327. /// Otherwise, returns NULL.
  2328. FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
  2329. /// Determines whether this function is a function template
  2330. /// specialization or a member of a class template specialization that can
  2331. /// be implicitly instantiated.
  2332. bool isImplicitlyInstantiable() const;
  2333. /// Determines if the given function was instantiated from a
  2334. /// function template.
  2335. bool isTemplateInstantiation() const;
  2336. /// Retrieve the function declaration from which this function could
  2337. /// be instantiated, if it is an instantiation (rather than a non-template
  2338. /// or a specialization, for example).
  2339. ///
  2340. /// If \p ForDefinition is \c false, explicit specializations will be treated
  2341. /// as if they were implicit instantiations. This will then find the pattern
  2342. /// corresponding to non-definition portions of the declaration, such as
  2343. /// default arguments and the exception specification.
  2344. FunctionDecl *
  2345. getTemplateInstantiationPattern(bool ForDefinition = true) const;
  2346. /// Retrieve the primary template that this function template
  2347. /// specialization either specializes or was instantiated from.
  2348. ///
  2349. /// If this function declaration is not a function template specialization,
  2350. /// returns NULL.
  2351. FunctionTemplateDecl *getPrimaryTemplate() const;
  2352. /// Retrieve the template arguments used to produce this function
  2353. /// template specialization from the primary template.
  2354. ///
  2355. /// If this function declaration is not a function template specialization,
  2356. /// returns NULL.
  2357. const TemplateArgumentList *getTemplateSpecializationArgs() const;
  2358. /// Retrieve the template argument list as written in the sources,
  2359. /// if any.
  2360. ///
  2361. /// If this function declaration is not a function template specialization
  2362. /// or if it had no explicit template argument list, returns NULL.
  2363. /// Note that it an explicit template argument list may be written empty,
  2364. /// e.g., template<> void foo<>(char* s);
  2365. const ASTTemplateArgumentListInfo*
  2366. getTemplateSpecializationArgsAsWritten() const;
  2367. /// Specify that this function declaration is actually a function
  2368. /// template specialization.
  2369. ///
  2370. /// \param Template the function template that this function template
  2371. /// specialization specializes.
  2372. ///
  2373. /// \param TemplateArgs the template arguments that produced this
  2374. /// function template specialization from the template.
  2375. ///
  2376. /// \param InsertPos If non-NULL, the position in the function template
  2377. /// specialization set where the function template specialization data will
  2378. /// be inserted.
  2379. ///
  2380. /// \param TSK the kind of template specialization this is.
  2381. ///
  2382. /// \param TemplateArgsAsWritten location info of template arguments.
  2383. ///
  2384. /// \param PointOfInstantiation point at which the function template
  2385. /// specialization was first instantiated.
  2386. void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
  2387. const TemplateArgumentList *TemplateArgs,
  2388. void *InsertPos,
  2389. TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
  2390. const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
  2391. SourceLocation PointOfInstantiation = SourceLocation()) {
  2392. setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
  2393. InsertPos, TSK, TemplateArgsAsWritten,
  2394. PointOfInstantiation);
  2395. }
  2396. /// Specifies that this function declaration is actually a
  2397. /// dependent function template specialization.
  2398. void setDependentTemplateSpecialization(ASTContext &Context,
  2399. const UnresolvedSetImpl &Templates,
  2400. const TemplateArgumentListInfo &TemplateArgs);
  2401. DependentFunctionTemplateSpecializationInfo *
  2402. getDependentSpecializationInfo() const;
  2403. /// Determine what kind of template instantiation this function
  2404. /// represents.
  2405. TemplateSpecializationKind getTemplateSpecializationKind() const;
  2406. /// Determine the kind of template specialization this function represents
  2407. /// for the purpose of template instantiation.
  2408. TemplateSpecializationKind
  2409. getTemplateSpecializationKindForInstantiation() const;
  2410. /// Determine what kind of template instantiation this function
  2411. /// represents.
  2412. void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  2413. SourceLocation PointOfInstantiation = SourceLocation());
  2414. /// Retrieve the (first) point of instantiation of a function template
  2415. /// specialization or a member of a class template specialization.
  2416. ///
  2417. /// \returns the first point of instantiation, if this function was
  2418. /// instantiated from a template; otherwise, returns an invalid source
  2419. /// location.
  2420. SourceLocation getPointOfInstantiation() const;
  2421. /// Determine whether this is or was instantiated from an out-of-line
  2422. /// definition of a member function.
  2423. bool isOutOfLine() const override;
  2424. /// Identify a memory copying or setting function.
  2425. /// If the given function is a memory copy or setting function, returns
  2426. /// the corresponding Builtin ID. If the function is not a memory function,
  2427. /// returns 0.
  2428. unsigned getMemoryFunctionKind() const;
  2429. /// Returns ODRHash of the function. This value is calculated and
  2430. /// stored on first call, then the stored value returned on the other calls.
  2431. unsigned getODRHash();
  2432. /// Returns cached ODRHash of the function. This must have been previously
  2433. /// computed and stored.
  2434. unsigned getODRHash() const;
  2435. // Implement isa/cast/dyncast/etc.
  2436. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2437. static bool classofKind(Kind K) {
  2438. return K >= firstFunction && K <= lastFunction;
  2439. }
  2440. static DeclContext *castToDeclContext(const FunctionDecl *D) {
  2441. return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
  2442. }
  2443. static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
  2444. return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
  2445. }
  2446. };
  2447. /// Represents a member of a struct/union/class.
  2448. class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
  2449. unsigned BitField : 1;
  2450. unsigned Mutable : 1;
  2451. mutable unsigned CachedFieldIndex : 30;
  2452. /// The kinds of value we can store in InitializerOrBitWidth.
  2453. ///
  2454. /// Note that this is compatible with InClassInitStyle except for
  2455. /// ISK_CapturedVLAType.
  2456. enum InitStorageKind {
  2457. /// If the pointer is null, there's nothing special. Otherwise,
  2458. /// this is a bitfield and the pointer is the Expr* storing the
  2459. /// bit-width.
  2460. ISK_NoInit = (unsigned) ICIS_NoInit,
  2461. /// The pointer is an (optional due to delayed parsing) Expr*
  2462. /// holding the copy-initializer.
  2463. ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
  2464. /// The pointer is an (optional due to delayed parsing) Expr*
  2465. /// holding the list-initializer.
  2466. ISK_InClassListInit = (unsigned) ICIS_ListInit,
  2467. /// The pointer is a VariableArrayType* that's been captured;
  2468. /// the enclosing context is a lambda or captured statement.
  2469. ISK_CapturedVLAType,
  2470. };
  2471. /// If this is a bitfield with a default member initializer, this
  2472. /// structure is used to represent the two expressions.
  2473. struct InitAndBitWidth {
  2474. Expr *Init;
  2475. Expr *BitWidth;
  2476. };
  2477. /// Storage for either the bit-width, the in-class initializer, or
  2478. /// both (via InitAndBitWidth), or the captured variable length array bound.
  2479. ///
  2480. /// If the storage kind is ISK_InClassCopyInit or
  2481. /// ISK_InClassListInit, but the initializer is null, then this
  2482. /// field has an in-class initializer that has not yet been parsed
  2483. /// and attached.
  2484. // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
  2485. // overwhelmingly common case that we have none of these things.
  2486. llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
  2487. protected:
  2488. FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
  2489. SourceLocation IdLoc, IdentifierInfo *Id,
  2490. QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
  2491. InClassInitStyle InitStyle)
  2492. : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
  2493. BitField(false), Mutable(Mutable), CachedFieldIndex(0),
  2494. InitStorage(nullptr, (InitStorageKind) InitStyle) {
  2495. if (BW)
  2496. setBitWidth(BW);
  2497. }
  2498. public:
  2499. friend class ASTDeclReader;
  2500. friend class ASTDeclWriter;
  2501. static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
  2502. SourceLocation StartLoc, SourceLocation IdLoc,
  2503. IdentifierInfo *Id, QualType T,
  2504. TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
  2505. InClassInitStyle InitStyle);
  2506. static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2507. /// Returns the index of this field within its record,
  2508. /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
  2509. unsigned getFieldIndex() const;
  2510. /// Determines whether this field is mutable (C++ only).
  2511. bool isMutable() const { return Mutable; }
  2512. /// Determines whether this field is a bitfield.
  2513. bool isBitField() const { return BitField; }
  2514. /// Determines whether this is an unnamed bitfield.
  2515. bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
  2516. /// Determines whether this field is a
  2517. /// representative for an anonymous struct or union. Such fields are
  2518. /// unnamed and are implicitly generated by the implementation to
  2519. /// store the data for the anonymous union or struct.
  2520. bool isAnonymousStructOrUnion() const;
  2521. Expr *getBitWidth() const {
  2522. if (!BitField)
  2523. return nullptr;
  2524. void *Ptr = InitStorage.getPointer();
  2525. if (getInClassInitStyle())
  2526. return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
  2527. return static_cast<Expr*>(Ptr);
  2528. }
  2529. unsigned getBitWidthValue(const ASTContext &Ctx) const;
  2530. /// Set the bit-field width for this member.
  2531. // Note: used by some clients (i.e., do not remove it).
  2532. void setBitWidth(Expr *Width) {
  2533. assert(!hasCapturedVLAType() && !BitField &&
  2534. "bit width or captured type already set");
  2535. assert(Width && "no bit width specified");
  2536. InitStorage.setPointer(
  2537. InitStorage.getInt()
  2538. ? new (getASTContext())
  2539. InitAndBitWidth{getInClassInitializer(), Width}
  2540. : static_cast<void*>(Width));
  2541. BitField = true;
  2542. }
  2543. /// Remove the bit-field width from this member.
  2544. // Note: used by some clients (i.e., do not remove it).
  2545. void removeBitWidth() {
  2546. assert(isBitField() && "no bitfield width to remove");
  2547. InitStorage.setPointer(getInClassInitializer());
  2548. BitField = false;
  2549. }
  2550. /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
  2551. /// at all and instead act as a separator between contiguous runs of other
  2552. /// bit-fields.
  2553. bool isZeroLengthBitField(const ASTContext &Ctx) const;
  2554. /// Determine if this field is a subobject of zero size, that is, either a
  2555. /// zero-length bit-field or a field of empty class type with the
  2556. /// [[no_unique_address]] attribute.
  2557. bool isZeroSize(const ASTContext &Ctx) const;
  2558. /// Get the kind of (C++11) default member initializer that this field has.
  2559. InClassInitStyle getInClassInitStyle() const {
  2560. InitStorageKind storageKind = InitStorage.getInt();
  2561. return (storageKind == ISK_CapturedVLAType
  2562. ? ICIS_NoInit : (InClassInitStyle) storageKind);
  2563. }
  2564. /// Determine whether this member has a C++11 default member initializer.
  2565. bool hasInClassInitializer() const {
  2566. return getInClassInitStyle() != ICIS_NoInit;
  2567. }
  2568. /// Get the C++11 default member initializer for this member, or null if one
  2569. /// has not been set. If a valid declaration has a default member initializer,
  2570. /// but this returns null, then we have not parsed and attached it yet.
  2571. Expr *getInClassInitializer() const {
  2572. if (!hasInClassInitializer())
  2573. return nullptr;
  2574. void *Ptr = InitStorage.getPointer();
  2575. if (BitField)
  2576. return static_cast<InitAndBitWidth*>(Ptr)->Init;
  2577. return static_cast<Expr*>(Ptr);
  2578. }
  2579. /// Set the C++11 in-class initializer for this member.
  2580. void setInClassInitializer(Expr *Init) {
  2581. assert(hasInClassInitializer() && !getInClassInitializer());
  2582. if (BitField)
  2583. static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
  2584. else
  2585. InitStorage.setPointer(Init);
  2586. }
  2587. /// Remove the C++11 in-class initializer from this member.
  2588. void removeInClassInitializer() {
  2589. assert(hasInClassInitializer() && "no initializer to remove");
  2590. InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
  2591. }
  2592. /// Determine whether this member captures the variable length array
  2593. /// type.
  2594. bool hasCapturedVLAType() const {
  2595. return InitStorage.getInt() == ISK_CapturedVLAType;
  2596. }
  2597. /// Get the captured variable length array type.
  2598. const VariableArrayType *getCapturedVLAType() const {
  2599. return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
  2600. InitStorage.getPointer())
  2601. : nullptr;
  2602. }
  2603. /// Set the captured variable length array type for this field.
  2604. void setCapturedVLAType(const VariableArrayType *VLAType);
  2605. /// Returns the parent of this field declaration, which
  2606. /// is the struct in which this field is defined.
  2607. ///
  2608. /// Returns null if this is not a normal class/struct field declaration, e.g.
  2609. /// ObjCAtDefsFieldDecl, ObjCIvarDecl.
  2610. const RecordDecl *getParent() const {
  2611. return dyn_cast<RecordDecl>(getDeclContext());
  2612. }
  2613. RecordDecl *getParent() {
  2614. return dyn_cast<RecordDecl>(getDeclContext());
  2615. }
  2616. SourceRange getSourceRange() const override LLVM_READONLY;
  2617. /// Retrieves the canonical declaration of this field.
  2618. FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
  2619. const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
  2620. // Implement isa/cast/dyncast/etc.
  2621. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2622. static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
  2623. };
  2624. /// An instance of this object exists for each enum constant
  2625. /// that is defined. For example, in "enum X {a,b}", each of a/b are
  2626. /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
  2627. /// TagType for the X EnumDecl.
  2628. class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
  2629. Stmt *Init; // an integer constant expression
  2630. llvm::APSInt Val; // The value.
  2631. protected:
  2632. EnumConstantDecl(DeclContext *DC, SourceLocation L,
  2633. IdentifierInfo *Id, QualType T, Expr *E,
  2634. const llvm::APSInt &V)
  2635. : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
  2636. public:
  2637. friend class StmtIteratorBase;
  2638. static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
  2639. SourceLocation L, IdentifierInfo *Id,
  2640. QualType T, Expr *E,
  2641. const llvm::APSInt &V);
  2642. static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2643. const Expr *getInitExpr() const { return (const Expr*) Init; }
  2644. Expr *getInitExpr() { return (Expr*) Init; }
  2645. const llvm::APSInt &getInitVal() const { return Val; }
  2646. void setInitExpr(Expr *E) { Init = (Stmt*) E; }
  2647. void setInitVal(const llvm::APSInt &V) { Val = V; }
  2648. SourceRange getSourceRange() const override LLVM_READONLY;
  2649. /// Retrieves the canonical declaration of this enumerator.
  2650. EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
  2651. const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
  2652. // Implement isa/cast/dyncast/etc.
  2653. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2654. static bool classofKind(Kind K) { return K == EnumConstant; }
  2655. };
  2656. /// Represents a field injected from an anonymous union/struct into the parent
  2657. /// scope. These are always implicit.
  2658. class IndirectFieldDecl : public ValueDecl,
  2659. public Mergeable<IndirectFieldDecl> {
  2660. NamedDecl **Chaining;
  2661. unsigned ChainingSize;
  2662. IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
  2663. DeclarationName N, QualType T,
  2664. MutableArrayRef<NamedDecl *> CH);
  2665. void anchor() override;
  2666. public:
  2667. friend class ASTDeclReader;
  2668. static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
  2669. SourceLocation L, IdentifierInfo *Id,
  2670. QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
  2671. static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2672. using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
  2673. ArrayRef<NamedDecl *> chain() const {
  2674. return llvm::ArrayRef(Chaining, ChainingSize);
  2675. }
  2676. chain_iterator chain_begin() const { return chain().begin(); }
  2677. chain_iterator chain_end() const { return chain().end(); }
  2678. unsigned getChainingSize() const { return ChainingSize; }
  2679. FieldDecl *getAnonField() const {
  2680. assert(chain().size() >= 2);
  2681. return cast<FieldDecl>(chain().back());
  2682. }
  2683. VarDecl *getVarDecl() const {
  2684. assert(chain().size() >= 2);
  2685. return dyn_cast<VarDecl>(chain().front());
  2686. }
  2687. IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
  2688. const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
  2689. // Implement isa/cast/dyncast/etc.
  2690. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2691. static bool classofKind(Kind K) { return K == IndirectField; }
  2692. };
  2693. /// Represents a declaration of a type.
  2694. class TypeDecl : public NamedDecl {
  2695. friend class ASTContext;
  2696. /// This indicates the Type object that represents
  2697. /// this TypeDecl. It is a cache maintained by
  2698. /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
  2699. /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
  2700. mutable const Type *TypeForDecl = nullptr;
  2701. /// The start of the source range for this declaration.
  2702. SourceLocation LocStart;
  2703. void anchor() override;
  2704. protected:
  2705. TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
  2706. SourceLocation StartL = SourceLocation())
  2707. : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
  2708. public:
  2709. // Low-level accessor. If you just want the type defined by this node,
  2710. // check out ASTContext::getTypeDeclType or one of
  2711. // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
  2712. // already know the specific kind of node this is.
  2713. const Type *getTypeForDecl() const { return TypeForDecl; }
  2714. void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
  2715. SourceLocation getBeginLoc() const LLVM_READONLY { return LocStart; }
  2716. void setLocStart(SourceLocation L) { LocStart = L; }
  2717. SourceRange getSourceRange() const override LLVM_READONLY {
  2718. if (LocStart.isValid())
  2719. return SourceRange(LocStart, getLocation());
  2720. else
  2721. return SourceRange(getLocation());
  2722. }
  2723. // Implement isa/cast/dyncast/etc.
  2724. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2725. static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
  2726. };
  2727. /// Base class for declarations which introduce a typedef-name.
  2728. class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
  2729. struct alignas(8) ModedTInfo {
  2730. TypeSourceInfo *first;
  2731. QualType second;
  2732. };
  2733. /// If int part is 0, we have not computed IsTransparentTag.
  2734. /// Otherwise, IsTransparentTag is (getInt() >> 1).
  2735. mutable llvm::PointerIntPair<
  2736. llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
  2737. MaybeModedTInfo;
  2738. void anchor() override;
  2739. protected:
  2740. TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
  2741. SourceLocation StartLoc, SourceLocation IdLoc,
  2742. IdentifierInfo *Id, TypeSourceInfo *TInfo)
  2743. : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
  2744. MaybeModedTInfo(TInfo, 0) {}
  2745. using redeclarable_base = Redeclarable<TypedefNameDecl>;
  2746. TypedefNameDecl *getNextRedeclarationImpl() override {
  2747. return getNextRedeclaration();
  2748. }
  2749. TypedefNameDecl *getPreviousDeclImpl() override {
  2750. return getPreviousDecl();
  2751. }
  2752. TypedefNameDecl *getMostRecentDeclImpl() override {
  2753. return getMostRecentDecl();
  2754. }
  2755. public:
  2756. using redecl_range = redeclarable_base::redecl_range;
  2757. using redecl_iterator = redeclarable_base::redecl_iterator;
  2758. using redeclarable_base::redecls_begin;
  2759. using redeclarable_base::redecls_end;
  2760. using redeclarable_base::redecls;
  2761. using redeclarable_base::getPreviousDecl;
  2762. using redeclarable_base::getMostRecentDecl;
  2763. using redeclarable_base::isFirstDecl;
  2764. bool isModed() const {
  2765. return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
  2766. }
  2767. TypeSourceInfo *getTypeSourceInfo() const {
  2768. return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
  2769. : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
  2770. }
  2771. QualType getUnderlyingType() const {
  2772. return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
  2773. : MaybeModedTInfo.getPointer()
  2774. .get<TypeSourceInfo *>()
  2775. ->getType();
  2776. }
  2777. void setTypeSourceInfo(TypeSourceInfo *newType) {
  2778. MaybeModedTInfo.setPointer(newType);
  2779. }
  2780. void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
  2781. MaybeModedTInfo.setPointer(new (getASTContext(), 8)
  2782. ModedTInfo({unmodedTSI, modedTy}));
  2783. }
  2784. /// Retrieves the canonical declaration of this typedef-name.
  2785. TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
  2786. const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
  2787. /// Retrieves the tag declaration for which this is the typedef name for
  2788. /// linkage purposes, if any.
  2789. ///
  2790. /// \param AnyRedecl Look for the tag declaration in any redeclaration of
  2791. /// this typedef declaration.
  2792. TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
  2793. /// Determines if this typedef shares a name and spelling location with its
  2794. /// underlying tag type, as is the case with the NS_ENUM macro.
  2795. bool isTransparentTag() const {
  2796. if (MaybeModedTInfo.getInt())
  2797. return MaybeModedTInfo.getInt() & 0x2;
  2798. return isTransparentTagSlow();
  2799. }
  2800. // Implement isa/cast/dyncast/etc.
  2801. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2802. static bool classofKind(Kind K) {
  2803. return K >= firstTypedefName && K <= lastTypedefName;
  2804. }
  2805. private:
  2806. bool isTransparentTagSlow() const;
  2807. };
  2808. /// Represents the declaration of a typedef-name via the 'typedef'
  2809. /// type specifier.
  2810. class TypedefDecl : public TypedefNameDecl {
  2811. TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  2812. SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
  2813. : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
  2814. public:
  2815. static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
  2816. SourceLocation StartLoc, SourceLocation IdLoc,
  2817. IdentifierInfo *Id, TypeSourceInfo *TInfo);
  2818. static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2819. SourceRange getSourceRange() const override LLVM_READONLY;
  2820. // Implement isa/cast/dyncast/etc.
  2821. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2822. static bool classofKind(Kind K) { return K == Typedef; }
  2823. };
  2824. /// Represents the declaration of a typedef-name via a C++11
  2825. /// alias-declaration.
  2826. class TypeAliasDecl : public TypedefNameDecl {
  2827. /// The template for which this is the pattern, if any.
  2828. TypeAliasTemplateDecl *Template;
  2829. TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  2830. SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
  2831. : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
  2832. Template(nullptr) {}
  2833. public:
  2834. static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
  2835. SourceLocation StartLoc, SourceLocation IdLoc,
  2836. IdentifierInfo *Id, TypeSourceInfo *TInfo);
  2837. static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2838. SourceRange getSourceRange() const override LLVM_READONLY;
  2839. TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
  2840. void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
  2841. // Implement isa/cast/dyncast/etc.
  2842. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2843. static bool classofKind(Kind K) { return K == TypeAlias; }
  2844. };
  2845. /// Represents the declaration of a struct/union/class/enum.
  2846. class TagDecl : public TypeDecl,
  2847. public DeclContext,
  2848. public Redeclarable<TagDecl> {
  2849. // This class stores some data in DeclContext::TagDeclBits
  2850. // to save some space. Use the provided accessors to access it.
  2851. public:
  2852. // This is really ugly.
  2853. using TagKind = TagTypeKind;
  2854. private:
  2855. SourceRange BraceRange;
  2856. // A struct representing syntactic qualifier info,
  2857. // to be used for the (uncommon) case of out-of-line declarations.
  2858. using ExtInfo = QualifierInfo;
  2859. /// If the (out-of-line) tag declaration name
  2860. /// is qualified, it points to the qualifier info (nns and range);
  2861. /// otherwise, if the tag declaration is anonymous and it is part of
  2862. /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
  2863. /// otherwise, if the tag declaration is anonymous and it is used as a
  2864. /// declaration specifier for variables, it points to the first VarDecl (used
  2865. /// for mangling);
  2866. /// otherwise, it is a null (TypedefNameDecl) pointer.
  2867. llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
  2868. bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
  2869. ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
  2870. const ExtInfo *getExtInfo() const {
  2871. return TypedefNameDeclOrQualifier.get<ExtInfo *>();
  2872. }
  2873. protected:
  2874. TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
  2875. SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
  2876. SourceLocation StartL);
  2877. using redeclarable_base = Redeclarable<TagDecl>;
  2878. TagDecl *getNextRedeclarationImpl() override {
  2879. return getNextRedeclaration();
  2880. }
  2881. TagDecl *getPreviousDeclImpl() override {
  2882. return getPreviousDecl();
  2883. }
  2884. TagDecl *getMostRecentDeclImpl() override {
  2885. return getMostRecentDecl();
  2886. }
  2887. /// Completes the definition of this tag declaration.
  2888. ///
  2889. /// This is a helper function for derived classes.
  2890. void completeDefinition();
  2891. /// True if this decl is currently being defined.
  2892. void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; }
  2893. /// Indicates whether it is possible for declarations of this kind
  2894. /// to have an out-of-date definition.
  2895. ///
  2896. /// This option is only enabled when modules are enabled.
  2897. void setMayHaveOutOfDateDef(bool V = true) {
  2898. TagDeclBits.MayHaveOutOfDateDef = V;
  2899. }
  2900. public:
  2901. friend class ASTDeclReader;
  2902. friend class ASTDeclWriter;
  2903. using redecl_range = redeclarable_base::redecl_range;
  2904. using redecl_iterator = redeclarable_base::redecl_iterator;
  2905. using redeclarable_base::redecls_begin;
  2906. using redeclarable_base::redecls_end;
  2907. using redeclarable_base::redecls;
  2908. using redeclarable_base::getPreviousDecl;
  2909. using redeclarable_base::getMostRecentDecl;
  2910. using redeclarable_base::isFirstDecl;
  2911. SourceRange getBraceRange() const { return BraceRange; }
  2912. void setBraceRange(SourceRange R) { BraceRange = R; }
  2913. /// Return SourceLocation representing start of source
  2914. /// range ignoring outer template declarations.
  2915. SourceLocation getInnerLocStart() const { return getBeginLoc(); }
  2916. /// Return SourceLocation representing start of source
  2917. /// range taking into account any outer template declarations.
  2918. SourceLocation getOuterLocStart() const;
  2919. SourceRange getSourceRange() const override LLVM_READONLY;
  2920. TagDecl *getCanonicalDecl() override;
  2921. const TagDecl *getCanonicalDecl() const {
  2922. return const_cast<TagDecl*>(this)->getCanonicalDecl();
  2923. }
  2924. /// Return true if this declaration is a completion definition of the type.
  2925. /// Provided for consistency.
  2926. bool isThisDeclarationADefinition() const {
  2927. return isCompleteDefinition();
  2928. }
  2929. /// Return true if this decl has its body fully specified.
  2930. bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; }
  2931. /// True if this decl has its body fully specified.
  2932. void setCompleteDefinition(bool V = true) {
  2933. TagDeclBits.IsCompleteDefinition = V;
  2934. }
  2935. /// Return true if this complete decl is
  2936. /// required to be complete for some existing use.
  2937. bool isCompleteDefinitionRequired() const {
  2938. return TagDeclBits.IsCompleteDefinitionRequired;
  2939. }
  2940. /// True if this complete decl is
  2941. /// required to be complete for some existing use.
  2942. void setCompleteDefinitionRequired(bool V = true) {
  2943. TagDeclBits.IsCompleteDefinitionRequired = V;
  2944. }
  2945. /// Return true if this decl is currently being defined.
  2946. bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; }
  2947. /// True if this tag declaration is "embedded" (i.e., defined or declared
  2948. /// for the very first time) in the syntax of a declarator.
  2949. bool isEmbeddedInDeclarator() const {
  2950. return TagDeclBits.IsEmbeddedInDeclarator;
  2951. }
  2952. /// True if this tag declaration is "embedded" (i.e., defined or declared
  2953. /// for the very first time) in the syntax of a declarator.
  2954. void setEmbeddedInDeclarator(bool isInDeclarator) {
  2955. TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator;
  2956. }
  2957. /// True if this tag is free standing, e.g. "struct foo;".
  2958. bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; }
  2959. /// True if this tag is free standing, e.g. "struct foo;".
  2960. void setFreeStanding(bool isFreeStanding = true) {
  2961. TagDeclBits.IsFreeStanding = isFreeStanding;
  2962. }
  2963. /// Indicates whether it is possible for declarations of this kind
  2964. /// to have an out-of-date definition.
  2965. ///
  2966. /// This option is only enabled when modules are enabled.
  2967. bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; }
  2968. /// Whether this declaration declares a type that is
  2969. /// dependent, i.e., a type that somehow depends on template
  2970. /// parameters.
  2971. bool isDependentType() const { return isDependentContext(); }
  2972. /// Whether this declaration was a definition in some module but was forced
  2973. /// to be a declaration.
  2974. ///
  2975. /// Useful for clients checking if a module has a definition of a specific
  2976. /// symbol and not interested in the final AST with deduplicated definitions.
  2977. bool isThisDeclarationADemotedDefinition() const {
  2978. return TagDeclBits.IsThisDeclarationADemotedDefinition;
  2979. }
  2980. /// Mark a definition as a declaration and maintain information it _was_
  2981. /// a definition.
  2982. void demoteThisDefinitionToDeclaration() {
  2983. assert(isCompleteDefinition() &&
  2984. "Should demote definitions only, not forward declarations");
  2985. setCompleteDefinition(false);
  2986. TagDeclBits.IsThisDeclarationADemotedDefinition = true;
  2987. }
  2988. /// Starts the definition of this tag declaration.
  2989. ///
  2990. /// This method should be invoked at the beginning of the definition
  2991. /// of this tag declaration. It will set the tag type into a state
  2992. /// where it is in the process of being defined.
  2993. void startDefinition();
  2994. /// Returns the TagDecl that actually defines this
  2995. /// struct/union/class/enum. When determining whether or not a
  2996. /// struct/union/class/enum has a definition, one should use this
  2997. /// method as opposed to 'isDefinition'. 'isDefinition' indicates
  2998. /// whether or not a specific TagDecl is defining declaration, not
  2999. /// whether or not the struct/union/class/enum type is defined.
  3000. /// This method returns NULL if there is no TagDecl that defines
  3001. /// the struct/union/class/enum.
  3002. TagDecl *getDefinition() const;
  3003. StringRef getKindName() const {
  3004. return TypeWithKeyword::getTagTypeKindName(getTagKind());
  3005. }
  3006. TagKind getTagKind() const {
  3007. return static_cast<TagKind>(TagDeclBits.TagDeclKind);
  3008. }
  3009. void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; }
  3010. bool isStruct() const { return getTagKind() == TTK_Struct; }
  3011. bool isInterface() const { return getTagKind() == TTK_Interface; }
  3012. bool isClass() const { return getTagKind() == TTK_Class; }
  3013. bool isUnion() const { return getTagKind() == TTK_Union; }
  3014. bool isEnum() const { return getTagKind() == TTK_Enum; }
  3015. /// Is this tag type named, either directly or via being defined in
  3016. /// a typedef of this type?
  3017. ///
  3018. /// C++11 [basic.link]p8:
  3019. /// A type is said to have linkage if and only if:
  3020. /// - it is a class or enumeration type that is named (or has a
  3021. /// name for linkage purposes) and the name has linkage; ...
  3022. /// C++11 [dcl.typedef]p9:
  3023. /// If the typedef declaration defines an unnamed class (or enum),
  3024. /// the first typedef-name declared by the declaration to be that
  3025. /// class type (or enum type) is used to denote the class type (or
  3026. /// enum type) for linkage purposes only.
  3027. ///
  3028. /// C does not have an analogous rule, but the same concept is
  3029. /// nonetheless useful in some places.
  3030. bool hasNameForLinkage() const {
  3031. return (getDeclName() || getTypedefNameForAnonDecl());
  3032. }
  3033. TypedefNameDecl *getTypedefNameForAnonDecl() const {
  3034. return hasExtInfo() ? nullptr
  3035. : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
  3036. }
  3037. void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
  3038. /// Retrieve the nested-name-specifier that qualifies the name of this
  3039. /// declaration, if it was present in the source.
  3040. NestedNameSpecifier *getQualifier() const {
  3041. return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
  3042. : nullptr;
  3043. }
  3044. /// Retrieve the nested-name-specifier (with source-location
  3045. /// information) that qualifies the name of this declaration, if it was
  3046. /// present in the source.
  3047. NestedNameSpecifierLoc getQualifierLoc() const {
  3048. return hasExtInfo() ? getExtInfo()->QualifierLoc
  3049. : NestedNameSpecifierLoc();
  3050. }
  3051. void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
  3052. unsigned getNumTemplateParameterLists() const {
  3053. return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
  3054. }
  3055. TemplateParameterList *getTemplateParameterList(unsigned i) const {
  3056. assert(i < getNumTemplateParameterLists());
  3057. return getExtInfo()->TemplParamLists[i];
  3058. }
  3059. void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override;
  3060. void setTemplateParameterListsInfo(ASTContext &Context,
  3061. ArrayRef<TemplateParameterList *> TPLists);
  3062. // Implement isa/cast/dyncast/etc.
  3063. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3064. static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
  3065. static DeclContext *castToDeclContext(const TagDecl *D) {
  3066. return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
  3067. }
  3068. static TagDecl *castFromDeclContext(const DeclContext *DC) {
  3069. return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
  3070. }
  3071. };
  3072. /// Represents an enum. In C++11, enums can be forward-declared
  3073. /// with a fixed underlying type, and in C we allow them to be forward-declared
  3074. /// with no underlying type as an extension.
  3075. class EnumDecl : public TagDecl {
  3076. // This class stores some data in DeclContext::EnumDeclBits
  3077. // to save some space. Use the provided accessors to access it.
  3078. /// This represent the integer type that the enum corresponds
  3079. /// to for code generation purposes. Note that the enumerator constants may
  3080. /// have a different type than this does.
  3081. ///
  3082. /// If the underlying integer type was explicitly stated in the source
  3083. /// code, this is a TypeSourceInfo* for that type. Otherwise this type
  3084. /// was automatically deduced somehow, and this is a Type*.
  3085. ///
  3086. /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
  3087. /// some cases it won't.
  3088. ///
  3089. /// The underlying type of an enumeration never has any qualifiers, so
  3090. /// we can get away with just storing a raw Type*, and thus save an
  3091. /// extra pointer when TypeSourceInfo is needed.
  3092. llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
  3093. /// The integer type that values of this type should
  3094. /// promote to. In C, enumerators are generally of an integer type
  3095. /// directly, but gcc-style large enumerators (and all enumerators
  3096. /// in C++) are of the enum type instead.
  3097. QualType PromotionType;
  3098. /// If this enumeration is an instantiation of a member enumeration
  3099. /// of a class template specialization, this is the member specialization
  3100. /// information.
  3101. MemberSpecializationInfo *SpecializationInfo = nullptr;
  3102. /// Store the ODRHash after first calculation.
  3103. /// The corresponding flag HasODRHash is in EnumDeclBits
  3104. /// and can be accessed with the provided accessors.
  3105. unsigned ODRHash;
  3106. EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  3107. SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
  3108. bool Scoped, bool ScopedUsingClassTag, bool Fixed);
  3109. void anchor() override;
  3110. void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
  3111. TemplateSpecializationKind TSK);
  3112. /// Sets the width in bits required to store all the
  3113. /// non-negative enumerators of this enum.
  3114. void setNumPositiveBits(unsigned Num) {
  3115. EnumDeclBits.NumPositiveBits = Num;
  3116. assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount");
  3117. }
  3118. /// Returns the width in bits required to store all the
  3119. /// negative enumerators of this enum. (see getNumNegativeBits)
  3120. void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; }
  3121. public:
  3122. /// True if this tag declaration is a scoped enumeration. Only
  3123. /// possible in C++11 mode.
  3124. void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; }
  3125. /// If this tag declaration is a scoped enum,
  3126. /// then this is true if the scoped enum was declared using the class
  3127. /// tag, false if it was declared with the struct tag. No meaning is
  3128. /// associated if this tag declaration is not a scoped enum.
  3129. void setScopedUsingClassTag(bool ScopedUCT = true) {
  3130. EnumDeclBits.IsScopedUsingClassTag = ScopedUCT;
  3131. }
  3132. /// True if this is an Objective-C, C++11, or
  3133. /// Microsoft-style enumeration with a fixed underlying type.
  3134. void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; }
  3135. private:
  3136. /// True if a valid hash is stored in ODRHash.
  3137. bool hasODRHash() const { return EnumDeclBits.HasODRHash; }
  3138. void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; }
  3139. public:
  3140. friend class ASTDeclReader;
  3141. EnumDecl *getCanonicalDecl() override {
  3142. return cast<EnumDecl>(TagDecl::getCanonicalDecl());
  3143. }
  3144. const EnumDecl *getCanonicalDecl() const {
  3145. return const_cast<EnumDecl*>(this)->getCanonicalDecl();
  3146. }
  3147. EnumDecl *getPreviousDecl() {
  3148. return cast_or_null<EnumDecl>(
  3149. static_cast<TagDecl *>(this)->getPreviousDecl());
  3150. }
  3151. const EnumDecl *getPreviousDecl() const {
  3152. return const_cast<EnumDecl*>(this)->getPreviousDecl();
  3153. }
  3154. EnumDecl *getMostRecentDecl() {
  3155. return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
  3156. }
  3157. const EnumDecl *getMostRecentDecl() const {
  3158. return const_cast<EnumDecl*>(this)->getMostRecentDecl();
  3159. }
  3160. EnumDecl *getDefinition() const {
  3161. return cast_or_null<EnumDecl>(TagDecl::getDefinition());
  3162. }
  3163. static EnumDecl *Create(ASTContext &C, DeclContext *DC,
  3164. SourceLocation StartLoc, SourceLocation IdLoc,
  3165. IdentifierInfo *Id, EnumDecl *PrevDecl,
  3166. bool IsScoped, bool IsScopedUsingClassTag,
  3167. bool IsFixed);
  3168. static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  3169. /// Overrides to provide correct range when there's an enum-base specifier
  3170. /// with forward declarations.
  3171. SourceRange getSourceRange() const override LLVM_READONLY;
  3172. /// When created, the EnumDecl corresponds to a
  3173. /// forward-declared enum. This method is used to mark the
  3174. /// declaration as being defined; its enumerators have already been
  3175. /// added (via DeclContext::addDecl). NewType is the new underlying
  3176. /// type of the enumeration type.
  3177. void completeDefinition(QualType NewType,
  3178. QualType PromotionType,
  3179. unsigned NumPositiveBits,
  3180. unsigned NumNegativeBits);
  3181. // Iterates through the enumerators of this enumeration.
  3182. using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
  3183. using enumerator_range =
  3184. llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
  3185. enumerator_range enumerators() const {
  3186. return enumerator_range(enumerator_begin(), enumerator_end());
  3187. }
  3188. enumerator_iterator enumerator_begin() const {
  3189. const EnumDecl *E = getDefinition();
  3190. if (!E)
  3191. E = this;
  3192. return enumerator_iterator(E->decls_begin());
  3193. }
  3194. enumerator_iterator enumerator_end() const {
  3195. const EnumDecl *E = getDefinition();
  3196. if (!E)
  3197. E = this;
  3198. return enumerator_iterator(E->decls_end());
  3199. }
  3200. /// Return the integer type that enumerators should promote to.
  3201. QualType getPromotionType() const { return PromotionType; }
  3202. /// Set the promotion type.
  3203. void setPromotionType(QualType T) { PromotionType = T; }
  3204. /// Return the integer type this enum decl corresponds to.
  3205. /// This returns a null QualType for an enum forward definition with no fixed
  3206. /// underlying type.
  3207. QualType getIntegerType() const {
  3208. if (!IntegerType)
  3209. return QualType();
  3210. if (const Type *T = IntegerType.dyn_cast<const Type*>())
  3211. return QualType(T, 0);
  3212. return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
  3213. }
  3214. /// Set the underlying integer type.
  3215. void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
  3216. /// Set the underlying integer type source info.
  3217. void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
  3218. /// Return the type source info for the underlying integer type,
  3219. /// if no type source info exists, return 0.
  3220. TypeSourceInfo *getIntegerTypeSourceInfo() const {
  3221. return IntegerType.dyn_cast<TypeSourceInfo*>();
  3222. }
  3223. /// Retrieve the source range that covers the underlying type if
  3224. /// specified.
  3225. SourceRange getIntegerTypeRange() const LLVM_READONLY;
  3226. /// Returns the width in bits required to store all the
  3227. /// non-negative enumerators of this enum.
  3228. unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; }
  3229. /// Returns the width in bits required to store all the
  3230. /// negative enumerators of this enum. These widths include
  3231. /// the rightmost leading 1; that is:
  3232. ///
  3233. /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
  3234. /// ------------------------ ------- -----------------
  3235. /// -1 1111111 1
  3236. /// -10 1110110 5
  3237. /// -101 1001011 8
  3238. unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; }
  3239. /// Calculates the [Min,Max) values the enum can store based on the
  3240. /// NumPositiveBits and NumNegativeBits. This matters for enums that do not
  3241. /// have a fixed underlying type.
  3242. void getValueRange(llvm::APInt &Max, llvm::APInt &Min) const;
  3243. /// Returns true if this is a C++11 scoped enumeration.
  3244. bool isScoped() const { return EnumDeclBits.IsScoped; }
  3245. /// Returns true if this is a C++11 scoped enumeration.
  3246. bool isScopedUsingClassTag() const {
  3247. return EnumDeclBits.IsScopedUsingClassTag;
  3248. }
  3249. /// Returns true if this is an Objective-C, C++11, or
  3250. /// Microsoft-style enumeration with a fixed underlying type.
  3251. bool isFixed() const { return EnumDeclBits.IsFixed; }
  3252. unsigned getODRHash();
  3253. /// Returns true if this can be considered a complete type.
  3254. bool isComplete() const {
  3255. // IntegerType is set for fixed type enums and non-fixed but implicitly
  3256. // int-sized Microsoft enums.
  3257. return isCompleteDefinition() || IntegerType;
  3258. }
  3259. /// Returns true if this enum is either annotated with
  3260. /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
  3261. bool isClosed() const;
  3262. /// Returns true if this enum is annotated with flag_enum and isn't annotated
  3263. /// with enum_extensibility(open).
  3264. bool isClosedFlag() const;
  3265. /// Returns true if this enum is annotated with neither flag_enum nor
  3266. /// enum_extensibility(open).
  3267. bool isClosedNonFlag() const;
  3268. /// Retrieve the enum definition from which this enumeration could
  3269. /// be instantiated, if it is an instantiation (rather than a non-template).
  3270. EnumDecl *getTemplateInstantiationPattern() const;
  3271. /// Returns the enumeration (declared within the template)
  3272. /// from which this enumeration type was instantiated, or NULL if
  3273. /// this enumeration was not instantiated from any template.
  3274. EnumDecl *getInstantiatedFromMemberEnum() const;
  3275. /// If this enumeration is a member of a specialization of a
  3276. /// templated class, determine what kind of template specialization
  3277. /// or instantiation this is.
  3278. TemplateSpecializationKind getTemplateSpecializationKind() const;
  3279. /// For an enumeration member that was instantiated from a member
  3280. /// enumeration of a templated class, set the template specialiation kind.
  3281. void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  3282. SourceLocation PointOfInstantiation = SourceLocation());
  3283. /// If this enumeration is an instantiation of a member enumeration of
  3284. /// a class template specialization, retrieves the member specialization
  3285. /// information.
  3286. MemberSpecializationInfo *getMemberSpecializationInfo() const {
  3287. return SpecializationInfo;
  3288. }
  3289. /// Specify that this enumeration is an instantiation of the
  3290. /// member enumeration ED.
  3291. void setInstantiationOfMemberEnum(EnumDecl *ED,
  3292. TemplateSpecializationKind TSK) {
  3293. setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
  3294. }
  3295. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3296. static bool classofKind(Kind K) { return K == Enum; }
  3297. };
  3298. /// Represents a struct/union/class. For example:
  3299. /// struct X; // Forward declaration, no "body".
  3300. /// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
  3301. /// This decl will be marked invalid if *any* members are invalid.
  3302. class RecordDecl : public TagDecl {
  3303. // This class stores some data in DeclContext::RecordDeclBits
  3304. // to save some space. Use the provided accessors to access it.
  3305. public:
  3306. friend class DeclContext;
  3307. friend class ASTDeclReader;
  3308. /// Enum that represents the different ways arguments are passed to and
  3309. /// returned from function calls. This takes into account the target-specific
  3310. /// and version-specific rules along with the rules determined by the
  3311. /// language.
  3312. enum ArgPassingKind : unsigned {
  3313. /// The argument of this type can be passed directly in registers.
  3314. APK_CanPassInRegs,
  3315. /// The argument of this type cannot be passed directly in registers.
  3316. /// Records containing this type as a subobject are not forced to be passed
  3317. /// indirectly. This value is used only in C++. This value is required by
  3318. /// C++ because, in uncommon situations, it is possible for a class to have
  3319. /// only trivial copy/move constructors even when one of its subobjects has
  3320. /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
  3321. /// constructor in the derived class is deleted).
  3322. APK_CannotPassInRegs,
  3323. /// The argument of this type cannot be passed directly in registers.
  3324. /// Records containing this type as a subobject are forced to be passed
  3325. /// indirectly.
  3326. APK_CanNeverPassInRegs
  3327. };
  3328. protected:
  3329. RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
  3330. SourceLocation StartLoc, SourceLocation IdLoc,
  3331. IdentifierInfo *Id, RecordDecl *PrevDecl);
  3332. public:
  3333. static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
  3334. SourceLocation StartLoc, SourceLocation IdLoc,
  3335. IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
  3336. static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
  3337. RecordDecl *getPreviousDecl() {
  3338. return cast_or_null<RecordDecl>(
  3339. static_cast<TagDecl *>(this)->getPreviousDecl());
  3340. }
  3341. const RecordDecl *getPreviousDecl() const {
  3342. return const_cast<RecordDecl*>(this)->getPreviousDecl();
  3343. }
  3344. RecordDecl *getMostRecentDecl() {
  3345. return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
  3346. }
  3347. const RecordDecl *getMostRecentDecl() const {
  3348. return const_cast<RecordDecl*>(this)->getMostRecentDecl();
  3349. }
  3350. bool hasFlexibleArrayMember() const {
  3351. return RecordDeclBits.HasFlexibleArrayMember;
  3352. }
  3353. void setHasFlexibleArrayMember(bool V) {
  3354. RecordDeclBits.HasFlexibleArrayMember = V;
  3355. }
  3356. /// Whether this is an anonymous struct or union. To be an anonymous
  3357. /// struct or union, it must have been declared without a name and
  3358. /// there must be no objects of this type declared, e.g.,
  3359. /// @code
  3360. /// union { int i; float f; };
  3361. /// @endcode
  3362. /// is an anonymous union but neither of the following are:
  3363. /// @code
  3364. /// union X { int i; float f; };
  3365. /// union { int i; float f; } obj;
  3366. /// @endcode
  3367. bool isAnonymousStructOrUnion() const {
  3368. return RecordDeclBits.AnonymousStructOrUnion;
  3369. }
  3370. void setAnonymousStructOrUnion(bool Anon) {
  3371. RecordDeclBits.AnonymousStructOrUnion = Anon;
  3372. }
  3373. bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; }
  3374. void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; }
  3375. bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; }
  3376. void setHasVolatileMember(bool val) {
  3377. RecordDeclBits.HasVolatileMember = val;
  3378. }
  3379. bool hasLoadedFieldsFromExternalStorage() const {
  3380. return RecordDeclBits.LoadedFieldsFromExternalStorage;
  3381. }
  3382. void setHasLoadedFieldsFromExternalStorage(bool val) const {
  3383. RecordDeclBits.LoadedFieldsFromExternalStorage = val;
  3384. }
  3385. /// Functions to query basic properties of non-trivial C structs.
  3386. bool isNonTrivialToPrimitiveDefaultInitialize() const {
  3387. return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize;
  3388. }
  3389. void setNonTrivialToPrimitiveDefaultInitialize(bool V) {
  3390. RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V;
  3391. }
  3392. bool isNonTrivialToPrimitiveCopy() const {
  3393. return RecordDeclBits.NonTrivialToPrimitiveCopy;
  3394. }
  3395. void setNonTrivialToPrimitiveCopy(bool V) {
  3396. RecordDeclBits.NonTrivialToPrimitiveCopy = V;
  3397. }
  3398. bool isNonTrivialToPrimitiveDestroy() const {
  3399. return RecordDeclBits.NonTrivialToPrimitiveDestroy;
  3400. }
  3401. void setNonTrivialToPrimitiveDestroy(bool V) {
  3402. RecordDeclBits.NonTrivialToPrimitiveDestroy = V;
  3403. }
  3404. bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
  3405. return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion;
  3406. }
  3407. void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V) {
  3408. RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V;
  3409. }
  3410. bool hasNonTrivialToPrimitiveDestructCUnion() const {
  3411. return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion;
  3412. }
  3413. void setHasNonTrivialToPrimitiveDestructCUnion(bool V) {
  3414. RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V;
  3415. }
  3416. bool hasNonTrivialToPrimitiveCopyCUnion() const {
  3417. return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion;
  3418. }
  3419. void setHasNonTrivialToPrimitiveCopyCUnion(bool V) {
  3420. RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V;
  3421. }
  3422. /// Determine whether this class can be passed in registers. In C++ mode,
  3423. /// it must have at least one trivial, non-deleted copy or move constructor.
  3424. /// FIXME: This should be set as part of completeDefinition.
  3425. bool canPassInRegisters() const {
  3426. return getArgPassingRestrictions() == APK_CanPassInRegs;
  3427. }
  3428. ArgPassingKind getArgPassingRestrictions() const {
  3429. return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions);
  3430. }
  3431. void setArgPassingRestrictions(ArgPassingKind Kind) {
  3432. RecordDeclBits.ArgPassingRestrictions = Kind;
  3433. }
  3434. bool isParamDestroyedInCallee() const {
  3435. return RecordDeclBits.ParamDestroyedInCallee;
  3436. }
  3437. void setParamDestroyedInCallee(bool V) {
  3438. RecordDeclBits.ParamDestroyedInCallee = V;
  3439. }
  3440. bool isRandomized() const { return RecordDeclBits.IsRandomized; }
  3441. void setIsRandomized(bool V) { RecordDeclBits.IsRandomized = V; }
  3442. void reorderDecls(const SmallVectorImpl<Decl *> &Decls);
  3443. /// Determines whether this declaration represents the
  3444. /// injected class name.
  3445. ///
  3446. /// The injected class name in C++ is the name of the class that
  3447. /// appears inside the class itself. For example:
  3448. ///
  3449. /// \code
  3450. /// struct C {
  3451. /// // C is implicitly declared here as a synonym for the class name.
  3452. /// };
  3453. ///
  3454. /// C::C c; // same as "C c;"
  3455. /// \endcode
  3456. bool isInjectedClassName() const;
  3457. /// Determine whether this record is a class describing a lambda
  3458. /// function object.
  3459. bool isLambda() const;
  3460. /// Determine whether this record is a record for captured variables in
  3461. /// CapturedStmt construct.
  3462. bool isCapturedRecord() const;
  3463. /// Mark the record as a record for captured variables in CapturedStmt
  3464. /// construct.
  3465. void setCapturedRecord();
  3466. /// Returns the RecordDecl that actually defines
  3467. /// this struct/union/class. When determining whether or not a
  3468. /// struct/union/class is completely defined, one should use this
  3469. /// method as opposed to 'isCompleteDefinition'.
  3470. /// 'isCompleteDefinition' indicates whether or not a specific
  3471. /// RecordDecl is a completed definition, not whether or not the
  3472. /// record type is defined. This method returns NULL if there is
  3473. /// no RecordDecl that defines the struct/union/tag.
  3474. RecordDecl *getDefinition() const {
  3475. return cast_or_null<RecordDecl>(TagDecl::getDefinition());
  3476. }
  3477. /// Returns whether this record is a union, or contains (at any nesting level)
  3478. /// a union member. This is used by CMSE to warn about possible information
  3479. /// leaks.
  3480. bool isOrContainsUnion() const;
  3481. // Iterator access to field members. The field iterator only visits
  3482. // the non-static data members of this class, ignoring any static
  3483. // data members, functions, constructors, destructors, etc.
  3484. using field_iterator = specific_decl_iterator<FieldDecl>;
  3485. using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
  3486. field_range fields() const { return field_range(field_begin(), field_end()); }
  3487. field_iterator field_begin() const;
  3488. field_iterator field_end() const {
  3489. return field_iterator(decl_iterator());
  3490. }
  3491. // Whether there are any fields (non-static data members) in this record.
  3492. bool field_empty() const {
  3493. return field_begin() == field_end();
  3494. }
  3495. /// Note that the definition of this type is now complete.
  3496. virtual void completeDefinition();
  3497. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3498. static bool classofKind(Kind K) {
  3499. return K >= firstRecord && K <= lastRecord;
  3500. }
  3501. /// Get whether or not this is an ms_struct which can
  3502. /// be turned on with an attribute, pragma, or -mms-bitfields
  3503. /// commandline option.
  3504. bool isMsStruct(const ASTContext &C) const;
  3505. /// Whether we are allowed to insert extra padding between fields.
  3506. /// These padding are added to help AddressSanitizer detect
  3507. /// intra-object-overflow bugs.
  3508. bool mayInsertExtraPadding(bool EmitRemark = false) const;
  3509. /// Finds the first data member which has a name.
  3510. /// nullptr is returned if no named data member exists.
  3511. const FieldDecl *findFirstNamedDataMember() const;
  3512. /// Get precomputed ODRHash or add a new one.
  3513. unsigned getODRHash();
  3514. private:
  3515. /// Deserialize just the fields.
  3516. void LoadFieldsFromExternalStorage() const;
  3517. /// True if a valid hash is stored in ODRHash.
  3518. bool hasODRHash() const { return RecordDeclBits.ODRHash; }
  3519. void setODRHash(unsigned Hash) { RecordDeclBits.ODRHash = Hash; }
  3520. };
  3521. class FileScopeAsmDecl : public Decl {
  3522. StringLiteral *AsmString;
  3523. SourceLocation RParenLoc;
  3524. FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
  3525. SourceLocation StartL, SourceLocation EndL)
  3526. : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
  3527. virtual void anchor();
  3528. public:
  3529. static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
  3530. StringLiteral *Str, SourceLocation AsmLoc,
  3531. SourceLocation RParenLoc);
  3532. static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  3533. SourceLocation getAsmLoc() const { return getLocation(); }
  3534. SourceLocation getRParenLoc() const { return RParenLoc; }
  3535. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  3536. SourceRange getSourceRange() const override LLVM_READONLY {
  3537. return SourceRange(getAsmLoc(), getRParenLoc());
  3538. }
  3539. const StringLiteral *getAsmString() const { return AsmString; }
  3540. StringLiteral *getAsmString() { return AsmString; }
  3541. void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
  3542. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3543. static bool classofKind(Kind K) { return K == FileScopeAsm; }
  3544. };
  3545. /// A declaration that models statements at global scope. This declaration
  3546. /// supports incremental and interactive C/C++.
  3547. ///
  3548. /// \note This is used in libInterpreter, clang -cc1 -fincremental-extensions
  3549. /// and in tools such as clang-repl.
  3550. class TopLevelStmtDecl : public Decl {
  3551. friend class ASTDeclReader;
  3552. friend class ASTDeclWriter;
  3553. Stmt *Statement = nullptr;
  3554. TopLevelStmtDecl(DeclContext *DC, SourceLocation L, Stmt *S)
  3555. : Decl(TopLevelStmt, DC, L), Statement(S) {}
  3556. virtual void anchor();
  3557. public:
  3558. static TopLevelStmtDecl *Create(ASTContext &C, Stmt *Statement);
  3559. static TopLevelStmtDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  3560. SourceRange getSourceRange() const override LLVM_READONLY;
  3561. Stmt *getStmt() { return Statement; }
  3562. const Stmt *getStmt() const { return Statement; }
  3563. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3564. static bool classofKind(Kind K) { return K == TopLevelStmt; }
  3565. };
  3566. /// Represents a block literal declaration, which is like an
  3567. /// unnamed FunctionDecl. For example:
  3568. /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
  3569. class BlockDecl : public Decl, public DeclContext {
  3570. // This class stores some data in DeclContext::BlockDeclBits
  3571. // to save some space. Use the provided accessors to access it.
  3572. public:
  3573. /// A class which contains all the information about a particular
  3574. /// captured value.
  3575. class Capture {
  3576. enum {
  3577. flag_isByRef = 0x1,
  3578. flag_isNested = 0x2
  3579. };
  3580. /// The variable being captured.
  3581. llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
  3582. /// The copy expression, expressed in terms of a DeclRef (or
  3583. /// BlockDeclRef) to the captured variable. Only required if the
  3584. /// variable has a C++ class type.
  3585. Expr *CopyExpr;
  3586. public:
  3587. Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
  3588. : VariableAndFlags(variable,
  3589. (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
  3590. CopyExpr(copy) {}
  3591. /// The variable being captured.
  3592. VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
  3593. /// Whether this is a "by ref" capture, i.e. a capture of a __block
  3594. /// variable.
  3595. bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
  3596. bool isEscapingByref() const {
  3597. return getVariable()->isEscapingByref();
  3598. }
  3599. bool isNonEscapingByref() const {
  3600. return getVariable()->isNonEscapingByref();
  3601. }
  3602. /// Whether this is a nested capture, i.e. the variable captured
  3603. /// is not from outside the immediately enclosing function/block.
  3604. bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
  3605. bool hasCopyExpr() const { return CopyExpr != nullptr; }
  3606. Expr *getCopyExpr() const { return CopyExpr; }
  3607. void setCopyExpr(Expr *e) { CopyExpr = e; }
  3608. };
  3609. private:
  3610. /// A new[]'d array of pointers to ParmVarDecls for the formal
  3611. /// parameters of this function. This is null if a prototype or if there are
  3612. /// no formals.
  3613. ParmVarDecl **ParamInfo = nullptr;
  3614. unsigned NumParams = 0;
  3615. Stmt *Body = nullptr;
  3616. TypeSourceInfo *SignatureAsWritten = nullptr;
  3617. const Capture *Captures = nullptr;
  3618. unsigned NumCaptures = 0;
  3619. unsigned ManglingNumber = 0;
  3620. Decl *ManglingContextDecl = nullptr;
  3621. protected:
  3622. BlockDecl(DeclContext *DC, SourceLocation CaretLoc);
  3623. public:
  3624. static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
  3625. static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  3626. SourceLocation getCaretLocation() const { return getLocation(); }
  3627. bool isVariadic() const { return BlockDeclBits.IsVariadic; }
  3628. void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; }
  3629. CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
  3630. Stmt *getBody() const override { return (Stmt*) Body; }
  3631. void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
  3632. void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
  3633. TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
  3634. // ArrayRef access to formal parameters.
  3635. ArrayRef<ParmVarDecl *> parameters() const {
  3636. return {ParamInfo, getNumParams()};
  3637. }
  3638. MutableArrayRef<ParmVarDecl *> parameters() {
  3639. return {ParamInfo, getNumParams()};
  3640. }
  3641. // Iterator access to formal parameters.
  3642. using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
  3643. using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
  3644. bool param_empty() const { return parameters().empty(); }
  3645. param_iterator param_begin() { return parameters().begin(); }
  3646. param_iterator param_end() { return parameters().end(); }
  3647. param_const_iterator param_begin() const { return parameters().begin(); }
  3648. param_const_iterator param_end() const { return parameters().end(); }
  3649. size_t param_size() const { return parameters().size(); }
  3650. unsigned getNumParams() const { return NumParams; }
  3651. const ParmVarDecl *getParamDecl(unsigned i) const {
  3652. assert(i < getNumParams() && "Illegal param #");
  3653. return ParamInfo[i];
  3654. }
  3655. ParmVarDecl *getParamDecl(unsigned i) {
  3656. assert(i < getNumParams() && "Illegal param #");
  3657. return ParamInfo[i];
  3658. }
  3659. void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
  3660. /// True if this block (or its nested blocks) captures
  3661. /// anything of local storage from its enclosing scopes.
  3662. bool hasCaptures() const { return NumCaptures || capturesCXXThis(); }
  3663. /// Returns the number of captured variables.
  3664. /// Does not include an entry for 'this'.
  3665. unsigned getNumCaptures() const { return NumCaptures; }
  3666. using capture_const_iterator = ArrayRef<Capture>::const_iterator;
  3667. ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
  3668. capture_const_iterator capture_begin() const { return captures().begin(); }
  3669. capture_const_iterator capture_end() const { return captures().end(); }
  3670. bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; }
  3671. void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; }
  3672. bool blockMissingReturnType() const {
  3673. return BlockDeclBits.BlockMissingReturnType;
  3674. }
  3675. void setBlockMissingReturnType(bool val = true) {
  3676. BlockDeclBits.BlockMissingReturnType = val;
  3677. }
  3678. bool isConversionFromLambda() const {
  3679. return BlockDeclBits.IsConversionFromLambda;
  3680. }
  3681. void setIsConversionFromLambda(bool val = true) {
  3682. BlockDeclBits.IsConversionFromLambda = val;
  3683. }
  3684. bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; }
  3685. void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; }
  3686. bool canAvoidCopyToHeap() const {
  3687. return BlockDeclBits.CanAvoidCopyToHeap;
  3688. }
  3689. void setCanAvoidCopyToHeap(bool B = true) {
  3690. BlockDeclBits.CanAvoidCopyToHeap = B;
  3691. }
  3692. bool capturesVariable(const VarDecl *var) const;
  3693. void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
  3694. bool CapturesCXXThis);
  3695. unsigned getBlockManglingNumber() const { return ManglingNumber; }
  3696. Decl *getBlockManglingContextDecl() const { return ManglingContextDecl; }
  3697. void setBlockMangling(unsigned Number, Decl *Ctx) {
  3698. ManglingNumber = Number;
  3699. ManglingContextDecl = Ctx;
  3700. }
  3701. SourceRange getSourceRange() const override LLVM_READONLY;
  3702. // Implement isa/cast/dyncast/etc.
  3703. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3704. static bool classofKind(Kind K) { return K == Block; }
  3705. static DeclContext *castToDeclContext(const BlockDecl *D) {
  3706. return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
  3707. }
  3708. static BlockDecl *castFromDeclContext(const DeclContext *DC) {
  3709. return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
  3710. }
  3711. };
  3712. /// Represents the body of a CapturedStmt, and serves as its DeclContext.
  3713. class CapturedDecl final
  3714. : public Decl,
  3715. public DeclContext,
  3716. private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
  3717. protected:
  3718. size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
  3719. return NumParams;
  3720. }
  3721. private:
  3722. /// The number of parameters to the outlined function.
  3723. unsigned NumParams;
  3724. /// The position of context parameter in list of parameters.
  3725. unsigned ContextParam;
  3726. /// The body of the outlined function.
  3727. llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
  3728. explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
  3729. ImplicitParamDecl *const *getParams() const {
  3730. return getTrailingObjects<ImplicitParamDecl *>();
  3731. }
  3732. ImplicitParamDecl **getParams() {
  3733. return getTrailingObjects<ImplicitParamDecl *>();
  3734. }
  3735. public:
  3736. friend class ASTDeclReader;
  3737. friend class ASTDeclWriter;
  3738. friend TrailingObjects;
  3739. static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
  3740. unsigned NumParams);
  3741. static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
  3742. unsigned NumParams);
  3743. Stmt *getBody() const override;
  3744. void setBody(Stmt *B);
  3745. bool isNothrow() const;
  3746. void setNothrow(bool Nothrow = true);
  3747. unsigned getNumParams() const { return NumParams; }
  3748. ImplicitParamDecl *getParam(unsigned i) const {
  3749. assert(i < NumParams);
  3750. return getParams()[i];
  3751. }
  3752. void setParam(unsigned i, ImplicitParamDecl *P) {
  3753. assert(i < NumParams);
  3754. getParams()[i] = P;
  3755. }
  3756. // ArrayRef interface to parameters.
  3757. ArrayRef<ImplicitParamDecl *> parameters() const {
  3758. return {getParams(), getNumParams()};
  3759. }
  3760. MutableArrayRef<ImplicitParamDecl *> parameters() {
  3761. return {getParams(), getNumParams()};
  3762. }
  3763. /// Retrieve the parameter containing captured variables.
  3764. ImplicitParamDecl *getContextParam() const {
  3765. assert(ContextParam < NumParams);
  3766. return getParam(ContextParam);
  3767. }
  3768. void setContextParam(unsigned i, ImplicitParamDecl *P) {
  3769. assert(i < NumParams);
  3770. ContextParam = i;
  3771. setParam(i, P);
  3772. }
  3773. unsigned getContextParamPosition() const { return ContextParam; }
  3774. using param_iterator = ImplicitParamDecl *const *;
  3775. using param_range = llvm::iterator_range<param_iterator>;
  3776. /// Retrieve an iterator pointing to the first parameter decl.
  3777. param_iterator param_begin() const { return getParams(); }
  3778. /// Retrieve an iterator one past the last parameter decl.
  3779. param_iterator param_end() const { return getParams() + NumParams; }
  3780. // Implement isa/cast/dyncast/etc.
  3781. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3782. static bool classofKind(Kind K) { return K == Captured; }
  3783. static DeclContext *castToDeclContext(const CapturedDecl *D) {
  3784. return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
  3785. }
  3786. static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
  3787. return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
  3788. }
  3789. };
  3790. /// Describes a module import declaration, which makes the contents
  3791. /// of the named module visible in the current translation unit.
  3792. ///
  3793. /// An import declaration imports the named module (or submodule). For example:
  3794. /// \code
  3795. /// @import std.vector;
  3796. /// \endcode
  3797. ///
  3798. /// A C++20 module import declaration imports the named module or partition.
  3799. /// Periods are permitted in C++20 module names, but have no semantic meaning.
  3800. /// For example:
  3801. /// \code
  3802. /// import NamedModule;
  3803. /// import :SomePartition; // Must be a partition of the current module.
  3804. /// import Names.Like.this; // Allowed.
  3805. /// import :and.Also.Partition.names;
  3806. /// \endcode
  3807. ///
  3808. /// Import declarations can also be implicitly generated from
  3809. /// \#include/\#import directives.
  3810. class ImportDecl final : public Decl,
  3811. llvm::TrailingObjects<ImportDecl, SourceLocation> {
  3812. friend class ASTContext;
  3813. friend class ASTDeclReader;
  3814. friend class ASTReader;
  3815. friend TrailingObjects;
  3816. /// The imported module.
  3817. Module *ImportedModule = nullptr;
  3818. /// The next import in the list of imports local to the translation
  3819. /// unit being parsed (not loaded from an AST file).
  3820. ///
  3821. /// Includes a bit that indicates whether we have source-location information
  3822. /// for each identifier in the module name.
  3823. ///
  3824. /// When the bit is false, we only have a single source location for the
  3825. /// end of the import declaration.
  3826. llvm::PointerIntPair<ImportDecl *, 1, bool> NextLocalImportAndComplete;
  3827. ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
  3828. ArrayRef<SourceLocation> IdentifierLocs);
  3829. ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
  3830. SourceLocation EndLoc);
  3831. ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
  3832. bool isImportComplete() const { return NextLocalImportAndComplete.getInt(); }
  3833. void setImportComplete(bool C) { NextLocalImportAndComplete.setInt(C); }
  3834. /// The next import in the list of imports local to the translation
  3835. /// unit being parsed (not loaded from an AST file).
  3836. ImportDecl *getNextLocalImport() const {
  3837. return NextLocalImportAndComplete.getPointer();
  3838. }
  3839. void setNextLocalImport(ImportDecl *Import) {
  3840. NextLocalImportAndComplete.setPointer(Import);
  3841. }
  3842. public:
  3843. /// Create a new module import declaration.
  3844. static ImportDecl *Create(ASTContext &C, DeclContext *DC,
  3845. SourceLocation StartLoc, Module *Imported,
  3846. ArrayRef<SourceLocation> IdentifierLocs);
  3847. /// Create a new module import declaration for an implicitly-generated
  3848. /// import.
  3849. static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
  3850. SourceLocation StartLoc, Module *Imported,
  3851. SourceLocation EndLoc);
  3852. /// Create a new, deserialized module import declaration.
  3853. static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
  3854. unsigned NumLocations);
  3855. /// Retrieve the module that was imported by the import declaration.
  3856. Module *getImportedModule() const { return ImportedModule; }
  3857. /// Retrieves the locations of each of the identifiers that make up
  3858. /// the complete module name in the import declaration.
  3859. ///
  3860. /// This will return an empty array if the locations of the individual
  3861. /// identifiers aren't available.
  3862. ArrayRef<SourceLocation> getIdentifierLocs() const;
  3863. SourceRange getSourceRange() const override LLVM_READONLY;
  3864. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3865. static bool classofKind(Kind K) { return K == Import; }
  3866. };
  3867. /// Represents a C++ Modules TS module export declaration.
  3868. ///
  3869. /// For example:
  3870. /// \code
  3871. /// export void foo();
  3872. /// \endcode
  3873. class ExportDecl final : public Decl, public DeclContext {
  3874. virtual void anchor();
  3875. private:
  3876. friend class ASTDeclReader;
  3877. /// The source location for the right brace (if valid).
  3878. SourceLocation RBraceLoc;
  3879. ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
  3880. : Decl(Export, DC, ExportLoc), DeclContext(Export),
  3881. RBraceLoc(SourceLocation()) {}
  3882. public:
  3883. static ExportDecl *Create(ASTContext &C, DeclContext *DC,
  3884. SourceLocation ExportLoc);
  3885. static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  3886. SourceLocation getExportLoc() const { return getLocation(); }
  3887. SourceLocation getRBraceLoc() const { return RBraceLoc; }
  3888. void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
  3889. bool hasBraces() const { return RBraceLoc.isValid(); }
  3890. SourceLocation getEndLoc() const LLVM_READONLY {
  3891. if (hasBraces())
  3892. return RBraceLoc;
  3893. // No braces: get the end location of the (only) declaration in context
  3894. // (if present).
  3895. return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
  3896. }
  3897. SourceRange getSourceRange() const override LLVM_READONLY {
  3898. return SourceRange(getLocation(), getEndLoc());
  3899. }
  3900. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3901. static bool classofKind(Kind K) { return K == Export; }
  3902. static DeclContext *castToDeclContext(const ExportDecl *D) {
  3903. return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
  3904. }
  3905. static ExportDecl *castFromDeclContext(const DeclContext *DC) {
  3906. return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
  3907. }
  3908. };
  3909. /// Represents an empty-declaration.
  3910. class EmptyDecl : public Decl {
  3911. EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
  3912. virtual void anchor();
  3913. public:
  3914. static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
  3915. SourceLocation L);
  3916. static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  3917. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3918. static bool classofKind(Kind K) { return K == Empty; }
  3919. };
  3920. /// HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
  3921. class HLSLBufferDecl final : public NamedDecl, public DeclContext {
  3922. /// LBraceLoc - The ending location of the source range.
  3923. SourceLocation LBraceLoc;
  3924. /// RBraceLoc - The ending location of the source range.
  3925. SourceLocation RBraceLoc;
  3926. /// KwLoc - The location of the cbuffer or tbuffer keyword.
  3927. SourceLocation KwLoc;
  3928. /// IsCBuffer - Whether the buffer is a cbuffer (and not a tbuffer).
  3929. bool IsCBuffer;
  3930. HLSLBufferDecl(DeclContext *DC, bool CBuffer, SourceLocation KwLoc,
  3931. IdentifierInfo *ID, SourceLocation IDLoc,
  3932. SourceLocation LBrace);
  3933. public:
  3934. static HLSLBufferDecl *Create(ASTContext &C, DeclContext *LexicalParent,
  3935. bool CBuffer, SourceLocation KwLoc,
  3936. IdentifierInfo *ID, SourceLocation IDLoc,
  3937. SourceLocation LBrace);
  3938. static HLSLBufferDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  3939. SourceRange getSourceRange() const override LLVM_READONLY {
  3940. return SourceRange(getLocStart(), RBraceLoc);
  3941. }
  3942. SourceLocation getLocStart() const LLVM_READONLY { return KwLoc; }
  3943. SourceLocation getLBraceLoc() const { return LBraceLoc; }
  3944. SourceLocation getRBraceLoc() const { return RBraceLoc; }
  3945. void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
  3946. bool isCBuffer() const { return IsCBuffer; }
  3947. // Implement isa/cast/dyncast/etc.
  3948. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3949. static bool classofKind(Kind K) { return K == HLSLBuffer; }
  3950. static DeclContext *castToDeclContext(const HLSLBufferDecl *D) {
  3951. return static_cast<DeclContext *>(const_cast<HLSLBufferDecl *>(D));
  3952. }
  3953. static HLSLBufferDecl *castFromDeclContext(const DeclContext *DC) {
  3954. return static_cast<HLSLBufferDecl *>(const_cast<DeclContext *>(DC));
  3955. }
  3956. friend class ASTDeclReader;
  3957. friend class ASTDeclWriter;
  3958. };
  3959. /// Insertion operator for diagnostics. This allows sending NamedDecl's
  3960. /// into a diagnostic with <<.
  3961. inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
  3962. const NamedDecl *ND) {
  3963. PD.AddTaggedVal(reinterpret_cast<uint64_t>(ND),
  3964. DiagnosticsEngine::ak_nameddecl);
  3965. return PD;
  3966. }
  3967. template<typename decl_type>
  3968. void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
  3969. // Note: This routine is implemented here because we need both NamedDecl
  3970. // and Redeclarable to be defined.
  3971. assert(RedeclLink.isFirst() &&
  3972. "setPreviousDecl on a decl already in a redeclaration chain");
  3973. if (PrevDecl) {
  3974. // Point to previous. Make sure that this is actually the most recent
  3975. // redeclaration, or we can build invalid chains. If the most recent
  3976. // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
  3977. First = PrevDecl->getFirstDecl();
  3978. assert(First->RedeclLink.isFirst() && "Expected first");
  3979. decl_type *MostRecent = First->getNextRedeclaration();
  3980. RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
  3981. // If the declaration was previously visible, a redeclaration of it remains
  3982. // visible even if it wouldn't be visible by itself.
  3983. static_cast<decl_type*>(this)->IdentifierNamespace |=
  3984. MostRecent->getIdentifierNamespace() &
  3985. (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
  3986. } else {
  3987. // Make this first.
  3988. First = static_cast<decl_type*>(this);
  3989. }
  3990. // First one will point to this one as latest.
  3991. First->RedeclLink.setLatest(static_cast<decl_type*>(this));
  3992. assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
  3993. cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
  3994. }
  3995. // Inline function definitions.
  3996. /// Check if the given decl is complete.
  3997. ///
  3998. /// We use this function to break a cycle between the inline definitions in
  3999. /// Type.h and Decl.h.
  4000. inline bool IsEnumDeclComplete(EnumDecl *ED) {
  4001. return ED->isComplete();
  4002. }
  4003. /// Check if the given decl is scoped.
  4004. ///
  4005. /// We use this function to break a cycle between the inline definitions in
  4006. /// Type.h and Decl.h.
  4007. inline bool IsEnumDeclScoped(EnumDecl *ED) {
  4008. return ED->isScoped();
  4009. }
  4010. /// OpenMP variants are mangled early based on their OpenMP context selector.
  4011. /// The new name looks likes this:
  4012. /// <name> + OpenMPVariantManglingSeparatorStr + <mangled OpenMP context>
  4013. static constexpr StringRef getOpenMPVariantManglingSeparatorStr() {
  4014. return "$ompvariant";
  4015. }
  4016. } // namespace clang
  4017. #endif // LLVM_CLANG_AST_DECL_H
  4018. #ifdef __GNUC__
  4019. #pragma GCC diagnostic pop
  4020. #endif