Decl.cpp 174 KB

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