Decl.cpp 194 KB

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