Decl.cpp 173 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876
  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. const DeclContext *Ctx = getDeclContext();
  1364. // For ObjC methods and properties, look through categories and use the
  1365. // interface as context.
  1366. if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
  1367. if (auto *ID = MD->getClassInterface())
  1368. Ctx = ID;
  1369. if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
  1370. if (auto *MD = PD->getGetterMethodDecl())
  1371. if (auto *ID = MD->getClassInterface())
  1372. Ctx = ID;
  1373. }
  1374. if (Ctx->isFunctionOrMethod()) {
  1375. printName(OS);
  1376. return;
  1377. }
  1378. using ContextsTy = SmallVector<const DeclContext *, 8>;
  1379. ContextsTy Contexts;
  1380. // Collect named contexts.
  1381. while (Ctx) {
  1382. if (isa<NamedDecl>(Ctx))
  1383. Contexts.push_back(Ctx);
  1384. Ctx = Ctx->getParent();
  1385. }
  1386. for (const DeclContext *DC : llvm::reverse(Contexts)) {
  1387. if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  1388. OS << Spec->getName();
  1389. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  1390. printTemplateArgumentList(OS, TemplateArgs.asArray(), P);
  1391. } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
  1392. if (P.SuppressUnwrittenScope &&
  1393. (ND->isAnonymousNamespace() || ND->isInline()))
  1394. continue;
  1395. if (ND->isAnonymousNamespace()) {
  1396. OS << (P.MSVCFormatting ? "`anonymous namespace\'"
  1397. : "(anonymous namespace)");
  1398. }
  1399. else
  1400. OS << *ND;
  1401. } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
  1402. if (!RD->getIdentifier())
  1403. OS << "(anonymous " << RD->getKindName() << ')';
  1404. else
  1405. OS << *RD;
  1406. } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
  1407. const FunctionProtoType *FT = nullptr;
  1408. if (FD->hasWrittenPrototype())
  1409. FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
  1410. OS << *FD << '(';
  1411. if (FT) {
  1412. unsigned NumParams = FD->getNumParams();
  1413. for (unsigned i = 0; i < NumParams; ++i) {
  1414. if (i)
  1415. OS << ", ";
  1416. OS << FD->getParamDecl(i)->getType().stream(P);
  1417. }
  1418. if (FT->isVariadic()) {
  1419. if (NumParams > 0)
  1420. OS << ", ";
  1421. OS << "...";
  1422. }
  1423. }
  1424. OS << ')';
  1425. } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
  1426. // C++ [dcl.enum]p10: Each enum-name and each unscoped
  1427. // enumerator is declared in the scope that immediately contains
  1428. // the enum-specifier. Each scoped enumerator is declared in the
  1429. // scope of the enumeration.
  1430. // For the case of unscoped enumerator, do not include in the qualified
  1431. // name any information about its enum enclosing scope, as its visibility
  1432. // is global.
  1433. if (ED->isScoped())
  1434. OS << *ED;
  1435. else
  1436. continue;
  1437. } else {
  1438. OS << *cast<NamedDecl>(DC);
  1439. }
  1440. OS << "::";
  1441. }
  1442. if (getDeclName() || isa<DecompositionDecl>(this))
  1443. OS << *this;
  1444. else
  1445. OS << "(anonymous)";
  1446. }
  1447. void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
  1448. const PrintingPolicy &Policy,
  1449. bool Qualified) const {
  1450. if (Qualified)
  1451. printQualifiedName(OS, Policy);
  1452. else
  1453. printName(OS);
  1454. }
  1455. template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
  1456. return true;
  1457. }
  1458. static bool isRedeclarableImpl(...) { return false; }
  1459. static bool isRedeclarable(Decl::Kind K) {
  1460. switch (K) {
  1461. #define DECL(Type, Base) \
  1462. case Decl::Type: \
  1463. return isRedeclarableImpl((Type##Decl *)nullptr);
  1464. #define ABSTRACT_DECL(DECL)
  1465. #include "clang/AST/DeclNodes.inc"
  1466. }
  1467. llvm_unreachable("unknown decl kind");
  1468. }
  1469. bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
  1470. assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
  1471. // Never replace one imported declaration with another; we need both results
  1472. // when re-exporting.
  1473. if (OldD->isFromASTFile() && isFromASTFile())
  1474. return false;
  1475. // A kind mismatch implies that the declaration is not replaced.
  1476. if (OldD->getKind() != getKind())
  1477. return false;
  1478. // For method declarations, we never replace. (Why?)
  1479. if (isa<ObjCMethodDecl>(this))
  1480. return false;
  1481. // For parameters, pick the newer one. This is either an error or (in
  1482. // Objective-C) permitted as an extension.
  1483. if (isa<ParmVarDecl>(this))
  1484. return true;
  1485. // Inline namespaces can give us two declarations with the same
  1486. // name and kind in the same scope but different contexts; we should
  1487. // keep both declarations in this case.
  1488. if (!this->getDeclContext()->getRedeclContext()->Equals(
  1489. OldD->getDeclContext()->getRedeclContext()))
  1490. return false;
  1491. // Using declarations can be replaced if they import the same name from the
  1492. // same context.
  1493. if (auto *UD = dyn_cast<UsingDecl>(this)) {
  1494. ASTContext &Context = getASTContext();
  1495. return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
  1496. Context.getCanonicalNestedNameSpecifier(
  1497. cast<UsingDecl>(OldD)->getQualifier());
  1498. }
  1499. if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
  1500. ASTContext &Context = getASTContext();
  1501. return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
  1502. Context.getCanonicalNestedNameSpecifier(
  1503. cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
  1504. }
  1505. if (isRedeclarable(getKind())) {
  1506. if (getCanonicalDecl() != OldD->getCanonicalDecl())
  1507. return false;
  1508. if (IsKnownNewer)
  1509. return true;
  1510. // Check whether this is actually newer than OldD. We want to keep the
  1511. // newer declaration. This loop will usually only iterate once, because
  1512. // OldD is usually the previous declaration.
  1513. for (auto D : redecls()) {
  1514. if (D == OldD)
  1515. break;
  1516. // If we reach the canonical declaration, then OldD is not actually older
  1517. // than this one.
  1518. //
  1519. // FIXME: In this case, we should not add this decl to the lookup table.
  1520. if (D->isCanonicalDecl())
  1521. return false;
  1522. }
  1523. // It's a newer declaration of the same kind of declaration in the same
  1524. // scope: we want this decl instead of the existing one.
  1525. return true;
  1526. }
  1527. // In all other cases, we need to keep both declarations in case they have
  1528. // different visibility. Any attempt to use the name will result in an
  1529. // ambiguity if more than one is visible.
  1530. return false;
  1531. }
  1532. bool NamedDecl::hasLinkage() const {
  1533. return getFormalLinkage() != NoLinkage;
  1534. }
  1535. NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
  1536. NamedDecl *ND = this;
  1537. while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
  1538. ND = UD->getTargetDecl();
  1539. if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
  1540. return AD->getClassInterface();
  1541. if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
  1542. return AD->getNamespace();
  1543. return ND;
  1544. }
  1545. bool NamedDecl::isCXXInstanceMember() const {
  1546. if (!isCXXClassMember())
  1547. return false;
  1548. const NamedDecl *D = this;
  1549. if (isa<UsingShadowDecl>(D))
  1550. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  1551. if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
  1552. return true;
  1553. if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
  1554. return MD->isInstance();
  1555. return false;
  1556. }
  1557. //===----------------------------------------------------------------------===//
  1558. // DeclaratorDecl Implementation
  1559. //===----------------------------------------------------------------------===//
  1560. template <typename DeclT>
  1561. static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
  1562. if (decl->getNumTemplateParameterLists() > 0)
  1563. return decl->getTemplateParameterList(0)->getTemplateLoc();
  1564. else
  1565. return decl->getInnerLocStart();
  1566. }
  1567. SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
  1568. TypeSourceInfo *TSI = getTypeSourceInfo();
  1569. if (TSI) return TSI->getTypeLoc().getBeginLoc();
  1570. return SourceLocation();
  1571. }
  1572. void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
  1573. if (QualifierLoc) {
  1574. // Make sure the extended decl info is allocated.
  1575. if (!hasExtInfo()) {
  1576. // Save (non-extended) type source info pointer.
  1577. auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
  1578. // Allocate external info struct.
  1579. DeclInfo = new (getASTContext()) ExtInfo;
  1580. // Restore savedTInfo into (extended) decl info.
  1581. getExtInfo()->TInfo = savedTInfo;
  1582. }
  1583. // Set qualifier info.
  1584. getExtInfo()->QualifierLoc = QualifierLoc;
  1585. } else {
  1586. // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
  1587. if (hasExtInfo()) {
  1588. if (getExtInfo()->NumTemplParamLists == 0) {
  1589. // Save type source info pointer.
  1590. TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
  1591. // Deallocate the extended decl info.
  1592. getASTContext().Deallocate(getExtInfo());
  1593. // Restore savedTInfo into (non-extended) decl info.
  1594. DeclInfo = savedTInfo;
  1595. }
  1596. else
  1597. getExtInfo()->QualifierLoc = QualifierLoc;
  1598. }
  1599. }
  1600. }
  1601. void DeclaratorDecl::setTemplateParameterListsInfo(
  1602. ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
  1603. assert(!TPLists.empty());
  1604. // Make sure the extended decl info is allocated.
  1605. if (!hasExtInfo()) {
  1606. // Save (non-extended) type source info pointer.
  1607. auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
  1608. // Allocate external info struct.
  1609. DeclInfo = new (getASTContext()) ExtInfo;
  1610. // Restore savedTInfo into (extended) decl info.
  1611. getExtInfo()->TInfo = savedTInfo;
  1612. }
  1613. // Set the template parameter lists info.
  1614. getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
  1615. }
  1616. SourceLocation DeclaratorDecl::getOuterLocStart() const {
  1617. return getTemplateOrInnerLocStart(this);
  1618. }
  1619. // Helper function: returns true if QT is or contains a type
  1620. // having a postfix component.
  1621. static bool typeIsPostfix(QualType QT) {
  1622. while (true) {
  1623. const Type* T = QT.getTypePtr();
  1624. switch (T->getTypeClass()) {
  1625. default:
  1626. return false;
  1627. case Type::Pointer:
  1628. QT = cast<PointerType>(T)->getPointeeType();
  1629. break;
  1630. case Type::BlockPointer:
  1631. QT = cast<BlockPointerType>(T)->getPointeeType();
  1632. break;
  1633. case Type::MemberPointer:
  1634. QT = cast<MemberPointerType>(T)->getPointeeType();
  1635. break;
  1636. case Type::LValueReference:
  1637. case Type::RValueReference:
  1638. QT = cast<ReferenceType>(T)->getPointeeType();
  1639. break;
  1640. case Type::PackExpansion:
  1641. QT = cast<PackExpansionType>(T)->getPattern();
  1642. break;
  1643. case Type::Paren:
  1644. case Type::ConstantArray:
  1645. case Type::DependentSizedArray:
  1646. case Type::IncompleteArray:
  1647. case Type::VariableArray:
  1648. case Type::FunctionProto:
  1649. case Type::FunctionNoProto:
  1650. return true;
  1651. }
  1652. }
  1653. }
  1654. SourceRange DeclaratorDecl::getSourceRange() const {
  1655. SourceLocation RangeEnd = getLocation();
  1656. if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
  1657. // If the declaration has no name or the type extends past the name take the
  1658. // end location of the type.
  1659. if (!getDeclName() || typeIsPostfix(TInfo->getType()))
  1660. RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
  1661. }
  1662. return SourceRange(getOuterLocStart(), RangeEnd);
  1663. }
  1664. void QualifierInfo::setTemplateParameterListsInfo(
  1665. ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
  1666. // Free previous template parameters (if any).
  1667. if (NumTemplParamLists > 0) {
  1668. Context.Deallocate(TemplParamLists);
  1669. TemplParamLists = nullptr;
  1670. NumTemplParamLists = 0;
  1671. }
  1672. // Set info on matched template parameter lists (if any).
  1673. if (!TPLists.empty()) {
  1674. TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
  1675. NumTemplParamLists = TPLists.size();
  1676. std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
  1677. }
  1678. }
  1679. //===----------------------------------------------------------------------===//
  1680. // VarDecl Implementation
  1681. //===----------------------------------------------------------------------===//
  1682. const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
  1683. switch (SC) {
  1684. case SC_None: break;
  1685. case SC_Auto: return "auto";
  1686. case SC_Extern: return "extern";
  1687. case SC_PrivateExtern: return "__private_extern__";
  1688. case SC_Register: return "register";
  1689. case SC_Static: return "static";
  1690. }
  1691. llvm_unreachable("Invalid storage class");
  1692. }
  1693. VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
  1694. SourceLocation StartLoc, SourceLocation IdLoc,
  1695. IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
  1696. StorageClass SC)
  1697. : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
  1698. redeclarable_base(C) {
  1699. static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
  1700. "VarDeclBitfields too large!");
  1701. static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
  1702. "ParmVarDeclBitfields too large!");
  1703. static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
  1704. "NonParmVarDeclBitfields too large!");
  1705. AllBits = 0;
  1706. VarDeclBits.SClass = SC;
  1707. // Everything else is implicitly initialized to false.
  1708. }
  1709. VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
  1710. SourceLocation StartL, SourceLocation IdL,
  1711. IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
  1712. StorageClass S) {
  1713. return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
  1714. }
  1715. VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  1716. return new (C, ID)
  1717. VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
  1718. QualType(), nullptr, SC_None);
  1719. }
  1720. void VarDecl::setStorageClass(StorageClass SC) {
  1721. assert(isLegalForVariable(SC));
  1722. VarDeclBits.SClass = SC;
  1723. }
  1724. VarDecl::TLSKind VarDecl::getTLSKind() const {
  1725. switch (VarDeclBits.TSCSpec) {
  1726. case TSCS_unspecified:
  1727. if (!hasAttr<ThreadAttr>() &&
  1728. !(getASTContext().getLangOpts().OpenMPUseTLS &&
  1729. getASTContext().getTargetInfo().isTLSSupported() &&
  1730. hasAttr<OMPThreadPrivateDeclAttr>()))
  1731. return TLS_None;
  1732. return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
  1733. LangOptions::MSVC2015)) ||
  1734. hasAttr<OMPThreadPrivateDeclAttr>())
  1735. ? TLS_Dynamic
  1736. : TLS_Static;
  1737. case TSCS___thread: // Fall through.
  1738. case TSCS__Thread_local:
  1739. return TLS_Static;
  1740. case TSCS_thread_local:
  1741. return TLS_Dynamic;
  1742. }
  1743. llvm_unreachable("Unknown thread storage class specifier!");
  1744. }
  1745. SourceRange VarDecl::getSourceRange() const {
  1746. if (const Expr *Init = getInit()) {
  1747. SourceLocation InitEnd = Init->getEndLoc();
  1748. // If Init is implicit, ignore its source range and fallback on
  1749. // DeclaratorDecl::getSourceRange() to handle postfix elements.
  1750. if (InitEnd.isValid() && InitEnd != getLocation())
  1751. return SourceRange(getOuterLocStart(), InitEnd);
  1752. }
  1753. return DeclaratorDecl::getSourceRange();
  1754. }
  1755. template<typename T>
  1756. static LanguageLinkage getDeclLanguageLinkage(const T &D) {
  1757. // C++ [dcl.link]p1: All function types, function names with external linkage,
  1758. // and variable names with external linkage have a language linkage.
  1759. if (!D.hasExternalFormalLinkage())
  1760. return NoLanguageLinkage;
  1761. // Language linkage is a C++ concept, but saying that everything else in C has
  1762. // C language linkage fits the implementation nicely.
  1763. ASTContext &Context = D.getASTContext();
  1764. if (!Context.getLangOpts().CPlusPlus)
  1765. return CLanguageLinkage;
  1766. // C++ [dcl.link]p4: A C language linkage is ignored in determining the
  1767. // language linkage of the names of class members and the function type of
  1768. // class member functions.
  1769. const DeclContext *DC = D.getDeclContext();
  1770. if (DC->isRecord())
  1771. return CXXLanguageLinkage;
  1772. // If the first decl is in an extern "C" context, any other redeclaration
  1773. // will have C language linkage. If the first one is not in an extern "C"
  1774. // context, we would have reported an error for any other decl being in one.
  1775. if (isFirstInExternCContext(&D))
  1776. return CLanguageLinkage;
  1777. return CXXLanguageLinkage;
  1778. }
  1779. template<typename T>
  1780. static bool isDeclExternC(const T &D) {
  1781. // Since the context is ignored for class members, they can only have C++
  1782. // language linkage or no language linkage.
  1783. const DeclContext *DC = D.getDeclContext();
  1784. if (DC->isRecord()) {
  1785. assert(D.getASTContext().getLangOpts().CPlusPlus);
  1786. return false;
  1787. }
  1788. return D.getLanguageLinkage() == CLanguageLinkage;
  1789. }
  1790. LanguageLinkage VarDecl::getLanguageLinkage() const {
  1791. return getDeclLanguageLinkage(*this);
  1792. }
  1793. bool VarDecl::isExternC() const {
  1794. return isDeclExternC(*this);
  1795. }
  1796. bool VarDecl::isInExternCContext() const {
  1797. return getLexicalDeclContext()->isExternCContext();
  1798. }
  1799. bool VarDecl::isInExternCXXContext() const {
  1800. return getLexicalDeclContext()->isExternCXXContext();
  1801. }
  1802. VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
  1803. VarDecl::DefinitionKind
  1804. VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
  1805. if (isThisDeclarationADemotedDefinition())
  1806. return DeclarationOnly;
  1807. // C++ [basic.def]p2:
  1808. // A declaration is a definition unless [...] it contains the 'extern'
  1809. // specifier or a linkage-specification and neither an initializer [...],
  1810. // it declares a non-inline static data member in a class declaration [...],
  1811. // it declares a static data member outside a class definition and the variable
  1812. // was defined within the class with the constexpr specifier [...],
  1813. // C++1y [temp.expl.spec]p15:
  1814. // An explicit specialization of a static data member or an explicit
  1815. // specialization of a static data member template is a definition if the
  1816. // declaration includes an initializer; otherwise, it is a declaration.
  1817. //
  1818. // FIXME: How do you declare (but not define) a partial specialization of
  1819. // a static data member template outside the containing class?
  1820. if (isStaticDataMember()) {
  1821. if (isOutOfLine() &&
  1822. !(getCanonicalDecl()->isInline() &&
  1823. getCanonicalDecl()->isConstexpr()) &&
  1824. (hasInit() ||
  1825. // If the first declaration is out-of-line, this may be an
  1826. // instantiation of an out-of-line partial specialization of a variable
  1827. // template for which we have not yet instantiated the initializer.
  1828. (getFirstDecl()->isOutOfLine()
  1829. ? getTemplateSpecializationKind() == TSK_Undeclared
  1830. : getTemplateSpecializationKind() !=
  1831. TSK_ExplicitSpecialization) ||
  1832. isa<VarTemplatePartialSpecializationDecl>(this)))
  1833. return Definition;
  1834. else if (!isOutOfLine() && isInline())
  1835. return Definition;
  1836. else
  1837. return DeclarationOnly;
  1838. }
  1839. // C99 6.7p5:
  1840. // A definition of an identifier is a declaration for that identifier that
  1841. // [...] causes storage to be reserved for that object.
  1842. // Note: that applies for all non-file-scope objects.
  1843. // C99 6.9.2p1:
  1844. // If the declaration of an identifier for an object has file scope and an
  1845. // initializer, the declaration is an external definition for the identifier
  1846. if (hasInit())
  1847. return Definition;
  1848. if (hasDefiningAttr())
  1849. return Definition;
  1850. if (const auto *SAA = getAttr<SelectAnyAttr>())
  1851. if (!SAA->isInherited())
  1852. return Definition;
  1853. // A variable template specialization (other than a static data member
  1854. // template or an explicit specialization) is a declaration until we
  1855. // instantiate its initializer.
  1856. if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
  1857. if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
  1858. !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
  1859. !VTSD->IsCompleteDefinition)
  1860. return DeclarationOnly;
  1861. }
  1862. if (hasExternalStorage())
  1863. return DeclarationOnly;
  1864. // [dcl.link] p7:
  1865. // A declaration directly contained in a linkage-specification is treated
  1866. // as if it contains the extern specifier for the purpose of determining
  1867. // the linkage of the declared name and whether it is a definition.
  1868. if (isSingleLineLanguageLinkage(*this))
  1869. return DeclarationOnly;
  1870. // C99 6.9.2p2:
  1871. // A declaration of an object that has file scope without an initializer,
  1872. // and without a storage class specifier or the scs 'static', constitutes
  1873. // a tentative definition.
  1874. // No such thing in C++.
  1875. if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
  1876. return TentativeDefinition;
  1877. // What's left is (in C, block-scope) declarations without initializers or
  1878. // external storage. These are definitions.
  1879. return Definition;
  1880. }
  1881. VarDecl *VarDecl::getActingDefinition() {
  1882. DefinitionKind Kind = isThisDeclarationADefinition();
  1883. if (Kind != TentativeDefinition)
  1884. return nullptr;
  1885. VarDecl *LastTentative = nullptr;
  1886. VarDecl *First = getFirstDecl();
  1887. for (auto I : First->redecls()) {
  1888. Kind = I->isThisDeclarationADefinition();
  1889. if (Kind == Definition)
  1890. return nullptr;
  1891. else if (Kind == TentativeDefinition)
  1892. LastTentative = I;
  1893. }
  1894. return LastTentative;
  1895. }
  1896. VarDecl *VarDecl::getDefinition(ASTContext &C) {
  1897. VarDecl *First = getFirstDecl();
  1898. for (auto I : First->redecls()) {
  1899. if (I->isThisDeclarationADefinition(C) == Definition)
  1900. return I;
  1901. }
  1902. return nullptr;
  1903. }
  1904. VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
  1905. DefinitionKind Kind = DeclarationOnly;
  1906. const VarDecl *First = getFirstDecl();
  1907. for (auto I : First->redecls()) {
  1908. Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
  1909. if (Kind == Definition)
  1910. break;
  1911. }
  1912. return Kind;
  1913. }
  1914. const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
  1915. for (auto I : redecls()) {
  1916. if (auto Expr = I->getInit()) {
  1917. D = I;
  1918. return Expr;
  1919. }
  1920. }
  1921. return nullptr;
  1922. }
  1923. bool VarDecl::hasInit() const {
  1924. if (auto *P = dyn_cast<ParmVarDecl>(this))
  1925. if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
  1926. return false;
  1927. return !Init.isNull();
  1928. }
  1929. Expr *VarDecl::getInit() {
  1930. if (!hasInit())
  1931. return nullptr;
  1932. if (auto *S = Init.dyn_cast<Stmt *>())
  1933. return cast<Expr>(S);
  1934. return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
  1935. }
  1936. Stmt **VarDecl::getInitAddress() {
  1937. if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
  1938. return &ES->Value;
  1939. return Init.getAddrOfPtr1();
  1940. }
  1941. VarDecl *VarDecl::getInitializingDeclaration() {
  1942. VarDecl *Def = nullptr;
  1943. for (auto I : redecls()) {
  1944. if (I->hasInit())
  1945. return I;
  1946. if (I->isThisDeclarationADefinition()) {
  1947. if (isStaticDataMember())
  1948. return I;
  1949. else
  1950. Def = I;
  1951. }
  1952. }
  1953. return Def;
  1954. }
  1955. bool VarDecl::isOutOfLine() const {
  1956. if (Decl::isOutOfLine())
  1957. return true;
  1958. if (!isStaticDataMember())
  1959. return false;
  1960. // If this static data member was instantiated from a static data member of
  1961. // a class template, check whether that static data member was defined
  1962. // out-of-line.
  1963. if (VarDecl *VD = getInstantiatedFromStaticDataMember())
  1964. return VD->isOutOfLine();
  1965. return false;
  1966. }
  1967. void VarDecl::setInit(Expr *I) {
  1968. if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
  1969. Eval->~EvaluatedStmt();
  1970. getASTContext().Deallocate(Eval);
  1971. }
  1972. Init = I;
  1973. }
  1974. bool VarDecl::mightBeUsableInConstantExpressions(ASTContext &C) const {
  1975. const LangOptions &Lang = C.getLangOpts();
  1976. if (!Lang.CPlusPlus)
  1977. return false;
  1978. // Function parameters are never usable in constant expressions.
  1979. if (isa<ParmVarDecl>(this))
  1980. return false;
  1981. // In C++11, any variable of reference type can be used in a constant
  1982. // expression if it is initialized by a constant expression.
  1983. if (Lang.CPlusPlus11 && getType()->isReferenceType())
  1984. return true;
  1985. // Only const objects can be used in constant expressions in C++. C++98 does
  1986. // not require the variable to be non-volatile, but we consider this to be a
  1987. // defect.
  1988. if (!getType().isConstQualified() || getType().isVolatileQualified())
  1989. return false;
  1990. // In C++, const, non-volatile variables of integral or enumeration types
  1991. // can be used in constant expressions.
  1992. if (getType()->isIntegralOrEnumerationType())
  1993. return true;
  1994. // Additionally, in C++11, non-volatile constexpr variables can be used in
  1995. // constant expressions.
  1996. return Lang.CPlusPlus11 && isConstexpr();
  1997. }
  1998. bool VarDecl::isUsableInConstantExpressions(ASTContext &Context) const {
  1999. // C++2a [expr.const]p3:
  2000. // A variable is usable in constant expressions after its initializing
  2001. // declaration is encountered...
  2002. const VarDecl *DefVD = nullptr;
  2003. const Expr *Init = getAnyInitializer(DefVD);
  2004. if (!Init || Init->isValueDependent() || getType()->isDependentType())
  2005. return false;
  2006. // ... if it is a constexpr variable, or it is of reference type or of
  2007. // const-qualified integral or enumeration type, ...
  2008. if (!DefVD->mightBeUsableInConstantExpressions(Context))
  2009. return false;
  2010. // ... and its initializer is a constant initializer.
  2011. return DefVD->checkInitIsICE();
  2012. }
  2013. /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
  2014. /// form, which contains extra information on the evaluated value of the
  2015. /// initializer.
  2016. EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
  2017. auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
  2018. if (!Eval) {
  2019. // Note: EvaluatedStmt contains an APValue, which usually holds
  2020. // resources not allocated from the ASTContext. We need to do some
  2021. // work to avoid leaking those, but we do so in VarDecl::evaluateValue
  2022. // where we can detect whether there's anything to clean up or not.
  2023. Eval = new (getASTContext()) EvaluatedStmt;
  2024. Eval->Value = Init.get<Stmt *>();
  2025. Init = Eval;
  2026. }
  2027. return Eval;
  2028. }
  2029. APValue *VarDecl::evaluateValue() const {
  2030. SmallVector<PartialDiagnosticAt, 8> Notes;
  2031. return evaluateValue(Notes);
  2032. }
  2033. APValue *VarDecl::evaluateValue(
  2034. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  2035. EvaluatedStmt *Eval = ensureEvaluatedStmt();
  2036. // We only produce notes indicating why an initializer is non-constant the
  2037. // first time it is evaluated. FIXME: The notes won't always be emitted the
  2038. // first time we try evaluation, so might not be produced at all.
  2039. if (Eval->WasEvaluated)
  2040. return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
  2041. const auto *Init = cast<Expr>(Eval->Value);
  2042. assert(!Init->isValueDependent());
  2043. if (Eval->IsEvaluating) {
  2044. // FIXME: Produce a diagnostic for self-initialization.
  2045. Eval->CheckedICE = true;
  2046. Eval->IsICE = false;
  2047. return nullptr;
  2048. }
  2049. Eval->IsEvaluating = true;
  2050. bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
  2051. this, Notes);
  2052. // Ensure the computed APValue is cleaned up later if evaluation succeeded,
  2053. // or that it's empty (so that there's nothing to clean up) if evaluation
  2054. // failed.
  2055. if (!Result)
  2056. Eval->Evaluated = APValue();
  2057. else if (Eval->Evaluated.needsCleanup())
  2058. getASTContext().addDestruction(&Eval->Evaluated);
  2059. Eval->IsEvaluating = false;
  2060. Eval->WasEvaluated = true;
  2061. // In C++11, we have determined whether the initializer was a constant
  2062. // expression as a side-effect.
  2063. if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
  2064. Eval->CheckedICE = true;
  2065. Eval->IsICE = Result && Notes.empty();
  2066. }
  2067. return Result ? &Eval->Evaluated : nullptr;
  2068. }
  2069. APValue *VarDecl::getEvaluatedValue() const {
  2070. if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
  2071. if (Eval->WasEvaluated)
  2072. return &Eval->Evaluated;
  2073. return nullptr;
  2074. }
  2075. bool VarDecl::isInitKnownICE() const {
  2076. if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
  2077. return Eval->CheckedICE;
  2078. return false;
  2079. }
  2080. bool VarDecl::isInitICE() const {
  2081. assert(isInitKnownICE() &&
  2082. "Check whether we already know that the initializer is an ICE");
  2083. return Init.get<EvaluatedStmt *>()->IsICE;
  2084. }
  2085. bool VarDecl::checkInitIsICE() const {
  2086. // Initializers of weak variables are never ICEs.
  2087. if (isWeak())
  2088. return false;
  2089. EvaluatedStmt *Eval = ensureEvaluatedStmt();
  2090. if (Eval->CheckedICE)
  2091. // We have already checked whether this subexpression is an
  2092. // integral constant expression.
  2093. return Eval->IsICE;
  2094. const auto *Init = cast<Expr>(Eval->Value);
  2095. assert(!Init->isValueDependent());
  2096. // In C++11, evaluate the initializer to check whether it's a constant
  2097. // expression.
  2098. if (getASTContext().getLangOpts().CPlusPlus11) {
  2099. SmallVector<PartialDiagnosticAt, 8> Notes;
  2100. evaluateValue(Notes);
  2101. return Eval->IsICE;
  2102. }
  2103. // It's an ICE whether or not the definition we found is
  2104. // out-of-line. See DR 721 and the discussion in Clang PR
  2105. // 6206 for details.
  2106. if (Eval->CheckingICE)
  2107. return false;
  2108. Eval->CheckingICE = true;
  2109. Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
  2110. Eval->CheckingICE = false;
  2111. Eval->CheckedICE = true;
  2112. return Eval->IsICE;
  2113. }
  2114. bool VarDecl::isParameterPack() const {
  2115. return isa<PackExpansionType>(getType());
  2116. }
  2117. template<typename DeclT>
  2118. static DeclT *getDefinitionOrSelf(DeclT *D) {
  2119. assert(D);
  2120. if (auto *Def = D->getDefinition())
  2121. return Def;
  2122. return D;
  2123. }
  2124. bool VarDecl::isEscapingByref() const {
  2125. return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
  2126. }
  2127. bool VarDecl::isNonEscapingByref() const {
  2128. return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
  2129. }
  2130. VarDecl *VarDecl::getTemplateInstantiationPattern() const {
  2131. const VarDecl *VD = this;
  2132. // If this is an instantiated member, walk back to the template from which
  2133. // it was instantiated.
  2134. if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
  2135. if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
  2136. VD = VD->getInstantiatedFromStaticDataMember();
  2137. while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
  2138. VD = NewVD;
  2139. }
  2140. }
  2141. // If it's an instantiated variable template specialization, find the
  2142. // template or partial specialization from which it was instantiated.
  2143. if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
  2144. if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
  2145. auto From = VDTemplSpec->getInstantiatedFrom();
  2146. if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
  2147. while (!VTD->isMemberSpecialization()) {
  2148. auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
  2149. if (!NewVTD)
  2150. break;
  2151. VTD = NewVTD;
  2152. }
  2153. return getDefinitionOrSelf(VTD->getTemplatedDecl());
  2154. }
  2155. if (auto *VTPSD =
  2156. From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
  2157. while (!VTPSD->isMemberSpecialization()) {
  2158. auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
  2159. if (!NewVTPSD)
  2160. break;
  2161. VTPSD = NewVTPSD;
  2162. }
  2163. return getDefinitionOrSelf<VarDecl>(VTPSD);
  2164. }
  2165. }
  2166. }
  2167. // If this is the pattern of a variable template, find where it was
  2168. // instantiated from. FIXME: Is this necessary?
  2169. if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
  2170. while (!VarTemplate->isMemberSpecialization()) {
  2171. auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
  2172. if (!NewVT)
  2173. break;
  2174. VarTemplate = NewVT;
  2175. }
  2176. return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
  2177. }
  2178. if (VD == this)
  2179. return nullptr;
  2180. return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
  2181. }
  2182. VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
  2183. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  2184. return cast<VarDecl>(MSI->getInstantiatedFrom());
  2185. return nullptr;
  2186. }
  2187. TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
  2188. if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
  2189. return Spec->getSpecializationKind();
  2190. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  2191. return MSI->getTemplateSpecializationKind();
  2192. return TSK_Undeclared;
  2193. }
  2194. TemplateSpecializationKind
  2195. VarDecl::getTemplateSpecializationKindForInstantiation() const {
  2196. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  2197. return MSI->getTemplateSpecializationKind();
  2198. if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
  2199. return Spec->getSpecializationKind();
  2200. return TSK_Undeclared;
  2201. }
  2202. SourceLocation VarDecl::getPointOfInstantiation() const {
  2203. if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
  2204. return Spec->getPointOfInstantiation();
  2205. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  2206. return MSI->getPointOfInstantiation();
  2207. return SourceLocation();
  2208. }
  2209. VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
  2210. return getASTContext().getTemplateOrSpecializationInfo(this)
  2211. .dyn_cast<VarTemplateDecl *>();
  2212. }
  2213. void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
  2214. getASTContext().setTemplateOrSpecializationInfo(this, Template);
  2215. }
  2216. bool VarDecl::isKnownToBeDefined() const {
  2217. const auto &LangOpts = getASTContext().getLangOpts();
  2218. // In CUDA mode without relocatable device code, variables of form 'extern
  2219. // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
  2220. // memory pool. These are never undefined variables, even if they appear
  2221. // inside of an anon namespace or static function.
  2222. //
  2223. // With CUDA relocatable device code enabled, these variables don't get
  2224. // special handling; they're treated like regular extern variables.
  2225. if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
  2226. hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
  2227. isa<IncompleteArrayType>(getType()))
  2228. return true;
  2229. return hasDefinition();
  2230. }
  2231. bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
  2232. return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
  2233. (!Ctx.getLangOpts().RegisterStaticDestructors &&
  2234. !hasAttr<AlwaysDestroyAttr>()));
  2235. }
  2236. MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
  2237. if (isStaticDataMember())
  2238. // FIXME: Remove ?
  2239. // return getASTContext().getInstantiatedFromStaticDataMember(this);
  2240. return getASTContext().getTemplateOrSpecializationInfo(this)
  2241. .dyn_cast<MemberSpecializationInfo *>();
  2242. return nullptr;
  2243. }
  2244. void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  2245. SourceLocation PointOfInstantiation) {
  2246. assert((isa<VarTemplateSpecializationDecl>(this) ||
  2247. getMemberSpecializationInfo()) &&
  2248. "not a variable or static data member template specialization");
  2249. if (VarTemplateSpecializationDecl *Spec =
  2250. dyn_cast<VarTemplateSpecializationDecl>(this)) {
  2251. Spec->setSpecializationKind(TSK);
  2252. if (TSK != TSK_ExplicitSpecialization &&
  2253. PointOfInstantiation.isValid() &&
  2254. Spec->getPointOfInstantiation().isInvalid()) {
  2255. Spec->setPointOfInstantiation(PointOfInstantiation);
  2256. if (ASTMutationListener *L = getASTContext().getASTMutationListener())
  2257. L->InstantiationRequested(this);
  2258. }
  2259. } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
  2260. MSI->setTemplateSpecializationKind(TSK);
  2261. if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
  2262. MSI->getPointOfInstantiation().isInvalid()) {
  2263. MSI->setPointOfInstantiation(PointOfInstantiation);
  2264. if (ASTMutationListener *L = getASTContext().getASTMutationListener())
  2265. L->InstantiationRequested(this);
  2266. }
  2267. }
  2268. }
  2269. void
  2270. VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
  2271. TemplateSpecializationKind TSK) {
  2272. assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
  2273. "Previous template or instantiation?");
  2274. getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
  2275. }
  2276. //===----------------------------------------------------------------------===//
  2277. // ParmVarDecl Implementation
  2278. //===----------------------------------------------------------------------===//
  2279. ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
  2280. SourceLocation StartLoc,
  2281. SourceLocation IdLoc, IdentifierInfo *Id,
  2282. QualType T, TypeSourceInfo *TInfo,
  2283. StorageClass S, Expr *DefArg) {
  2284. return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
  2285. S, DefArg);
  2286. }
  2287. QualType ParmVarDecl::getOriginalType() const {
  2288. TypeSourceInfo *TSI = getTypeSourceInfo();
  2289. QualType T = TSI ? TSI->getType() : getType();
  2290. if (const auto *DT = dyn_cast<DecayedType>(T))
  2291. return DT->getOriginalType();
  2292. return T;
  2293. }
  2294. ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2295. return new (C, ID)
  2296. ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
  2297. nullptr, QualType(), nullptr, SC_None, nullptr);
  2298. }
  2299. SourceRange ParmVarDecl::getSourceRange() const {
  2300. if (!hasInheritedDefaultArg()) {
  2301. SourceRange ArgRange = getDefaultArgRange();
  2302. if (ArgRange.isValid())
  2303. return SourceRange(getOuterLocStart(), ArgRange.getEnd());
  2304. }
  2305. // DeclaratorDecl considers the range of postfix types as overlapping with the
  2306. // declaration name, but this is not the case with parameters in ObjC methods.
  2307. if (isa<ObjCMethodDecl>(getDeclContext()))
  2308. return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
  2309. return DeclaratorDecl::getSourceRange();
  2310. }
  2311. Expr *ParmVarDecl::getDefaultArg() {
  2312. assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
  2313. assert(!hasUninstantiatedDefaultArg() &&
  2314. "Default argument is not yet instantiated!");
  2315. Expr *Arg = getInit();
  2316. if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
  2317. return E->getSubExpr();
  2318. return Arg;
  2319. }
  2320. void ParmVarDecl::setDefaultArg(Expr *defarg) {
  2321. ParmVarDeclBits.DefaultArgKind = DAK_Normal;
  2322. Init = defarg;
  2323. }
  2324. SourceRange ParmVarDecl::getDefaultArgRange() const {
  2325. switch (ParmVarDeclBits.DefaultArgKind) {
  2326. case DAK_None:
  2327. case DAK_Unparsed:
  2328. // Nothing we can do here.
  2329. return SourceRange();
  2330. case DAK_Uninstantiated:
  2331. return getUninstantiatedDefaultArg()->getSourceRange();
  2332. case DAK_Normal:
  2333. if (const Expr *E = getInit())
  2334. return E->getSourceRange();
  2335. // Missing an actual expression, may be invalid.
  2336. return SourceRange();
  2337. }
  2338. llvm_unreachable("Invalid default argument kind.");
  2339. }
  2340. void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
  2341. ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
  2342. Init = arg;
  2343. }
  2344. Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
  2345. assert(hasUninstantiatedDefaultArg() &&
  2346. "Wrong kind of initialization expression!");
  2347. return cast_or_null<Expr>(Init.get<Stmt *>());
  2348. }
  2349. bool ParmVarDecl::hasDefaultArg() const {
  2350. // FIXME: We should just return false for DAK_None here once callers are
  2351. // prepared for the case that we encountered an invalid default argument and
  2352. // were unable to even build an invalid expression.
  2353. return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
  2354. !Init.isNull();
  2355. }
  2356. void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
  2357. getASTContext().setParameterIndex(this, parameterIndex);
  2358. ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
  2359. }
  2360. unsigned ParmVarDecl::getParameterIndexLarge() const {
  2361. return getASTContext().getParameterIndex(this);
  2362. }
  2363. //===----------------------------------------------------------------------===//
  2364. // FunctionDecl Implementation
  2365. //===----------------------------------------------------------------------===//
  2366. FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
  2367. SourceLocation StartLoc,
  2368. const DeclarationNameInfo &NameInfo, QualType T,
  2369. TypeSourceInfo *TInfo, StorageClass S,
  2370. bool isInlineSpecified,
  2371. ConstexprSpecKind ConstexprKind)
  2372. : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
  2373. StartLoc),
  2374. DeclContext(DK), redeclarable_base(C), ODRHash(0),
  2375. EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
  2376. assert(T.isNull() || T->isFunctionType());
  2377. FunctionDeclBits.SClass = S;
  2378. FunctionDeclBits.IsInline = isInlineSpecified;
  2379. FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
  2380. FunctionDeclBits.IsVirtualAsWritten = false;
  2381. FunctionDeclBits.IsPure = false;
  2382. FunctionDeclBits.HasInheritedPrototype = false;
  2383. FunctionDeclBits.HasWrittenPrototype = true;
  2384. FunctionDeclBits.IsDeleted = false;
  2385. FunctionDeclBits.IsTrivial = false;
  2386. FunctionDeclBits.IsTrivialForCall = false;
  2387. FunctionDeclBits.IsDefaulted = false;
  2388. FunctionDeclBits.IsExplicitlyDefaulted = false;
  2389. FunctionDeclBits.HasImplicitReturnZero = false;
  2390. FunctionDeclBits.IsLateTemplateParsed = false;
  2391. FunctionDeclBits.ConstexprKind = ConstexprKind;
  2392. FunctionDeclBits.InstantiationIsPending = false;
  2393. FunctionDeclBits.UsesSEHTry = false;
  2394. FunctionDeclBits.HasSkippedBody = false;
  2395. FunctionDeclBits.WillHaveBody = false;
  2396. FunctionDeclBits.IsMultiVersion = false;
  2397. FunctionDeclBits.IsCopyDeductionCandidate = false;
  2398. FunctionDeclBits.HasODRHash = false;
  2399. }
  2400. void FunctionDecl::getNameForDiagnostic(
  2401. raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
  2402. NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
  2403. const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
  2404. if (TemplateArgs)
  2405. printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
  2406. }
  2407. bool FunctionDecl::isVariadic() const {
  2408. if (const auto *FT = getType()->getAs<FunctionProtoType>())
  2409. return FT->isVariadic();
  2410. return false;
  2411. }
  2412. bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
  2413. for (auto I : redecls()) {
  2414. if (I->doesThisDeclarationHaveABody()) {
  2415. Definition = I;
  2416. return true;
  2417. }
  2418. }
  2419. return false;
  2420. }
  2421. bool FunctionDecl::hasTrivialBody() const
  2422. {
  2423. Stmt *S = getBody();
  2424. if (!S) {
  2425. // Since we don't have a body for this function, we don't know if it's
  2426. // trivial or not.
  2427. return false;
  2428. }
  2429. if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
  2430. return true;
  2431. return false;
  2432. }
  2433. bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
  2434. for (auto I : redecls()) {
  2435. if (I->isThisDeclarationADefinition()) {
  2436. Definition = I;
  2437. return true;
  2438. }
  2439. }
  2440. return false;
  2441. }
  2442. Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
  2443. if (!hasBody(Definition))
  2444. return nullptr;
  2445. if (Definition->Body)
  2446. return Definition->Body.get(getASTContext().getExternalSource());
  2447. return nullptr;
  2448. }
  2449. void FunctionDecl::setBody(Stmt *B) {
  2450. Body = B;
  2451. if (B)
  2452. EndRangeLoc = B->getEndLoc();
  2453. }
  2454. void FunctionDecl::setPure(bool P) {
  2455. FunctionDeclBits.IsPure = P;
  2456. if (P)
  2457. if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
  2458. Parent->markedVirtualFunctionPure();
  2459. }
  2460. template<std::size_t Len>
  2461. static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
  2462. IdentifierInfo *II = ND->getIdentifier();
  2463. return II && II->isStr(Str);
  2464. }
  2465. bool FunctionDecl::isMain() const {
  2466. const TranslationUnitDecl *tunit =
  2467. dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
  2468. return tunit &&
  2469. !tunit->getASTContext().getLangOpts().Freestanding &&
  2470. isNamed(this, "main");
  2471. }
  2472. bool FunctionDecl::isMSVCRTEntryPoint() const {
  2473. const TranslationUnitDecl *TUnit =
  2474. dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
  2475. if (!TUnit)
  2476. return false;
  2477. // Even though we aren't really targeting MSVCRT if we are freestanding,
  2478. // semantic analysis for these functions remains the same.
  2479. // MSVCRT entry points only exist on MSVCRT targets.
  2480. if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
  2481. return false;
  2482. // Nameless functions like constructors cannot be entry points.
  2483. if (!getIdentifier())
  2484. return false;
  2485. return llvm::StringSwitch<bool>(getName())
  2486. .Cases("main", // an ANSI console app
  2487. "wmain", // a Unicode console App
  2488. "WinMain", // an ANSI GUI app
  2489. "wWinMain", // a Unicode GUI app
  2490. "DllMain", // a DLL
  2491. true)
  2492. .Default(false);
  2493. }
  2494. bool FunctionDecl::isReservedGlobalPlacementOperator() const {
  2495. assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
  2496. assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
  2497. getDeclName().getCXXOverloadedOperator() == OO_Delete ||
  2498. getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
  2499. getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
  2500. if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
  2501. return false;
  2502. const auto *proto = getType()->castAs<FunctionProtoType>();
  2503. if (proto->getNumParams() != 2 || proto->isVariadic())
  2504. return false;
  2505. ASTContext &Context =
  2506. cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
  2507. ->getASTContext();
  2508. // The result type and first argument type are constant across all
  2509. // these operators. The second argument must be exactly void*.
  2510. return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
  2511. }
  2512. bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const {
  2513. if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
  2514. return false;
  2515. if (getDeclName().getCXXOverloadedOperator() != OO_New &&
  2516. getDeclName().getCXXOverloadedOperator() != OO_Delete &&
  2517. getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
  2518. getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
  2519. return false;
  2520. if (isa<CXXRecordDecl>(getDeclContext()))
  2521. return false;
  2522. // This can only fail for an invalid 'operator new' declaration.
  2523. if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
  2524. return false;
  2525. const auto *FPT = getType()->castAs<FunctionProtoType>();
  2526. if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
  2527. return false;
  2528. // If this is a single-parameter function, it must be a replaceable global
  2529. // allocation or deallocation function.
  2530. if (FPT->getNumParams() == 1)
  2531. return true;
  2532. unsigned Params = 1;
  2533. QualType Ty = FPT->getParamType(Params);
  2534. ASTContext &Ctx = getASTContext();
  2535. auto Consume = [&] {
  2536. ++Params;
  2537. Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
  2538. };
  2539. // In C++14, the next parameter can be a 'std::size_t' for sized delete.
  2540. bool IsSizedDelete = false;
  2541. if (Ctx.getLangOpts().SizedDeallocation &&
  2542. (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
  2543. getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
  2544. Ctx.hasSameType(Ty, Ctx.getSizeType())) {
  2545. IsSizedDelete = true;
  2546. Consume();
  2547. }
  2548. // In C++17, the next parameter can be a 'std::align_val_t' for aligned
  2549. // new/delete.
  2550. if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
  2551. if (IsAligned)
  2552. *IsAligned = true;
  2553. Consume();
  2554. }
  2555. // Finally, if this is not a sized delete, the final parameter can
  2556. // be a 'const std::nothrow_t&'.
  2557. if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
  2558. Ty = Ty->getPointeeType();
  2559. if (Ty.getCVRQualifiers() != Qualifiers::Const)
  2560. return false;
  2561. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  2562. if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace())
  2563. Consume();
  2564. }
  2565. return Params == FPT->getNumParams();
  2566. }
  2567. bool FunctionDecl::isDestroyingOperatorDelete() const {
  2568. // C++ P0722:
  2569. // Within a class C, a single object deallocation function with signature
  2570. // (T, std::destroying_delete_t, <more params>)
  2571. // is a destroying operator delete.
  2572. if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
  2573. getNumParams() < 2)
  2574. return false;
  2575. auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
  2576. return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
  2577. RD->getIdentifier()->isStr("destroying_delete_t");
  2578. }
  2579. LanguageLinkage FunctionDecl::getLanguageLinkage() const {
  2580. return getDeclLanguageLinkage(*this);
  2581. }
  2582. bool FunctionDecl::isExternC() const {
  2583. return isDeclExternC(*this);
  2584. }
  2585. bool FunctionDecl::isInExternCContext() const {
  2586. if (hasAttr<OpenCLKernelAttr>())
  2587. return true;
  2588. return getLexicalDeclContext()->isExternCContext();
  2589. }
  2590. bool FunctionDecl::isInExternCXXContext() const {
  2591. return getLexicalDeclContext()->isExternCXXContext();
  2592. }
  2593. bool FunctionDecl::isGlobal() const {
  2594. if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
  2595. return Method->isStatic();
  2596. if (getCanonicalDecl()->getStorageClass() == SC_Static)
  2597. return false;
  2598. for (const DeclContext *DC = getDeclContext();
  2599. DC->isNamespace();
  2600. DC = DC->getParent()) {
  2601. if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
  2602. if (!Namespace->getDeclName())
  2603. return false;
  2604. break;
  2605. }
  2606. }
  2607. return true;
  2608. }
  2609. bool FunctionDecl::isNoReturn() const {
  2610. if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
  2611. hasAttr<C11NoReturnAttr>())
  2612. return true;
  2613. if (auto *FnTy = getType()->getAs<FunctionType>())
  2614. return FnTy->getNoReturnAttr();
  2615. return false;
  2616. }
  2617. MultiVersionKind FunctionDecl::getMultiVersionKind() const {
  2618. if (hasAttr<TargetAttr>())
  2619. return MultiVersionKind::Target;
  2620. if (hasAttr<CPUDispatchAttr>())
  2621. return MultiVersionKind::CPUDispatch;
  2622. if (hasAttr<CPUSpecificAttr>())
  2623. return MultiVersionKind::CPUSpecific;
  2624. return MultiVersionKind::None;
  2625. }
  2626. bool FunctionDecl::isCPUDispatchMultiVersion() const {
  2627. return isMultiVersion() && hasAttr<CPUDispatchAttr>();
  2628. }
  2629. bool FunctionDecl::isCPUSpecificMultiVersion() const {
  2630. return isMultiVersion() && hasAttr<CPUSpecificAttr>();
  2631. }
  2632. bool FunctionDecl::isTargetMultiVersion() const {
  2633. return isMultiVersion() && hasAttr<TargetAttr>();
  2634. }
  2635. void
  2636. FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
  2637. redeclarable_base::setPreviousDecl(PrevDecl);
  2638. if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
  2639. FunctionTemplateDecl *PrevFunTmpl
  2640. = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
  2641. assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
  2642. FunTmpl->setPreviousDecl(PrevFunTmpl);
  2643. }
  2644. if (PrevDecl && PrevDecl->isInlined())
  2645. setImplicitlyInline(true);
  2646. }
  2647. FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
  2648. /// Returns a value indicating whether this function corresponds to a builtin
  2649. /// function.
  2650. ///
  2651. /// The function corresponds to a built-in function if it is declared at
  2652. /// translation scope or within an extern "C" block and its name matches with
  2653. /// the name of a builtin. The returned value will be 0 for functions that do
  2654. /// not correspond to a builtin, a value of type \c Builtin::ID if in the
  2655. /// target-independent range \c [1,Builtin::First), or a target-specific builtin
  2656. /// value.
  2657. ///
  2658. /// \param ConsiderWrapperFunctions If true, we should consider wrapper
  2659. /// functions as their wrapped builtins. This shouldn't be done in general, but
  2660. /// it's useful in Sema to diagnose calls to wrappers based on their semantics.
  2661. unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
  2662. if (!getIdentifier())
  2663. return 0;
  2664. unsigned BuiltinID = getIdentifier()->getBuiltinID();
  2665. if (!BuiltinID)
  2666. return 0;
  2667. ASTContext &Context = getASTContext();
  2668. if (Context.getLangOpts().CPlusPlus) {
  2669. const auto *LinkageDecl =
  2670. dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
  2671. // In C++, the first declaration of a builtin is always inside an implicit
  2672. // extern "C".
  2673. // FIXME: A recognised library function may not be directly in an extern "C"
  2674. // declaration, for instance "extern "C" { namespace std { decl } }".
  2675. if (!LinkageDecl) {
  2676. if (BuiltinID == Builtin::BI__GetExceptionInfo &&
  2677. Context.getTargetInfo().getCXXABI().isMicrosoft())
  2678. return Builtin::BI__GetExceptionInfo;
  2679. return 0;
  2680. }
  2681. if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
  2682. return 0;
  2683. }
  2684. // If the function is marked "overloadable", it has a different mangled name
  2685. // and is not the C library function.
  2686. if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>())
  2687. return 0;
  2688. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
  2689. return BuiltinID;
  2690. // This function has the name of a known C library
  2691. // function. Determine whether it actually refers to the C library
  2692. // function or whether it just has the same name.
  2693. // If this is a static function, it's not a builtin.
  2694. if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
  2695. return 0;
  2696. // OpenCL v1.2 s6.9.f - The library functions defined in
  2697. // the C99 standard headers are not available.
  2698. if (Context.getLangOpts().OpenCL &&
  2699. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
  2700. return 0;
  2701. // CUDA does not have device-side standard library. printf and malloc are the
  2702. // only special cases that are supported by device-side runtime.
  2703. if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
  2704. !hasAttr<CUDAHostAttr>() &&
  2705. !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
  2706. return 0;
  2707. return BuiltinID;
  2708. }
  2709. /// getNumParams - Return the number of parameters this function must have
  2710. /// based on its FunctionType. This is the length of the ParamInfo array
  2711. /// after it has been created.
  2712. unsigned FunctionDecl::getNumParams() const {
  2713. const auto *FPT = getType()->getAs<FunctionProtoType>();
  2714. return FPT ? FPT->getNumParams() : 0;
  2715. }
  2716. void FunctionDecl::setParams(ASTContext &C,
  2717. ArrayRef<ParmVarDecl *> NewParamInfo) {
  2718. assert(!ParamInfo && "Already has param info!");
  2719. assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
  2720. // Zero params -> null pointer.
  2721. if (!NewParamInfo.empty()) {
  2722. ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
  2723. std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
  2724. }
  2725. }
  2726. /// getMinRequiredArguments - Returns the minimum number of arguments
  2727. /// needed to call this function. This may be fewer than the number of
  2728. /// function parameters, if some of the parameters have default
  2729. /// arguments (in C++) or are parameter packs (C++11).
  2730. unsigned FunctionDecl::getMinRequiredArguments() const {
  2731. if (!getASTContext().getLangOpts().CPlusPlus)
  2732. return getNumParams();
  2733. unsigned NumRequiredArgs = 0;
  2734. for (auto *Param : parameters())
  2735. if (!Param->isParameterPack() && !Param->hasDefaultArg())
  2736. ++NumRequiredArgs;
  2737. return NumRequiredArgs;
  2738. }
  2739. /// The combination of the extern and inline keywords under MSVC forces
  2740. /// the function to be required.
  2741. ///
  2742. /// Note: This function assumes that we will only get called when isInlined()
  2743. /// would return true for this FunctionDecl.
  2744. bool FunctionDecl::isMSExternInline() const {
  2745. assert(isInlined() && "expected to get called on an inlined function!");
  2746. const ASTContext &Context = getASTContext();
  2747. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  2748. !hasAttr<DLLExportAttr>())
  2749. return false;
  2750. for (const FunctionDecl *FD = getMostRecentDecl(); FD;
  2751. FD = FD->getPreviousDecl())
  2752. if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
  2753. return true;
  2754. return false;
  2755. }
  2756. static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
  2757. if (Redecl->getStorageClass() != SC_Extern)
  2758. return false;
  2759. for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
  2760. FD = FD->getPreviousDecl())
  2761. if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
  2762. return false;
  2763. return true;
  2764. }
  2765. static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
  2766. // Only consider file-scope declarations in this test.
  2767. if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
  2768. return false;
  2769. // Only consider explicit declarations; the presence of a builtin for a
  2770. // libcall shouldn't affect whether a definition is externally visible.
  2771. if (Redecl->isImplicit())
  2772. return false;
  2773. if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
  2774. return true; // Not an inline definition
  2775. return false;
  2776. }
  2777. /// For a function declaration in C or C++, determine whether this
  2778. /// declaration causes the definition to be externally visible.
  2779. ///
  2780. /// For instance, this determines if adding the current declaration to the set
  2781. /// of redeclarations of the given functions causes
  2782. /// isInlineDefinitionExternallyVisible to change from false to true.
  2783. bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
  2784. assert(!doesThisDeclarationHaveABody() &&
  2785. "Must have a declaration without a body.");
  2786. ASTContext &Context = getASTContext();
  2787. if (Context.getLangOpts().MSVCCompat) {
  2788. const FunctionDecl *Definition;
  2789. if (hasBody(Definition) && Definition->isInlined() &&
  2790. redeclForcesDefMSVC(this))
  2791. return true;
  2792. }
  2793. if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
  2794. // With GNU inlining, a declaration with 'inline' but not 'extern', forces
  2795. // an externally visible definition.
  2796. //
  2797. // FIXME: What happens if gnu_inline gets added on after the first
  2798. // declaration?
  2799. if (!isInlineSpecified() || getStorageClass() == SC_Extern)
  2800. return false;
  2801. const FunctionDecl *Prev = this;
  2802. bool FoundBody = false;
  2803. while ((Prev = Prev->getPreviousDecl())) {
  2804. FoundBody |= Prev->Body.isValid();
  2805. if (Prev->Body) {
  2806. // If it's not the case that both 'inline' and 'extern' are
  2807. // specified on the definition, then it is always externally visible.
  2808. if (!Prev->isInlineSpecified() ||
  2809. Prev->getStorageClass() != SC_Extern)
  2810. return false;
  2811. } else if (Prev->isInlineSpecified() &&
  2812. Prev->getStorageClass() != SC_Extern) {
  2813. return false;
  2814. }
  2815. }
  2816. return FoundBody;
  2817. }
  2818. if (Context.getLangOpts().CPlusPlus)
  2819. return false;
  2820. // C99 6.7.4p6:
  2821. // [...] If all of the file scope declarations for a function in a
  2822. // translation unit include the inline function specifier without extern,
  2823. // then the definition in that translation unit is an inline definition.
  2824. if (isInlineSpecified() && getStorageClass() != SC_Extern)
  2825. return false;
  2826. const FunctionDecl *Prev = this;
  2827. bool FoundBody = false;
  2828. while ((Prev = Prev->getPreviousDecl())) {
  2829. FoundBody |= Prev->Body.isValid();
  2830. if (RedeclForcesDefC99(Prev))
  2831. return false;
  2832. }
  2833. return FoundBody;
  2834. }
  2835. SourceRange FunctionDecl::getReturnTypeSourceRange() const {
  2836. const TypeSourceInfo *TSI = getTypeSourceInfo();
  2837. if (!TSI)
  2838. return SourceRange();
  2839. FunctionTypeLoc FTL =
  2840. TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
  2841. if (!FTL)
  2842. return SourceRange();
  2843. // Skip self-referential return types.
  2844. const SourceManager &SM = getASTContext().getSourceManager();
  2845. SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
  2846. SourceLocation Boundary = getNameInfo().getBeginLoc();
  2847. if (RTRange.isInvalid() || Boundary.isInvalid() ||
  2848. !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
  2849. return SourceRange();
  2850. return RTRange;
  2851. }
  2852. SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
  2853. const TypeSourceInfo *TSI = getTypeSourceInfo();
  2854. if (!TSI)
  2855. return SourceRange();
  2856. FunctionTypeLoc FTL =
  2857. TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
  2858. if (!FTL)
  2859. return SourceRange();
  2860. return FTL.getExceptionSpecRange();
  2861. }
  2862. /// For an inline function definition in C, or for a gnu_inline function
  2863. /// in C++, determine whether the definition will be externally visible.
  2864. ///
  2865. /// Inline function definitions are always available for inlining optimizations.
  2866. /// However, depending on the language dialect, declaration specifiers, and
  2867. /// attributes, the definition of an inline function may or may not be
  2868. /// "externally" visible to other translation units in the program.
  2869. ///
  2870. /// In C99, inline definitions are not externally visible by default. However,
  2871. /// if even one of the global-scope declarations is marked "extern inline", the
  2872. /// inline definition becomes externally visible (C99 6.7.4p6).
  2873. ///
  2874. /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
  2875. /// definition, we use the GNU semantics for inline, which are nearly the
  2876. /// opposite of C99 semantics. In particular, "inline" by itself will create
  2877. /// an externally visible symbol, but "extern inline" will not create an
  2878. /// externally visible symbol.
  2879. bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
  2880. assert((doesThisDeclarationHaveABody() || willHaveBody()) &&
  2881. "Must be a function definition");
  2882. assert(isInlined() && "Function must be inline");
  2883. ASTContext &Context = getASTContext();
  2884. if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
  2885. // Note: If you change the logic here, please change
  2886. // doesDeclarationForceExternallyVisibleDefinition as well.
  2887. //
  2888. // If it's not the case that both 'inline' and 'extern' are
  2889. // specified on the definition, then this inline definition is
  2890. // externally visible.
  2891. if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
  2892. return true;
  2893. // If any declaration is 'inline' but not 'extern', then this definition
  2894. // is externally visible.
  2895. for (auto Redecl : redecls()) {
  2896. if (Redecl->isInlineSpecified() &&
  2897. Redecl->getStorageClass() != SC_Extern)
  2898. return true;
  2899. }
  2900. return false;
  2901. }
  2902. // The rest of this function is C-only.
  2903. assert(!Context.getLangOpts().CPlusPlus &&
  2904. "should not use C inline rules in C++");
  2905. // C99 6.7.4p6:
  2906. // [...] If all of the file scope declarations for a function in a
  2907. // translation unit include the inline function specifier without extern,
  2908. // then the definition in that translation unit is an inline definition.
  2909. for (auto Redecl : redecls()) {
  2910. if (RedeclForcesDefC99(Redecl))
  2911. return true;
  2912. }
  2913. // C99 6.7.4p6:
  2914. // An inline definition does not provide an external definition for the
  2915. // function, and does not forbid an external definition in another
  2916. // translation unit.
  2917. return false;
  2918. }
  2919. /// getOverloadedOperator - Which C++ overloaded operator this
  2920. /// function represents, if any.
  2921. OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
  2922. if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
  2923. return getDeclName().getCXXOverloadedOperator();
  2924. else
  2925. return OO_None;
  2926. }
  2927. /// getLiteralIdentifier - The literal suffix identifier this function
  2928. /// represents, if any.
  2929. const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
  2930. if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
  2931. return getDeclName().getCXXLiteralIdentifier();
  2932. else
  2933. return nullptr;
  2934. }
  2935. FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
  2936. if (TemplateOrSpecialization.isNull())
  2937. return TK_NonTemplate;
  2938. if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
  2939. return TK_FunctionTemplate;
  2940. if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
  2941. return TK_MemberSpecialization;
  2942. if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
  2943. return TK_FunctionTemplateSpecialization;
  2944. if (TemplateOrSpecialization.is
  2945. <DependentFunctionTemplateSpecializationInfo*>())
  2946. return TK_DependentFunctionTemplateSpecialization;
  2947. llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
  2948. }
  2949. FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
  2950. if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
  2951. return cast<FunctionDecl>(Info->getInstantiatedFrom());
  2952. return nullptr;
  2953. }
  2954. MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
  2955. if (auto *MSI =
  2956. TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
  2957. return MSI;
  2958. if (auto *FTSI = TemplateOrSpecialization
  2959. .dyn_cast<FunctionTemplateSpecializationInfo *>())
  2960. return FTSI->getMemberSpecializationInfo();
  2961. return nullptr;
  2962. }
  2963. void
  2964. FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
  2965. FunctionDecl *FD,
  2966. TemplateSpecializationKind TSK) {
  2967. assert(TemplateOrSpecialization.isNull() &&
  2968. "Member function is already a specialization");
  2969. MemberSpecializationInfo *Info
  2970. = new (C) MemberSpecializationInfo(FD, TSK);
  2971. TemplateOrSpecialization = Info;
  2972. }
  2973. FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
  2974. return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
  2975. }
  2976. void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
  2977. assert(TemplateOrSpecialization.isNull() &&
  2978. "Member function is already a specialization");
  2979. TemplateOrSpecialization = Template;
  2980. }
  2981. bool FunctionDecl::isImplicitlyInstantiable() const {
  2982. // If the function is invalid, it can't be implicitly instantiated.
  2983. if (isInvalidDecl())
  2984. return false;
  2985. switch (getTemplateSpecializationKindForInstantiation()) {
  2986. case TSK_Undeclared:
  2987. case TSK_ExplicitInstantiationDefinition:
  2988. case TSK_ExplicitSpecialization:
  2989. return false;
  2990. case TSK_ImplicitInstantiation:
  2991. return true;
  2992. case TSK_ExplicitInstantiationDeclaration:
  2993. // Handled below.
  2994. break;
  2995. }
  2996. // Find the actual template from which we will instantiate.
  2997. const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
  2998. bool HasPattern = false;
  2999. if (PatternDecl)
  3000. HasPattern = PatternDecl->hasBody(PatternDecl);
  3001. // C++0x [temp.explicit]p9:
  3002. // Except for inline functions, other explicit instantiation declarations
  3003. // have the effect of suppressing the implicit instantiation of the entity
  3004. // to which they refer.
  3005. if (!HasPattern || !PatternDecl)
  3006. return true;
  3007. return PatternDecl->isInlined();
  3008. }
  3009. bool FunctionDecl::isTemplateInstantiation() const {
  3010. // FIXME: Remove this, it's not clear what it means. (Which template
  3011. // specialization kind?)
  3012. return clang::isTemplateInstantiation(getTemplateSpecializationKind());
  3013. }
  3014. FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
  3015. // If this is a generic lambda call operator specialization, its
  3016. // instantiation pattern is always its primary template's pattern
  3017. // even if its primary template was instantiated from another
  3018. // member template (which happens with nested generic lambdas).
  3019. // Since a lambda's call operator's body is transformed eagerly,
  3020. // we don't have to go hunting for a prototype definition template
  3021. // (i.e. instantiated-from-member-template) to use as an instantiation
  3022. // pattern.
  3023. if (isGenericLambdaCallOperatorSpecialization(
  3024. dyn_cast<CXXMethodDecl>(this))) {
  3025. assert(getPrimaryTemplate() && "not a generic lambda call operator?");
  3026. return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
  3027. }
  3028. if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) {
  3029. if (!clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
  3030. return nullptr;
  3031. return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
  3032. }
  3033. if (!clang::isTemplateInstantiation(getTemplateSpecializationKind()))
  3034. return nullptr;
  3035. if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
  3036. // If we hit a point where the user provided a specialization of this
  3037. // template, we're done looking.
  3038. while (!Primary->isMemberSpecialization()) {
  3039. auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
  3040. if (!NewPrimary)
  3041. break;
  3042. Primary = NewPrimary;
  3043. }
  3044. return getDefinitionOrSelf(Primary->getTemplatedDecl());
  3045. }
  3046. return nullptr;
  3047. }
  3048. FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
  3049. if (FunctionTemplateSpecializationInfo *Info
  3050. = TemplateOrSpecialization
  3051. .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
  3052. return Info->getTemplate();
  3053. }
  3054. return nullptr;
  3055. }
  3056. FunctionTemplateSpecializationInfo *
  3057. FunctionDecl::getTemplateSpecializationInfo() const {
  3058. return TemplateOrSpecialization
  3059. .dyn_cast<FunctionTemplateSpecializationInfo *>();
  3060. }
  3061. const TemplateArgumentList *
  3062. FunctionDecl::getTemplateSpecializationArgs() const {
  3063. if (FunctionTemplateSpecializationInfo *Info
  3064. = TemplateOrSpecialization
  3065. .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
  3066. return Info->TemplateArguments;
  3067. }
  3068. return nullptr;
  3069. }
  3070. const ASTTemplateArgumentListInfo *
  3071. FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
  3072. if (FunctionTemplateSpecializationInfo *Info
  3073. = TemplateOrSpecialization
  3074. .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
  3075. return Info->TemplateArgumentsAsWritten;
  3076. }
  3077. return nullptr;
  3078. }
  3079. void
  3080. FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
  3081. FunctionTemplateDecl *Template,
  3082. const TemplateArgumentList *TemplateArgs,
  3083. void *InsertPos,
  3084. TemplateSpecializationKind TSK,
  3085. const TemplateArgumentListInfo *TemplateArgsAsWritten,
  3086. SourceLocation PointOfInstantiation) {
  3087. assert((TemplateOrSpecialization.isNull() ||
  3088. TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
  3089. "Member function is already a specialization");
  3090. assert(TSK != TSK_Undeclared &&
  3091. "Must specify the type of function template specialization");
  3092. assert((TemplateOrSpecialization.isNull() ||
  3093. TSK == TSK_ExplicitSpecialization) &&
  3094. "Member specialization must be an explicit specialization");
  3095. FunctionTemplateSpecializationInfo *Info =
  3096. FunctionTemplateSpecializationInfo::Create(
  3097. C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
  3098. PointOfInstantiation,
  3099. TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
  3100. TemplateOrSpecialization = Info;
  3101. Template->addSpecialization(Info, InsertPos);
  3102. }
  3103. void
  3104. FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
  3105. const UnresolvedSetImpl &Templates,
  3106. const TemplateArgumentListInfo &TemplateArgs) {
  3107. assert(TemplateOrSpecialization.isNull());
  3108. DependentFunctionTemplateSpecializationInfo *Info =
  3109. DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
  3110. TemplateArgs);
  3111. TemplateOrSpecialization = Info;
  3112. }
  3113. DependentFunctionTemplateSpecializationInfo *
  3114. FunctionDecl::getDependentSpecializationInfo() const {
  3115. return TemplateOrSpecialization
  3116. .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
  3117. }
  3118. DependentFunctionTemplateSpecializationInfo *
  3119. DependentFunctionTemplateSpecializationInfo::Create(
  3120. ASTContext &Context, const UnresolvedSetImpl &Ts,
  3121. const TemplateArgumentListInfo &TArgs) {
  3122. void *Buffer = Context.Allocate(
  3123. totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
  3124. TArgs.size(), Ts.size()));
  3125. return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
  3126. }
  3127. DependentFunctionTemplateSpecializationInfo::
  3128. DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
  3129. const TemplateArgumentListInfo &TArgs)
  3130. : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
  3131. NumTemplates = Ts.size();
  3132. NumArgs = TArgs.size();
  3133. FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
  3134. for (unsigned I = 0, E = Ts.size(); I != E; ++I)
  3135. TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
  3136. TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
  3137. for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
  3138. new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
  3139. }
  3140. TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
  3141. // For a function template specialization, query the specialization
  3142. // information object.
  3143. if (FunctionTemplateSpecializationInfo *FTSInfo =
  3144. TemplateOrSpecialization
  3145. .dyn_cast<FunctionTemplateSpecializationInfo *>())
  3146. return FTSInfo->getTemplateSpecializationKind();
  3147. if (MemberSpecializationInfo *MSInfo =
  3148. TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
  3149. return MSInfo->getTemplateSpecializationKind();
  3150. return TSK_Undeclared;
  3151. }
  3152. TemplateSpecializationKind
  3153. FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
  3154. // This is the same as getTemplateSpecializationKind(), except that for a
  3155. // function that is both a function template specialization and a member
  3156. // specialization, we prefer the member specialization information. Eg:
  3157. //
  3158. // template<typename T> struct A {
  3159. // template<typename U> void f() {}
  3160. // template<> void f<int>() {}
  3161. // };
  3162. //
  3163. // For A<int>::f<int>():
  3164. // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
  3165. // * getTemplateSpecializationKindForInstantiation() will return
  3166. // TSK_ImplicitInstantiation
  3167. //
  3168. // This reflects the facts that A<int>::f<int> is an explicit specialization
  3169. // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
  3170. // from A::f<int> if a definition is needed.
  3171. if (FunctionTemplateSpecializationInfo *FTSInfo =
  3172. TemplateOrSpecialization
  3173. .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
  3174. if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
  3175. return MSInfo->getTemplateSpecializationKind();
  3176. return FTSInfo->getTemplateSpecializationKind();
  3177. }
  3178. if (MemberSpecializationInfo *MSInfo =
  3179. TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
  3180. return MSInfo->getTemplateSpecializationKind();
  3181. return TSK_Undeclared;
  3182. }
  3183. void
  3184. FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  3185. SourceLocation PointOfInstantiation) {
  3186. if (FunctionTemplateSpecializationInfo *FTSInfo
  3187. = TemplateOrSpecialization.dyn_cast<
  3188. FunctionTemplateSpecializationInfo*>()) {
  3189. FTSInfo->setTemplateSpecializationKind(TSK);
  3190. if (TSK != TSK_ExplicitSpecialization &&
  3191. PointOfInstantiation.isValid() &&
  3192. FTSInfo->getPointOfInstantiation().isInvalid()) {
  3193. FTSInfo->setPointOfInstantiation(PointOfInstantiation);
  3194. if (ASTMutationListener *L = getASTContext().getASTMutationListener())
  3195. L->InstantiationRequested(this);
  3196. }
  3197. } else if (MemberSpecializationInfo *MSInfo
  3198. = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
  3199. MSInfo->setTemplateSpecializationKind(TSK);
  3200. if (TSK != TSK_ExplicitSpecialization &&
  3201. PointOfInstantiation.isValid() &&
  3202. MSInfo->getPointOfInstantiation().isInvalid()) {
  3203. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  3204. if (ASTMutationListener *L = getASTContext().getASTMutationListener())
  3205. L->InstantiationRequested(this);
  3206. }
  3207. } else
  3208. llvm_unreachable("Function cannot have a template specialization kind");
  3209. }
  3210. SourceLocation FunctionDecl::getPointOfInstantiation() const {
  3211. if (FunctionTemplateSpecializationInfo *FTSInfo
  3212. = TemplateOrSpecialization.dyn_cast<
  3213. FunctionTemplateSpecializationInfo*>())
  3214. return FTSInfo->getPointOfInstantiation();
  3215. else if (MemberSpecializationInfo *MSInfo
  3216. = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
  3217. return MSInfo->getPointOfInstantiation();
  3218. return SourceLocation();
  3219. }
  3220. bool FunctionDecl::isOutOfLine() const {
  3221. if (Decl::isOutOfLine())
  3222. return true;
  3223. // If this function was instantiated from a member function of a
  3224. // class template, check whether that member function was defined out-of-line.
  3225. if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
  3226. const FunctionDecl *Definition;
  3227. if (FD->hasBody(Definition))
  3228. return Definition->isOutOfLine();
  3229. }
  3230. // If this function was instantiated from a function template,
  3231. // check whether that function template was defined out-of-line.
  3232. if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
  3233. const FunctionDecl *Definition;
  3234. if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
  3235. return Definition->isOutOfLine();
  3236. }
  3237. return false;
  3238. }
  3239. SourceRange FunctionDecl::getSourceRange() const {
  3240. return SourceRange(getOuterLocStart(), EndRangeLoc);
  3241. }
  3242. unsigned FunctionDecl::getMemoryFunctionKind() const {
  3243. IdentifierInfo *FnInfo = getIdentifier();
  3244. if (!FnInfo)
  3245. return 0;
  3246. // Builtin handling.
  3247. switch (getBuiltinID()) {
  3248. case Builtin::BI__builtin_memset:
  3249. case Builtin::BI__builtin___memset_chk:
  3250. case Builtin::BImemset:
  3251. return Builtin::BImemset;
  3252. case Builtin::BI__builtin_memcpy:
  3253. case Builtin::BI__builtin___memcpy_chk:
  3254. case Builtin::BImemcpy:
  3255. return Builtin::BImemcpy;
  3256. case Builtin::BI__builtin_memmove:
  3257. case Builtin::BI__builtin___memmove_chk:
  3258. case Builtin::BImemmove:
  3259. return Builtin::BImemmove;
  3260. case Builtin::BIstrlcpy:
  3261. case Builtin::BI__builtin___strlcpy_chk:
  3262. return Builtin::BIstrlcpy;
  3263. case Builtin::BIstrlcat:
  3264. case Builtin::BI__builtin___strlcat_chk:
  3265. return Builtin::BIstrlcat;
  3266. case Builtin::BI__builtin_memcmp:
  3267. case Builtin::BImemcmp:
  3268. return Builtin::BImemcmp;
  3269. case Builtin::BI__builtin_bcmp:
  3270. case Builtin::BIbcmp:
  3271. return Builtin::BIbcmp;
  3272. case Builtin::BI__builtin_strncpy:
  3273. case Builtin::BI__builtin___strncpy_chk:
  3274. case Builtin::BIstrncpy:
  3275. return Builtin::BIstrncpy;
  3276. case Builtin::BI__builtin_strncmp:
  3277. case Builtin::BIstrncmp:
  3278. return Builtin::BIstrncmp;
  3279. case Builtin::BI__builtin_strncasecmp:
  3280. case Builtin::BIstrncasecmp:
  3281. return Builtin::BIstrncasecmp;
  3282. case Builtin::BI__builtin_strncat:
  3283. case Builtin::BI__builtin___strncat_chk:
  3284. case Builtin::BIstrncat:
  3285. return Builtin::BIstrncat;
  3286. case Builtin::BI__builtin_strndup:
  3287. case Builtin::BIstrndup:
  3288. return Builtin::BIstrndup;
  3289. case Builtin::BI__builtin_strlen:
  3290. case Builtin::BIstrlen:
  3291. return Builtin::BIstrlen;
  3292. case Builtin::BI__builtin_bzero:
  3293. case Builtin::BIbzero:
  3294. return Builtin::BIbzero;
  3295. default:
  3296. if (isExternC()) {
  3297. if (FnInfo->isStr("memset"))
  3298. return Builtin::BImemset;
  3299. else if (FnInfo->isStr("memcpy"))
  3300. return Builtin::BImemcpy;
  3301. else if (FnInfo->isStr("memmove"))
  3302. return Builtin::BImemmove;
  3303. else if (FnInfo->isStr("memcmp"))
  3304. return Builtin::BImemcmp;
  3305. else if (FnInfo->isStr("bcmp"))
  3306. return Builtin::BIbcmp;
  3307. else if (FnInfo->isStr("strncpy"))
  3308. return Builtin::BIstrncpy;
  3309. else if (FnInfo->isStr("strncmp"))
  3310. return Builtin::BIstrncmp;
  3311. else if (FnInfo->isStr("strncasecmp"))
  3312. return Builtin::BIstrncasecmp;
  3313. else if (FnInfo->isStr("strncat"))
  3314. return Builtin::BIstrncat;
  3315. else if (FnInfo->isStr("strndup"))
  3316. return Builtin::BIstrndup;
  3317. else if (FnInfo->isStr("strlen"))
  3318. return Builtin::BIstrlen;
  3319. else if (FnInfo->isStr("bzero"))
  3320. return Builtin::BIbzero;
  3321. }
  3322. break;
  3323. }
  3324. return 0;
  3325. }
  3326. unsigned FunctionDecl::getODRHash() const {
  3327. assert(hasODRHash());
  3328. return ODRHash;
  3329. }
  3330. unsigned FunctionDecl::getODRHash() {
  3331. if (hasODRHash())
  3332. return ODRHash;
  3333. if (auto *FT = getInstantiatedFromMemberFunction()) {
  3334. setHasODRHash(true);
  3335. ODRHash = FT->getODRHash();
  3336. return ODRHash;
  3337. }
  3338. class ODRHash Hash;
  3339. Hash.AddFunctionDecl(this);
  3340. setHasODRHash(true);
  3341. ODRHash = Hash.CalculateHash();
  3342. return ODRHash;
  3343. }
  3344. //===----------------------------------------------------------------------===//
  3345. // FieldDecl Implementation
  3346. //===----------------------------------------------------------------------===//
  3347. FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
  3348. SourceLocation StartLoc, SourceLocation IdLoc,
  3349. IdentifierInfo *Id, QualType T,
  3350. TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
  3351. InClassInitStyle InitStyle) {
  3352. return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
  3353. BW, Mutable, InitStyle);
  3354. }
  3355. FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3356. return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
  3357. SourceLocation(), nullptr, QualType(), nullptr,
  3358. nullptr, false, ICIS_NoInit);
  3359. }
  3360. bool FieldDecl::isAnonymousStructOrUnion() const {
  3361. if (!isImplicit() || getDeclName())
  3362. return false;
  3363. if (const auto *Record = getType()->getAs<RecordType>())
  3364. return Record->getDecl()->isAnonymousStructOrUnion();
  3365. return false;
  3366. }
  3367. unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
  3368. assert(isBitField() && "not a bitfield");
  3369. return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
  3370. }
  3371. bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
  3372. return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
  3373. getBitWidthValue(Ctx) == 0;
  3374. }
  3375. bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
  3376. if (isZeroLengthBitField(Ctx))
  3377. return true;
  3378. // C++2a [intro.object]p7:
  3379. // An object has nonzero size if it
  3380. // -- is not a potentially-overlapping subobject, or
  3381. if (!hasAttr<NoUniqueAddressAttr>())
  3382. return false;
  3383. // -- is not of class type, or
  3384. const auto *RT = getType()->getAs<RecordType>();
  3385. if (!RT)
  3386. return false;
  3387. const RecordDecl *RD = RT->getDecl()->getDefinition();
  3388. if (!RD) {
  3389. assert(isInvalidDecl() && "valid field has incomplete type");
  3390. return false;
  3391. }
  3392. // -- [has] virtual member functions or virtual base classes, or
  3393. // -- has subobjects of nonzero size or bit-fields of nonzero length
  3394. const auto *CXXRD = cast<CXXRecordDecl>(RD);
  3395. if (!CXXRD->isEmpty())
  3396. return false;
  3397. // Otherwise, [...] the circumstances under which the object has zero size
  3398. // are implementation-defined.
  3399. // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
  3400. // ABI will do.
  3401. return true;
  3402. }
  3403. unsigned FieldDecl::getFieldIndex() const {
  3404. const FieldDecl *Canonical = getCanonicalDecl();
  3405. if (Canonical != this)
  3406. return Canonical->getFieldIndex();
  3407. if (CachedFieldIndex) return CachedFieldIndex - 1;
  3408. unsigned Index = 0;
  3409. const RecordDecl *RD = getParent()->getDefinition();
  3410. assert(RD && "requested index for field of struct with no definition");
  3411. for (auto *Field : RD->fields()) {
  3412. Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
  3413. ++Index;
  3414. }
  3415. assert(CachedFieldIndex && "failed to find field in parent");
  3416. return CachedFieldIndex - 1;
  3417. }
  3418. SourceRange FieldDecl::getSourceRange() const {
  3419. const Expr *FinalExpr = getInClassInitializer();
  3420. if (!FinalExpr)
  3421. FinalExpr = getBitWidth();
  3422. if (FinalExpr)
  3423. return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
  3424. return DeclaratorDecl::getSourceRange();
  3425. }
  3426. void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
  3427. assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
  3428. "capturing type in non-lambda or captured record.");
  3429. assert(InitStorage.getInt() == ISK_NoInit &&
  3430. InitStorage.getPointer() == nullptr &&
  3431. "bit width, initializer or captured type already set");
  3432. InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
  3433. ISK_CapturedVLAType);
  3434. }
  3435. //===----------------------------------------------------------------------===//
  3436. // TagDecl Implementation
  3437. //===----------------------------------------------------------------------===//
  3438. TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
  3439. SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
  3440. SourceLocation StartL)
  3441. : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
  3442. TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
  3443. assert((DK != Enum || TK == TTK_Enum) &&
  3444. "EnumDecl not matched with TTK_Enum");
  3445. setPreviousDecl(PrevDecl);
  3446. setTagKind(TK);
  3447. setCompleteDefinition(false);
  3448. setBeingDefined(false);
  3449. setEmbeddedInDeclarator(false);
  3450. setFreeStanding(false);
  3451. setCompleteDefinitionRequired(false);
  3452. }
  3453. SourceLocation TagDecl::getOuterLocStart() const {
  3454. return getTemplateOrInnerLocStart(this);
  3455. }
  3456. SourceRange TagDecl::getSourceRange() const {
  3457. SourceLocation RBraceLoc = BraceRange.getEnd();
  3458. SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
  3459. return SourceRange(getOuterLocStart(), E);
  3460. }
  3461. TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
  3462. void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
  3463. TypedefNameDeclOrQualifier = TDD;
  3464. if (const Type *T = getTypeForDecl()) {
  3465. (void)T;
  3466. assert(T->isLinkageValid());
  3467. }
  3468. assert(isLinkageValid());
  3469. }
  3470. void TagDecl::startDefinition() {
  3471. setBeingDefined(true);
  3472. if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
  3473. struct CXXRecordDecl::DefinitionData *Data =
  3474. new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
  3475. for (auto I : redecls())
  3476. cast<CXXRecordDecl>(I)->DefinitionData = Data;
  3477. }
  3478. }
  3479. void TagDecl::completeDefinition() {
  3480. assert((!isa<CXXRecordDecl>(this) ||
  3481. cast<CXXRecordDecl>(this)->hasDefinition()) &&
  3482. "definition completed but not started");
  3483. setCompleteDefinition(true);
  3484. setBeingDefined(false);
  3485. if (ASTMutationListener *L = getASTMutationListener())
  3486. L->CompletedTagDefinition(this);
  3487. }
  3488. TagDecl *TagDecl::getDefinition() const {
  3489. if (isCompleteDefinition())
  3490. return const_cast<TagDecl *>(this);
  3491. // If it's possible for us to have an out-of-date definition, check now.
  3492. if (mayHaveOutOfDateDef()) {
  3493. if (IdentifierInfo *II = getIdentifier()) {
  3494. if (II->isOutOfDate()) {
  3495. updateOutOfDate(*II);
  3496. }
  3497. }
  3498. }
  3499. if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
  3500. return CXXRD->getDefinition();
  3501. for (auto R : redecls())
  3502. if (R->isCompleteDefinition())
  3503. return R;
  3504. return nullptr;
  3505. }
  3506. void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
  3507. if (QualifierLoc) {
  3508. // Make sure the extended qualifier info is allocated.
  3509. if (!hasExtInfo())
  3510. TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
  3511. // Set qualifier info.
  3512. getExtInfo()->QualifierLoc = QualifierLoc;
  3513. } else {
  3514. // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
  3515. if (hasExtInfo()) {
  3516. if (getExtInfo()->NumTemplParamLists == 0) {
  3517. getASTContext().Deallocate(getExtInfo());
  3518. TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
  3519. }
  3520. else
  3521. getExtInfo()->QualifierLoc = QualifierLoc;
  3522. }
  3523. }
  3524. }
  3525. void TagDecl::setTemplateParameterListsInfo(
  3526. ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
  3527. assert(!TPLists.empty());
  3528. // Make sure the extended decl info is allocated.
  3529. if (!hasExtInfo())
  3530. // Allocate external info struct.
  3531. TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
  3532. // Set the template parameter lists info.
  3533. getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
  3534. }
  3535. //===----------------------------------------------------------------------===//
  3536. // EnumDecl Implementation
  3537. //===----------------------------------------------------------------------===//
  3538. EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  3539. SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
  3540. bool Scoped, bool ScopedUsingClassTag, bool Fixed)
  3541. : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
  3542. assert(Scoped || !ScopedUsingClassTag);
  3543. IntegerType = nullptr;
  3544. setNumPositiveBits(0);
  3545. setNumNegativeBits(0);
  3546. setScoped(Scoped);
  3547. setScopedUsingClassTag(ScopedUsingClassTag);
  3548. setFixed(Fixed);
  3549. setHasODRHash(false);
  3550. ODRHash = 0;
  3551. }
  3552. void EnumDecl::anchor() {}
  3553. EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
  3554. SourceLocation StartLoc, SourceLocation IdLoc,
  3555. IdentifierInfo *Id,
  3556. EnumDecl *PrevDecl, bool IsScoped,
  3557. bool IsScopedUsingClassTag, bool IsFixed) {
  3558. auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
  3559. IsScoped, IsScopedUsingClassTag, IsFixed);
  3560. Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
  3561. C.getTypeDeclType(Enum, PrevDecl);
  3562. return Enum;
  3563. }
  3564. EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3565. EnumDecl *Enum =
  3566. new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
  3567. nullptr, nullptr, false, false, false);
  3568. Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
  3569. return Enum;
  3570. }
  3571. SourceRange EnumDecl::getIntegerTypeRange() const {
  3572. if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
  3573. return TI->getTypeLoc().getSourceRange();
  3574. return SourceRange();
  3575. }
  3576. void EnumDecl::completeDefinition(QualType NewType,
  3577. QualType NewPromotionType,
  3578. unsigned NumPositiveBits,
  3579. unsigned NumNegativeBits) {
  3580. assert(!isCompleteDefinition() && "Cannot redefine enums!");
  3581. if (!IntegerType)
  3582. IntegerType = NewType.getTypePtr();
  3583. PromotionType = NewPromotionType;
  3584. setNumPositiveBits(NumPositiveBits);
  3585. setNumNegativeBits(NumNegativeBits);
  3586. TagDecl::completeDefinition();
  3587. }
  3588. bool EnumDecl::isClosed() const {
  3589. if (const auto *A = getAttr<EnumExtensibilityAttr>())
  3590. return A->getExtensibility() == EnumExtensibilityAttr::Closed;
  3591. return true;
  3592. }
  3593. bool EnumDecl::isClosedFlag() const {
  3594. return isClosed() && hasAttr<FlagEnumAttr>();
  3595. }
  3596. bool EnumDecl::isClosedNonFlag() const {
  3597. return isClosed() && !hasAttr<FlagEnumAttr>();
  3598. }
  3599. TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
  3600. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  3601. return MSI->getTemplateSpecializationKind();
  3602. return TSK_Undeclared;
  3603. }
  3604. void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  3605. SourceLocation PointOfInstantiation) {
  3606. MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
  3607. assert(MSI && "Not an instantiated member enumeration?");
  3608. MSI->setTemplateSpecializationKind(TSK);
  3609. if (TSK != TSK_ExplicitSpecialization &&
  3610. PointOfInstantiation.isValid() &&
  3611. MSI->getPointOfInstantiation().isInvalid())
  3612. MSI->setPointOfInstantiation(PointOfInstantiation);
  3613. }
  3614. EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
  3615. if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
  3616. if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
  3617. EnumDecl *ED = getInstantiatedFromMemberEnum();
  3618. while (auto *NewED = ED->getInstantiatedFromMemberEnum())
  3619. ED = NewED;
  3620. return getDefinitionOrSelf(ED);
  3621. }
  3622. }
  3623. assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
  3624. "couldn't find pattern for enum instantiation");
  3625. return nullptr;
  3626. }
  3627. EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
  3628. if (SpecializationInfo)
  3629. return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
  3630. return nullptr;
  3631. }
  3632. void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
  3633. TemplateSpecializationKind TSK) {
  3634. assert(!SpecializationInfo && "Member enum is already a specialization");
  3635. SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
  3636. }
  3637. unsigned EnumDecl::getODRHash() {
  3638. if (hasODRHash())
  3639. return ODRHash;
  3640. class ODRHash Hash;
  3641. Hash.AddEnumDecl(this);
  3642. setHasODRHash(true);
  3643. ODRHash = Hash.CalculateHash();
  3644. return ODRHash;
  3645. }
  3646. //===----------------------------------------------------------------------===//
  3647. // RecordDecl Implementation
  3648. //===----------------------------------------------------------------------===//
  3649. RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
  3650. DeclContext *DC, SourceLocation StartLoc,
  3651. SourceLocation IdLoc, IdentifierInfo *Id,
  3652. RecordDecl *PrevDecl)
  3653. : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
  3654. assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
  3655. setHasFlexibleArrayMember(false);
  3656. setAnonymousStructOrUnion(false);
  3657. setHasObjectMember(false);
  3658. setHasVolatileMember(false);
  3659. setHasLoadedFieldsFromExternalStorage(false);
  3660. setNonTrivialToPrimitiveDefaultInitialize(false);
  3661. setNonTrivialToPrimitiveCopy(false);
  3662. setNonTrivialToPrimitiveDestroy(false);
  3663. setParamDestroyedInCallee(false);
  3664. setArgPassingRestrictions(APK_CanPassInRegs);
  3665. }
  3666. RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
  3667. SourceLocation StartLoc, SourceLocation IdLoc,
  3668. IdentifierInfo *Id, RecordDecl* PrevDecl) {
  3669. RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
  3670. StartLoc, IdLoc, Id, PrevDecl);
  3671. R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
  3672. C.getTypeDeclType(R, PrevDecl);
  3673. return R;
  3674. }
  3675. RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
  3676. RecordDecl *R =
  3677. new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
  3678. SourceLocation(), nullptr, nullptr);
  3679. R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
  3680. return R;
  3681. }
  3682. bool RecordDecl::isInjectedClassName() const {
  3683. return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
  3684. cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
  3685. }
  3686. bool RecordDecl::isLambda() const {
  3687. if (auto RD = dyn_cast<CXXRecordDecl>(this))
  3688. return RD->isLambda();
  3689. return false;
  3690. }
  3691. bool RecordDecl::isCapturedRecord() const {
  3692. return hasAttr<CapturedRecordAttr>();
  3693. }
  3694. void RecordDecl::setCapturedRecord() {
  3695. addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
  3696. }
  3697. RecordDecl::field_iterator RecordDecl::field_begin() const {
  3698. if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
  3699. LoadFieldsFromExternalStorage();
  3700. return field_iterator(decl_iterator(FirstDecl));
  3701. }
  3702. /// completeDefinition - Notes that the definition of this type is now
  3703. /// complete.
  3704. void RecordDecl::completeDefinition() {
  3705. assert(!isCompleteDefinition() && "Cannot redefine record!");
  3706. TagDecl::completeDefinition();
  3707. }
  3708. /// isMsStruct - Get whether or not this record uses ms_struct layout.
  3709. /// This which can be turned on with an attribute, pragma, or the
  3710. /// -mms-bitfields command-line option.
  3711. bool RecordDecl::isMsStruct(const ASTContext &C) const {
  3712. return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
  3713. }
  3714. void RecordDecl::LoadFieldsFromExternalStorage() const {
  3715. ExternalASTSource *Source = getASTContext().getExternalSource();
  3716. assert(hasExternalLexicalStorage() && Source && "No external storage?");
  3717. // Notify that we have a RecordDecl doing some initialization.
  3718. ExternalASTSource::Deserializing TheFields(Source);
  3719. SmallVector<Decl*, 64> Decls;
  3720. setHasLoadedFieldsFromExternalStorage(true);
  3721. Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
  3722. return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
  3723. }, Decls);
  3724. #ifndef NDEBUG
  3725. // Check that all decls we got were FieldDecls.
  3726. for (unsigned i=0, e=Decls.size(); i != e; ++i)
  3727. assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
  3728. #endif
  3729. if (Decls.empty())
  3730. return;
  3731. std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
  3732. /*FieldsAlreadyLoaded=*/false);
  3733. }
  3734. bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
  3735. ASTContext &Context = getASTContext();
  3736. const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
  3737. (SanitizerKind::Address | SanitizerKind::KernelAddress);
  3738. if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
  3739. return false;
  3740. const auto &Blacklist = Context.getSanitizerBlacklist();
  3741. const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
  3742. // We may be able to relax some of these requirements.
  3743. int ReasonToReject = -1;
  3744. if (!CXXRD || CXXRD->isExternCContext())
  3745. ReasonToReject = 0; // is not C++.
  3746. else if (CXXRD->hasAttr<PackedAttr>())
  3747. ReasonToReject = 1; // is packed.
  3748. else if (CXXRD->isUnion())
  3749. ReasonToReject = 2; // is a union.
  3750. else if (CXXRD->isTriviallyCopyable())
  3751. ReasonToReject = 3; // is trivially copyable.
  3752. else if (CXXRD->hasTrivialDestructor())
  3753. ReasonToReject = 4; // has trivial destructor.
  3754. else if (CXXRD->isStandardLayout())
  3755. ReasonToReject = 5; // is standard layout.
  3756. else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
  3757. "field-padding"))
  3758. ReasonToReject = 6; // is in a blacklisted file.
  3759. else if (Blacklist.isBlacklistedType(EnabledAsanMask,
  3760. getQualifiedNameAsString(),
  3761. "field-padding"))
  3762. ReasonToReject = 7; // is blacklisted.
  3763. if (EmitRemark) {
  3764. if (ReasonToReject >= 0)
  3765. Context.getDiagnostics().Report(
  3766. getLocation(),
  3767. diag::remark_sanitize_address_insert_extra_padding_rejected)
  3768. << getQualifiedNameAsString() << ReasonToReject;
  3769. else
  3770. Context.getDiagnostics().Report(
  3771. getLocation(),
  3772. diag::remark_sanitize_address_insert_extra_padding_accepted)
  3773. << getQualifiedNameAsString();
  3774. }
  3775. return ReasonToReject < 0;
  3776. }
  3777. const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
  3778. for (const auto *I : fields()) {
  3779. if (I->getIdentifier())
  3780. return I;
  3781. if (const auto *RT = I->getType()->getAs<RecordType>())
  3782. if (const FieldDecl *NamedDataMember =
  3783. RT->getDecl()->findFirstNamedDataMember())
  3784. return NamedDataMember;
  3785. }
  3786. // We didn't find a named data member.
  3787. return nullptr;
  3788. }
  3789. //===----------------------------------------------------------------------===//
  3790. // BlockDecl Implementation
  3791. //===----------------------------------------------------------------------===//
  3792. BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
  3793. : Decl(Block, DC, CaretLoc), DeclContext(Block) {
  3794. setIsVariadic(false);
  3795. setCapturesCXXThis(false);
  3796. setBlockMissingReturnType(true);
  3797. setIsConversionFromLambda(false);
  3798. setDoesNotEscape(false);
  3799. setCanAvoidCopyToHeap(false);
  3800. }
  3801. void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
  3802. assert(!ParamInfo && "Already has param info!");
  3803. // Zero params -> null pointer.
  3804. if (!NewParamInfo.empty()) {
  3805. NumParams = NewParamInfo.size();
  3806. ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
  3807. std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
  3808. }
  3809. }
  3810. void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
  3811. bool CapturesCXXThis) {
  3812. this->setCapturesCXXThis(CapturesCXXThis);
  3813. this->NumCaptures = Captures.size();
  3814. if (Captures.empty()) {
  3815. this->Captures = nullptr;
  3816. return;
  3817. }
  3818. this->Captures = Captures.copy(Context).data();
  3819. }
  3820. bool BlockDecl::capturesVariable(const VarDecl *variable) const {
  3821. for (const auto &I : captures())
  3822. // Only auto vars can be captured, so no redeclaration worries.
  3823. if (I.getVariable() == variable)
  3824. return true;
  3825. return false;
  3826. }
  3827. SourceRange BlockDecl::getSourceRange() const {
  3828. return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
  3829. }
  3830. //===----------------------------------------------------------------------===//
  3831. // Other Decl Allocation/Deallocation Method Implementations
  3832. //===----------------------------------------------------------------------===//
  3833. void TranslationUnitDecl::anchor() {}
  3834. TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
  3835. return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
  3836. }
  3837. void PragmaCommentDecl::anchor() {}
  3838. PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
  3839. TranslationUnitDecl *DC,
  3840. SourceLocation CommentLoc,
  3841. PragmaMSCommentKind CommentKind,
  3842. StringRef Arg) {
  3843. PragmaCommentDecl *PCD =
  3844. new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
  3845. PragmaCommentDecl(DC, CommentLoc, CommentKind);
  3846. memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
  3847. PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
  3848. return PCD;
  3849. }
  3850. PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
  3851. unsigned ID,
  3852. unsigned ArgSize) {
  3853. return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
  3854. PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
  3855. }
  3856. void PragmaDetectMismatchDecl::anchor() {}
  3857. PragmaDetectMismatchDecl *
  3858. PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
  3859. SourceLocation Loc, StringRef Name,
  3860. StringRef Value) {
  3861. size_t ValueStart = Name.size() + 1;
  3862. PragmaDetectMismatchDecl *PDMD =
  3863. new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
  3864. PragmaDetectMismatchDecl(DC, Loc, ValueStart);
  3865. memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
  3866. PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
  3867. memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
  3868. Value.size());
  3869. PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
  3870. return PDMD;
  3871. }
  3872. PragmaDetectMismatchDecl *
  3873. PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
  3874. unsigned NameValueSize) {
  3875. return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
  3876. PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
  3877. }
  3878. void ExternCContextDecl::anchor() {}
  3879. ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
  3880. TranslationUnitDecl *DC) {
  3881. return new (C, DC) ExternCContextDecl(DC);
  3882. }
  3883. void LabelDecl::anchor() {}
  3884. LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
  3885. SourceLocation IdentL, IdentifierInfo *II) {
  3886. return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
  3887. }
  3888. LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
  3889. SourceLocation IdentL, IdentifierInfo *II,
  3890. SourceLocation GnuLabelL) {
  3891. assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
  3892. return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
  3893. }
  3894. LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3895. return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
  3896. SourceLocation());
  3897. }
  3898. void LabelDecl::setMSAsmLabel(StringRef Name) {
  3899. char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
  3900. memcpy(Buffer, Name.data(), Name.size());
  3901. Buffer[Name.size()] = '\0';
  3902. MSAsmName = Buffer;
  3903. }
  3904. void ValueDecl::anchor() {}
  3905. bool ValueDecl::isWeak() const {
  3906. for (const auto *I : attrs())
  3907. if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
  3908. return true;
  3909. return isWeakImported();
  3910. }
  3911. void ImplicitParamDecl::anchor() {}
  3912. ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
  3913. SourceLocation IdLoc,
  3914. IdentifierInfo *Id, QualType Type,
  3915. ImplicitParamKind ParamKind) {
  3916. return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
  3917. }
  3918. ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
  3919. ImplicitParamKind ParamKind) {
  3920. return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
  3921. }
  3922. ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
  3923. unsigned ID) {
  3924. return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
  3925. }
  3926. FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
  3927. SourceLocation StartLoc,
  3928. const DeclarationNameInfo &NameInfo,
  3929. QualType T, TypeSourceInfo *TInfo,
  3930. StorageClass SC, bool isInlineSpecified,
  3931. bool hasWrittenPrototype,
  3932. ConstexprSpecKind ConstexprKind) {
  3933. FunctionDecl *New =
  3934. new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
  3935. SC, isInlineSpecified, ConstexprKind);
  3936. New->setHasWrittenPrototype(hasWrittenPrototype);
  3937. return New;
  3938. }
  3939. FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3940. return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
  3941. DeclarationNameInfo(), QualType(), nullptr,
  3942. SC_None, false, CSK_unspecified);
  3943. }
  3944. BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
  3945. return new (C, DC) BlockDecl(DC, L);
  3946. }
  3947. BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3948. return new (C, ID) BlockDecl(nullptr, SourceLocation());
  3949. }
  3950. CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
  3951. : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
  3952. NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
  3953. CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
  3954. unsigned NumParams) {
  3955. return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
  3956. CapturedDecl(DC, NumParams);
  3957. }
  3958. CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
  3959. unsigned NumParams) {
  3960. return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
  3961. CapturedDecl(nullptr, NumParams);
  3962. }
  3963. Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
  3964. void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
  3965. bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
  3966. void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
  3967. EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
  3968. SourceLocation L,
  3969. IdentifierInfo *Id, QualType T,
  3970. Expr *E, const llvm::APSInt &V) {
  3971. return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
  3972. }
  3973. EnumConstantDecl *
  3974. EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3975. return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
  3976. QualType(), nullptr, llvm::APSInt());
  3977. }
  3978. void IndirectFieldDecl::anchor() {}
  3979. IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
  3980. SourceLocation L, DeclarationName N,
  3981. QualType T,
  3982. MutableArrayRef<NamedDecl *> CH)
  3983. : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
  3984. ChainingSize(CH.size()) {
  3985. // In C++, indirect field declarations conflict with tag declarations in the
  3986. // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
  3987. if (C.getLangOpts().CPlusPlus)
  3988. IdentifierNamespace |= IDNS_Tag;
  3989. }
  3990. IndirectFieldDecl *
  3991. IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
  3992. IdentifierInfo *Id, QualType T,
  3993. llvm::MutableArrayRef<NamedDecl *> CH) {
  3994. return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
  3995. }
  3996. IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
  3997. unsigned ID) {
  3998. return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
  3999. DeclarationName(), QualType(), None);
  4000. }
  4001. SourceRange EnumConstantDecl::getSourceRange() const {
  4002. SourceLocation End = getLocation();
  4003. if (Init)
  4004. End = Init->getEndLoc();
  4005. return SourceRange(getLocation(), End);
  4006. }
  4007. void TypeDecl::anchor() {}
  4008. TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
  4009. SourceLocation StartLoc, SourceLocation IdLoc,
  4010. IdentifierInfo *Id, TypeSourceInfo *TInfo) {
  4011. return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
  4012. }
  4013. void TypedefNameDecl::anchor() {}
  4014. TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
  4015. if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
  4016. auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
  4017. auto *ThisTypedef = this;
  4018. if (AnyRedecl && OwningTypedef) {
  4019. OwningTypedef = OwningTypedef->getCanonicalDecl();
  4020. ThisTypedef = ThisTypedef->getCanonicalDecl();
  4021. }
  4022. if (OwningTypedef == ThisTypedef)
  4023. return TT->getDecl();
  4024. }
  4025. return nullptr;
  4026. }
  4027. bool TypedefNameDecl::isTransparentTagSlow() const {
  4028. auto determineIsTransparent = [&]() {
  4029. if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
  4030. if (auto *TD = TT->getDecl()) {
  4031. if (TD->getName() != getName())
  4032. return false;
  4033. SourceLocation TTLoc = getLocation();
  4034. SourceLocation TDLoc = TD->getLocation();
  4035. if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
  4036. return false;
  4037. SourceManager &SM = getASTContext().getSourceManager();
  4038. return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
  4039. }
  4040. }
  4041. return false;
  4042. };
  4043. bool isTransparent = determineIsTransparent();
  4044. MaybeModedTInfo.setInt((isTransparent << 1) | 1);
  4045. return isTransparent;
  4046. }
  4047. TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  4048. return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
  4049. nullptr, nullptr);
  4050. }
  4051. TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
  4052. SourceLocation StartLoc,
  4053. SourceLocation IdLoc, IdentifierInfo *Id,
  4054. TypeSourceInfo *TInfo) {
  4055. return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
  4056. }
  4057. TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  4058. return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
  4059. SourceLocation(), nullptr, nullptr);
  4060. }
  4061. SourceRange TypedefDecl::getSourceRange() const {
  4062. SourceLocation RangeEnd = getLocation();
  4063. if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
  4064. if (typeIsPostfix(TInfo->getType()))
  4065. RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
  4066. }
  4067. return SourceRange(getBeginLoc(), RangeEnd);
  4068. }
  4069. SourceRange TypeAliasDecl::getSourceRange() const {
  4070. SourceLocation RangeEnd = getBeginLoc();
  4071. if (TypeSourceInfo *TInfo = getTypeSourceInfo())
  4072. RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
  4073. return SourceRange(getBeginLoc(), RangeEnd);
  4074. }
  4075. void FileScopeAsmDecl::anchor() {}
  4076. FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
  4077. StringLiteral *Str,
  4078. SourceLocation AsmLoc,
  4079. SourceLocation RParenLoc) {
  4080. return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
  4081. }
  4082. FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
  4083. unsigned ID) {
  4084. return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
  4085. SourceLocation());
  4086. }
  4087. void EmptyDecl::anchor() {}
  4088. EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
  4089. return new (C, DC) EmptyDecl(DC, L);
  4090. }
  4091. EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  4092. return new (C, ID) EmptyDecl(nullptr, SourceLocation());
  4093. }
  4094. //===----------------------------------------------------------------------===//
  4095. // ImportDecl Implementation
  4096. //===----------------------------------------------------------------------===//
  4097. /// Retrieve the number of module identifiers needed to name the given
  4098. /// module.
  4099. static unsigned getNumModuleIdentifiers(Module *Mod) {
  4100. unsigned Result = 1;
  4101. while (Mod->Parent) {
  4102. Mod = Mod->Parent;
  4103. ++Result;
  4104. }
  4105. return Result;
  4106. }
  4107. ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
  4108. Module *Imported,
  4109. ArrayRef<SourceLocation> IdentifierLocs)
  4110. : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) {
  4111. assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
  4112. auto *StoredLocs = getTrailingObjects<SourceLocation>();
  4113. std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
  4114. StoredLocs);
  4115. }
  4116. ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
  4117. Module *Imported, SourceLocation EndLoc)
  4118. : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) {
  4119. *getTrailingObjects<SourceLocation>() = EndLoc;
  4120. }
  4121. ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
  4122. SourceLocation StartLoc, Module *Imported,
  4123. ArrayRef<SourceLocation> IdentifierLocs) {
  4124. return new (C, DC,
  4125. additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
  4126. ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
  4127. }
  4128. ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
  4129. SourceLocation StartLoc,
  4130. Module *Imported,
  4131. SourceLocation EndLoc) {
  4132. ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
  4133. ImportDecl(DC, StartLoc, Imported, EndLoc);
  4134. Import->setImplicit();
  4135. return Import;
  4136. }
  4137. ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
  4138. unsigned NumLocations) {
  4139. return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
  4140. ImportDecl(EmptyShell());
  4141. }
  4142. ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
  4143. if (!ImportedAndComplete.getInt())
  4144. return None;
  4145. const auto *StoredLocs = getTrailingObjects<SourceLocation>();
  4146. return llvm::makeArrayRef(StoredLocs,
  4147. getNumModuleIdentifiers(getImportedModule()));
  4148. }
  4149. SourceRange ImportDecl::getSourceRange() const {
  4150. if (!ImportedAndComplete.getInt())
  4151. return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
  4152. return SourceRange(getLocation(), getIdentifierLocs().back());
  4153. }
  4154. //===----------------------------------------------------------------------===//
  4155. // ExportDecl Implementation
  4156. //===----------------------------------------------------------------------===//
  4157. void ExportDecl::anchor() {}
  4158. ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
  4159. SourceLocation ExportLoc) {
  4160. return new (C, DC) ExportDecl(DC, ExportLoc);
  4161. }
  4162. ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  4163. return new (C, ID) ExportDecl(nullptr, SourceLocation());
  4164. }