Decl.cpp 174 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904
  1. //===- Decl.cpp - Declaration AST Node Implementation ---------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Decl subclasses.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/Decl.h"
  13. #include "Linkage.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTDiagnostic.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/ASTMutationListener.h"
  18. #include "clang/AST/CanonicalType.h"
  19. #include "clang/AST/DeclBase.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclOpenMP.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/DeclarationName.h"
  25. #include "clang/AST/Expr.h"
  26. #include "clang/AST/ExprCXX.h"
  27. #include "clang/AST/ExternalASTSource.h"
  28. #include "clang/AST/ODRHash.h"
  29. #include "clang/AST/PrettyDeclStackTrace.h"
  30. #include "clang/AST/PrettyPrinter.h"
  31. #include "clang/AST/Redeclarable.h"
  32. #include "clang/AST/Stmt.h"
  33. #include "clang/AST/TemplateBase.h"
  34. #include "clang/AST/Type.h"
  35. #include "clang/AST/TypeLoc.h"
  36. #include "clang/Basic/Builtins.h"
  37. #include "clang/Basic/IdentifierTable.h"
  38. #include "clang/Basic/LLVM.h"
  39. #include "clang/Basic/LangOptions.h"
  40. #include "clang/Basic/Linkage.h"
  41. #include "clang/Basic/Module.h"
  42. #include "clang/Basic/PartialDiagnostic.h"
  43. #include "clang/Basic/SanitizerBlacklist.h"
  44. #include "clang/Basic/Sanitizers.h"
  45. #include "clang/Basic/SourceLocation.h"
  46. #include "clang/Basic/SourceManager.h"
  47. #include "clang/Basic/Specifiers.h"
  48. #include "clang/Basic/TargetCXXABI.h"
  49. #include "clang/Basic/TargetInfo.h"
  50. #include "clang/Basic/Visibility.h"
  51. #include "llvm/ADT/APSInt.h"
  52. #include "llvm/ADT/ArrayRef.h"
  53. #include "llvm/ADT/None.h"
  54. #include "llvm/ADT/Optional.h"
  55. #include "llvm/ADT/STLExtras.h"
  56. #include "llvm/ADT/SmallVector.h"
  57. #include "llvm/ADT/StringSwitch.h"
  58. #include "llvm/ADT/StringRef.h"
  59. #include "llvm/ADT/Triple.h"
  60. #include "llvm/Support/Casting.h"
  61. #include "llvm/Support/ErrorHandling.h"
  62. #include "llvm/Support/raw_ostream.h"
  63. #include <algorithm>
  64. #include <cassert>
  65. #include <cstddef>
  66. #include <cstring>
  67. #include <memory>
  68. #include <string>
  69. #include <tuple>
  70. #include <type_traits>
  71. using namespace clang;
  72. Decl *clang::getPrimaryMergedDecl(Decl *D) {
  73. return D->getASTContext().getPrimaryMergedDecl(D);
  74. }
  75. void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
  76. SourceLocation Loc = this->Loc;
  77. if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
  78. if (Loc.isValid()) {
  79. Loc.print(OS, Context.getSourceManager());
  80. OS << ": ";
  81. }
  82. OS << Message;
  83. if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
  84. OS << " '";
  85. ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
  86. OS << "'";
  87. }
  88. OS << '\n';
  89. }
  90. // Defined here so that it can be inlined into its direct callers.
  91. bool Decl::isOutOfLine() const {
  92. return !getLexicalDeclContext()->Equals(getDeclContext());
  93. }
  94. TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
  95. : Decl(TranslationUnit, nullptr, SourceLocation()),
  96. DeclContext(TranslationUnit), Ctx(ctx) {}
  97. //===----------------------------------------------------------------------===//
  98. // NamedDecl Implementation
  99. //===----------------------------------------------------------------------===//
  100. // Visibility rules aren't rigorously externally specified, but here
  101. // are the basic principles behind what we implement:
  102. //
  103. // 1. An explicit visibility attribute is generally a direct expression
  104. // of the user's intent and should be honored. Only the innermost
  105. // visibility attribute applies. If no visibility attribute applies,
  106. // global visibility settings are considered.
  107. //
  108. // 2. There is one caveat to the above: on or in a template pattern,
  109. // an explicit visibility attribute is just a default rule, and
  110. // visibility can be decreased by the visibility of template
  111. // arguments. But this, too, has an exception: an attribute on an
  112. // explicit specialization or instantiation causes all the visibility
  113. // restrictions of the template arguments to be ignored.
  114. //
  115. // 3. A variable that does not otherwise have explicit visibility can
  116. // be restricted by the visibility of its type.
  117. //
  118. // 4. A visibility restriction is explicit if it comes from an
  119. // attribute (or something like it), not a global visibility setting.
  120. // When emitting a reference to an external symbol, visibility
  121. // restrictions are ignored unless they are explicit.
  122. //
  123. // 5. When computing the visibility of a non-type, including a
  124. // non-type member of a class, only non-type visibility restrictions
  125. // are considered: the 'visibility' attribute, global value-visibility
  126. // settings, and a few special cases like __private_extern.
  127. //
  128. // 6. When computing the visibility of a type, including a type member
  129. // of a class, only type visibility restrictions are considered:
  130. // the 'type_visibility' attribute and global type-visibility settings.
  131. // However, a 'visibility' attribute counts as a 'type_visibility'
  132. // attribute on any declaration that only has the former.
  133. //
  134. // The visibility of a "secondary" entity, like a template argument,
  135. // is computed using the kind of that entity, not the kind of the
  136. // primary entity for which we are computing visibility. For example,
  137. // the visibility of a specialization of either of these templates:
  138. // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
  139. // template <class T, bool (&compare)(T, X)> class matcher;
  140. // is restricted according to the type visibility of the argument 'T',
  141. // the type visibility of 'bool(&)(T,X)', and the value visibility of
  142. // the argument function 'compare'. That 'has_match' is a value
  143. // and 'matcher' is a type only matters when looking for attributes
  144. // and settings from the immediate context.
  145. /// Does this computation kind permit us to consider additional
  146. /// visibility settings from attributes and the like?
  147. static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
  148. return computation.IgnoreExplicitVisibility;
  149. }
  150. /// Given an LVComputationKind, return one of the same type/value sort
  151. /// that records that it already has explicit visibility.
  152. static LVComputationKind
  153. withExplicitVisibilityAlready(LVComputationKind Kind) {
  154. Kind.IgnoreExplicitVisibility = true;
  155. return Kind;
  156. }
  157. static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
  158. LVComputationKind kind) {
  159. assert(!kind.IgnoreExplicitVisibility &&
  160. "asking for explicit visibility when we shouldn't be");
  161. return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
  162. }
  163. /// Is the given declaration a "type" or a "value" for the purposes of
  164. /// visibility computation?
  165. static bool usesTypeVisibility(const NamedDecl *D) {
  166. return isa<TypeDecl>(D) ||
  167. isa<ClassTemplateDecl>(D) ||
  168. isa<ObjCInterfaceDecl>(D);
  169. }
  170. /// Does the given declaration have member specialization information,
  171. /// and if so, is it an explicit specialization?
  172. template <class T> static typename
  173. std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
  174. isExplicitMemberSpecialization(const T *D) {
  175. if (const MemberSpecializationInfo *member =
  176. D->getMemberSpecializationInfo()) {
  177. return member->isExplicitSpecialization();
  178. }
  179. return false;
  180. }
  181. /// For templates, this question is easier: a member template can't be
  182. /// explicitly instantiated, so there's a single bit indicating whether
  183. /// or not this is an explicit member specialization.
  184. static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
  185. return D->isMemberSpecialization();
  186. }
  187. /// Given a visibility attribute, return the explicit visibility
  188. /// associated with it.
  189. template <class T>
  190. static Visibility getVisibilityFromAttr(const T *attr) {
  191. switch (attr->getVisibility()) {
  192. case T::Default:
  193. return DefaultVisibility;
  194. case T::Hidden:
  195. return HiddenVisibility;
  196. case T::Protected:
  197. return ProtectedVisibility;
  198. }
  199. llvm_unreachable("bad visibility kind");
  200. }
  201. /// Return the explicit visibility of the given declaration.
  202. static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
  203. NamedDecl::ExplicitVisibilityKind kind) {
  204. // If we're ultimately computing the visibility of a type, look for
  205. // a 'type_visibility' attribute before looking for 'visibility'.
  206. if (kind == NamedDecl::VisibilityForType) {
  207. if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
  208. return getVisibilityFromAttr(A);
  209. }
  210. }
  211. // If this declaration has an explicit visibility attribute, use it.
  212. if (const auto *A = D->getAttr<VisibilityAttr>()) {
  213. return getVisibilityFromAttr(A);
  214. }
  215. return None;
  216. }
  217. LinkageInfo LinkageComputer::getLVForType(const Type &T,
  218. LVComputationKind computation) {
  219. if (computation.IgnoreAllVisibility)
  220. return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
  221. return getTypeLinkageAndVisibility(&T);
  222. }
  223. /// Get the most restrictive linkage for the types in the given
  224. /// template parameter list. For visibility purposes, template
  225. /// parameters are part of the signature of a template.
  226. LinkageInfo LinkageComputer::getLVForTemplateParameterList(
  227. const TemplateParameterList *Params, LVComputationKind computation) {
  228. LinkageInfo LV;
  229. for (const NamedDecl *P : *Params) {
  230. // Template type parameters are the most common and never
  231. // contribute to visibility, pack or not.
  232. if (isa<TemplateTypeParmDecl>(P))
  233. continue;
  234. // Non-type template parameters can be restricted by the value type, e.g.
  235. // template <enum X> class A { ... };
  236. // We have to be careful here, though, because we can be dealing with
  237. // dependent types.
  238. if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
  239. // Handle the non-pack case first.
  240. if (!NTTP->isExpandedParameterPack()) {
  241. if (!NTTP->getType()->isDependentType()) {
  242. LV.merge(getLVForType(*NTTP->getType(), computation));
  243. }
  244. continue;
  245. }
  246. // Look at all the types in an expanded pack.
  247. for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
  248. QualType type = NTTP->getExpansionType(i);
  249. if (!type->isDependentType())
  250. LV.merge(getTypeLinkageAndVisibility(type));
  251. }
  252. continue;
  253. }
  254. // Template template parameters can be restricted by their
  255. // template parameters, recursively.
  256. const auto *TTP = cast<TemplateTemplateParmDecl>(P);
  257. // Handle the non-pack case first.
  258. if (!TTP->isExpandedParameterPack()) {
  259. LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
  260. computation));
  261. continue;
  262. }
  263. // Look at all expansions in an expanded pack.
  264. for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
  265. i != n; ++i) {
  266. LV.merge(getLVForTemplateParameterList(
  267. TTP->getExpansionTemplateParameters(i), computation));
  268. }
  269. }
  270. return LV;
  271. }
  272. static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
  273. const Decl *Ret = nullptr;
  274. const DeclContext *DC = D->getDeclContext();
  275. while (DC->getDeclKind() != Decl::TranslationUnit) {
  276. if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
  277. Ret = cast<Decl>(DC);
  278. DC = DC->getParent();
  279. }
  280. return Ret;
  281. }
  282. /// Get the most restrictive linkage for the types and
  283. /// declarations in the given template argument list.
  284. ///
  285. /// Note that we don't take an LVComputationKind because we always
  286. /// want to honor the visibility of template arguments in the same way.
  287. LinkageInfo
  288. LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
  289. LVComputationKind computation) {
  290. LinkageInfo LV;
  291. for (const TemplateArgument &Arg : Args) {
  292. switch (Arg.getKind()) {
  293. case TemplateArgument::Null:
  294. case TemplateArgument::Integral:
  295. case TemplateArgument::Expression:
  296. continue;
  297. case TemplateArgument::Type:
  298. LV.merge(getLVForType(*Arg.getAsType(), computation));
  299. continue;
  300. case TemplateArgument::Declaration: {
  301. const NamedDecl *ND = Arg.getAsDecl();
  302. assert(!usesTypeVisibility(ND));
  303. LV.merge(getLVForDecl(ND, computation));
  304. continue;
  305. }
  306. case TemplateArgument::NullPtr:
  307. LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
  308. continue;
  309. case TemplateArgument::Template:
  310. case TemplateArgument::TemplateExpansion:
  311. if (TemplateDecl *Template =
  312. Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
  313. LV.merge(getLVForDecl(Template, computation));
  314. continue;
  315. case TemplateArgument::Pack:
  316. LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
  317. continue;
  318. }
  319. llvm_unreachable("bad template argument kind");
  320. }
  321. return LV;
  322. }
  323. LinkageInfo
  324. LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
  325. LVComputationKind computation) {
  326. return getLVForTemplateArgumentList(TArgs.asArray(), computation);
  327. }
  328. static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
  329. const FunctionTemplateSpecializationInfo *specInfo) {
  330. // Include visibility from the template parameters and arguments
  331. // only if this is not an explicit instantiation or specialization
  332. // with direct explicit visibility. (Implicit instantiations won't
  333. // have a direct attribute.)
  334. if (!specInfo->isExplicitInstantiationOrSpecialization())
  335. return true;
  336. return !fn->hasAttr<VisibilityAttr>();
  337. }
  338. /// Merge in template-related linkage and visibility for the given
  339. /// function template specialization.
  340. ///
  341. /// We don't need a computation kind here because we can assume
  342. /// LVForValue.
  343. ///
  344. /// \param[out] LV the computation to use for the parent
  345. void LinkageComputer::mergeTemplateLV(
  346. LinkageInfo &LV, const FunctionDecl *fn,
  347. const FunctionTemplateSpecializationInfo *specInfo,
  348. LVComputationKind computation) {
  349. bool considerVisibility =
  350. shouldConsiderTemplateVisibility(fn, specInfo);
  351. // Merge information from the template parameters.
  352. FunctionTemplateDecl *temp = specInfo->getTemplate();
  353. LinkageInfo tempLV =
  354. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  355. LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
  356. // Merge information from the template arguments.
  357. const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
  358. LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
  359. LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
  360. }
  361. /// Does the given declaration have a direct visibility attribute
  362. /// that would match the given rules?
  363. static bool hasDirectVisibilityAttribute(const NamedDecl *D,
  364. LVComputationKind computation) {
  365. if (computation.IgnoreAllVisibility)
  366. return false;
  367. return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
  368. D->hasAttr<VisibilityAttr>();
  369. }
  370. /// Should we consider visibility associated with the template
  371. /// arguments and parameters of the given class template specialization?
  372. static bool shouldConsiderTemplateVisibility(
  373. const ClassTemplateSpecializationDecl *spec,
  374. LVComputationKind computation) {
  375. // Include visibility from the template parameters and arguments
  376. // only if this is not an explicit instantiation or specialization
  377. // with direct explicit visibility (and note that implicit
  378. // instantiations won't have a direct attribute).
  379. //
  380. // Furthermore, we want to ignore template parameters and arguments
  381. // for an explicit specialization when computing the visibility of a
  382. // member thereof with explicit visibility.
  383. //
  384. // This is a bit complex; let's unpack it.
  385. //
  386. // An explicit class specialization is an independent, top-level
  387. // declaration. As such, if it or any of its members has an
  388. // explicit visibility attribute, that must directly express the
  389. // user's intent, and we should honor it. The same logic applies to
  390. // an explicit instantiation of a member of such a thing.
  391. // Fast path: if this is not an explicit instantiation or
  392. // specialization, we always want to consider template-related
  393. // visibility restrictions.
  394. if (!spec->isExplicitInstantiationOrSpecialization())
  395. return true;
  396. // This is the 'member thereof' check.
  397. if (spec->isExplicitSpecialization() &&
  398. hasExplicitVisibilityAlready(computation))
  399. return false;
  400. return !hasDirectVisibilityAttribute(spec, computation);
  401. }
  402. /// Merge in template-related linkage and visibility for the given
  403. /// class template specialization.
  404. void LinkageComputer::mergeTemplateLV(
  405. LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
  406. LVComputationKind computation) {
  407. bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
  408. // Merge information from the template parameters, but ignore
  409. // visibility if we're only considering template arguments.
  410. ClassTemplateDecl *temp = spec->getSpecializedTemplate();
  411. LinkageInfo tempLV =
  412. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  413. LV.mergeMaybeWithVisibility(tempLV,
  414. considerVisibility && !hasExplicitVisibilityAlready(computation));
  415. // Merge information from the template arguments. We ignore
  416. // template-argument visibility if we've got an explicit
  417. // instantiation with a visibility attribute.
  418. const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
  419. LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
  420. if (considerVisibility)
  421. LV.mergeVisibility(argsLV);
  422. LV.mergeExternalVisibility(argsLV);
  423. }
  424. /// Should we consider visibility associated with the template
  425. /// arguments and parameters of the given variable template
  426. /// specialization? As usual, follow class template specialization
  427. /// logic up to initialization.
  428. static bool shouldConsiderTemplateVisibility(
  429. const VarTemplateSpecializationDecl *spec,
  430. LVComputationKind computation) {
  431. // Include visibility from the template parameters and arguments
  432. // only if this is not an explicit instantiation or specialization
  433. // with direct explicit visibility (and note that implicit
  434. // instantiations won't have a direct attribute).
  435. if (!spec->isExplicitInstantiationOrSpecialization())
  436. return true;
  437. // An explicit variable specialization is an independent, top-level
  438. // declaration. As such, if it has an explicit visibility attribute,
  439. // that must directly express the user's intent, and we should honor
  440. // it.
  441. if (spec->isExplicitSpecialization() &&
  442. hasExplicitVisibilityAlready(computation))
  443. return false;
  444. return !hasDirectVisibilityAttribute(spec, computation);
  445. }
  446. /// Merge in template-related linkage and visibility for the given
  447. /// variable template specialization. As usual, follow class template
  448. /// specialization logic up to initialization.
  449. void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
  450. const VarTemplateSpecializationDecl *spec,
  451. LVComputationKind computation) {
  452. bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
  453. // Merge information from the template parameters, but ignore
  454. // visibility if we're only considering template arguments.
  455. VarTemplateDecl *temp = spec->getSpecializedTemplate();
  456. LinkageInfo tempLV =
  457. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  458. LV.mergeMaybeWithVisibility(tempLV,
  459. considerVisibility && !hasExplicitVisibilityAlready(computation));
  460. // Merge information from the template arguments. We ignore
  461. // template-argument visibility if we've got an explicit
  462. // instantiation with a visibility attribute.
  463. const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
  464. LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
  465. if (considerVisibility)
  466. LV.mergeVisibility(argsLV);
  467. LV.mergeExternalVisibility(argsLV);
  468. }
  469. static bool useInlineVisibilityHidden(const NamedDecl *D) {
  470. // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
  471. const LangOptions &Opts = D->getASTContext().getLangOpts();
  472. if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
  473. return false;
  474. const auto *FD = dyn_cast<FunctionDecl>(D);
  475. if (!FD)
  476. return false;
  477. TemplateSpecializationKind TSK = TSK_Undeclared;
  478. if (FunctionTemplateSpecializationInfo *spec
  479. = FD->getTemplateSpecializationInfo()) {
  480. TSK = spec->getTemplateSpecializationKind();
  481. } else if (MemberSpecializationInfo *MSI =
  482. FD->getMemberSpecializationInfo()) {
  483. TSK = MSI->getTemplateSpecializationKind();
  484. }
  485. const FunctionDecl *Def = nullptr;
  486. // InlineVisibilityHidden only applies to definitions, and
  487. // isInlined() only gives meaningful answers on definitions
  488. // anyway.
  489. return TSK != TSK_ExplicitInstantiationDeclaration &&
  490. TSK != TSK_ExplicitInstantiationDefinition &&
  491. FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
  492. }
  493. template <typename T> static bool isFirstInExternCContext(T *D) {
  494. const T *First = D->getFirstDecl();
  495. return First->isInExternCContext();
  496. }
  497. static bool isSingleLineLanguageLinkage(const Decl &D) {
  498. if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
  499. if (!SD->hasBraces())
  500. return true;
  501. return false;
  502. }
  503. /// Determine whether D is declared in the purview of a named module.
  504. static bool isInModulePurview(const NamedDecl *D) {
  505. if (auto *M = D->getOwningModule())
  506. return M->isModulePurview();
  507. return false;
  508. }
  509. static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {
  510. // FIXME: Handle isModulePrivate.
  511. switch (D->getModuleOwnershipKind()) {
  512. case Decl::ModuleOwnershipKind::Unowned:
  513. case Decl::ModuleOwnershipKind::ModulePrivate:
  514. return false;
  515. case Decl::ModuleOwnershipKind::Visible:
  516. case Decl::ModuleOwnershipKind::VisibleWhenImported:
  517. return isInModulePurview(D);
  518. }
  519. llvm_unreachable("unexpected module ownership kind");
  520. }
  521. static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
  522. // Internal linkage declarations within a module interface unit are modeled
  523. // as "module-internal linkage", which means that they have internal linkage
  524. // formally but can be indirectly accessed from outside the module via inline
  525. // functions and templates defined within the module.
  526. if (isInModulePurview(D))
  527. return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
  528. return LinkageInfo::internal();
  529. }
  530. static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
  531. // C++ Modules TS [basic.link]/6.8:
  532. // - A name declared at namespace scope that does not have internal linkage
  533. // by the previous rules and that is introduced by a non-exported
  534. // declaration has module linkage.
  535. if (isInModulePurview(D) && !isExportedFromModuleInterfaceUnit(
  536. cast<NamedDecl>(D->getCanonicalDecl())))
  537. return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
  538. return LinkageInfo::external();
  539. }
  540. static StorageClass getStorageClass(const Decl *D) {
  541. if (auto *TD = dyn_cast<TemplateDecl>(D))
  542. D = TD->getTemplatedDecl();
  543. if (D) {
  544. if (auto *VD = dyn_cast<VarDecl>(D))
  545. return VD->getStorageClass();
  546. if (auto *FD = dyn_cast<FunctionDecl>(D))
  547. return FD->getStorageClass();
  548. }
  549. return SC_None;
  550. }
  551. LinkageInfo
  552. LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
  553. LVComputationKind computation,
  554. bool IgnoreVarTypeLinkage) {
  555. assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
  556. "Not a name having namespace scope");
  557. ASTContext &Context = D->getASTContext();
  558. // C++ [basic.link]p3:
  559. // A name having namespace scope (3.3.6) has internal linkage if it
  560. // is the name of
  561. if (getStorageClass(D->getCanonicalDecl()) == SC_Static) {
  562. // - a variable, variable template, function, or function template
  563. // that is explicitly declared static; or
  564. // (This bullet corresponds to C99 6.2.2p3.)
  565. return getInternalLinkageFor(D);
  566. }
  567. if (const auto *Var = dyn_cast<VarDecl>(D)) {
  568. // - a non-template variable of non-volatile const-qualified type, unless
  569. // - it is explicitly declared extern, or
  570. // - it is inline or exported, or
  571. // - it was previously declared and the prior declaration did not have
  572. // internal linkage
  573. // (There is no equivalent in C99.)
  574. if (Context.getLangOpts().CPlusPlus &&
  575. Var->getType().isConstQualified() &&
  576. !Var->getType().isVolatileQualified() &&
  577. !Var->isInline() &&
  578. !isExportedFromModuleInterfaceUnit(Var) &&
  579. !isa<VarTemplateSpecializationDecl>(Var) &&
  580. !Var->getDescribedVarTemplate()) {
  581. const VarDecl *PrevVar = Var->getPreviousDecl();
  582. if (PrevVar)
  583. return getLVForDecl(PrevVar, computation);
  584. if (Var->getStorageClass() != SC_Extern &&
  585. Var->getStorageClass() != SC_PrivateExtern &&
  586. !isSingleLineLanguageLinkage(*Var))
  587. return getInternalLinkageFor(Var);
  588. }
  589. for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
  590. PrevVar = PrevVar->getPreviousDecl()) {
  591. if (PrevVar->getStorageClass() == SC_PrivateExtern &&
  592. Var->getStorageClass() == SC_None)
  593. return getDeclLinkageAndVisibility(PrevVar);
  594. // Explicitly declared static.
  595. if (PrevVar->getStorageClass() == SC_Static)
  596. return getInternalLinkageFor(Var);
  597. }
  598. } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
  599. // - a data member of an anonymous union.
  600. const VarDecl *VD = IFD->getVarDecl();
  601. assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
  602. return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
  603. }
  604. assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
  605. // FIXME: This gives internal linkage to names that should have no linkage
  606. // (those not covered by [basic.link]p6).
  607. if (D->isInAnonymousNamespace()) {
  608. const auto *Var = dyn_cast<VarDecl>(D);
  609. const auto *Func = dyn_cast<FunctionDecl>(D);
  610. // FIXME: The check for extern "C" here is not justified by the standard
  611. // wording, but we retain it from the pre-DR1113 model to avoid breaking
  612. // code.
  613. //
  614. // C++11 [basic.link]p4:
  615. // An unnamed namespace or a namespace declared directly or indirectly
  616. // within an unnamed namespace has internal linkage.
  617. if ((!Var || !isFirstInExternCContext(Var)) &&
  618. (!Func || !isFirstInExternCContext(Func)))
  619. return getInternalLinkageFor(D);
  620. }
  621. // Set up the defaults.
  622. // C99 6.2.2p5:
  623. // If the declaration of an identifier for an object has file
  624. // scope and no storage-class specifier, its linkage is
  625. // external.
  626. LinkageInfo LV = getExternalLinkageFor(D);
  627. if (!hasExplicitVisibilityAlready(computation)) {
  628. if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
  629. LV.mergeVisibility(*Vis, true);
  630. } else {
  631. // If we're declared in a namespace with a visibility attribute,
  632. // use that namespace's visibility, and it still counts as explicit.
  633. for (const DeclContext *DC = D->getDeclContext();
  634. !isa<TranslationUnitDecl>(DC);
  635. DC = DC->getParent()) {
  636. const auto *ND = dyn_cast<NamespaceDecl>(DC);
  637. if (!ND) continue;
  638. if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
  639. LV.mergeVisibility(*Vis, true);
  640. break;
  641. }
  642. }
  643. }
  644. // Add in global settings if the above didn't give us direct visibility.
  645. if (!LV.isVisibilityExplicit()) {
  646. // Use global type/value visibility as appropriate.
  647. Visibility globalVisibility =
  648. computation.isValueVisibility()
  649. ? Context.getLangOpts().getValueVisibilityMode()
  650. : Context.getLangOpts().getTypeVisibilityMode();
  651. LV.mergeVisibility(globalVisibility, /*explicit*/ false);
  652. // If we're paying attention to global visibility, apply
  653. // -finline-visibility-hidden if this is an inline method.
  654. if (useInlineVisibilityHidden(D))
  655. LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
  656. }
  657. }
  658. // C++ [basic.link]p4:
  659. // A name having namespace scope that has not been given internal linkage
  660. // above and that is the name of
  661. // [...bullets...]
  662. // has its linkage determined as follows:
  663. // - if the enclosing namespace has internal linkage, the name has
  664. // internal linkage; [handled above]
  665. // - otherwise, if the declaration of the name is attached to a named
  666. // module and is not exported, the name has module linkage;
  667. // - otherwise, the name has external linkage.
  668. // LV is currently set up to handle the last two bullets.
  669. //
  670. // The bullets are:
  671. // - a variable; or
  672. if (const auto *Var = dyn_cast<VarDecl>(D)) {
  673. // GCC applies the following optimization to variables and static
  674. // data members, but not to functions:
  675. //
  676. // Modify the variable's LV by the LV of its type unless this is
  677. // C or extern "C". This follows from [basic.link]p9:
  678. // A type without linkage shall not be used as the type of a
  679. // variable or function with external linkage unless
  680. // - the entity has C language linkage, or
  681. // - the entity is declared within an unnamed namespace, or
  682. // - the entity is not used or is defined in the same
  683. // translation unit.
  684. // and [basic.link]p10:
  685. // ...the types specified by all declarations referring to a
  686. // given variable or function shall be identical...
  687. // C does not have an equivalent rule.
  688. //
  689. // Ignore this if we've got an explicit attribute; the user
  690. // probably knows what they're doing.
  691. //
  692. // Note that we don't want to make the variable non-external
  693. // because of this, but unique-external linkage suits us.
  694. if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
  695. !IgnoreVarTypeLinkage) {
  696. LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
  697. if (!isExternallyVisible(TypeLV.getLinkage()))
  698. return LinkageInfo::uniqueExternal();
  699. if (!LV.isVisibilityExplicit())
  700. LV.mergeVisibility(TypeLV);
  701. }
  702. if (Var->getStorageClass() == SC_PrivateExtern)
  703. LV.mergeVisibility(HiddenVisibility, true);
  704. // Note that Sema::MergeVarDecl already takes care of implementing
  705. // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
  706. // to do it here.
  707. // As per function and class template specializations (below),
  708. // consider LV for the template and template arguments. We're at file
  709. // scope, so we do not need to worry about nested specializations.
  710. if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
  711. mergeTemplateLV(LV, spec, computation);
  712. }
  713. // - a function; or
  714. } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
  715. // In theory, we can modify the function's LV by the LV of its
  716. // type unless it has C linkage (see comment above about variables
  717. // for justification). In practice, GCC doesn't do this, so it's
  718. // just too painful to make work.
  719. if (Function->getStorageClass() == SC_PrivateExtern)
  720. LV.mergeVisibility(HiddenVisibility, true);
  721. // Note that Sema::MergeCompatibleFunctionDecls already takes care of
  722. // merging storage classes and visibility attributes, so we don't have to
  723. // look at previous decls in here.
  724. // In C++, then if the type of the function uses a type with
  725. // unique-external linkage, it's not legally usable from outside
  726. // this translation unit. However, we should use the C linkage
  727. // rules instead for extern "C" declarations.
  728. if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
  729. // Only look at the type-as-written. Otherwise, deducing the return type
  730. // of a function could change its linkage.
  731. QualType TypeAsWritten = Function->getType();
  732. if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
  733. TypeAsWritten = TSI->getType();
  734. if (!isExternallyVisible(TypeAsWritten->getLinkage()))
  735. return LinkageInfo::uniqueExternal();
  736. }
  737. // Consider LV from the template and the template arguments.
  738. // We're at file scope, so we do not need to worry about nested
  739. // specializations.
  740. if (FunctionTemplateSpecializationInfo *specInfo
  741. = Function->getTemplateSpecializationInfo()) {
  742. mergeTemplateLV(LV, Function, specInfo, computation);
  743. }
  744. // - a named class (Clause 9), or an unnamed class defined in a
  745. // typedef declaration in which the class has the typedef name
  746. // for linkage purposes (7.1.3); or
  747. // - a named enumeration (7.2), or an unnamed enumeration
  748. // defined in a typedef declaration in which the enumeration
  749. // has the typedef name for linkage purposes (7.1.3); or
  750. } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
  751. // Unnamed tags have no linkage.
  752. if (!Tag->hasNameForLinkage())
  753. return LinkageInfo::none();
  754. // If this is a class template specialization, consider the
  755. // linkage of the template and template arguments. We're at file
  756. // scope, so we do not need to worry about nested specializations.
  757. if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
  758. mergeTemplateLV(LV, spec, computation);
  759. }
  760. // FIXME: This is not part of the C++ standard any more.
  761. // - an enumerator belonging to an enumeration with external linkage; or
  762. } else if (isa<EnumConstantDecl>(D)) {
  763. LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
  764. computation);
  765. if (!isExternalFormalLinkage(EnumLV.getLinkage()))
  766. return LinkageInfo::none();
  767. LV.merge(EnumLV);
  768. // - a template
  769. } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
  770. bool considerVisibility = !hasExplicitVisibilityAlready(computation);
  771. LinkageInfo tempLV =
  772. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  773. LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
  774. // An unnamed namespace or a namespace declared directly or indirectly
  775. // within an unnamed namespace has internal linkage. All other namespaces
  776. // have external linkage.
  777. //
  778. // We handled names in anonymous namespaces above.
  779. } else if (isa<NamespaceDecl>(D)) {
  780. return LV;
  781. // By extension, we assign external linkage to Objective-C
  782. // interfaces.
  783. } else if (isa<ObjCInterfaceDecl>(D)) {
  784. // fallout
  785. } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  786. // A typedef declaration has linkage if it gives a type a name for
  787. // linkage purposes.
  788. if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
  789. return LinkageInfo::none();
  790. // Everything not covered here has no linkage.
  791. } else {
  792. return LinkageInfo::none();
  793. }
  794. // If we ended up with non-externally-visible linkage, visibility should
  795. // always be default.
  796. if (!isExternallyVisible(LV.getLinkage()))
  797. return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
  798. return LV;
  799. }
  800. LinkageInfo
  801. LinkageComputer::getLVForClassMember(const NamedDecl *D,
  802. LVComputationKind computation,
  803. bool IgnoreVarTypeLinkage) {
  804. // Only certain class members have linkage. Note that fields don't
  805. // really have linkage, but it's convenient to say they do for the
  806. // purposes of calculating linkage of pointer-to-data-member
  807. // template arguments.
  808. //
  809. // Templates also don't officially have linkage, but since we ignore
  810. // the C++ standard and look at template arguments when determining
  811. // linkage and visibility of a template specialization, we might hit
  812. // a template template argument that way. If we do, we need to
  813. // consider its linkage.
  814. if (!(isa<CXXMethodDecl>(D) ||
  815. isa<VarDecl>(D) ||
  816. isa<FieldDecl>(D) ||
  817. isa<IndirectFieldDecl>(D) ||
  818. isa<TagDecl>(D) ||
  819. isa<TemplateDecl>(D)))
  820. return LinkageInfo::none();
  821. LinkageInfo LV;
  822. // If we have an explicit visibility attribute, merge that in.
  823. if (!hasExplicitVisibilityAlready(computation)) {
  824. if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
  825. LV.mergeVisibility(*Vis, true);
  826. // If we're paying attention to global visibility, apply
  827. // -finline-visibility-hidden if this is an inline method.
  828. //
  829. // Note that we do this before merging information about
  830. // the class visibility.
  831. if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
  832. LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
  833. }
  834. // If this class member has an explicit visibility attribute, the only
  835. // thing that can change its visibility is the template arguments, so
  836. // only look for them when processing the class.
  837. LVComputationKind classComputation = computation;
  838. if (LV.isVisibilityExplicit())
  839. classComputation = withExplicitVisibilityAlready(computation);
  840. LinkageInfo classLV =
  841. getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
  842. // The member has the same linkage as the class. If that's not externally
  843. // visible, we don't need to compute anything about the linkage.
  844. // FIXME: If we're only computing linkage, can we bail out here?
  845. if (!isExternallyVisible(classLV.getLinkage()))
  846. return classLV;
  847. // Otherwise, don't merge in classLV yet, because in certain cases
  848. // we need to completely ignore the visibility from it.
  849. // Specifically, if this decl exists and has an explicit attribute.
  850. const NamedDecl *explicitSpecSuppressor = nullptr;
  851. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  852. // Only look at the type-as-written. Otherwise, deducing the return type
  853. // of a function could change its linkage.
  854. QualType TypeAsWritten = MD->getType();
  855. if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
  856. TypeAsWritten = TSI->getType();
  857. if (!isExternallyVisible(TypeAsWritten->getLinkage()))
  858. return LinkageInfo::uniqueExternal();
  859. // If this is a method template specialization, use the linkage for
  860. // the template parameters and arguments.
  861. if (FunctionTemplateSpecializationInfo *spec
  862. = MD->getTemplateSpecializationInfo()) {
  863. mergeTemplateLV(LV, MD, spec, computation);
  864. if (spec->isExplicitSpecialization()) {
  865. explicitSpecSuppressor = MD;
  866. } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
  867. explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
  868. }
  869. } else if (isExplicitMemberSpecialization(MD)) {
  870. explicitSpecSuppressor = MD;
  871. }
  872. } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  873. if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
  874. mergeTemplateLV(LV, spec, computation);
  875. if (spec->isExplicitSpecialization()) {
  876. explicitSpecSuppressor = spec;
  877. } else {
  878. const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
  879. if (isExplicitMemberSpecialization(temp)) {
  880. explicitSpecSuppressor = temp->getTemplatedDecl();
  881. }
  882. }
  883. } else if (isExplicitMemberSpecialization(RD)) {
  884. explicitSpecSuppressor = RD;
  885. }
  886. // Static data members.
  887. } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
  888. if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
  889. mergeTemplateLV(LV, spec, computation);
  890. // Modify the variable's linkage by its type, but ignore the
  891. // type's visibility unless it's a definition.
  892. if (!IgnoreVarTypeLinkage) {
  893. LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
  894. // FIXME: If the type's linkage is not externally visible, we can
  895. // give this static data member UniqueExternalLinkage.
  896. if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
  897. LV.mergeVisibility(typeLV);
  898. LV.mergeExternalVisibility(typeLV);
  899. }
  900. if (isExplicitMemberSpecialization(VD)) {
  901. explicitSpecSuppressor = VD;
  902. }
  903. // Template members.
  904. } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
  905. bool considerVisibility =
  906. (!LV.isVisibilityExplicit() &&
  907. !classLV.isVisibilityExplicit() &&
  908. !hasExplicitVisibilityAlready(computation));
  909. LinkageInfo tempLV =
  910. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  911. LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
  912. if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
  913. if (isExplicitMemberSpecialization(redeclTemp)) {
  914. explicitSpecSuppressor = temp->getTemplatedDecl();
  915. }
  916. }
  917. }
  918. // We should never be looking for an attribute directly on a template.
  919. assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
  920. // If this member is an explicit member specialization, and it has
  921. // an explicit attribute, ignore visibility from the parent.
  922. bool considerClassVisibility = true;
  923. if (explicitSpecSuppressor &&
  924. // optimization: hasDVA() is true only with explicit visibility.
  925. LV.isVisibilityExplicit() &&
  926. classLV.getVisibility() != DefaultVisibility &&
  927. hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
  928. considerClassVisibility = false;
  929. }
  930. // Finally, merge in information from the class.
  931. LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
  932. return LV;
  933. }
  934. void NamedDecl::anchor() {}
  935. bool NamedDecl::isLinkageValid() const {
  936. if (!hasCachedLinkage())
  937. return true;
  938. Linkage L = LinkageComputer{}
  939. .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
  940. .getLinkage();
  941. return L == getCachedLinkage();
  942. }
  943. ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
  944. StringRef name = getName();
  945. if (name.empty()) return SFF_None;
  946. if (name.front() == 'C')
  947. if (name == "CFStringCreateWithFormat" ||
  948. name == "CFStringCreateWithFormatAndArguments" ||
  949. name == "CFStringAppendFormat" ||
  950. name == "CFStringAppendFormatAndArguments")
  951. return SFF_CFString;
  952. return SFF_None;
  953. }
  954. Linkage NamedDecl::getLinkageInternal() const {
  955. // We don't care about visibility here, so ask for the cheapest
  956. // possible visibility analysis.
  957. return LinkageComputer{}
  958. .getLVForDecl(this, LVComputationKind::forLinkageOnly())
  959. .getLinkage();
  960. }
  961. LinkageInfo NamedDecl::getLinkageAndVisibility() const {
  962. return LinkageComputer{}.getDeclLinkageAndVisibility(this);
  963. }
  964. static Optional<Visibility>
  965. getExplicitVisibilityAux(const NamedDecl *ND,
  966. NamedDecl::ExplicitVisibilityKind kind,
  967. bool IsMostRecent) {
  968. assert(!IsMostRecent || ND == ND->getMostRecentDecl());
  969. // Check the declaration itself first.
  970. if (Optional<Visibility> V = getVisibilityOf(ND, kind))
  971. return V;
  972. // If this is a member class of a specialization of a class template
  973. // and the corresponding decl has explicit visibility, use that.
  974. if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
  975. CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
  976. if (InstantiatedFrom)
  977. return getVisibilityOf(InstantiatedFrom, kind);
  978. }
  979. // If there wasn't explicit visibility there, and this is a
  980. // specialization of a class template, check for visibility
  981. // on the pattern.
  982. if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
  983. // Walk all the template decl till this point to see if there are
  984. // explicit visibility attributes.
  985. const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
  986. while (TD != nullptr) {
  987. auto Vis = getVisibilityOf(TD, kind);
  988. if (Vis != None)
  989. return Vis;
  990. TD = TD->getPreviousDecl();
  991. }
  992. return None;
  993. }
  994. // Use the most recent declaration.
  995. if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
  996. const NamedDecl *MostRecent = ND->getMostRecentDecl();
  997. if (MostRecent != ND)
  998. return getExplicitVisibilityAux(MostRecent, kind, true);
  999. }
  1000. if (const auto *Var = dyn_cast<VarDecl>(ND)) {
  1001. if (Var->isStaticDataMember()) {
  1002. VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
  1003. if (InstantiatedFrom)
  1004. return getVisibilityOf(InstantiatedFrom, kind);
  1005. }
  1006. if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
  1007. return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
  1008. kind);
  1009. return None;
  1010. }
  1011. // Also handle function template specializations.
  1012. if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
  1013. // If the function is a specialization of a template with an
  1014. // explicit visibility attribute, use that.
  1015. if (FunctionTemplateSpecializationInfo *templateInfo
  1016. = fn->getTemplateSpecializationInfo())
  1017. return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
  1018. kind);
  1019. // If the function is a member of a specialization of a class template
  1020. // and the corresponding decl has explicit visibility, use that.
  1021. FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
  1022. if (InstantiatedFrom)
  1023. return getVisibilityOf(InstantiatedFrom, kind);
  1024. return None;
  1025. }
  1026. // The visibility of a template is stored in the templated decl.
  1027. if (const auto *TD = dyn_cast<TemplateDecl>(ND))
  1028. return getVisibilityOf(TD->getTemplatedDecl(), kind);
  1029. return None;
  1030. }
  1031. Optional<Visibility>
  1032. NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
  1033. return getExplicitVisibilityAux(this, kind, false);
  1034. }
  1035. LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
  1036. Decl *ContextDecl,
  1037. LVComputationKind computation) {
  1038. // This lambda has its linkage/visibility determined by its owner.
  1039. const NamedDecl *Owner;
  1040. if (!ContextDecl)
  1041. Owner = dyn_cast<NamedDecl>(DC);
  1042. else if (isa<ParmVarDecl>(ContextDecl))
  1043. Owner =
  1044. dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
  1045. else
  1046. Owner = cast<NamedDecl>(ContextDecl);
  1047. if (!Owner)
  1048. return LinkageInfo::none();
  1049. // If the owner has a deduced type, we need to skip querying the linkage and
  1050. // visibility of that type, because it might involve this closure type. The
  1051. // only effect of this is that we might give a lambda VisibleNoLinkage rather
  1052. // than NoLinkage when we don't strictly need to, which is benign.
  1053. auto *VD = dyn_cast<VarDecl>(Owner);
  1054. LinkageInfo OwnerLV =
  1055. VD && VD->getType()->getContainedDeducedType()
  1056. ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
  1057. : getLVForDecl(Owner, computation);
  1058. // A lambda never formally has linkage. But if the owner is externally
  1059. // visible, then the lambda is too. We apply the same rules to blocks.
  1060. if (!isExternallyVisible(OwnerLV.getLinkage()))
  1061. return LinkageInfo::none();
  1062. return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
  1063. OwnerLV.isVisibilityExplicit());
  1064. }
  1065. LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
  1066. LVComputationKind computation) {
  1067. if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
  1068. if (Function->isInAnonymousNamespace() &&
  1069. !isFirstInExternCContext(Function))
  1070. return getInternalLinkageFor(Function);
  1071. // This is a "void f();" which got merged with a file static.
  1072. if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
  1073. return getInternalLinkageFor(Function);
  1074. LinkageInfo LV;
  1075. if (!hasExplicitVisibilityAlready(computation)) {
  1076. if (Optional<Visibility> Vis =
  1077. getExplicitVisibility(Function, computation))
  1078. LV.mergeVisibility(*Vis, true);
  1079. }
  1080. // Note that Sema::MergeCompatibleFunctionDecls already takes care of
  1081. // merging storage classes and visibility attributes, so we don't have to
  1082. // look at previous decls in here.
  1083. return LV;
  1084. }
  1085. if (const auto *Var = dyn_cast<VarDecl>(D)) {
  1086. if (Var->hasExternalStorage()) {
  1087. if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
  1088. return getInternalLinkageFor(Var);
  1089. LinkageInfo LV;
  1090. if (Var->getStorageClass() == SC_PrivateExtern)
  1091. LV.mergeVisibility(HiddenVisibility, true);
  1092. else if (!hasExplicitVisibilityAlready(computation)) {
  1093. if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
  1094. LV.mergeVisibility(*Vis, true);
  1095. }
  1096. if (const VarDecl *Prev = Var->getPreviousDecl()) {
  1097. LinkageInfo PrevLV = getLVForDecl(Prev, computation);
  1098. if (PrevLV.getLinkage())
  1099. LV.setLinkage(PrevLV.getLinkage());
  1100. LV.mergeVisibility(PrevLV);
  1101. }
  1102. return LV;
  1103. }
  1104. if (!Var->isStaticLocal())
  1105. return LinkageInfo::none();
  1106. }
  1107. ASTContext &Context = D->getASTContext();
  1108. if (!Context.getLangOpts().CPlusPlus)
  1109. return LinkageInfo::none();
  1110. const Decl *OuterD = getOutermostFuncOrBlockContext(D);
  1111. if (!OuterD || OuterD->isInvalidDecl())
  1112. return LinkageInfo::none();
  1113. LinkageInfo LV;
  1114. if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
  1115. if (!BD->getBlockManglingNumber())
  1116. return LinkageInfo::none();
  1117. LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
  1118. BD->getBlockManglingContextDecl(), computation);
  1119. } else {
  1120. const auto *FD = cast<FunctionDecl>(OuterD);
  1121. if (!FD->isInlined() &&
  1122. !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
  1123. return LinkageInfo::none();
  1124. // If a function is hidden by -fvisibility-inlines-hidden option and
  1125. // is not explicitly attributed as a hidden function,
  1126. // we should not make static local variables in the function hidden.
  1127. LV = getLVForDecl(FD, computation);
  1128. if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
  1129. !LV.isVisibilityExplicit()) {
  1130. assert(cast<VarDecl>(D)->isStaticLocal());
  1131. // If this was an implicitly hidden inline method, check again for
  1132. // explicit visibility on the parent class, and use that for static locals
  1133. // if present.
  1134. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  1135. LV = getLVForDecl(MD->getParent(), computation);
  1136. if (!LV.isVisibilityExplicit()) {
  1137. Visibility globalVisibility =
  1138. computation.isValueVisibility()
  1139. ? Context.getLangOpts().getValueVisibilityMode()
  1140. : Context.getLangOpts().getTypeVisibilityMode();
  1141. return LinkageInfo(VisibleNoLinkage, globalVisibility,
  1142. /*visibilityExplicit=*/false);
  1143. }
  1144. }
  1145. }
  1146. if (!isExternallyVisible(LV.getLinkage()))
  1147. return LinkageInfo::none();
  1148. return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
  1149. LV.isVisibilityExplicit());
  1150. }
  1151. static inline const CXXRecordDecl*
  1152. getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
  1153. const CXXRecordDecl *Ret = Record;
  1154. while (Record && Record->isLambda()) {
  1155. Ret = Record;
  1156. if (!Record->getParent()) break;
  1157. // Get the Containing Class of this Lambda Class
  1158. Record = dyn_cast_or_null<CXXRecordDecl>(
  1159. Record->getParent()->getParent());
  1160. }
  1161. return Ret;
  1162. }
  1163. LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
  1164. LVComputationKind computation,
  1165. bool IgnoreVarTypeLinkage) {
  1166. // Internal_linkage attribute overrides other considerations.
  1167. if (D->hasAttr<InternalLinkageAttr>())
  1168. return getInternalLinkageFor(D);
  1169. // Objective-C: treat all Objective-C declarations as having external
  1170. // linkage.
  1171. switch (D->getKind()) {
  1172. default:
  1173. break;
  1174. // Per C++ [basic.link]p2, only the names of objects, references,
  1175. // functions, types, templates, namespaces, and values ever have linkage.
  1176. //
  1177. // Note that the name of a typedef, namespace alias, using declaration,
  1178. // and so on are not the name of the corresponding type, namespace, or
  1179. // declaration, so they do *not* have linkage.
  1180. case Decl::ImplicitParam:
  1181. case Decl::Label:
  1182. case Decl::NamespaceAlias:
  1183. case Decl::ParmVar:
  1184. case Decl::Using:
  1185. case Decl::UsingShadow:
  1186. case Decl::UsingDirective:
  1187. return LinkageInfo::none();
  1188. case Decl::EnumConstant:
  1189. // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
  1190. if (D->getASTContext().getLangOpts().CPlusPlus)
  1191. return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
  1192. return LinkageInfo::visible_none();
  1193. case Decl::Typedef:
  1194. case Decl::TypeAlias:
  1195. // A typedef declaration has linkage if it gives a type a name for
  1196. // linkage purposes.
  1197. if (!cast<TypedefNameDecl>(D)
  1198. ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
  1199. return LinkageInfo::none();
  1200. break;
  1201. case Decl::TemplateTemplateParm: // count these as external
  1202. case Decl::NonTypeTemplateParm:
  1203. case Decl::ObjCAtDefsField:
  1204. case Decl::ObjCCategory:
  1205. case Decl::ObjCCategoryImpl:
  1206. case Decl::ObjCCompatibleAlias:
  1207. case Decl::ObjCImplementation:
  1208. case Decl::ObjCMethod:
  1209. case Decl::ObjCProperty:
  1210. case Decl::ObjCPropertyImpl:
  1211. case Decl::ObjCProtocol:
  1212. return getExternalLinkageFor(D);
  1213. case Decl::CXXRecord: {
  1214. const auto *Record = cast<CXXRecordDecl>(D);
  1215. if (Record->isLambda()) {
  1216. if (!Record->getLambdaManglingNumber()) {
  1217. // This lambda has no mangling number, so it's internal.
  1218. return getInternalLinkageFor(D);
  1219. }
  1220. // This lambda has its linkage/visibility determined:
  1221. // - either by the outermost lambda if that lambda has no mangling
  1222. // number.
  1223. // - or by the parent of the outer most lambda
  1224. // This prevents infinite recursion in settings such as nested lambdas
  1225. // used in NSDMI's, for e.g.
  1226. // struct L {
  1227. // int t{};
  1228. // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
  1229. // };
  1230. const CXXRecordDecl *OuterMostLambda =
  1231. getOutermostEnclosingLambda(Record);
  1232. if (!OuterMostLambda->getLambdaManglingNumber())
  1233. return getInternalLinkageFor(D);
  1234. return getLVForClosure(
  1235. OuterMostLambda->getDeclContext()->getRedeclContext(),
  1236. OuterMostLambda->getLambdaContextDecl(), computation);
  1237. }
  1238. break;
  1239. }
  1240. }
  1241. // Handle linkage for namespace-scope names.
  1242. if (D->getDeclContext()->getRedeclContext()->isFileContext())
  1243. return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
  1244. // C++ [basic.link]p5:
  1245. // In addition, a member function, static data member, a named
  1246. // class or enumeration of class scope, or an unnamed class or
  1247. // enumeration defined in a class-scope typedef declaration such
  1248. // that the class or enumeration has the typedef name for linkage
  1249. // purposes (7.1.3), has external linkage if the name of the class
  1250. // has external linkage.
  1251. if (D->getDeclContext()->isRecord())
  1252. return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
  1253. // C++ [basic.link]p6:
  1254. // The name of a function declared in block scope and the name of
  1255. // an object declared by a block scope extern declaration have
  1256. // linkage. If there is a visible declaration of an entity with
  1257. // linkage having the same name and type, ignoring entities
  1258. // declared outside the innermost enclosing namespace scope, the
  1259. // block scope declaration declares that same entity and receives
  1260. // the linkage of the previous declaration. If there is more than
  1261. // one such matching entity, the program is ill-formed. Otherwise,
  1262. // if no matching entity is found, the block scope entity receives
  1263. // external linkage.
  1264. if (D->getDeclContext()->isFunctionOrMethod())
  1265. return getLVForLocalDecl(D, computation);
  1266. // C++ [basic.link]p6:
  1267. // Names not covered by these rules have no linkage.
  1268. return LinkageInfo::none();
  1269. }
  1270. /// getLVForDecl - Get the linkage and visibility for the given declaration.
  1271. LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
  1272. LVComputationKind computation) {
  1273. // Internal_linkage attribute overrides other considerations.
  1274. if (D->hasAttr<InternalLinkageAttr>())
  1275. return getInternalLinkageFor(D);
  1276. if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
  1277. return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
  1278. if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
  1279. return *LI;
  1280. LinkageInfo LV = computeLVForDecl(D, computation);
  1281. if (D->hasCachedLinkage())
  1282. assert(D->getCachedLinkage() == LV.getLinkage());
  1283. D->setCachedLinkage(LV.getLinkage());
  1284. cache(D, computation, LV);
  1285. #ifndef NDEBUG
  1286. // In C (because of gnu inline) and in c++ with microsoft extensions an
  1287. // static can follow an extern, so we can have two decls with different
  1288. // linkages.
  1289. const LangOptions &Opts = D->getASTContext().getLangOpts();
  1290. if (!Opts.CPlusPlus || Opts.MicrosoftExt)
  1291. return LV;
  1292. // We have just computed the linkage for this decl. By induction we know
  1293. // that all other computed linkages match, check that the one we just
  1294. // computed also does.
  1295. NamedDecl *Old = nullptr;
  1296. for (auto I : D->redecls()) {
  1297. auto *T = cast<NamedDecl>(I);
  1298. if (T == D)
  1299. continue;
  1300. if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
  1301. Old = T;
  1302. break;
  1303. }
  1304. }
  1305. assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
  1306. #endif
  1307. return LV;
  1308. }
  1309. LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
  1310. return getLVForDecl(D,
  1311. LVComputationKind(usesTypeVisibility(D)
  1312. ? NamedDecl::VisibilityForType
  1313. : NamedDecl::VisibilityForValue));
  1314. }
  1315. Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
  1316. Module *M = getOwningModule();
  1317. if (!M)
  1318. return nullptr;
  1319. switch (M->Kind) {
  1320. case Module::ModuleMapModule:
  1321. // Module map modules have no special linkage semantics.
  1322. return nullptr;
  1323. case Module::ModuleInterfaceUnit:
  1324. return M;
  1325. case Module::GlobalModuleFragment: {
  1326. // External linkage declarations in the global module have no owning module
  1327. // for linkage purposes. But internal linkage declarations in the global
  1328. // module fragment of a particular module are owned by that module for
  1329. // linkage purposes.
  1330. if (IgnoreLinkage)
  1331. return nullptr;
  1332. bool InternalLinkage;
  1333. if (auto *ND = dyn_cast<NamedDecl>(this))
  1334. InternalLinkage = !ND->hasExternalFormalLinkage();
  1335. else {
  1336. auto *NSD = dyn_cast<NamespaceDecl>(this);
  1337. InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
  1338. isInAnonymousNamespace();
  1339. }
  1340. return InternalLinkage ? M->Parent : nullptr;
  1341. }
  1342. case Module::PrivateModuleFragment:
  1343. // The private module fragment is part of its containing module for linkage
  1344. // purposes.
  1345. return M->Parent;
  1346. }
  1347. llvm_unreachable("unknown module kind");
  1348. }
  1349. void NamedDecl::printName(raw_ostream &os) const {
  1350. os << Name;
  1351. }
  1352. std::string NamedDecl::getQualifiedNameAsString() const {
  1353. std::string QualName;
  1354. llvm::raw_string_ostream OS(QualName);
  1355. printQualifiedName(OS, getASTContext().getPrintingPolicy());
  1356. return OS.str();
  1357. }
  1358. void NamedDecl::printQualifiedName(raw_ostream &OS) const {
  1359. printQualifiedName(OS, getASTContext().getPrintingPolicy());
  1360. }
  1361. void NamedDecl::printQualifiedName(raw_ostream &OS,
  1362. const PrintingPolicy &P) const {
  1363. if (getDeclContext()->isFunctionOrMethod()) {
  1364. // We do not print '(anonymous)' for function parameters without name.
  1365. printName(OS);
  1366. return;
  1367. }
  1368. printNestedNameSpecifier(OS, P);
  1369. if (getDeclName() || isa<DecompositionDecl>(this))
  1370. OS << *this;
  1371. else
  1372. OS << "(anonymous)";
  1373. }
  1374. void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
  1375. printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
  1376. }
  1377. void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
  1378. const PrintingPolicy &P) const {
  1379. const DeclContext *Ctx = getDeclContext();
  1380. // For ObjC methods and properties, look through categories and use the
  1381. // interface as context.
  1382. if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
  1383. if (auto *ID = MD->getClassInterface())
  1384. Ctx = ID;
  1385. if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
  1386. if (auto *MD = PD->getGetterMethodDecl())
  1387. if (auto *ID = MD->getClassInterface())
  1388. Ctx = ID;
  1389. }
  1390. if (Ctx->isFunctionOrMethod())
  1391. return;
  1392. using ContextsTy = SmallVector<const DeclContext *, 8>;
  1393. ContextsTy Contexts;
  1394. // Collect named contexts.
  1395. while (Ctx) {
  1396. if (isa<NamedDecl>(Ctx))
  1397. Contexts.push_back(Ctx);
  1398. Ctx = Ctx->getParent();
  1399. }
  1400. for (const DeclContext *DC : llvm::reverse(Contexts)) {
  1401. if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  1402. OS << Spec->getName();
  1403. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  1404. printTemplateArgumentList(OS, TemplateArgs.asArray(), P);
  1405. } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
  1406. if (P.SuppressUnwrittenScope &&
  1407. (ND->isAnonymousNamespace() || ND->isInline()))
  1408. continue;
  1409. if (ND->isAnonymousNamespace()) {
  1410. OS << (P.MSVCFormatting ? "`anonymous namespace\'"
  1411. : "(anonymous namespace)");
  1412. }
  1413. else
  1414. OS << *ND;
  1415. } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
  1416. if (!RD->getIdentifier())
  1417. OS << "(anonymous " << RD->getKindName() << ')';
  1418. else
  1419. OS << *RD;
  1420. } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
  1421. const FunctionProtoType *FT = nullptr;
  1422. if (FD->hasWrittenPrototype())
  1423. FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
  1424. OS << *FD << '(';
  1425. if (FT) {
  1426. unsigned NumParams = FD->getNumParams();
  1427. for (unsigned i = 0; i < NumParams; ++i) {
  1428. if (i)
  1429. OS << ", ";
  1430. OS << FD->getParamDecl(i)->getType().stream(P);
  1431. }
  1432. if (FT->isVariadic()) {
  1433. if (NumParams > 0)
  1434. OS << ", ";
  1435. OS << "...";
  1436. }
  1437. }
  1438. OS << ')';
  1439. } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
  1440. // C++ [dcl.enum]p10: Each enum-name and each unscoped
  1441. // enumerator is declared in the scope that immediately contains
  1442. // the enum-specifier. Each scoped enumerator is declared in the
  1443. // scope of the enumeration.
  1444. // For the case of unscoped enumerator, do not include in the qualified
  1445. // name any information about its enum enclosing scope, as its visibility
  1446. // is global.
  1447. if (ED->isScoped())
  1448. OS << *ED;
  1449. else
  1450. continue;
  1451. } else {
  1452. OS << *cast<NamedDecl>(DC);
  1453. }
  1454. OS << "::";
  1455. }
  1456. }
  1457. void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
  1458. const PrintingPolicy &Policy,
  1459. bool Qualified) const {
  1460. if (Qualified)
  1461. printQualifiedName(OS, Policy);
  1462. else
  1463. printName(OS);
  1464. }
  1465. template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
  1466. return true;
  1467. }
  1468. static bool isRedeclarableImpl(...) { return false; }
  1469. static bool isRedeclarable(Decl::Kind K) {
  1470. switch (K) {
  1471. #define DECL(Type, Base) \
  1472. case Decl::Type: \
  1473. return isRedeclarableImpl((Type##Decl *)nullptr);
  1474. #define ABSTRACT_DECL(DECL)
  1475. #include "clang/AST/DeclNodes.inc"
  1476. }
  1477. llvm_unreachable("unknown decl kind");
  1478. }
  1479. bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
  1480. assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
  1481. // Never replace one imported declaration with another; we need both results
  1482. // when re-exporting.
  1483. if (OldD->isFromASTFile() && isFromASTFile())
  1484. return false;
  1485. // A kind mismatch implies that the declaration is not replaced.
  1486. if (OldD->getKind() != getKind())
  1487. return false;
  1488. // For method declarations, we never replace. (Why?)
  1489. if (isa<ObjCMethodDecl>(this))
  1490. return false;
  1491. // For parameters, pick the newer one. This is either an error or (in
  1492. // Objective-C) permitted as an extension.
  1493. if (isa<ParmVarDecl>(this))
  1494. return true;
  1495. // Inline namespaces can give us two declarations with the same
  1496. // name and kind in the same scope but different contexts; we should
  1497. // keep both declarations in this case.
  1498. if (!this->getDeclContext()->getRedeclContext()->Equals(
  1499. OldD->getDeclContext()->getRedeclContext()))
  1500. return false;
  1501. // Using declarations can be replaced if they import the same name from the
  1502. // same context.
  1503. if (auto *UD = dyn_cast<UsingDecl>(this)) {
  1504. ASTContext &Context = getASTContext();
  1505. return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
  1506. Context.getCanonicalNestedNameSpecifier(
  1507. cast<UsingDecl>(OldD)->getQualifier());
  1508. }
  1509. if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
  1510. ASTContext &Context = getASTContext();
  1511. return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
  1512. Context.getCanonicalNestedNameSpecifier(
  1513. cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
  1514. }
  1515. if (isRedeclarable(getKind())) {
  1516. if (getCanonicalDecl() != OldD->getCanonicalDecl())
  1517. return false;
  1518. if (IsKnownNewer)
  1519. return true;
  1520. // Check whether this is actually newer than OldD. We want to keep the
  1521. // newer declaration. This loop will usually only iterate once, because
  1522. // OldD is usually the previous declaration.
  1523. for (auto D : redecls()) {
  1524. if (D == OldD)
  1525. break;
  1526. // If we reach the canonical declaration, then OldD is not actually older
  1527. // than this one.
  1528. //
  1529. // FIXME: In this case, we should not add this decl to the lookup table.
  1530. if (D->isCanonicalDecl())
  1531. return false;
  1532. }
  1533. // It's a newer declaration of the same kind of declaration in the same
  1534. // scope: we want this decl instead of the existing one.
  1535. return true;
  1536. }
  1537. // In all other cases, we need to keep both declarations in case they have
  1538. // different visibility. Any attempt to use the name will result in an
  1539. // ambiguity if more than one is visible.
  1540. return false;
  1541. }
  1542. bool NamedDecl::hasLinkage() const {
  1543. return getFormalLinkage() != NoLinkage;
  1544. }
  1545. NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
  1546. NamedDecl *ND = this;
  1547. while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
  1548. ND = UD->getTargetDecl();
  1549. if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
  1550. return AD->getClassInterface();
  1551. if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
  1552. return AD->getNamespace();
  1553. return ND;
  1554. }
  1555. bool NamedDecl::isCXXInstanceMember() const {
  1556. if (!isCXXClassMember())
  1557. return false;
  1558. const NamedDecl *D = this;
  1559. if (isa<UsingShadowDecl>(D))
  1560. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  1561. if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
  1562. return true;
  1563. if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
  1564. return MD->isInstance();
  1565. return false;
  1566. }
  1567. //===----------------------------------------------------------------------===//
  1568. // DeclaratorDecl Implementation
  1569. //===----------------------------------------------------------------------===//
  1570. template <typename DeclT>
  1571. static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
  1572. if (decl->getNumTemplateParameterLists() > 0)
  1573. return decl->getTemplateParameterList(0)->getTemplateLoc();
  1574. else
  1575. return decl->getInnerLocStart();
  1576. }
  1577. SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
  1578. TypeSourceInfo *TSI = getTypeSourceInfo();
  1579. if (TSI) return TSI->getTypeLoc().getBeginLoc();
  1580. return SourceLocation();
  1581. }
  1582. void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
  1583. if (QualifierLoc) {
  1584. // Make sure the extended decl info is allocated.
  1585. if (!hasExtInfo()) {
  1586. // Save (non-extended) type source info pointer.
  1587. auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
  1588. // Allocate external info struct.
  1589. DeclInfo = new (getASTContext()) ExtInfo;
  1590. // Restore savedTInfo into (extended) decl info.
  1591. getExtInfo()->TInfo = savedTInfo;
  1592. }
  1593. // Set qualifier info.
  1594. getExtInfo()->QualifierLoc = QualifierLoc;
  1595. } else {
  1596. // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
  1597. if (hasExtInfo()) {
  1598. if (getExtInfo()->NumTemplParamLists == 0) {
  1599. // Save type source info pointer.
  1600. TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
  1601. // Deallocate the extended decl info.
  1602. getASTContext().Deallocate(getExtInfo());
  1603. // Restore savedTInfo into (non-extended) decl info.
  1604. DeclInfo = savedTInfo;
  1605. }
  1606. else
  1607. getExtInfo()->QualifierLoc = QualifierLoc;
  1608. }
  1609. }
  1610. }
  1611. void DeclaratorDecl::setTemplateParameterListsInfo(
  1612. ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
  1613. assert(!TPLists.empty());
  1614. // Make sure the extended decl info is allocated.
  1615. if (!hasExtInfo()) {
  1616. // Save (non-extended) type source info pointer.
  1617. auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
  1618. // Allocate external info struct.
  1619. DeclInfo = new (getASTContext()) ExtInfo;
  1620. // Restore savedTInfo into (extended) decl info.
  1621. getExtInfo()->TInfo = savedTInfo;
  1622. }
  1623. // Set the template parameter lists info.
  1624. getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
  1625. }
  1626. SourceLocation DeclaratorDecl::getOuterLocStart() const {
  1627. return getTemplateOrInnerLocStart(this);
  1628. }
  1629. // Helper function: returns true if QT is or contains a type
  1630. // having a postfix component.
  1631. static bool typeIsPostfix(QualType QT) {
  1632. while (true) {
  1633. const Type* T = QT.getTypePtr();
  1634. switch (T->getTypeClass()) {
  1635. default:
  1636. return false;
  1637. case Type::Pointer:
  1638. QT = cast<PointerType>(T)->getPointeeType();
  1639. break;
  1640. case Type::BlockPointer:
  1641. QT = cast<BlockPointerType>(T)->getPointeeType();
  1642. break;
  1643. case Type::MemberPointer:
  1644. QT = cast<MemberPointerType>(T)->getPointeeType();
  1645. break;
  1646. case Type::LValueReference:
  1647. case Type::RValueReference:
  1648. QT = cast<ReferenceType>(T)->getPointeeType();
  1649. break;
  1650. case Type::PackExpansion:
  1651. QT = cast<PackExpansionType>(T)->getPattern();
  1652. break;
  1653. case Type::Paren:
  1654. case Type::ConstantArray:
  1655. case Type::DependentSizedArray:
  1656. case Type::IncompleteArray:
  1657. case Type::VariableArray:
  1658. case Type::FunctionProto:
  1659. case Type::FunctionNoProto:
  1660. return true;
  1661. }
  1662. }
  1663. }
  1664. SourceRange DeclaratorDecl::getSourceRange() const {
  1665. SourceLocation RangeEnd = getLocation();
  1666. if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
  1667. // If the declaration has no name or the type extends past the name take the
  1668. // end location of the type.
  1669. if (!getDeclName() || typeIsPostfix(TInfo->getType()))
  1670. RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
  1671. }
  1672. return SourceRange(getOuterLocStart(), RangeEnd);
  1673. }
  1674. void QualifierInfo::setTemplateParameterListsInfo(
  1675. ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
  1676. // Free previous template parameters (if any).
  1677. if (NumTemplParamLists > 0) {
  1678. Context.Deallocate(TemplParamLists);
  1679. TemplParamLists = nullptr;
  1680. NumTemplParamLists = 0;
  1681. }
  1682. // Set info on matched template parameter lists (if any).
  1683. if (!TPLists.empty()) {
  1684. TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
  1685. NumTemplParamLists = TPLists.size();
  1686. std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
  1687. }
  1688. }
  1689. //===----------------------------------------------------------------------===//
  1690. // VarDecl Implementation
  1691. //===----------------------------------------------------------------------===//
  1692. const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
  1693. switch (SC) {
  1694. case SC_None: break;
  1695. case SC_Auto: return "auto";
  1696. case SC_Extern: return "extern";
  1697. case SC_PrivateExtern: return "__private_extern__";
  1698. case SC_Register: return "register";
  1699. case SC_Static: return "static";
  1700. }
  1701. llvm_unreachable("Invalid storage class");
  1702. }
  1703. VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
  1704. SourceLocation StartLoc, SourceLocation IdLoc,
  1705. IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
  1706. StorageClass SC)
  1707. : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
  1708. redeclarable_base(C) {
  1709. static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
  1710. "VarDeclBitfields too large!");
  1711. static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
  1712. "ParmVarDeclBitfields too large!");
  1713. static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
  1714. "NonParmVarDeclBitfields too large!");
  1715. AllBits = 0;
  1716. VarDeclBits.SClass = SC;
  1717. // Everything else is implicitly initialized to false.
  1718. }
  1719. VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
  1720. SourceLocation StartL, SourceLocation IdL,
  1721. IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
  1722. StorageClass S) {
  1723. return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
  1724. }
  1725. VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  1726. return new (C, ID)
  1727. VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
  1728. QualType(), nullptr, SC_None);
  1729. }
  1730. void VarDecl::setStorageClass(StorageClass SC) {
  1731. assert(isLegalForVariable(SC));
  1732. VarDeclBits.SClass = SC;
  1733. }
  1734. VarDecl::TLSKind VarDecl::getTLSKind() const {
  1735. switch (VarDeclBits.TSCSpec) {
  1736. case TSCS_unspecified:
  1737. if (!hasAttr<ThreadAttr>() &&
  1738. !(getASTContext().getLangOpts().OpenMPUseTLS &&
  1739. getASTContext().getTargetInfo().isTLSSupported() &&
  1740. hasAttr<OMPThreadPrivateDeclAttr>()))
  1741. return TLS_None;
  1742. return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
  1743. LangOptions::MSVC2015)) ||
  1744. hasAttr<OMPThreadPrivateDeclAttr>())
  1745. ? TLS_Dynamic
  1746. : TLS_Static;
  1747. case TSCS___thread: // Fall through.
  1748. case TSCS__Thread_local:
  1749. return TLS_Static;
  1750. case TSCS_thread_local:
  1751. return TLS_Dynamic;
  1752. }
  1753. llvm_unreachable("Unknown thread storage class specifier!");
  1754. }
  1755. SourceRange VarDecl::getSourceRange() const {
  1756. if (const Expr *Init = getInit()) {
  1757. SourceLocation InitEnd = Init->getEndLoc();
  1758. // If Init is implicit, ignore its source range and fallback on
  1759. // DeclaratorDecl::getSourceRange() to handle postfix elements.
  1760. if (InitEnd.isValid() && InitEnd != getLocation())
  1761. return SourceRange(getOuterLocStart(), InitEnd);
  1762. }
  1763. return DeclaratorDecl::getSourceRange();
  1764. }
  1765. template<typename T>
  1766. static LanguageLinkage getDeclLanguageLinkage(const T &D) {
  1767. // C++ [dcl.link]p1: All function types, function names with external linkage,
  1768. // and variable names with external linkage have a language linkage.
  1769. if (!D.hasExternalFormalLinkage())
  1770. return NoLanguageLinkage;
  1771. // Language linkage is a C++ concept, but saying that everything else in C has
  1772. // C language linkage fits the implementation nicely.
  1773. ASTContext &Context = D.getASTContext();
  1774. if (!Context.getLangOpts().CPlusPlus)
  1775. return CLanguageLinkage;
  1776. // C++ [dcl.link]p4: A C language linkage is ignored in determining the
  1777. // language linkage of the names of class members and the function type of
  1778. // class member functions.
  1779. const DeclContext *DC = D.getDeclContext();
  1780. if (DC->isRecord())
  1781. return CXXLanguageLinkage;
  1782. // If the first decl is in an extern "C" context, any other redeclaration
  1783. // will have C language linkage. If the first one is not in an extern "C"
  1784. // context, we would have reported an error for any other decl being in one.
  1785. if (isFirstInExternCContext(&D))
  1786. return CLanguageLinkage;
  1787. return CXXLanguageLinkage;
  1788. }
  1789. template<typename T>
  1790. static bool isDeclExternC(const T &D) {
  1791. // Since the context is ignored for class members, they can only have C++
  1792. // language linkage or no language linkage.
  1793. const DeclContext *DC = D.getDeclContext();
  1794. if (DC->isRecord()) {
  1795. assert(D.getASTContext().getLangOpts().CPlusPlus);
  1796. return false;
  1797. }
  1798. return D.getLanguageLinkage() == CLanguageLinkage;
  1799. }
  1800. LanguageLinkage VarDecl::getLanguageLinkage() const {
  1801. return getDeclLanguageLinkage(*this);
  1802. }
  1803. bool VarDecl::isExternC() const {
  1804. return isDeclExternC(*this);
  1805. }
  1806. bool VarDecl::isInExternCContext() const {
  1807. return getLexicalDeclContext()->isExternCContext();
  1808. }
  1809. bool VarDecl::isInExternCXXContext() const {
  1810. return getLexicalDeclContext()->isExternCXXContext();
  1811. }
  1812. VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
  1813. VarDecl::DefinitionKind
  1814. VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
  1815. if (isThisDeclarationADemotedDefinition())
  1816. return DeclarationOnly;
  1817. // C++ [basic.def]p2:
  1818. // A declaration is a definition unless [...] it contains the 'extern'
  1819. // specifier or a linkage-specification and neither an initializer [...],
  1820. // it declares a non-inline static data member in a class declaration [...],
  1821. // it declares a static data member outside a class definition and the variable
  1822. // was defined within the class with the constexpr specifier [...],
  1823. // C++1y [temp.expl.spec]p15:
  1824. // An explicit specialization of a static data member or an explicit
  1825. // specialization of a static data member template is a definition if the
  1826. // declaration includes an initializer; otherwise, it is a declaration.
  1827. //
  1828. // FIXME: How do you declare (but not define) a partial specialization of
  1829. // a static data member template outside the containing class?
  1830. if (isStaticDataMember()) {
  1831. if (isOutOfLine() &&
  1832. !(getCanonicalDecl()->isInline() &&
  1833. getCanonicalDecl()->isConstexpr()) &&
  1834. (hasInit() ||
  1835. // If the first declaration is out-of-line, this may be an
  1836. // instantiation of an out-of-line partial specialization of a variable
  1837. // template for which we have not yet instantiated the initializer.
  1838. (getFirstDecl()->isOutOfLine()
  1839. ? getTemplateSpecializationKind() == TSK_Undeclared
  1840. : getTemplateSpecializationKind() !=
  1841. TSK_ExplicitSpecialization) ||
  1842. isa<VarTemplatePartialSpecializationDecl>(this)))
  1843. return Definition;
  1844. else if (!isOutOfLine() && isInline())
  1845. return Definition;
  1846. else
  1847. return DeclarationOnly;
  1848. }
  1849. // C99 6.7p5:
  1850. // A definition of an identifier is a declaration for that identifier that
  1851. // [...] causes storage to be reserved for that object.
  1852. // Note: that applies for all non-file-scope objects.
  1853. // C99 6.9.2p1:
  1854. // If the declaration of an identifier for an object has file scope and an
  1855. // initializer, the declaration is an external definition for the identifier
  1856. if (hasInit())
  1857. return Definition;
  1858. if (hasDefiningAttr())
  1859. return Definition;
  1860. if (const auto *SAA = getAttr<SelectAnyAttr>())
  1861. if (!SAA->isInherited())
  1862. return Definition;
  1863. // A variable template specialization (other than a static data member
  1864. // template or an explicit specialization) is a declaration until we
  1865. // instantiate its initializer.
  1866. if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
  1867. if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
  1868. !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
  1869. !VTSD->IsCompleteDefinition)
  1870. return DeclarationOnly;
  1871. }
  1872. if (hasExternalStorage())
  1873. return DeclarationOnly;
  1874. // [dcl.link] p7:
  1875. // A declaration directly contained in a linkage-specification is treated
  1876. // as if it contains the extern specifier for the purpose of determining
  1877. // the linkage of the declared name and whether it is a definition.
  1878. if (isSingleLineLanguageLinkage(*this))
  1879. return DeclarationOnly;
  1880. // C99 6.9.2p2:
  1881. // A declaration of an object that has file scope without an initializer,
  1882. // and without a storage class specifier or the scs 'static', constitutes
  1883. // a tentative definition.
  1884. // No such thing in C++.
  1885. if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
  1886. return TentativeDefinition;
  1887. // What's left is (in C, block-scope) declarations without initializers or
  1888. // external storage. These are definitions.
  1889. return Definition;
  1890. }
  1891. VarDecl *VarDecl::getActingDefinition() {
  1892. DefinitionKind Kind = isThisDeclarationADefinition();
  1893. if (Kind != TentativeDefinition)
  1894. return nullptr;
  1895. VarDecl *LastTentative = nullptr;
  1896. VarDecl *First = getFirstDecl();
  1897. for (auto I : First->redecls()) {
  1898. Kind = I->isThisDeclarationADefinition();
  1899. if (Kind == Definition)
  1900. return nullptr;
  1901. else if (Kind == TentativeDefinition)
  1902. LastTentative = I;
  1903. }
  1904. return LastTentative;
  1905. }
  1906. VarDecl *VarDecl::getDefinition(ASTContext &C) {
  1907. VarDecl *First = getFirstDecl();
  1908. for (auto I : First->redecls()) {
  1909. if (I->isThisDeclarationADefinition(C) == Definition)
  1910. return I;
  1911. }
  1912. return nullptr;
  1913. }
  1914. VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
  1915. DefinitionKind Kind = DeclarationOnly;
  1916. const VarDecl *First = getFirstDecl();
  1917. for (auto I : First->redecls()) {
  1918. Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
  1919. if (Kind == Definition)
  1920. break;
  1921. }
  1922. return Kind;
  1923. }
  1924. const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
  1925. for (auto I : redecls()) {
  1926. if (auto Expr = I->getInit()) {
  1927. D = I;
  1928. return Expr;
  1929. }
  1930. }
  1931. return nullptr;
  1932. }
  1933. bool VarDecl::hasInit() const {
  1934. if (auto *P = dyn_cast<ParmVarDecl>(this))
  1935. if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
  1936. return false;
  1937. return !Init.isNull();
  1938. }
  1939. Expr *VarDecl::getInit() {
  1940. if (!hasInit())
  1941. return nullptr;
  1942. if (auto *S = Init.dyn_cast<Stmt *>())
  1943. return cast<Expr>(S);
  1944. return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
  1945. }
  1946. Stmt **VarDecl::getInitAddress() {
  1947. if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
  1948. return &ES->Value;
  1949. return Init.getAddrOfPtr1();
  1950. }
  1951. VarDecl *VarDecl::getInitializingDeclaration() {
  1952. VarDecl *Def = nullptr;
  1953. for (auto I : redecls()) {
  1954. if (I->hasInit())
  1955. return I;
  1956. if (I->isThisDeclarationADefinition()) {
  1957. if (isStaticDataMember())
  1958. return I;
  1959. else
  1960. Def = I;
  1961. }
  1962. }
  1963. return Def;
  1964. }
  1965. bool VarDecl::isOutOfLine() const {
  1966. if (Decl::isOutOfLine())
  1967. return true;
  1968. if (!isStaticDataMember())
  1969. return false;
  1970. // If this static data member was instantiated from a static data member of
  1971. // a class template, check whether that static data member was defined
  1972. // out-of-line.
  1973. if (VarDecl *VD = getInstantiatedFromStaticDataMember())
  1974. return VD->isOutOfLine();
  1975. return false;
  1976. }
  1977. void VarDecl::setInit(Expr *I) {
  1978. if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
  1979. Eval->~EvaluatedStmt();
  1980. getASTContext().Deallocate(Eval);
  1981. }
  1982. Init = I;
  1983. }
  1984. bool VarDecl::mightBeUsableInConstantExpressions(ASTContext &C) const {
  1985. const LangOptions &Lang = C.getLangOpts();
  1986. if (!Lang.CPlusPlus)
  1987. return false;
  1988. // Function parameters are never usable in constant expressions.
  1989. if (isa<ParmVarDecl>(this))
  1990. return false;
  1991. // In C++11, any variable of reference type can be used in a constant
  1992. // expression if it is initialized by a constant expression.
  1993. if (Lang.CPlusPlus11 && getType()->isReferenceType())
  1994. return true;
  1995. // Only const objects can be used in constant expressions in C++. C++98 does
  1996. // not require the variable to be non-volatile, but we consider this to be a
  1997. // defect.
  1998. if (!getType().isConstQualified() || getType().isVolatileQualified())
  1999. return false;
  2000. // In C++, const, non-volatile variables of integral or enumeration types
  2001. // can be used in constant expressions.
  2002. if (getType()->isIntegralOrEnumerationType())
  2003. return true;
  2004. // Additionally, in C++11, non-volatile constexpr variables can be used in
  2005. // constant expressions.
  2006. return Lang.CPlusPlus11 && isConstexpr();
  2007. }
  2008. bool VarDecl::isUsableInConstantExpressions(ASTContext &Context) const {
  2009. // C++2a [expr.const]p3:
  2010. // A variable is usable in constant expressions after its initializing
  2011. // declaration is encountered...
  2012. const VarDecl *DefVD = nullptr;
  2013. const Expr *Init = getAnyInitializer(DefVD);
  2014. if (!Init || Init->isValueDependent() || getType()->isDependentType())
  2015. return false;
  2016. // ... if it is a constexpr variable, or it is of reference type or of
  2017. // const-qualified integral or enumeration type, ...
  2018. if (!DefVD->mightBeUsableInConstantExpressions(Context))
  2019. return false;
  2020. // ... and its initializer is a constant initializer.
  2021. return DefVD->checkInitIsICE();
  2022. }
  2023. /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
  2024. /// form, which contains extra information on the evaluated value of the
  2025. /// initializer.
  2026. EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
  2027. auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
  2028. if (!Eval) {
  2029. // Note: EvaluatedStmt contains an APValue, which usually holds
  2030. // resources not allocated from the ASTContext. We need to do some
  2031. // work to avoid leaking those, but we do so in VarDecl::evaluateValue
  2032. // where we can detect whether there's anything to clean up or not.
  2033. Eval = new (getASTContext()) EvaluatedStmt;
  2034. Eval->Value = Init.get<Stmt *>();
  2035. Init = Eval;
  2036. }
  2037. return Eval;
  2038. }
  2039. APValue *VarDecl::evaluateValue() const {
  2040. SmallVector<PartialDiagnosticAt, 8> Notes;
  2041. return evaluateValue(Notes);
  2042. }
  2043. APValue *VarDecl::evaluateValue(
  2044. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  2045. EvaluatedStmt *Eval = ensureEvaluatedStmt();
  2046. // We only produce notes indicating why an initializer is non-constant the
  2047. // first time it is evaluated. FIXME: The notes won't always be emitted the
  2048. // first time we try evaluation, so might not be produced at all.
  2049. if (Eval->WasEvaluated)
  2050. return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
  2051. const auto *Init = cast<Expr>(Eval->Value);
  2052. assert(!Init->isValueDependent());
  2053. if (Eval->IsEvaluating) {
  2054. // FIXME: Produce a diagnostic for self-initialization.
  2055. Eval->CheckedICE = true;
  2056. Eval->IsICE = false;
  2057. return nullptr;
  2058. }
  2059. Eval->IsEvaluating = true;
  2060. bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
  2061. this, Notes);
  2062. // Ensure the computed APValue is cleaned up later if evaluation succeeded,
  2063. // or that it's empty (so that there's nothing to clean up) if evaluation
  2064. // failed.
  2065. if (!Result)
  2066. Eval->Evaluated = APValue();
  2067. else if (Eval->Evaluated.needsCleanup())
  2068. getASTContext().addDestruction(&Eval->Evaluated);
  2069. Eval->IsEvaluating = false;
  2070. Eval->WasEvaluated = true;
  2071. // In C++11, we have determined whether the initializer was a constant
  2072. // expression as a side-effect.
  2073. if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
  2074. Eval->CheckedICE = true;
  2075. Eval->IsICE = Result && Notes.empty();
  2076. }
  2077. return Result ? &Eval->Evaluated : nullptr;
  2078. }
  2079. APValue *VarDecl::getEvaluatedValue() const {
  2080. if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
  2081. if (Eval->WasEvaluated)
  2082. return &Eval->Evaluated;
  2083. return nullptr;
  2084. }
  2085. bool VarDecl::isInitKnownICE() const {
  2086. if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
  2087. return Eval->CheckedICE;
  2088. return false;
  2089. }
  2090. bool VarDecl::isInitICE() const {
  2091. assert(isInitKnownICE() &&
  2092. "Check whether we already know that the initializer is an ICE");
  2093. return Init.get<EvaluatedStmt *>()->IsICE;
  2094. }
  2095. bool VarDecl::checkInitIsICE() const {
  2096. // Initializers of weak variables are never ICEs.
  2097. if (isWeak())
  2098. return false;
  2099. EvaluatedStmt *Eval = ensureEvaluatedStmt();
  2100. if (Eval->CheckedICE)
  2101. // We have already checked whether this subexpression is an
  2102. // integral constant expression.
  2103. return Eval->IsICE;
  2104. const auto *Init = cast<Expr>(Eval->Value);
  2105. assert(!Init->isValueDependent());
  2106. // In C++11, evaluate the initializer to check whether it's a constant
  2107. // expression.
  2108. if (getASTContext().getLangOpts().CPlusPlus11) {
  2109. SmallVector<PartialDiagnosticAt, 8> Notes;
  2110. evaluateValue(Notes);
  2111. return Eval->IsICE;
  2112. }
  2113. // It's an ICE whether or not the definition we found is
  2114. // out-of-line. See DR 721 and the discussion in Clang PR
  2115. // 6206 for details.
  2116. if (Eval->CheckingICE)
  2117. return false;
  2118. Eval->CheckingICE = true;
  2119. Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
  2120. Eval->CheckingICE = false;
  2121. Eval->CheckedICE = true;
  2122. return Eval->IsICE;
  2123. }
  2124. bool VarDecl::isParameterPack() const {
  2125. return isa<PackExpansionType>(getType());
  2126. }
  2127. template<typename DeclT>
  2128. static DeclT *getDefinitionOrSelf(DeclT *D) {
  2129. assert(D);
  2130. if (auto *Def = D->getDefinition())
  2131. return Def;
  2132. return D;
  2133. }
  2134. bool VarDecl::isEscapingByref() const {
  2135. return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
  2136. }
  2137. bool VarDecl::isNonEscapingByref() const {
  2138. return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
  2139. }
  2140. VarDecl *VarDecl::getTemplateInstantiationPattern() const {
  2141. const VarDecl *VD = this;
  2142. // If this is an instantiated member, walk back to the template from which
  2143. // it was instantiated.
  2144. if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
  2145. if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
  2146. VD = VD->getInstantiatedFromStaticDataMember();
  2147. while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
  2148. VD = NewVD;
  2149. }
  2150. }
  2151. // If it's an instantiated variable template specialization, find the
  2152. // template or partial specialization from which it was instantiated.
  2153. if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
  2154. if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
  2155. auto From = VDTemplSpec->getInstantiatedFrom();
  2156. if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
  2157. while (!VTD->isMemberSpecialization()) {
  2158. auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
  2159. if (!NewVTD)
  2160. break;
  2161. VTD = NewVTD;
  2162. }
  2163. return getDefinitionOrSelf(VTD->getTemplatedDecl());
  2164. }
  2165. if (auto *VTPSD =
  2166. From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
  2167. while (!VTPSD->isMemberSpecialization()) {
  2168. auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
  2169. if (!NewVTPSD)
  2170. break;
  2171. VTPSD = NewVTPSD;
  2172. }
  2173. return getDefinitionOrSelf<VarDecl>(VTPSD);
  2174. }
  2175. }
  2176. }
  2177. // If this is the pattern of a variable template, find where it was
  2178. // instantiated from. FIXME: Is this necessary?
  2179. if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
  2180. while (!VarTemplate->isMemberSpecialization()) {
  2181. auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
  2182. if (!NewVT)
  2183. break;
  2184. VarTemplate = NewVT;
  2185. }
  2186. return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
  2187. }
  2188. if (VD == this)
  2189. return nullptr;
  2190. return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
  2191. }
  2192. VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
  2193. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  2194. return cast<VarDecl>(MSI->getInstantiatedFrom());
  2195. return nullptr;
  2196. }
  2197. TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
  2198. if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
  2199. return Spec->getSpecializationKind();
  2200. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  2201. return MSI->getTemplateSpecializationKind();
  2202. return TSK_Undeclared;
  2203. }
  2204. TemplateSpecializationKind
  2205. VarDecl::getTemplateSpecializationKindForInstantiation() const {
  2206. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  2207. return MSI->getTemplateSpecializationKind();
  2208. if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
  2209. return Spec->getSpecializationKind();
  2210. return TSK_Undeclared;
  2211. }
  2212. SourceLocation VarDecl::getPointOfInstantiation() const {
  2213. if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
  2214. return Spec->getPointOfInstantiation();
  2215. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  2216. return MSI->getPointOfInstantiation();
  2217. return SourceLocation();
  2218. }
  2219. VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
  2220. return getASTContext().getTemplateOrSpecializationInfo(this)
  2221. .dyn_cast<VarTemplateDecl *>();
  2222. }
  2223. void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
  2224. getASTContext().setTemplateOrSpecializationInfo(this, Template);
  2225. }
  2226. bool VarDecl::isKnownToBeDefined() const {
  2227. const auto &LangOpts = getASTContext().getLangOpts();
  2228. // In CUDA mode without relocatable device code, variables of form 'extern
  2229. // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
  2230. // memory pool. These are never undefined variables, even if they appear
  2231. // inside of an anon namespace or static function.
  2232. //
  2233. // With CUDA relocatable device code enabled, these variables don't get
  2234. // special handling; they're treated like regular extern variables.
  2235. if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
  2236. hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
  2237. isa<IncompleteArrayType>(getType()))
  2238. return true;
  2239. return hasDefinition();
  2240. }
  2241. bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
  2242. return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
  2243. (!Ctx.getLangOpts().RegisterStaticDestructors &&
  2244. !hasAttr<AlwaysDestroyAttr>()));
  2245. }
  2246. QualType::DestructionKind
  2247. VarDecl::needsDestruction(const ASTContext &Ctx) const {
  2248. if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
  2249. if (Eval->HasConstantDestruction)
  2250. return QualType::DK_none;
  2251. if (isNoDestroy(Ctx))
  2252. return QualType::DK_none;
  2253. return getType().isDestructedType();
  2254. }
  2255. MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
  2256. if (isStaticDataMember())
  2257. // FIXME: Remove ?
  2258. // return getASTContext().getInstantiatedFromStaticDataMember(this);
  2259. return getASTContext().getTemplateOrSpecializationInfo(this)
  2260. .dyn_cast<MemberSpecializationInfo *>();
  2261. return nullptr;
  2262. }
  2263. void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  2264. SourceLocation PointOfInstantiation) {
  2265. assert((isa<VarTemplateSpecializationDecl>(this) ||
  2266. getMemberSpecializationInfo()) &&
  2267. "not a variable or static data member template specialization");
  2268. if (VarTemplateSpecializationDecl *Spec =
  2269. dyn_cast<VarTemplateSpecializationDecl>(this)) {
  2270. Spec->setSpecializationKind(TSK);
  2271. if (TSK != TSK_ExplicitSpecialization &&
  2272. PointOfInstantiation.isValid() &&
  2273. Spec->getPointOfInstantiation().isInvalid()) {
  2274. Spec->setPointOfInstantiation(PointOfInstantiation);
  2275. if (ASTMutationListener *L = getASTContext().getASTMutationListener())
  2276. L->InstantiationRequested(this);
  2277. }
  2278. } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
  2279. MSI->setTemplateSpecializationKind(TSK);
  2280. if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
  2281. MSI->getPointOfInstantiation().isInvalid()) {
  2282. MSI->setPointOfInstantiation(PointOfInstantiation);
  2283. if (ASTMutationListener *L = getASTContext().getASTMutationListener())
  2284. L->InstantiationRequested(this);
  2285. }
  2286. }
  2287. }
  2288. void
  2289. VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
  2290. TemplateSpecializationKind TSK) {
  2291. assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
  2292. "Previous template or instantiation?");
  2293. getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
  2294. }
  2295. //===----------------------------------------------------------------------===//
  2296. // ParmVarDecl Implementation
  2297. //===----------------------------------------------------------------------===//
  2298. ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
  2299. SourceLocation StartLoc,
  2300. SourceLocation IdLoc, IdentifierInfo *Id,
  2301. QualType T, TypeSourceInfo *TInfo,
  2302. StorageClass S, Expr *DefArg) {
  2303. return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
  2304. S, DefArg);
  2305. }
  2306. QualType ParmVarDecl::getOriginalType() const {
  2307. TypeSourceInfo *TSI = getTypeSourceInfo();
  2308. QualType T = TSI ? TSI->getType() : getType();
  2309. if (const auto *DT = dyn_cast<DecayedType>(T))
  2310. return DT->getOriginalType();
  2311. return T;
  2312. }
  2313. ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2314. return new (C, ID)
  2315. ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
  2316. nullptr, QualType(), nullptr, SC_None, nullptr);
  2317. }
  2318. SourceRange ParmVarDecl::getSourceRange() const {
  2319. if (!hasInheritedDefaultArg()) {
  2320. SourceRange ArgRange = getDefaultArgRange();
  2321. if (ArgRange.isValid())
  2322. return SourceRange(getOuterLocStart(), ArgRange.getEnd());
  2323. }
  2324. // DeclaratorDecl considers the range of postfix types as overlapping with the
  2325. // declaration name, but this is not the case with parameters in ObjC methods.
  2326. if (isa<ObjCMethodDecl>(getDeclContext()))
  2327. return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
  2328. return DeclaratorDecl::getSourceRange();
  2329. }
  2330. Expr *ParmVarDecl::getDefaultArg() {
  2331. assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
  2332. assert(!hasUninstantiatedDefaultArg() &&
  2333. "Default argument is not yet instantiated!");
  2334. Expr *Arg = getInit();
  2335. if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
  2336. return E->getSubExpr();
  2337. return Arg;
  2338. }
  2339. void ParmVarDecl::setDefaultArg(Expr *defarg) {
  2340. ParmVarDeclBits.DefaultArgKind = DAK_Normal;
  2341. Init = defarg;
  2342. }
  2343. SourceRange ParmVarDecl::getDefaultArgRange() const {
  2344. switch (ParmVarDeclBits.DefaultArgKind) {
  2345. case DAK_None:
  2346. case DAK_Unparsed:
  2347. // Nothing we can do here.
  2348. return SourceRange();
  2349. case DAK_Uninstantiated:
  2350. return getUninstantiatedDefaultArg()->getSourceRange();
  2351. case DAK_Normal:
  2352. if (const Expr *E = getInit())
  2353. return E->getSourceRange();
  2354. // Missing an actual expression, may be invalid.
  2355. return SourceRange();
  2356. }
  2357. llvm_unreachable("Invalid default argument kind.");
  2358. }
  2359. void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
  2360. ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
  2361. Init = arg;
  2362. }
  2363. Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
  2364. assert(hasUninstantiatedDefaultArg() &&
  2365. "Wrong kind of initialization expression!");
  2366. return cast_or_null<Expr>(Init.get<Stmt *>());
  2367. }
  2368. bool ParmVarDecl::hasDefaultArg() const {
  2369. // FIXME: We should just return false for DAK_None here once callers are
  2370. // prepared for the case that we encountered an invalid default argument and
  2371. // were unable to even build an invalid expression.
  2372. return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
  2373. !Init.isNull();
  2374. }
  2375. void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
  2376. getASTContext().setParameterIndex(this, parameterIndex);
  2377. ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
  2378. }
  2379. unsigned ParmVarDecl::getParameterIndexLarge() const {
  2380. return getASTContext().getParameterIndex(this);
  2381. }
  2382. //===----------------------------------------------------------------------===//
  2383. // FunctionDecl Implementation
  2384. //===----------------------------------------------------------------------===//
  2385. FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
  2386. SourceLocation StartLoc,
  2387. const DeclarationNameInfo &NameInfo, QualType T,
  2388. TypeSourceInfo *TInfo, StorageClass S,
  2389. bool isInlineSpecified,
  2390. ConstexprSpecKind ConstexprKind)
  2391. : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
  2392. StartLoc),
  2393. DeclContext(DK), redeclarable_base(C), ODRHash(0),
  2394. EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
  2395. assert(T.isNull() || T->isFunctionType());
  2396. FunctionDeclBits.SClass = S;
  2397. FunctionDeclBits.IsInline = isInlineSpecified;
  2398. FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
  2399. FunctionDeclBits.IsVirtualAsWritten = false;
  2400. FunctionDeclBits.IsPure = false;
  2401. FunctionDeclBits.HasInheritedPrototype = false;
  2402. FunctionDeclBits.HasWrittenPrototype = true;
  2403. FunctionDeclBits.IsDeleted = false;
  2404. FunctionDeclBits.IsTrivial = false;
  2405. FunctionDeclBits.IsTrivialForCall = false;
  2406. FunctionDeclBits.IsDefaulted = false;
  2407. FunctionDeclBits.IsExplicitlyDefaulted = false;
  2408. FunctionDeclBits.HasImplicitReturnZero = false;
  2409. FunctionDeclBits.IsLateTemplateParsed = false;
  2410. FunctionDeclBits.ConstexprKind = ConstexprKind;
  2411. FunctionDeclBits.InstantiationIsPending = false;
  2412. FunctionDeclBits.UsesSEHTry = false;
  2413. FunctionDeclBits.HasSkippedBody = false;
  2414. FunctionDeclBits.WillHaveBody = false;
  2415. FunctionDeclBits.IsMultiVersion = false;
  2416. FunctionDeclBits.IsCopyDeductionCandidate = false;
  2417. FunctionDeclBits.HasODRHash = false;
  2418. }
  2419. void FunctionDecl::getNameForDiagnostic(
  2420. raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
  2421. NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
  2422. const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
  2423. if (TemplateArgs)
  2424. printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
  2425. }
  2426. bool FunctionDecl::isVariadic() const {
  2427. if (const auto *FT = getType()->getAs<FunctionProtoType>())
  2428. return FT->isVariadic();
  2429. return false;
  2430. }
  2431. bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
  2432. for (auto I : redecls()) {
  2433. if (I->doesThisDeclarationHaveABody()) {
  2434. Definition = I;
  2435. return true;
  2436. }
  2437. }
  2438. return false;
  2439. }
  2440. bool FunctionDecl::hasTrivialBody() const
  2441. {
  2442. Stmt *S = getBody();
  2443. if (!S) {
  2444. // Since we don't have a body for this function, we don't know if it's
  2445. // trivial or not.
  2446. return false;
  2447. }
  2448. if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
  2449. return true;
  2450. return false;
  2451. }
  2452. bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
  2453. for (auto I : redecls()) {
  2454. if (I->isThisDeclarationADefinition()) {
  2455. Definition = I;
  2456. return true;
  2457. }
  2458. }
  2459. return false;
  2460. }
  2461. Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
  2462. if (!hasBody(Definition))
  2463. return nullptr;
  2464. if (Definition->Body)
  2465. return Definition->Body.get(getASTContext().getExternalSource());
  2466. return nullptr;
  2467. }
  2468. void FunctionDecl::setBody(Stmt *B) {
  2469. Body = B;
  2470. if (B)
  2471. EndRangeLoc = B->getEndLoc();
  2472. }
  2473. void FunctionDecl::setPure(bool P) {
  2474. FunctionDeclBits.IsPure = P;
  2475. if (P)
  2476. if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
  2477. Parent->markedVirtualFunctionPure();
  2478. }
  2479. template<std::size_t Len>
  2480. static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
  2481. IdentifierInfo *II = ND->getIdentifier();
  2482. return II && II->isStr(Str);
  2483. }
  2484. bool FunctionDecl::isMain() const {
  2485. const TranslationUnitDecl *tunit =
  2486. dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
  2487. return tunit &&
  2488. !tunit->getASTContext().getLangOpts().Freestanding &&
  2489. isNamed(this, "main");
  2490. }
  2491. bool FunctionDecl::isMSVCRTEntryPoint() const {
  2492. const TranslationUnitDecl *TUnit =
  2493. dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
  2494. if (!TUnit)
  2495. return false;
  2496. // Even though we aren't really targeting MSVCRT if we are freestanding,
  2497. // semantic analysis for these functions remains the same.
  2498. // MSVCRT entry points only exist on MSVCRT targets.
  2499. if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
  2500. return false;
  2501. // Nameless functions like constructors cannot be entry points.
  2502. if (!getIdentifier())
  2503. return false;
  2504. return llvm::StringSwitch<bool>(getName())
  2505. .Cases("main", // an ANSI console app
  2506. "wmain", // a Unicode console App
  2507. "WinMain", // an ANSI GUI app
  2508. "wWinMain", // a Unicode GUI app
  2509. "DllMain", // a DLL
  2510. true)
  2511. .Default(false);
  2512. }
  2513. bool FunctionDecl::isReservedGlobalPlacementOperator() const {
  2514. assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
  2515. assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
  2516. getDeclName().getCXXOverloadedOperator() == OO_Delete ||
  2517. getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
  2518. getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
  2519. if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
  2520. return false;
  2521. const auto *proto = getType()->castAs<FunctionProtoType>();
  2522. if (proto->getNumParams() != 2 || proto->isVariadic())
  2523. return false;
  2524. ASTContext &Context =
  2525. cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
  2526. ->getASTContext();
  2527. // The result type and first argument type are constant across all
  2528. // these operators. The second argument must be exactly void*.
  2529. return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
  2530. }
  2531. bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const {
  2532. if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
  2533. return false;
  2534. if (getDeclName().getCXXOverloadedOperator() != OO_New &&
  2535. getDeclName().getCXXOverloadedOperator() != OO_Delete &&
  2536. getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
  2537. getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
  2538. return false;
  2539. if (isa<CXXRecordDecl>(getDeclContext()))
  2540. return false;
  2541. // This can only fail for an invalid 'operator new' declaration.
  2542. if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
  2543. return false;
  2544. const auto *FPT = getType()->castAs<FunctionProtoType>();
  2545. if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
  2546. return false;
  2547. // If this is a single-parameter function, it must be a replaceable global
  2548. // allocation or deallocation function.
  2549. if (FPT->getNumParams() == 1)
  2550. return true;
  2551. unsigned Params = 1;
  2552. QualType Ty = FPT->getParamType(Params);
  2553. ASTContext &Ctx = getASTContext();
  2554. auto Consume = [&] {
  2555. ++Params;
  2556. Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
  2557. };
  2558. // In C++14, the next parameter can be a 'std::size_t' for sized delete.
  2559. bool IsSizedDelete = false;
  2560. if (Ctx.getLangOpts().SizedDeallocation &&
  2561. (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
  2562. getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
  2563. Ctx.hasSameType(Ty, Ctx.getSizeType())) {
  2564. IsSizedDelete = true;
  2565. Consume();
  2566. }
  2567. // In C++17, the next parameter can be a 'std::align_val_t' for aligned
  2568. // new/delete.
  2569. if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
  2570. if (IsAligned)
  2571. *IsAligned = true;
  2572. Consume();
  2573. }
  2574. // Finally, if this is not a sized delete, the final parameter can
  2575. // be a 'const std::nothrow_t&'.
  2576. if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
  2577. Ty = Ty->getPointeeType();
  2578. if (Ty.getCVRQualifiers() != Qualifiers::Const)
  2579. return false;
  2580. if (Ty->isNothrowT())
  2581. Consume();
  2582. }
  2583. return Params == FPT->getNumParams();
  2584. }
  2585. bool FunctionDecl::isDestroyingOperatorDelete() const {
  2586. // C++ P0722:
  2587. // Within a class C, a single object deallocation function with signature
  2588. // (T, std::destroying_delete_t, <more params>)
  2589. // is a destroying operator delete.
  2590. if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
  2591. getNumParams() < 2)
  2592. return false;
  2593. auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
  2594. return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
  2595. RD->getIdentifier()->isStr("destroying_delete_t");
  2596. }
  2597. LanguageLinkage FunctionDecl::getLanguageLinkage() const {
  2598. return getDeclLanguageLinkage(*this);
  2599. }
  2600. bool FunctionDecl::isExternC() const {
  2601. return isDeclExternC(*this);
  2602. }
  2603. bool FunctionDecl::isInExternCContext() const {
  2604. if (hasAttr<OpenCLKernelAttr>())
  2605. return true;
  2606. return getLexicalDeclContext()->isExternCContext();
  2607. }
  2608. bool FunctionDecl::isInExternCXXContext() const {
  2609. return getLexicalDeclContext()->isExternCXXContext();
  2610. }
  2611. bool FunctionDecl::isGlobal() const {
  2612. if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
  2613. return Method->isStatic();
  2614. if (getCanonicalDecl()->getStorageClass() == SC_Static)
  2615. return false;
  2616. for (const DeclContext *DC = getDeclContext();
  2617. DC->isNamespace();
  2618. DC = DC->getParent()) {
  2619. if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
  2620. if (!Namespace->getDeclName())
  2621. return false;
  2622. break;
  2623. }
  2624. }
  2625. return true;
  2626. }
  2627. bool FunctionDecl::isNoReturn() const {
  2628. if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
  2629. hasAttr<C11NoReturnAttr>())
  2630. return true;
  2631. if (auto *FnTy = getType()->getAs<FunctionType>())
  2632. return FnTy->getNoReturnAttr();
  2633. return false;
  2634. }
  2635. MultiVersionKind FunctionDecl::getMultiVersionKind() const {
  2636. if (hasAttr<TargetAttr>())
  2637. return MultiVersionKind::Target;
  2638. if (hasAttr<CPUDispatchAttr>())
  2639. return MultiVersionKind::CPUDispatch;
  2640. if (hasAttr<CPUSpecificAttr>())
  2641. return MultiVersionKind::CPUSpecific;
  2642. return MultiVersionKind::None;
  2643. }
  2644. bool FunctionDecl::isCPUDispatchMultiVersion() const {
  2645. return isMultiVersion() && hasAttr<CPUDispatchAttr>();
  2646. }
  2647. bool FunctionDecl::isCPUSpecificMultiVersion() const {
  2648. return isMultiVersion() && hasAttr<CPUSpecificAttr>();
  2649. }
  2650. bool FunctionDecl::isTargetMultiVersion() const {
  2651. return isMultiVersion() && hasAttr<TargetAttr>();
  2652. }
  2653. void
  2654. FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
  2655. redeclarable_base::setPreviousDecl(PrevDecl);
  2656. if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
  2657. FunctionTemplateDecl *PrevFunTmpl
  2658. = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
  2659. assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
  2660. FunTmpl->setPreviousDecl(PrevFunTmpl);
  2661. }
  2662. if (PrevDecl && PrevDecl->isInlined())
  2663. setImplicitlyInline(true);
  2664. }
  2665. FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
  2666. /// Returns a value indicating whether this function corresponds to a builtin
  2667. /// function.
  2668. ///
  2669. /// The function corresponds to a built-in function if it is declared at
  2670. /// translation scope or within an extern "C" block and its name matches with
  2671. /// the name of a builtin. The returned value will be 0 for functions that do
  2672. /// not correspond to a builtin, a value of type \c Builtin::ID if in the
  2673. /// target-independent range \c [1,Builtin::First), or a target-specific builtin
  2674. /// value.
  2675. ///
  2676. /// \param ConsiderWrapperFunctions If true, we should consider wrapper
  2677. /// functions as their wrapped builtins. This shouldn't be done in general, but
  2678. /// it's useful in Sema to diagnose calls to wrappers based on their semantics.
  2679. unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
  2680. if (!getIdentifier())
  2681. return 0;
  2682. unsigned BuiltinID = getIdentifier()->getBuiltinID();
  2683. if (!BuiltinID)
  2684. return 0;
  2685. ASTContext &Context = getASTContext();
  2686. if (Context.getLangOpts().CPlusPlus) {
  2687. const auto *LinkageDecl =
  2688. dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
  2689. // In C++, the first declaration of a builtin is always inside an implicit
  2690. // extern "C".
  2691. // FIXME: A recognised library function may not be directly in an extern "C"
  2692. // declaration, for instance "extern "C" { namespace std { decl } }".
  2693. if (!LinkageDecl) {
  2694. if (BuiltinID == Builtin::BI__GetExceptionInfo &&
  2695. Context.getTargetInfo().getCXXABI().isMicrosoft())
  2696. return Builtin::BI__GetExceptionInfo;
  2697. return 0;
  2698. }
  2699. if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
  2700. return 0;
  2701. }
  2702. // If the function is marked "overloadable", it has a different mangled name
  2703. // and is not the C library function.
  2704. if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>())
  2705. return 0;
  2706. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
  2707. return BuiltinID;
  2708. // This function has the name of a known C library
  2709. // function. Determine whether it actually refers to the C library
  2710. // function or whether it just has the same name.
  2711. // If this is a static function, it's not a builtin.
  2712. if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
  2713. return 0;
  2714. // OpenCL v1.2 s6.9.f - The library functions defined in
  2715. // the C99 standard headers are not available.
  2716. if (Context.getLangOpts().OpenCL &&
  2717. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
  2718. return 0;
  2719. // CUDA does not have device-side standard library. printf and malloc are the
  2720. // only special cases that are supported by device-side runtime.
  2721. if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
  2722. !hasAttr<CUDAHostAttr>() &&
  2723. !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
  2724. return 0;
  2725. return BuiltinID;
  2726. }
  2727. /// getNumParams - Return the number of parameters this function must have
  2728. /// based on its FunctionType. This is the length of the ParamInfo array
  2729. /// after it has been created.
  2730. unsigned FunctionDecl::getNumParams() const {
  2731. const auto *FPT = getType()->getAs<FunctionProtoType>();
  2732. return FPT ? FPT->getNumParams() : 0;
  2733. }
  2734. void FunctionDecl::setParams(ASTContext &C,
  2735. ArrayRef<ParmVarDecl *> NewParamInfo) {
  2736. assert(!ParamInfo && "Already has param info!");
  2737. assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
  2738. // Zero params -> null pointer.
  2739. if (!NewParamInfo.empty()) {
  2740. ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
  2741. std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
  2742. }
  2743. }
  2744. /// getMinRequiredArguments - Returns the minimum number of arguments
  2745. /// needed to call this function. This may be fewer than the number of
  2746. /// function parameters, if some of the parameters have default
  2747. /// arguments (in C++) or are parameter packs (C++11).
  2748. unsigned FunctionDecl::getMinRequiredArguments() const {
  2749. if (!getASTContext().getLangOpts().CPlusPlus)
  2750. return getNumParams();
  2751. unsigned NumRequiredArgs = 0;
  2752. for (auto *Param : parameters())
  2753. if (!Param->isParameterPack() && !Param->hasDefaultArg())
  2754. ++NumRequiredArgs;
  2755. return NumRequiredArgs;
  2756. }
  2757. /// The combination of the extern and inline keywords under MSVC forces
  2758. /// the function to be required.
  2759. ///
  2760. /// Note: This function assumes that we will only get called when isInlined()
  2761. /// would return true for this FunctionDecl.
  2762. bool FunctionDecl::isMSExternInline() const {
  2763. assert(isInlined() && "expected to get called on an inlined function!");
  2764. const ASTContext &Context = getASTContext();
  2765. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  2766. !hasAttr<DLLExportAttr>())
  2767. return false;
  2768. for (const FunctionDecl *FD = getMostRecentDecl(); FD;
  2769. FD = FD->getPreviousDecl())
  2770. if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
  2771. return true;
  2772. return false;
  2773. }
  2774. static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
  2775. if (Redecl->getStorageClass() != SC_Extern)
  2776. return false;
  2777. for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
  2778. FD = FD->getPreviousDecl())
  2779. if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
  2780. return false;
  2781. return true;
  2782. }
  2783. static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
  2784. // Only consider file-scope declarations in this test.
  2785. if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
  2786. return false;
  2787. // Only consider explicit declarations; the presence of a builtin for a
  2788. // libcall shouldn't affect whether a definition is externally visible.
  2789. if (Redecl->isImplicit())
  2790. return false;
  2791. if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
  2792. return true; // Not an inline definition
  2793. return false;
  2794. }
  2795. /// For a function declaration in C or C++, determine whether this
  2796. /// declaration causes the definition to be externally visible.
  2797. ///
  2798. /// For instance, this determines if adding the current declaration to the set
  2799. /// of redeclarations of the given functions causes
  2800. /// isInlineDefinitionExternallyVisible to change from false to true.
  2801. bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
  2802. assert(!doesThisDeclarationHaveABody() &&
  2803. "Must have a declaration without a body.");
  2804. ASTContext &Context = getASTContext();
  2805. if (Context.getLangOpts().MSVCCompat) {
  2806. const FunctionDecl *Definition;
  2807. if (hasBody(Definition) && Definition->isInlined() &&
  2808. redeclForcesDefMSVC(this))
  2809. return true;
  2810. }
  2811. if (Context.getLangOpts().CPlusPlus)
  2812. return false;
  2813. if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
  2814. // With GNU inlining, a declaration with 'inline' but not 'extern', forces
  2815. // an externally visible definition.
  2816. //
  2817. // FIXME: What happens if gnu_inline gets added on after the first
  2818. // declaration?
  2819. if (!isInlineSpecified() || getStorageClass() == SC_Extern)
  2820. return false;
  2821. const FunctionDecl *Prev = this;
  2822. bool FoundBody = false;
  2823. while ((Prev = Prev->getPreviousDecl())) {
  2824. FoundBody |= Prev->Body.isValid();
  2825. if (Prev->Body) {
  2826. // If it's not the case that both 'inline' and 'extern' are
  2827. // specified on the definition, then it is always externally visible.
  2828. if (!Prev->isInlineSpecified() ||
  2829. Prev->getStorageClass() != SC_Extern)
  2830. return false;
  2831. } else if (Prev->isInlineSpecified() &&
  2832. Prev->getStorageClass() != SC_Extern) {
  2833. return false;
  2834. }
  2835. }
  2836. return FoundBody;
  2837. }
  2838. // C99 6.7.4p6:
  2839. // [...] If all of the file scope declarations for a function in a
  2840. // translation unit include the inline function specifier without extern,
  2841. // then the definition in that translation unit is an inline definition.
  2842. if (isInlineSpecified() && getStorageClass() != SC_Extern)
  2843. return false;
  2844. const FunctionDecl *Prev = this;
  2845. bool FoundBody = false;
  2846. while ((Prev = Prev->getPreviousDecl())) {
  2847. FoundBody |= Prev->Body.isValid();
  2848. if (RedeclForcesDefC99(Prev))
  2849. return false;
  2850. }
  2851. return FoundBody;
  2852. }
  2853. SourceRange FunctionDecl::getReturnTypeSourceRange() const {
  2854. const TypeSourceInfo *TSI = getTypeSourceInfo();
  2855. if (!TSI)
  2856. return SourceRange();
  2857. FunctionTypeLoc FTL =
  2858. TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
  2859. if (!FTL)
  2860. return SourceRange();
  2861. // Skip self-referential return types.
  2862. const SourceManager &SM = getASTContext().getSourceManager();
  2863. SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
  2864. SourceLocation Boundary = getNameInfo().getBeginLoc();
  2865. if (RTRange.isInvalid() || Boundary.isInvalid() ||
  2866. !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
  2867. return SourceRange();
  2868. return RTRange;
  2869. }
  2870. SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
  2871. const TypeSourceInfo *TSI = getTypeSourceInfo();
  2872. if (!TSI)
  2873. return SourceRange();
  2874. FunctionTypeLoc FTL =
  2875. TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
  2876. if (!FTL)
  2877. return SourceRange();
  2878. return FTL.getExceptionSpecRange();
  2879. }
  2880. /// For an inline function definition in C, or for a gnu_inline function
  2881. /// in C++, determine whether the definition will be externally visible.
  2882. ///
  2883. /// Inline function definitions are always available for inlining optimizations.
  2884. /// However, depending on the language dialect, declaration specifiers, and
  2885. /// attributes, the definition of an inline function may or may not be
  2886. /// "externally" visible to other translation units in the program.
  2887. ///
  2888. /// In C99, inline definitions are not externally visible by default. However,
  2889. /// if even one of the global-scope declarations is marked "extern inline", the
  2890. /// inline definition becomes externally visible (C99 6.7.4p6).
  2891. ///
  2892. /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
  2893. /// definition, we use the GNU semantics for inline, which are nearly the
  2894. /// opposite of C99 semantics. In particular, "inline" by itself will create
  2895. /// an externally visible symbol, but "extern inline" will not create an
  2896. /// externally visible symbol.
  2897. bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
  2898. assert((doesThisDeclarationHaveABody() || willHaveBody() ||
  2899. hasAttr<AliasAttr>()) &&
  2900. "Must be a function definition");
  2901. assert(isInlined() && "Function must be inline");
  2902. ASTContext &Context = getASTContext();
  2903. if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
  2904. // Note: If you change the logic here, please change
  2905. // doesDeclarationForceExternallyVisibleDefinition as well.
  2906. //
  2907. // If it's not the case that both 'inline' and 'extern' are
  2908. // specified on the definition, then this inline definition is
  2909. // externally visible.
  2910. if (Context.getLangOpts().CPlusPlus)
  2911. return false;
  2912. if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
  2913. return true;
  2914. // If any declaration is 'inline' but not 'extern', then this definition
  2915. // is externally visible.
  2916. for (auto Redecl : redecls()) {
  2917. if (Redecl->isInlineSpecified() &&
  2918. Redecl->getStorageClass() != SC_Extern)
  2919. return true;
  2920. }
  2921. return false;
  2922. }
  2923. // The rest of this function is C-only.
  2924. assert(!Context.getLangOpts().CPlusPlus &&
  2925. "should not use C inline rules in C++");
  2926. // C99 6.7.4p6:
  2927. // [...] If all of the file scope declarations for a function in a
  2928. // translation unit include the inline function specifier without extern,
  2929. // then the definition in that translation unit is an inline definition.
  2930. for (auto Redecl : redecls()) {
  2931. if (RedeclForcesDefC99(Redecl))
  2932. return true;
  2933. }
  2934. // C99 6.7.4p6:
  2935. // An inline definition does not provide an external definition for the
  2936. // function, and does not forbid an external definition in another
  2937. // translation unit.
  2938. return false;
  2939. }
  2940. /// getOverloadedOperator - Which C++ overloaded operator this
  2941. /// function represents, if any.
  2942. OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
  2943. if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
  2944. return getDeclName().getCXXOverloadedOperator();
  2945. else
  2946. return OO_None;
  2947. }
  2948. /// getLiteralIdentifier - The literal suffix identifier this function
  2949. /// represents, if any.
  2950. const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
  2951. if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
  2952. return getDeclName().getCXXLiteralIdentifier();
  2953. else
  2954. return nullptr;
  2955. }
  2956. FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
  2957. if (TemplateOrSpecialization.isNull())
  2958. return TK_NonTemplate;
  2959. if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
  2960. return TK_FunctionTemplate;
  2961. if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
  2962. return TK_MemberSpecialization;
  2963. if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
  2964. return TK_FunctionTemplateSpecialization;
  2965. if (TemplateOrSpecialization.is
  2966. <DependentFunctionTemplateSpecializationInfo*>())
  2967. return TK_DependentFunctionTemplateSpecialization;
  2968. llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
  2969. }
  2970. FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
  2971. if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
  2972. return cast<FunctionDecl>(Info->getInstantiatedFrom());
  2973. return nullptr;
  2974. }
  2975. MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
  2976. if (auto *MSI =
  2977. TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
  2978. return MSI;
  2979. if (auto *FTSI = TemplateOrSpecialization
  2980. .dyn_cast<FunctionTemplateSpecializationInfo *>())
  2981. return FTSI->getMemberSpecializationInfo();
  2982. return nullptr;
  2983. }
  2984. void
  2985. FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
  2986. FunctionDecl *FD,
  2987. TemplateSpecializationKind TSK) {
  2988. assert(TemplateOrSpecialization.isNull() &&
  2989. "Member function is already a specialization");
  2990. MemberSpecializationInfo *Info
  2991. = new (C) MemberSpecializationInfo(FD, TSK);
  2992. TemplateOrSpecialization = Info;
  2993. }
  2994. FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
  2995. return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
  2996. }
  2997. void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
  2998. assert(TemplateOrSpecialization.isNull() &&
  2999. "Member function is already a specialization");
  3000. TemplateOrSpecialization = Template;
  3001. }
  3002. bool FunctionDecl::isImplicitlyInstantiable() const {
  3003. // If the function is invalid, it can't be implicitly instantiated.
  3004. if (isInvalidDecl())
  3005. return false;
  3006. switch (getTemplateSpecializationKindForInstantiation()) {
  3007. case TSK_Undeclared:
  3008. case TSK_ExplicitInstantiationDefinition:
  3009. case TSK_ExplicitSpecialization:
  3010. return false;
  3011. case TSK_ImplicitInstantiation:
  3012. return true;
  3013. case TSK_ExplicitInstantiationDeclaration:
  3014. // Handled below.
  3015. break;
  3016. }
  3017. // Find the actual template from which we will instantiate.
  3018. const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
  3019. bool HasPattern = false;
  3020. if (PatternDecl)
  3021. HasPattern = PatternDecl->hasBody(PatternDecl);
  3022. // C++0x [temp.explicit]p9:
  3023. // Except for inline functions, other explicit instantiation declarations
  3024. // have the effect of suppressing the implicit instantiation of the entity
  3025. // to which they refer.
  3026. if (!HasPattern || !PatternDecl)
  3027. return true;
  3028. return PatternDecl->isInlined();
  3029. }
  3030. bool FunctionDecl::isTemplateInstantiation() const {
  3031. // FIXME: Remove this, it's not clear what it means. (Which template
  3032. // specialization kind?)
  3033. return clang::isTemplateInstantiation(getTemplateSpecializationKind());
  3034. }
  3035. FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
  3036. // If this is a generic lambda call operator specialization, its
  3037. // instantiation pattern is always its primary template's pattern
  3038. // even if its primary template was instantiated from another
  3039. // member template (which happens with nested generic lambdas).
  3040. // Since a lambda's call operator's body is transformed eagerly,
  3041. // we don't have to go hunting for a prototype definition template
  3042. // (i.e. instantiated-from-member-template) to use as an instantiation
  3043. // pattern.
  3044. if (isGenericLambdaCallOperatorSpecialization(
  3045. dyn_cast<CXXMethodDecl>(this))) {
  3046. assert(getPrimaryTemplate() && "not a generic lambda call operator?");
  3047. return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
  3048. }
  3049. if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) {
  3050. if (!clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
  3051. return nullptr;
  3052. return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
  3053. }
  3054. if (!clang::isTemplateInstantiation(getTemplateSpecializationKind()))
  3055. return nullptr;
  3056. if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
  3057. // If we hit a point where the user provided a specialization of this
  3058. // template, we're done looking.
  3059. while (!Primary->isMemberSpecialization()) {
  3060. auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
  3061. if (!NewPrimary)
  3062. break;
  3063. Primary = NewPrimary;
  3064. }
  3065. return getDefinitionOrSelf(Primary->getTemplatedDecl());
  3066. }
  3067. return nullptr;
  3068. }
  3069. FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
  3070. if (FunctionTemplateSpecializationInfo *Info
  3071. = TemplateOrSpecialization
  3072. .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
  3073. return Info->getTemplate();
  3074. }
  3075. return nullptr;
  3076. }
  3077. FunctionTemplateSpecializationInfo *
  3078. FunctionDecl::getTemplateSpecializationInfo() const {
  3079. return TemplateOrSpecialization
  3080. .dyn_cast<FunctionTemplateSpecializationInfo *>();
  3081. }
  3082. const TemplateArgumentList *
  3083. FunctionDecl::getTemplateSpecializationArgs() const {
  3084. if (FunctionTemplateSpecializationInfo *Info
  3085. = TemplateOrSpecialization
  3086. .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
  3087. return Info->TemplateArguments;
  3088. }
  3089. return nullptr;
  3090. }
  3091. const ASTTemplateArgumentListInfo *
  3092. FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
  3093. if (FunctionTemplateSpecializationInfo *Info
  3094. = TemplateOrSpecialization
  3095. .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
  3096. return Info->TemplateArgumentsAsWritten;
  3097. }
  3098. return nullptr;
  3099. }
  3100. void
  3101. FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
  3102. FunctionTemplateDecl *Template,
  3103. const TemplateArgumentList *TemplateArgs,
  3104. void *InsertPos,
  3105. TemplateSpecializationKind TSK,
  3106. const TemplateArgumentListInfo *TemplateArgsAsWritten,
  3107. SourceLocation PointOfInstantiation) {
  3108. assert((TemplateOrSpecialization.isNull() ||
  3109. TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
  3110. "Member function is already a specialization");
  3111. assert(TSK != TSK_Undeclared &&
  3112. "Must specify the type of function template specialization");
  3113. assert((TemplateOrSpecialization.isNull() ||
  3114. TSK == TSK_ExplicitSpecialization) &&
  3115. "Member specialization must be an explicit specialization");
  3116. FunctionTemplateSpecializationInfo *Info =
  3117. FunctionTemplateSpecializationInfo::Create(
  3118. C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
  3119. PointOfInstantiation,
  3120. TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
  3121. TemplateOrSpecialization = Info;
  3122. Template->addSpecialization(Info, InsertPos);
  3123. }
  3124. void
  3125. FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
  3126. const UnresolvedSetImpl &Templates,
  3127. const TemplateArgumentListInfo &TemplateArgs) {
  3128. assert(TemplateOrSpecialization.isNull());
  3129. DependentFunctionTemplateSpecializationInfo *Info =
  3130. DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
  3131. TemplateArgs);
  3132. TemplateOrSpecialization = Info;
  3133. }
  3134. DependentFunctionTemplateSpecializationInfo *
  3135. FunctionDecl::getDependentSpecializationInfo() const {
  3136. return TemplateOrSpecialization
  3137. .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
  3138. }
  3139. DependentFunctionTemplateSpecializationInfo *
  3140. DependentFunctionTemplateSpecializationInfo::Create(
  3141. ASTContext &Context, const UnresolvedSetImpl &Ts,
  3142. const TemplateArgumentListInfo &TArgs) {
  3143. void *Buffer = Context.Allocate(
  3144. totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
  3145. TArgs.size(), Ts.size()));
  3146. return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
  3147. }
  3148. DependentFunctionTemplateSpecializationInfo::
  3149. DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
  3150. const TemplateArgumentListInfo &TArgs)
  3151. : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
  3152. NumTemplates = Ts.size();
  3153. NumArgs = TArgs.size();
  3154. FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
  3155. for (unsigned I = 0, E = Ts.size(); I != E; ++I)
  3156. TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
  3157. TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
  3158. for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
  3159. new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
  3160. }
  3161. TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
  3162. // For a function template specialization, query the specialization
  3163. // information object.
  3164. if (FunctionTemplateSpecializationInfo *FTSInfo =
  3165. TemplateOrSpecialization
  3166. .dyn_cast<FunctionTemplateSpecializationInfo *>())
  3167. return FTSInfo->getTemplateSpecializationKind();
  3168. if (MemberSpecializationInfo *MSInfo =
  3169. TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
  3170. return MSInfo->getTemplateSpecializationKind();
  3171. return TSK_Undeclared;
  3172. }
  3173. TemplateSpecializationKind
  3174. FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
  3175. // This is the same as getTemplateSpecializationKind(), except that for a
  3176. // function that is both a function template specialization and a member
  3177. // specialization, we prefer the member specialization information. Eg:
  3178. //
  3179. // template<typename T> struct A {
  3180. // template<typename U> void f() {}
  3181. // template<> void f<int>() {}
  3182. // };
  3183. //
  3184. // For A<int>::f<int>():
  3185. // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
  3186. // * getTemplateSpecializationKindForInstantiation() will return
  3187. // TSK_ImplicitInstantiation
  3188. //
  3189. // This reflects the facts that A<int>::f<int> is an explicit specialization
  3190. // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
  3191. // from A::f<int> if a definition is needed.
  3192. if (FunctionTemplateSpecializationInfo *FTSInfo =
  3193. TemplateOrSpecialization
  3194. .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
  3195. if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
  3196. return MSInfo->getTemplateSpecializationKind();
  3197. return FTSInfo->getTemplateSpecializationKind();
  3198. }
  3199. if (MemberSpecializationInfo *MSInfo =
  3200. TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
  3201. return MSInfo->getTemplateSpecializationKind();
  3202. return TSK_Undeclared;
  3203. }
  3204. void
  3205. FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  3206. SourceLocation PointOfInstantiation) {
  3207. if (FunctionTemplateSpecializationInfo *FTSInfo
  3208. = TemplateOrSpecialization.dyn_cast<
  3209. FunctionTemplateSpecializationInfo*>()) {
  3210. FTSInfo->setTemplateSpecializationKind(TSK);
  3211. if (TSK != TSK_ExplicitSpecialization &&
  3212. PointOfInstantiation.isValid() &&
  3213. FTSInfo->getPointOfInstantiation().isInvalid()) {
  3214. FTSInfo->setPointOfInstantiation(PointOfInstantiation);
  3215. if (ASTMutationListener *L = getASTContext().getASTMutationListener())
  3216. L->InstantiationRequested(this);
  3217. }
  3218. } else if (MemberSpecializationInfo *MSInfo
  3219. = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
  3220. MSInfo->setTemplateSpecializationKind(TSK);
  3221. if (TSK != TSK_ExplicitSpecialization &&
  3222. PointOfInstantiation.isValid() &&
  3223. MSInfo->getPointOfInstantiation().isInvalid()) {
  3224. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  3225. if (ASTMutationListener *L = getASTContext().getASTMutationListener())
  3226. L->InstantiationRequested(this);
  3227. }
  3228. } else
  3229. llvm_unreachable("Function cannot have a template specialization kind");
  3230. }
  3231. SourceLocation FunctionDecl::getPointOfInstantiation() const {
  3232. if (FunctionTemplateSpecializationInfo *FTSInfo
  3233. = TemplateOrSpecialization.dyn_cast<
  3234. FunctionTemplateSpecializationInfo*>())
  3235. return FTSInfo->getPointOfInstantiation();
  3236. else if (MemberSpecializationInfo *MSInfo
  3237. = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
  3238. return MSInfo->getPointOfInstantiation();
  3239. return SourceLocation();
  3240. }
  3241. bool FunctionDecl::isOutOfLine() const {
  3242. if (Decl::isOutOfLine())
  3243. return true;
  3244. // If this function was instantiated from a member function of a
  3245. // class template, check whether that member function was defined out-of-line.
  3246. if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
  3247. const FunctionDecl *Definition;
  3248. if (FD->hasBody(Definition))
  3249. return Definition->isOutOfLine();
  3250. }
  3251. // If this function was instantiated from a function template,
  3252. // check whether that function template was defined out-of-line.
  3253. if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
  3254. const FunctionDecl *Definition;
  3255. if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
  3256. return Definition->isOutOfLine();
  3257. }
  3258. return false;
  3259. }
  3260. SourceRange FunctionDecl::getSourceRange() const {
  3261. return SourceRange(getOuterLocStart(), EndRangeLoc);
  3262. }
  3263. unsigned FunctionDecl::getMemoryFunctionKind() const {
  3264. IdentifierInfo *FnInfo = getIdentifier();
  3265. if (!FnInfo)
  3266. return 0;
  3267. // Builtin handling.
  3268. switch (getBuiltinID()) {
  3269. case Builtin::BI__builtin_memset:
  3270. case Builtin::BI__builtin___memset_chk:
  3271. case Builtin::BImemset:
  3272. return Builtin::BImemset;
  3273. case Builtin::BI__builtin_memcpy:
  3274. case Builtin::BI__builtin___memcpy_chk:
  3275. case Builtin::BImemcpy:
  3276. return Builtin::BImemcpy;
  3277. case Builtin::BI__builtin_memmove:
  3278. case Builtin::BI__builtin___memmove_chk:
  3279. case Builtin::BImemmove:
  3280. return Builtin::BImemmove;
  3281. case Builtin::BIstrlcpy:
  3282. case Builtin::BI__builtin___strlcpy_chk:
  3283. return Builtin::BIstrlcpy;
  3284. case Builtin::BIstrlcat:
  3285. case Builtin::BI__builtin___strlcat_chk:
  3286. return Builtin::BIstrlcat;
  3287. case Builtin::BI__builtin_memcmp:
  3288. case Builtin::BImemcmp:
  3289. return Builtin::BImemcmp;
  3290. case Builtin::BI__builtin_bcmp:
  3291. case Builtin::BIbcmp:
  3292. return Builtin::BIbcmp;
  3293. case Builtin::BI__builtin_strncpy:
  3294. case Builtin::BI__builtin___strncpy_chk:
  3295. case Builtin::BIstrncpy:
  3296. return Builtin::BIstrncpy;
  3297. case Builtin::BI__builtin_strncmp:
  3298. case Builtin::BIstrncmp:
  3299. return Builtin::BIstrncmp;
  3300. case Builtin::BI__builtin_strncasecmp:
  3301. case Builtin::BIstrncasecmp:
  3302. return Builtin::BIstrncasecmp;
  3303. case Builtin::BI__builtin_strncat:
  3304. case Builtin::BI__builtin___strncat_chk:
  3305. case Builtin::BIstrncat:
  3306. return Builtin::BIstrncat;
  3307. case Builtin::BI__builtin_strndup:
  3308. case Builtin::BIstrndup:
  3309. return Builtin::BIstrndup;
  3310. case Builtin::BI__builtin_strlen:
  3311. case Builtin::BIstrlen:
  3312. return Builtin::BIstrlen;
  3313. case Builtin::BI__builtin_bzero:
  3314. case Builtin::BIbzero:
  3315. return Builtin::BIbzero;
  3316. default:
  3317. if (isExternC()) {
  3318. if (FnInfo->isStr("memset"))
  3319. return Builtin::BImemset;
  3320. else if (FnInfo->isStr("memcpy"))
  3321. return Builtin::BImemcpy;
  3322. else if (FnInfo->isStr("memmove"))
  3323. return Builtin::BImemmove;
  3324. else if (FnInfo->isStr("memcmp"))
  3325. return Builtin::BImemcmp;
  3326. else if (FnInfo->isStr("bcmp"))
  3327. return Builtin::BIbcmp;
  3328. else if (FnInfo->isStr("strncpy"))
  3329. return Builtin::BIstrncpy;
  3330. else if (FnInfo->isStr("strncmp"))
  3331. return Builtin::BIstrncmp;
  3332. else if (FnInfo->isStr("strncasecmp"))
  3333. return Builtin::BIstrncasecmp;
  3334. else if (FnInfo->isStr("strncat"))
  3335. return Builtin::BIstrncat;
  3336. else if (FnInfo->isStr("strndup"))
  3337. return Builtin::BIstrndup;
  3338. else if (FnInfo->isStr("strlen"))
  3339. return Builtin::BIstrlen;
  3340. else if (FnInfo->isStr("bzero"))
  3341. return Builtin::BIbzero;
  3342. }
  3343. break;
  3344. }
  3345. return 0;
  3346. }
  3347. unsigned FunctionDecl::getODRHash() const {
  3348. assert(hasODRHash());
  3349. return ODRHash;
  3350. }
  3351. unsigned FunctionDecl::getODRHash() {
  3352. if (hasODRHash())
  3353. return ODRHash;
  3354. if (auto *FT = getInstantiatedFromMemberFunction()) {
  3355. setHasODRHash(true);
  3356. ODRHash = FT->getODRHash();
  3357. return ODRHash;
  3358. }
  3359. class ODRHash Hash;
  3360. Hash.AddFunctionDecl(this);
  3361. setHasODRHash(true);
  3362. ODRHash = Hash.CalculateHash();
  3363. return ODRHash;
  3364. }
  3365. //===----------------------------------------------------------------------===//
  3366. // FieldDecl Implementation
  3367. //===----------------------------------------------------------------------===//
  3368. FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
  3369. SourceLocation StartLoc, SourceLocation IdLoc,
  3370. IdentifierInfo *Id, QualType T,
  3371. TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
  3372. InClassInitStyle InitStyle) {
  3373. return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
  3374. BW, Mutable, InitStyle);
  3375. }
  3376. FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3377. return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
  3378. SourceLocation(), nullptr, QualType(), nullptr,
  3379. nullptr, false, ICIS_NoInit);
  3380. }
  3381. bool FieldDecl::isAnonymousStructOrUnion() const {
  3382. if (!isImplicit() || getDeclName())
  3383. return false;
  3384. if (const auto *Record = getType()->getAs<RecordType>())
  3385. return Record->getDecl()->isAnonymousStructOrUnion();
  3386. return false;
  3387. }
  3388. unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
  3389. assert(isBitField() && "not a bitfield");
  3390. return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
  3391. }
  3392. bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
  3393. return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
  3394. getBitWidthValue(Ctx) == 0;
  3395. }
  3396. bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
  3397. if (isZeroLengthBitField(Ctx))
  3398. return true;
  3399. // C++2a [intro.object]p7:
  3400. // An object has nonzero size if it
  3401. // -- is not a potentially-overlapping subobject, or
  3402. if (!hasAttr<NoUniqueAddressAttr>())
  3403. return false;
  3404. // -- is not of class type, or
  3405. const auto *RT = getType()->getAs<RecordType>();
  3406. if (!RT)
  3407. return false;
  3408. const RecordDecl *RD = RT->getDecl()->getDefinition();
  3409. if (!RD) {
  3410. assert(isInvalidDecl() && "valid field has incomplete type");
  3411. return false;
  3412. }
  3413. // -- [has] virtual member functions or virtual base classes, or
  3414. // -- has subobjects of nonzero size or bit-fields of nonzero length
  3415. const auto *CXXRD = cast<CXXRecordDecl>(RD);
  3416. if (!CXXRD->isEmpty())
  3417. return false;
  3418. // Otherwise, [...] the circumstances under which the object has zero size
  3419. // are implementation-defined.
  3420. // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
  3421. // ABI will do.
  3422. return true;
  3423. }
  3424. unsigned FieldDecl::getFieldIndex() const {
  3425. const FieldDecl *Canonical = getCanonicalDecl();
  3426. if (Canonical != this)
  3427. return Canonical->getFieldIndex();
  3428. if (CachedFieldIndex) return CachedFieldIndex - 1;
  3429. unsigned Index = 0;
  3430. const RecordDecl *RD = getParent()->getDefinition();
  3431. assert(RD && "requested index for field of struct with no definition");
  3432. for (auto *Field : RD->fields()) {
  3433. Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
  3434. ++Index;
  3435. }
  3436. assert(CachedFieldIndex && "failed to find field in parent");
  3437. return CachedFieldIndex - 1;
  3438. }
  3439. SourceRange FieldDecl::getSourceRange() const {
  3440. const Expr *FinalExpr = getInClassInitializer();
  3441. if (!FinalExpr)
  3442. FinalExpr = getBitWidth();
  3443. if (FinalExpr)
  3444. return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
  3445. return DeclaratorDecl::getSourceRange();
  3446. }
  3447. void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
  3448. assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
  3449. "capturing type in non-lambda or captured record.");
  3450. assert(InitStorage.getInt() == ISK_NoInit &&
  3451. InitStorage.getPointer() == nullptr &&
  3452. "bit width, initializer or captured type already set");
  3453. InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
  3454. ISK_CapturedVLAType);
  3455. }
  3456. //===----------------------------------------------------------------------===//
  3457. // TagDecl Implementation
  3458. //===----------------------------------------------------------------------===//
  3459. TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
  3460. SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
  3461. SourceLocation StartL)
  3462. : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
  3463. TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
  3464. assert((DK != Enum || TK == TTK_Enum) &&
  3465. "EnumDecl not matched with TTK_Enum");
  3466. setPreviousDecl(PrevDecl);
  3467. setTagKind(TK);
  3468. setCompleteDefinition(false);
  3469. setBeingDefined(false);
  3470. setEmbeddedInDeclarator(false);
  3471. setFreeStanding(false);
  3472. setCompleteDefinitionRequired(false);
  3473. }
  3474. SourceLocation TagDecl::getOuterLocStart() const {
  3475. return getTemplateOrInnerLocStart(this);
  3476. }
  3477. SourceRange TagDecl::getSourceRange() const {
  3478. SourceLocation RBraceLoc = BraceRange.getEnd();
  3479. SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
  3480. return SourceRange(getOuterLocStart(), E);
  3481. }
  3482. TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
  3483. void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
  3484. TypedefNameDeclOrQualifier = TDD;
  3485. if (const Type *T = getTypeForDecl()) {
  3486. (void)T;
  3487. assert(T->isLinkageValid());
  3488. }
  3489. assert(isLinkageValid());
  3490. }
  3491. void TagDecl::startDefinition() {
  3492. setBeingDefined(true);
  3493. if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
  3494. struct CXXRecordDecl::DefinitionData *Data =
  3495. new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
  3496. for (auto I : redecls())
  3497. cast<CXXRecordDecl>(I)->DefinitionData = Data;
  3498. }
  3499. }
  3500. void TagDecl::completeDefinition() {
  3501. assert((!isa<CXXRecordDecl>(this) ||
  3502. cast<CXXRecordDecl>(this)->hasDefinition()) &&
  3503. "definition completed but not started");
  3504. setCompleteDefinition(true);
  3505. setBeingDefined(false);
  3506. if (ASTMutationListener *L = getASTMutationListener())
  3507. L->CompletedTagDefinition(this);
  3508. }
  3509. TagDecl *TagDecl::getDefinition() const {
  3510. if (isCompleteDefinition())
  3511. return const_cast<TagDecl *>(this);
  3512. // If it's possible for us to have an out-of-date definition, check now.
  3513. if (mayHaveOutOfDateDef()) {
  3514. if (IdentifierInfo *II = getIdentifier()) {
  3515. if (II->isOutOfDate()) {
  3516. updateOutOfDate(*II);
  3517. }
  3518. }
  3519. }
  3520. if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
  3521. return CXXRD->getDefinition();
  3522. for (auto R : redecls())
  3523. if (R->isCompleteDefinition())
  3524. return R;
  3525. return nullptr;
  3526. }
  3527. void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
  3528. if (QualifierLoc) {
  3529. // Make sure the extended qualifier info is allocated.
  3530. if (!hasExtInfo())
  3531. TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
  3532. // Set qualifier info.
  3533. getExtInfo()->QualifierLoc = QualifierLoc;
  3534. } else {
  3535. // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
  3536. if (hasExtInfo()) {
  3537. if (getExtInfo()->NumTemplParamLists == 0) {
  3538. getASTContext().Deallocate(getExtInfo());
  3539. TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
  3540. }
  3541. else
  3542. getExtInfo()->QualifierLoc = QualifierLoc;
  3543. }
  3544. }
  3545. }
  3546. void TagDecl::setTemplateParameterListsInfo(
  3547. ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
  3548. assert(!TPLists.empty());
  3549. // Make sure the extended decl info is allocated.
  3550. if (!hasExtInfo())
  3551. // Allocate external info struct.
  3552. TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
  3553. // Set the template parameter lists info.
  3554. getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
  3555. }
  3556. //===----------------------------------------------------------------------===//
  3557. // EnumDecl Implementation
  3558. //===----------------------------------------------------------------------===//
  3559. EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  3560. SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
  3561. bool Scoped, bool ScopedUsingClassTag, bool Fixed)
  3562. : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
  3563. assert(Scoped || !ScopedUsingClassTag);
  3564. IntegerType = nullptr;
  3565. setNumPositiveBits(0);
  3566. setNumNegativeBits(0);
  3567. setScoped(Scoped);
  3568. setScopedUsingClassTag(ScopedUsingClassTag);
  3569. setFixed(Fixed);
  3570. setHasODRHash(false);
  3571. ODRHash = 0;
  3572. }
  3573. void EnumDecl::anchor() {}
  3574. EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
  3575. SourceLocation StartLoc, SourceLocation IdLoc,
  3576. IdentifierInfo *Id,
  3577. EnumDecl *PrevDecl, bool IsScoped,
  3578. bool IsScopedUsingClassTag, bool IsFixed) {
  3579. auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
  3580. IsScoped, IsScopedUsingClassTag, IsFixed);
  3581. Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
  3582. C.getTypeDeclType(Enum, PrevDecl);
  3583. return Enum;
  3584. }
  3585. EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3586. EnumDecl *Enum =
  3587. new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
  3588. nullptr, nullptr, false, false, false);
  3589. Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
  3590. return Enum;
  3591. }
  3592. SourceRange EnumDecl::getIntegerTypeRange() const {
  3593. if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
  3594. return TI->getTypeLoc().getSourceRange();
  3595. return SourceRange();
  3596. }
  3597. void EnumDecl::completeDefinition(QualType NewType,
  3598. QualType NewPromotionType,
  3599. unsigned NumPositiveBits,
  3600. unsigned NumNegativeBits) {
  3601. assert(!isCompleteDefinition() && "Cannot redefine enums!");
  3602. if (!IntegerType)
  3603. IntegerType = NewType.getTypePtr();
  3604. PromotionType = NewPromotionType;
  3605. setNumPositiveBits(NumPositiveBits);
  3606. setNumNegativeBits(NumNegativeBits);
  3607. TagDecl::completeDefinition();
  3608. }
  3609. bool EnumDecl::isClosed() const {
  3610. if (const auto *A = getAttr<EnumExtensibilityAttr>())
  3611. return A->getExtensibility() == EnumExtensibilityAttr::Closed;
  3612. return true;
  3613. }
  3614. bool EnumDecl::isClosedFlag() const {
  3615. return isClosed() && hasAttr<FlagEnumAttr>();
  3616. }
  3617. bool EnumDecl::isClosedNonFlag() const {
  3618. return isClosed() && !hasAttr<FlagEnumAttr>();
  3619. }
  3620. TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
  3621. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  3622. return MSI->getTemplateSpecializationKind();
  3623. return TSK_Undeclared;
  3624. }
  3625. void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  3626. SourceLocation PointOfInstantiation) {
  3627. MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
  3628. assert(MSI && "Not an instantiated member enumeration?");
  3629. MSI->setTemplateSpecializationKind(TSK);
  3630. if (TSK != TSK_ExplicitSpecialization &&
  3631. PointOfInstantiation.isValid() &&
  3632. MSI->getPointOfInstantiation().isInvalid())
  3633. MSI->setPointOfInstantiation(PointOfInstantiation);
  3634. }
  3635. EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
  3636. if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
  3637. if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
  3638. EnumDecl *ED = getInstantiatedFromMemberEnum();
  3639. while (auto *NewED = ED->getInstantiatedFromMemberEnum())
  3640. ED = NewED;
  3641. return getDefinitionOrSelf(ED);
  3642. }
  3643. }
  3644. assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
  3645. "couldn't find pattern for enum instantiation");
  3646. return nullptr;
  3647. }
  3648. EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
  3649. if (SpecializationInfo)
  3650. return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
  3651. return nullptr;
  3652. }
  3653. void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
  3654. TemplateSpecializationKind TSK) {
  3655. assert(!SpecializationInfo && "Member enum is already a specialization");
  3656. SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
  3657. }
  3658. unsigned EnumDecl::getODRHash() {
  3659. if (hasODRHash())
  3660. return ODRHash;
  3661. class ODRHash Hash;
  3662. Hash.AddEnumDecl(this);
  3663. setHasODRHash(true);
  3664. ODRHash = Hash.CalculateHash();
  3665. return ODRHash;
  3666. }
  3667. //===----------------------------------------------------------------------===//
  3668. // RecordDecl Implementation
  3669. //===----------------------------------------------------------------------===//
  3670. RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
  3671. DeclContext *DC, SourceLocation StartLoc,
  3672. SourceLocation IdLoc, IdentifierInfo *Id,
  3673. RecordDecl *PrevDecl)
  3674. : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
  3675. assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
  3676. setHasFlexibleArrayMember(false);
  3677. setAnonymousStructOrUnion(false);
  3678. setHasObjectMember(false);
  3679. setHasVolatileMember(false);
  3680. setHasLoadedFieldsFromExternalStorage(false);
  3681. setNonTrivialToPrimitiveDefaultInitialize(false);
  3682. setNonTrivialToPrimitiveCopy(false);
  3683. setNonTrivialToPrimitiveDestroy(false);
  3684. setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
  3685. setHasNonTrivialToPrimitiveDestructCUnion(false);
  3686. setHasNonTrivialToPrimitiveCopyCUnion(false);
  3687. setParamDestroyedInCallee(false);
  3688. setArgPassingRestrictions(APK_CanPassInRegs);
  3689. }
  3690. RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
  3691. SourceLocation StartLoc, SourceLocation IdLoc,
  3692. IdentifierInfo *Id, RecordDecl* PrevDecl) {
  3693. RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
  3694. StartLoc, IdLoc, Id, PrevDecl);
  3695. R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
  3696. C.getTypeDeclType(R, PrevDecl);
  3697. return R;
  3698. }
  3699. RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
  3700. RecordDecl *R =
  3701. new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
  3702. SourceLocation(), nullptr, nullptr);
  3703. R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
  3704. return R;
  3705. }
  3706. bool RecordDecl::isInjectedClassName() const {
  3707. return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
  3708. cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
  3709. }
  3710. bool RecordDecl::isLambda() const {
  3711. if (auto RD = dyn_cast<CXXRecordDecl>(this))
  3712. return RD->isLambda();
  3713. return false;
  3714. }
  3715. bool RecordDecl::isCapturedRecord() const {
  3716. return hasAttr<CapturedRecordAttr>();
  3717. }
  3718. void RecordDecl::setCapturedRecord() {
  3719. addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
  3720. }
  3721. RecordDecl::field_iterator RecordDecl::field_begin() const {
  3722. if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
  3723. LoadFieldsFromExternalStorage();
  3724. return field_iterator(decl_iterator(FirstDecl));
  3725. }
  3726. /// completeDefinition - Notes that the definition of this type is now
  3727. /// complete.
  3728. void RecordDecl::completeDefinition() {
  3729. assert(!isCompleteDefinition() && "Cannot redefine record!");
  3730. TagDecl::completeDefinition();
  3731. }
  3732. /// isMsStruct - Get whether or not this record uses ms_struct layout.
  3733. /// This which can be turned on with an attribute, pragma, or the
  3734. /// -mms-bitfields command-line option.
  3735. bool RecordDecl::isMsStruct(const ASTContext &C) const {
  3736. return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
  3737. }
  3738. void RecordDecl::LoadFieldsFromExternalStorage() const {
  3739. ExternalASTSource *Source = getASTContext().getExternalSource();
  3740. assert(hasExternalLexicalStorage() && Source && "No external storage?");
  3741. // Notify that we have a RecordDecl doing some initialization.
  3742. ExternalASTSource::Deserializing TheFields(Source);
  3743. SmallVector<Decl*, 64> Decls;
  3744. setHasLoadedFieldsFromExternalStorage(true);
  3745. Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
  3746. return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
  3747. }, Decls);
  3748. #ifndef NDEBUG
  3749. // Check that all decls we got were FieldDecls.
  3750. for (unsigned i=0, e=Decls.size(); i != e; ++i)
  3751. assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
  3752. #endif
  3753. if (Decls.empty())
  3754. return;
  3755. std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
  3756. /*FieldsAlreadyLoaded=*/false);
  3757. }
  3758. bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
  3759. ASTContext &Context = getASTContext();
  3760. const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
  3761. (SanitizerKind::Address | SanitizerKind::KernelAddress);
  3762. if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
  3763. return false;
  3764. const auto &Blacklist = Context.getSanitizerBlacklist();
  3765. const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
  3766. // We may be able to relax some of these requirements.
  3767. int ReasonToReject = -1;
  3768. if (!CXXRD || CXXRD->isExternCContext())
  3769. ReasonToReject = 0; // is not C++.
  3770. else if (CXXRD->hasAttr<PackedAttr>())
  3771. ReasonToReject = 1; // is packed.
  3772. else if (CXXRD->isUnion())
  3773. ReasonToReject = 2; // is a union.
  3774. else if (CXXRD->isTriviallyCopyable())
  3775. ReasonToReject = 3; // is trivially copyable.
  3776. else if (CXXRD->hasTrivialDestructor())
  3777. ReasonToReject = 4; // has trivial destructor.
  3778. else if (CXXRD->isStandardLayout())
  3779. ReasonToReject = 5; // is standard layout.
  3780. else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
  3781. "field-padding"))
  3782. ReasonToReject = 6; // is in a blacklisted file.
  3783. else if (Blacklist.isBlacklistedType(EnabledAsanMask,
  3784. getQualifiedNameAsString(),
  3785. "field-padding"))
  3786. ReasonToReject = 7; // is blacklisted.
  3787. if (EmitRemark) {
  3788. if (ReasonToReject >= 0)
  3789. Context.getDiagnostics().Report(
  3790. getLocation(),
  3791. diag::remark_sanitize_address_insert_extra_padding_rejected)
  3792. << getQualifiedNameAsString() << ReasonToReject;
  3793. else
  3794. Context.getDiagnostics().Report(
  3795. getLocation(),
  3796. diag::remark_sanitize_address_insert_extra_padding_accepted)
  3797. << getQualifiedNameAsString();
  3798. }
  3799. return ReasonToReject < 0;
  3800. }
  3801. const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
  3802. for (const auto *I : fields()) {
  3803. if (I->getIdentifier())
  3804. return I;
  3805. if (const auto *RT = I->getType()->getAs<RecordType>())
  3806. if (const FieldDecl *NamedDataMember =
  3807. RT->getDecl()->findFirstNamedDataMember())
  3808. return NamedDataMember;
  3809. }
  3810. // We didn't find a named data member.
  3811. return nullptr;
  3812. }
  3813. //===----------------------------------------------------------------------===//
  3814. // BlockDecl Implementation
  3815. //===----------------------------------------------------------------------===//
  3816. BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
  3817. : Decl(Block, DC, CaretLoc), DeclContext(Block) {
  3818. setIsVariadic(false);
  3819. setCapturesCXXThis(false);
  3820. setBlockMissingReturnType(true);
  3821. setIsConversionFromLambda(false);
  3822. setDoesNotEscape(false);
  3823. setCanAvoidCopyToHeap(false);
  3824. }
  3825. void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
  3826. assert(!ParamInfo && "Already has param info!");
  3827. // Zero params -> null pointer.
  3828. if (!NewParamInfo.empty()) {
  3829. NumParams = NewParamInfo.size();
  3830. ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
  3831. std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
  3832. }
  3833. }
  3834. void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
  3835. bool CapturesCXXThis) {
  3836. this->setCapturesCXXThis(CapturesCXXThis);
  3837. this->NumCaptures = Captures.size();
  3838. if (Captures.empty()) {
  3839. this->Captures = nullptr;
  3840. return;
  3841. }
  3842. this->Captures = Captures.copy(Context).data();
  3843. }
  3844. bool BlockDecl::capturesVariable(const VarDecl *variable) const {
  3845. for (const auto &I : captures())
  3846. // Only auto vars can be captured, so no redeclaration worries.
  3847. if (I.getVariable() == variable)
  3848. return true;
  3849. return false;
  3850. }
  3851. SourceRange BlockDecl::getSourceRange() const {
  3852. return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
  3853. }
  3854. //===----------------------------------------------------------------------===//
  3855. // Other Decl Allocation/Deallocation Method Implementations
  3856. //===----------------------------------------------------------------------===//
  3857. void TranslationUnitDecl::anchor() {}
  3858. TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
  3859. return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
  3860. }
  3861. void PragmaCommentDecl::anchor() {}
  3862. PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
  3863. TranslationUnitDecl *DC,
  3864. SourceLocation CommentLoc,
  3865. PragmaMSCommentKind CommentKind,
  3866. StringRef Arg) {
  3867. PragmaCommentDecl *PCD =
  3868. new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
  3869. PragmaCommentDecl(DC, CommentLoc, CommentKind);
  3870. memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
  3871. PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
  3872. return PCD;
  3873. }
  3874. PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
  3875. unsigned ID,
  3876. unsigned ArgSize) {
  3877. return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
  3878. PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
  3879. }
  3880. void PragmaDetectMismatchDecl::anchor() {}
  3881. PragmaDetectMismatchDecl *
  3882. PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
  3883. SourceLocation Loc, StringRef Name,
  3884. StringRef Value) {
  3885. size_t ValueStart = Name.size() + 1;
  3886. PragmaDetectMismatchDecl *PDMD =
  3887. new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
  3888. PragmaDetectMismatchDecl(DC, Loc, ValueStart);
  3889. memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
  3890. PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
  3891. memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
  3892. Value.size());
  3893. PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
  3894. return PDMD;
  3895. }
  3896. PragmaDetectMismatchDecl *
  3897. PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
  3898. unsigned NameValueSize) {
  3899. return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
  3900. PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
  3901. }
  3902. void ExternCContextDecl::anchor() {}
  3903. ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
  3904. TranslationUnitDecl *DC) {
  3905. return new (C, DC) ExternCContextDecl(DC);
  3906. }
  3907. void LabelDecl::anchor() {}
  3908. LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
  3909. SourceLocation IdentL, IdentifierInfo *II) {
  3910. return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
  3911. }
  3912. LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
  3913. SourceLocation IdentL, IdentifierInfo *II,
  3914. SourceLocation GnuLabelL) {
  3915. assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
  3916. return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
  3917. }
  3918. LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3919. return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
  3920. SourceLocation());
  3921. }
  3922. void LabelDecl::setMSAsmLabel(StringRef Name) {
  3923. char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
  3924. memcpy(Buffer, Name.data(), Name.size());
  3925. Buffer[Name.size()] = '\0';
  3926. MSAsmName = Buffer;
  3927. }
  3928. void ValueDecl::anchor() {}
  3929. bool ValueDecl::isWeak() const {
  3930. for (const auto *I : attrs())
  3931. if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
  3932. return true;
  3933. return isWeakImported();
  3934. }
  3935. void ImplicitParamDecl::anchor() {}
  3936. ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
  3937. SourceLocation IdLoc,
  3938. IdentifierInfo *Id, QualType Type,
  3939. ImplicitParamKind ParamKind) {
  3940. return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
  3941. }
  3942. ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
  3943. ImplicitParamKind ParamKind) {
  3944. return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
  3945. }
  3946. ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
  3947. unsigned ID) {
  3948. return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
  3949. }
  3950. FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
  3951. SourceLocation StartLoc,
  3952. const DeclarationNameInfo &NameInfo,
  3953. QualType T, TypeSourceInfo *TInfo,
  3954. StorageClass SC, bool isInlineSpecified,
  3955. bool hasWrittenPrototype,
  3956. ConstexprSpecKind ConstexprKind) {
  3957. FunctionDecl *New =
  3958. new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
  3959. SC, isInlineSpecified, ConstexprKind);
  3960. New->setHasWrittenPrototype(hasWrittenPrototype);
  3961. return New;
  3962. }
  3963. FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3964. return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
  3965. DeclarationNameInfo(), QualType(), nullptr,
  3966. SC_None, false, CSK_unspecified);
  3967. }
  3968. BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
  3969. return new (C, DC) BlockDecl(DC, L);
  3970. }
  3971. BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3972. return new (C, ID) BlockDecl(nullptr, SourceLocation());
  3973. }
  3974. CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
  3975. : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
  3976. NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
  3977. CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
  3978. unsigned NumParams) {
  3979. return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
  3980. CapturedDecl(DC, NumParams);
  3981. }
  3982. CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
  3983. unsigned NumParams) {
  3984. return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
  3985. CapturedDecl(nullptr, NumParams);
  3986. }
  3987. Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
  3988. void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
  3989. bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
  3990. void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
  3991. EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
  3992. SourceLocation L,
  3993. IdentifierInfo *Id, QualType T,
  3994. Expr *E, const llvm::APSInt &V) {
  3995. return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
  3996. }
  3997. EnumConstantDecl *
  3998. EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3999. return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
  4000. QualType(), nullptr, llvm::APSInt());
  4001. }
  4002. void IndirectFieldDecl::anchor() {}
  4003. IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
  4004. SourceLocation L, DeclarationName N,
  4005. QualType T,
  4006. MutableArrayRef<NamedDecl *> CH)
  4007. : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
  4008. ChainingSize(CH.size()) {
  4009. // In C++, indirect field declarations conflict with tag declarations in the
  4010. // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
  4011. if (C.getLangOpts().CPlusPlus)
  4012. IdentifierNamespace |= IDNS_Tag;
  4013. }
  4014. IndirectFieldDecl *
  4015. IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
  4016. IdentifierInfo *Id, QualType T,
  4017. llvm::MutableArrayRef<NamedDecl *> CH) {
  4018. return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
  4019. }
  4020. IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
  4021. unsigned ID) {
  4022. return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
  4023. DeclarationName(), QualType(), None);
  4024. }
  4025. SourceRange EnumConstantDecl::getSourceRange() const {
  4026. SourceLocation End = getLocation();
  4027. if (Init)
  4028. End = Init->getEndLoc();
  4029. return SourceRange(getLocation(), End);
  4030. }
  4031. void TypeDecl::anchor() {}
  4032. TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
  4033. SourceLocation StartLoc, SourceLocation IdLoc,
  4034. IdentifierInfo *Id, TypeSourceInfo *TInfo) {
  4035. return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
  4036. }
  4037. void TypedefNameDecl::anchor() {}
  4038. TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
  4039. if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
  4040. auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
  4041. auto *ThisTypedef = this;
  4042. if (AnyRedecl && OwningTypedef) {
  4043. OwningTypedef = OwningTypedef->getCanonicalDecl();
  4044. ThisTypedef = ThisTypedef->getCanonicalDecl();
  4045. }
  4046. if (OwningTypedef == ThisTypedef)
  4047. return TT->getDecl();
  4048. }
  4049. return nullptr;
  4050. }
  4051. bool TypedefNameDecl::isTransparentTagSlow() const {
  4052. auto determineIsTransparent = [&]() {
  4053. if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
  4054. if (auto *TD = TT->getDecl()) {
  4055. if (TD->getName() != getName())
  4056. return false;
  4057. SourceLocation TTLoc = getLocation();
  4058. SourceLocation TDLoc = TD->getLocation();
  4059. if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
  4060. return false;
  4061. SourceManager &SM = getASTContext().getSourceManager();
  4062. return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
  4063. }
  4064. }
  4065. return false;
  4066. };
  4067. bool isTransparent = determineIsTransparent();
  4068. MaybeModedTInfo.setInt((isTransparent << 1) | 1);
  4069. return isTransparent;
  4070. }
  4071. TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  4072. return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
  4073. nullptr, nullptr);
  4074. }
  4075. TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
  4076. SourceLocation StartLoc,
  4077. SourceLocation IdLoc, IdentifierInfo *Id,
  4078. TypeSourceInfo *TInfo) {
  4079. return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
  4080. }
  4081. TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  4082. return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
  4083. SourceLocation(), nullptr, nullptr);
  4084. }
  4085. SourceRange TypedefDecl::getSourceRange() const {
  4086. SourceLocation RangeEnd = getLocation();
  4087. if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
  4088. if (typeIsPostfix(TInfo->getType()))
  4089. RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
  4090. }
  4091. return SourceRange(getBeginLoc(), RangeEnd);
  4092. }
  4093. SourceRange TypeAliasDecl::getSourceRange() const {
  4094. SourceLocation RangeEnd = getBeginLoc();
  4095. if (TypeSourceInfo *TInfo = getTypeSourceInfo())
  4096. RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
  4097. return SourceRange(getBeginLoc(), RangeEnd);
  4098. }
  4099. void FileScopeAsmDecl::anchor() {}
  4100. FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
  4101. StringLiteral *Str,
  4102. SourceLocation AsmLoc,
  4103. SourceLocation RParenLoc) {
  4104. return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
  4105. }
  4106. FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
  4107. unsigned ID) {
  4108. return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
  4109. SourceLocation());
  4110. }
  4111. void EmptyDecl::anchor() {}
  4112. EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
  4113. return new (C, DC) EmptyDecl(DC, L);
  4114. }
  4115. EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  4116. return new (C, ID) EmptyDecl(nullptr, SourceLocation());
  4117. }
  4118. //===----------------------------------------------------------------------===//
  4119. // ImportDecl Implementation
  4120. //===----------------------------------------------------------------------===//
  4121. /// Retrieve the number of module identifiers needed to name the given
  4122. /// module.
  4123. static unsigned getNumModuleIdentifiers(Module *Mod) {
  4124. unsigned Result = 1;
  4125. while (Mod->Parent) {
  4126. Mod = Mod->Parent;
  4127. ++Result;
  4128. }
  4129. return Result;
  4130. }
  4131. ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
  4132. Module *Imported,
  4133. ArrayRef<SourceLocation> IdentifierLocs)
  4134. : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) {
  4135. assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
  4136. auto *StoredLocs = getTrailingObjects<SourceLocation>();
  4137. std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
  4138. StoredLocs);
  4139. }
  4140. ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
  4141. Module *Imported, SourceLocation EndLoc)
  4142. : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) {
  4143. *getTrailingObjects<SourceLocation>() = EndLoc;
  4144. }
  4145. ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
  4146. SourceLocation StartLoc, Module *Imported,
  4147. ArrayRef<SourceLocation> IdentifierLocs) {
  4148. return new (C, DC,
  4149. additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
  4150. ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
  4151. }
  4152. ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
  4153. SourceLocation StartLoc,
  4154. Module *Imported,
  4155. SourceLocation EndLoc) {
  4156. ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
  4157. ImportDecl(DC, StartLoc, Imported, EndLoc);
  4158. Import->setImplicit();
  4159. return Import;
  4160. }
  4161. ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
  4162. unsigned NumLocations) {
  4163. return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
  4164. ImportDecl(EmptyShell());
  4165. }
  4166. ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
  4167. if (!ImportedAndComplete.getInt())
  4168. return None;
  4169. const auto *StoredLocs = getTrailingObjects<SourceLocation>();
  4170. return llvm::makeArrayRef(StoredLocs,
  4171. getNumModuleIdentifiers(getImportedModule()));
  4172. }
  4173. SourceRange ImportDecl::getSourceRange() const {
  4174. if (!ImportedAndComplete.getInt())
  4175. return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
  4176. return SourceRange(getLocation(), getIdentifierLocs().back());
  4177. }
  4178. //===----------------------------------------------------------------------===//
  4179. // ExportDecl Implementation
  4180. //===----------------------------------------------------------------------===//
  4181. void ExportDecl::anchor() {}
  4182. ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
  4183. SourceLocation ExportLoc) {
  4184. return new (C, DC) ExportDecl(DC, ExportLoc);
  4185. }
  4186. ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  4187. return new (C, ID) ExportDecl(nullptr, SourceLocation());
  4188. }