ASTContext.cpp 324 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851
  1. //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the ASTContext interface.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ASTContext.h"
  14. #include "CXXABI.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/Attr.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/Comment.h"
  19. #include "clang/AST/CommentCommandTraits.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclTemplate.h"
  23. #include "clang/AST/Expr.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/ExternalASTSource.h"
  26. #include "clang/AST/Mangle.h"
  27. #include "clang/AST/MangleNumberingContext.h"
  28. #include "clang/AST/RecordLayout.h"
  29. #include "clang/AST/RecursiveASTVisitor.h"
  30. #include "clang/AST/TypeLoc.h"
  31. #include "clang/AST/VTableBuilder.h"
  32. #include "clang/Basic/Builtins.h"
  33. #include "clang/Basic/SourceManager.h"
  34. #include "clang/Basic/TargetInfo.h"
  35. #include "llvm/ADT/SmallString.h"
  36. #include "llvm/ADT/StringExtras.h"
  37. #include "llvm/ADT/Triple.h"
  38. #include "llvm/Support/Capacity.h"
  39. #include "llvm/Support/MathExtras.h"
  40. #include "llvm/Support/raw_ostream.h"
  41. #include <map>
  42. using namespace clang;
  43. unsigned ASTContext::NumImplicitDefaultConstructors;
  44. unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
  45. unsigned ASTContext::NumImplicitCopyConstructors;
  46. unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
  47. unsigned ASTContext::NumImplicitMoveConstructors;
  48. unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
  49. unsigned ASTContext::NumImplicitCopyAssignmentOperators;
  50. unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
  51. unsigned ASTContext::NumImplicitMoveAssignmentOperators;
  52. unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
  53. unsigned ASTContext::NumImplicitDestructors;
  54. unsigned ASTContext::NumImplicitDestructorsDeclared;
  55. enum FloatingRank {
  56. LitFloatRank, Min10FloatRank, HalfRank, FloatRank, DoubleRank, LongDoubleRank // HLSL Change - adds LitFloatRank and Min10FloatRank
  57. };
  58. RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
  59. if (!CommentsLoaded && ExternalSource) {
  60. ExternalSource->ReadComments();
  61. #ifndef NDEBUG
  62. ArrayRef<RawComment *> RawComments = Comments.getComments();
  63. assert(std::is_sorted(RawComments.begin(), RawComments.end(),
  64. BeforeThanCompare<RawComment>(SourceMgr)));
  65. #endif
  66. CommentsLoaded = true;
  67. }
  68. assert(D);
  69. // User can not attach documentation to implicit declarations.
  70. if (D->isImplicit())
  71. return nullptr;
  72. // User can not attach documentation to implicit instantiations.
  73. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  74. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  75. return nullptr;
  76. }
  77. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  78. if (VD->isStaticDataMember() &&
  79. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  80. return nullptr;
  81. }
  82. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
  83. if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  84. return nullptr;
  85. }
  86. if (const ClassTemplateSpecializationDecl *CTSD =
  87. dyn_cast<ClassTemplateSpecializationDecl>(D)) {
  88. TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
  89. if (TSK == TSK_ImplicitInstantiation ||
  90. TSK == TSK_Undeclared)
  91. return nullptr;
  92. }
  93. if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
  94. if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  95. return nullptr;
  96. }
  97. if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
  98. // When tag declaration (but not definition!) is part of the
  99. // decl-specifier-seq of some other declaration, it doesn't get comment
  100. if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
  101. return nullptr;
  102. }
  103. // TODO: handle comments for function parameters properly.
  104. if (isa<ParmVarDecl>(D))
  105. return nullptr;
  106. // TODO: we could look up template parameter documentation in the template
  107. // documentation.
  108. if (isa<TemplateTypeParmDecl>(D) ||
  109. isa<NonTypeTemplateParmDecl>(D) ||
  110. isa<TemplateTemplateParmDecl>(D))
  111. return nullptr;
  112. ArrayRef<RawComment *> RawComments = Comments.getComments();
  113. // If there are no comments anywhere, we won't find anything.
  114. if (RawComments.empty())
  115. return nullptr;
  116. // Find declaration location.
  117. // For Objective-C declarations we generally don't expect to have multiple
  118. // declarators, thus use declaration starting location as the "declaration
  119. // location".
  120. // For all other declarations multiple declarators are used quite frequently,
  121. // so we use the location of the identifier as the "declaration location".
  122. SourceLocation DeclLoc;
  123. if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
  124. isa<ObjCPropertyDecl>(D) ||
  125. isa<RedeclarableTemplateDecl>(D) ||
  126. isa<ClassTemplateSpecializationDecl>(D))
  127. DeclLoc = D->getLocStart();
  128. else {
  129. DeclLoc = D->getLocation();
  130. if (DeclLoc.isMacroID()) {
  131. if (isa<TypedefDecl>(D)) {
  132. // If location of the typedef name is in a macro, it is because being
  133. // declared via a macro. Try using declaration's starting location as
  134. // the "declaration location".
  135. DeclLoc = D->getLocStart();
  136. } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
  137. // If location of the tag decl is inside a macro, but the spelling of
  138. // the tag name comes from a macro argument, it looks like a special
  139. // macro like NS_ENUM is being used to define the tag decl. In that
  140. // case, adjust the source location to the expansion loc so that we can
  141. // attach the comment to the tag decl.
  142. if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
  143. TD->isCompleteDefinition())
  144. DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
  145. }
  146. }
  147. }
  148. // If the declaration doesn't map directly to a location in a file, we
  149. // can't find the comment.
  150. if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
  151. return nullptr;
  152. // Find the comment that occurs just after this declaration.
  153. ArrayRef<RawComment *>::iterator Comment;
  154. {
  155. // When searching for comments during parsing, the comment we are looking
  156. // for is usually among the last two comments we parsed -- check them
  157. // first.
  158. RawComment CommentAtDeclLoc(
  159. SourceMgr, SourceRange(DeclLoc), false,
  160. LangOpts.CommentOpts.ParseAllComments);
  161. BeforeThanCompare<RawComment> Compare(SourceMgr);
  162. ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
  163. bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
  164. if (!Found && RawComments.size() >= 2) {
  165. MaybeBeforeDecl--;
  166. Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
  167. }
  168. if (Found) {
  169. Comment = MaybeBeforeDecl + 1;
  170. assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
  171. &CommentAtDeclLoc, Compare));
  172. } else {
  173. // Slow path.
  174. Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
  175. &CommentAtDeclLoc, Compare);
  176. }
  177. }
  178. // Decompose the location for the declaration and find the beginning of the
  179. // file buffer.
  180. std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
  181. // First check whether we have a trailing comment.
  182. if (Comment != RawComments.end() &&
  183. (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
  184. (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
  185. isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
  186. std::pair<FileID, unsigned> CommentBeginDecomp
  187. = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
  188. // Check that Doxygen trailing comment comes after the declaration, starts
  189. // on the same line and in the same file as the declaration.
  190. if (DeclLocDecomp.first == CommentBeginDecomp.first &&
  191. SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
  192. == SourceMgr.getLineNumber(CommentBeginDecomp.first,
  193. CommentBeginDecomp.second)) {
  194. return *Comment;
  195. }
  196. }
  197. // The comment just after the declaration was not a trailing comment.
  198. // Let's look at the previous comment.
  199. if (Comment == RawComments.begin())
  200. return nullptr;
  201. --Comment;
  202. // Check that we actually have a non-member Doxygen comment.
  203. if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
  204. return nullptr;
  205. // Decompose the end of the comment.
  206. std::pair<FileID, unsigned> CommentEndDecomp
  207. = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
  208. // If the comment and the declaration aren't in the same file, then they
  209. // aren't related.
  210. if (DeclLocDecomp.first != CommentEndDecomp.first)
  211. return nullptr;
  212. // Get the corresponding buffer.
  213. bool Invalid = false;
  214. const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
  215. &Invalid).data();
  216. if (Invalid)
  217. return nullptr;
  218. // Extract text between the comment and declaration.
  219. StringRef Text(Buffer + CommentEndDecomp.second,
  220. DeclLocDecomp.second - CommentEndDecomp.second);
  221. // There should be no other declarations or preprocessor directives between
  222. // comment and declaration.
  223. if (Text.find_first_of(";{}#@") != StringRef::npos)
  224. return nullptr;
  225. return *Comment;
  226. }
  227. namespace {
  228. /// If we have a 'templated' declaration for a template, adjust 'D' to
  229. /// refer to the actual template.
  230. /// If we have an implicit instantiation, adjust 'D' to refer to template.
  231. const Decl *adjustDeclToTemplate(const Decl *D) {
  232. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  233. // Is this function declaration part of a function template?
  234. if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  235. return FTD;
  236. // Nothing to do if function is not an implicit instantiation.
  237. if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
  238. return D;
  239. // Function is an implicit instantiation of a function template?
  240. if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
  241. return FTD;
  242. // Function is instantiated from a member definition of a class template?
  243. if (const FunctionDecl *MemberDecl =
  244. FD->getInstantiatedFromMemberFunction())
  245. return MemberDecl;
  246. return D;
  247. }
  248. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  249. // Static data member is instantiated from a member definition of a class
  250. // template?
  251. if (VD->isStaticDataMember())
  252. if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
  253. return MemberDecl;
  254. return D;
  255. }
  256. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
  257. // Is this class declaration part of a class template?
  258. if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
  259. return CTD;
  260. // Class is an implicit instantiation of a class template or partial
  261. // specialization?
  262. if (const ClassTemplateSpecializationDecl *CTSD =
  263. dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
  264. if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
  265. return D;
  266. llvm::PointerUnion<ClassTemplateDecl *,
  267. ClassTemplatePartialSpecializationDecl *>
  268. PU = CTSD->getSpecializedTemplateOrPartial();
  269. return PU.is<ClassTemplateDecl*>() ?
  270. static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
  271. static_cast<const Decl*>(
  272. PU.get<ClassTemplatePartialSpecializationDecl *>());
  273. }
  274. // Class is instantiated from a member definition of a class template?
  275. if (const MemberSpecializationInfo *Info =
  276. CRD->getMemberSpecializationInfo())
  277. return Info->getInstantiatedFrom();
  278. return D;
  279. }
  280. if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
  281. // Enum is instantiated from a member definition of a class template?
  282. if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
  283. return MemberDecl;
  284. return D;
  285. }
  286. // FIXME: Adjust alias templates?
  287. return D;
  288. }
  289. } // unnamed namespace
  290. const RawComment *ASTContext::getRawCommentForAnyRedecl(
  291. const Decl *D,
  292. const Decl **OriginalDecl) const {
  293. D = adjustDeclToTemplate(D);
  294. // Check whether we have cached a comment for this declaration already.
  295. {
  296. llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
  297. RedeclComments.find(D);
  298. if (Pos != RedeclComments.end()) {
  299. const RawCommentAndCacheFlags &Raw = Pos->second;
  300. if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
  301. if (OriginalDecl)
  302. *OriginalDecl = Raw.getOriginalDecl();
  303. return Raw.getRaw();
  304. }
  305. }
  306. }
  307. // Search for comments attached to declarations in the redeclaration chain.
  308. const RawComment *RC = nullptr;
  309. const Decl *OriginalDeclForRC = nullptr;
  310. for (auto I : D->redecls()) {
  311. llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
  312. RedeclComments.find(I);
  313. if (Pos != RedeclComments.end()) {
  314. const RawCommentAndCacheFlags &Raw = Pos->second;
  315. if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
  316. RC = Raw.getRaw();
  317. OriginalDeclForRC = Raw.getOriginalDecl();
  318. break;
  319. }
  320. } else {
  321. RC = getRawCommentForDeclNoCache(I);
  322. OriginalDeclForRC = I;
  323. RawCommentAndCacheFlags Raw;
  324. if (RC) {
  325. Raw.setKind(RawCommentAndCacheFlags::FromDecl);
  326. Raw.setRaw(RC);
  327. } else
  328. Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
  329. Raw.setOriginalDecl(I);
  330. RedeclComments[I] = Raw;
  331. if (RC)
  332. break;
  333. }
  334. }
  335. // If we found a comment, it should be a documentation comment.
  336. assert(!RC || RC->isDocumentation());
  337. if (OriginalDecl)
  338. *OriginalDecl = OriginalDeclForRC;
  339. // Update cache for every declaration in the redeclaration chain.
  340. RawCommentAndCacheFlags Raw;
  341. Raw.setRaw(RC);
  342. Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
  343. Raw.setOriginalDecl(OriginalDeclForRC);
  344. for (auto I : D->redecls()) {
  345. RawCommentAndCacheFlags &R = RedeclComments[I];
  346. if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
  347. R = Raw;
  348. }
  349. return RC;
  350. }
  351. static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
  352. SmallVectorImpl<const NamedDecl *> &Redeclared) {
  353. const DeclContext *DC = ObjCMethod->getDeclContext();
  354. if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
  355. const ObjCInterfaceDecl *ID = IMD->getClassInterface();
  356. if (!ID)
  357. return;
  358. // Add redeclared method here.
  359. for (const auto *Ext : ID->known_extensions()) {
  360. if (ObjCMethodDecl *RedeclaredMethod =
  361. Ext->getMethod(ObjCMethod->getSelector(),
  362. ObjCMethod->isInstanceMethod()))
  363. Redeclared.push_back(RedeclaredMethod);
  364. }
  365. }
  366. }
  367. comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
  368. const Decl *D) const {
  369. comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
  370. ThisDeclInfo->CommentDecl = D;
  371. ThisDeclInfo->IsFilled = false;
  372. ThisDeclInfo->fill();
  373. ThisDeclInfo->CommentDecl = FC->getDecl();
  374. if (!ThisDeclInfo->TemplateParameters)
  375. ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
  376. comments::FullComment *CFC =
  377. new (*this) comments::FullComment(FC->getBlocks(),
  378. ThisDeclInfo);
  379. return CFC;
  380. }
  381. comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
  382. const RawComment *RC = getRawCommentForDeclNoCache(D);
  383. return RC ? RC->parse(*this, nullptr, D) : nullptr;
  384. }
  385. comments::FullComment *ASTContext::getCommentForDecl(
  386. const Decl *D,
  387. const Preprocessor *PP) const {
  388. if (D->isInvalidDecl())
  389. return nullptr;
  390. D = adjustDeclToTemplate(D);
  391. const Decl *Canonical = D->getCanonicalDecl();
  392. llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
  393. ParsedComments.find(Canonical);
  394. if (Pos != ParsedComments.end()) {
  395. if (Canonical != D) {
  396. comments::FullComment *FC = Pos->second;
  397. comments::FullComment *CFC = cloneFullComment(FC, D);
  398. return CFC;
  399. }
  400. return Pos->second;
  401. }
  402. const Decl *OriginalDecl;
  403. const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
  404. if (!RC) {
  405. if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
  406. SmallVector<const NamedDecl*, 8> Overridden;
  407. const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
  408. if (OMD && OMD->isPropertyAccessor())
  409. if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
  410. if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
  411. return cloneFullComment(FC, D);
  412. if (OMD)
  413. addRedeclaredMethods(OMD, Overridden);
  414. getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
  415. for (unsigned i = 0, e = Overridden.size(); i < e; i++)
  416. if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
  417. return cloneFullComment(FC, D);
  418. }
  419. else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
  420. // Attach any tag type's documentation to its typedef if latter
  421. // does not have one of its own.
  422. QualType QT = TD->getUnderlyingType();
  423. if (const TagType *TT = QT->getAs<TagType>())
  424. if (const Decl *TD = TT->getDecl())
  425. if (comments::FullComment *FC = getCommentForDecl(TD, PP))
  426. return cloneFullComment(FC, D);
  427. }
  428. else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
  429. while (IC->getSuperClass()) {
  430. IC = IC->getSuperClass();
  431. if (comments::FullComment *FC = getCommentForDecl(IC, PP))
  432. return cloneFullComment(FC, D);
  433. }
  434. }
  435. else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
  436. if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
  437. if (comments::FullComment *FC = getCommentForDecl(IC, PP))
  438. return cloneFullComment(FC, D);
  439. }
  440. else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  441. if (!(RD = RD->getDefinition()))
  442. return nullptr;
  443. // Check non-virtual bases.
  444. for (const auto &I : RD->bases()) {
  445. if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
  446. continue;
  447. QualType Ty = I.getType();
  448. if (Ty.isNull())
  449. continue;
  450. if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
  451. if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
  452. continue;
  453. if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
  454. return cloneFullComment(FC, D);
  455. }
  456. }
  457. // Check virtual bases.
  458. for (const auto &I : RD->vbases()) {
  459. if (I.getAccessSpecifier() != AS_public)
  460. continue;
  461. QualType Ty = I.getType();
  462. if (Ty.isNull())
  463. continue;
  464. if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
  465. if (!(VirtualBase= VirtualBase->getDefinition()))
  466. continue;
  467. if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
  468. return cloneFullComment(FC, D);
  469. }
  470. }
  471. }
  472. return nullptr;
  473. }
  474. // If the RawComment was attached to other redeclaration of this Decl, we
  475. // should parse the comment in context of that other Decl. This is important
  476. // because comments can contain references to parameter names which can be
  477. // different across redeclarations.
  478. if (D != OriginalDecl)
  479. return getCommentForDecl(OriginalDecl, PP);
  480. comments::FullComment *FC = RC->parse(*this, PP, D);
  481. ParsedComments[Canonical] = FC;
  482. return FC;
  483. }
  484. void
  485. ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
  486. TemplateTemplateParmDecl *Parm) {
  487. ID.AddInteger(Parm->getDepth());
  488. ID.AddInteger(Parm->getPosition());
  489. ID.AddBoolean(Parm->isParameterPack());
  490. TemplateParameterList *Params = Parm->getTemplateParameters();
  491. ID.AddInteger(Params->size());
  492. for (TemplateParameterList::const_iterator P = Params->begin(),
  493. PEnd = Params->end();
  494. P != PEnd; ++P) {
  495. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
  496. ID.AddInteger(0);
  497. ID.AddBoolean(TTP->isParameterPack());
  498. continue;
  499. }
  500. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  501. ID.AddInteger(1);
  502. ID.AddBoolean(NTTP->isParameterPack());
  503. ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
  504. if (NTTP->isExpandedParameterPack()) {
  505. ID.AddBoolean(true);
  506. ID.AddInteger(NTTP->getNumExpansionTypes());
  507. for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
  508. QualType T = NTTP->getExpansionType(I);
  509. ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
  510. }
  511. } else
  512. ID.AddBoolean(false);
  513. continue;
  514. }
  515. TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
  516. ID.AddInteger(2);
  517. Profile(ID, TTP);
  518. }
  519. }
  520. TemplateTemplateParmDecl *
  521. ASTContext::getCanonicalTemplateTemplateParmDecl(
  522. TemplateTemplateParmDecl *TTP) const {
  523. // Check if we already have a canonical template template parameter.
  524. llvm::FoldingSetNodeID ID;
  525. CanonicalTemplateTemplateParm::Profile(ID, TTP);
  526. void *InsertPos = nullptr;
  527. CanonicalTemplateTemplateParm *Canonical
  528. = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
  529. if (Canonical)
  530. return Canonical->getParam();
  531. // Build a canonical template parameter list.
  532. TemplateParameterList *Params = TTP->getTemplateParameters();
  533. SmallVector<NamedDecl *, 4> CanonParams;
  534. CanonParams.reserve(Params->size());
  535. for (TemplateParameterList::const_iterator P = Params->begin(),
  536. PEnd = Params->end();
  537. P != PEnd; ++P) {
  538. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
  539. CanonParams.push_back(
  540. TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
  541. SourceLocation(),
  542. SourceLocation(),
  543. TTP->getDepth(),
  544. TTP->getIndex(), nullptr, false,
  545. TTP->isParameterPack()));
  546. else if (NonTypeTemplateParmDecl *NTTP
  547. = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  548. QualType T = getCanonicalType(NTTP->getType());
  549. TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
  550. NonTypeTemplateParmDecl *Param;
  551. if (NTTP->isExpandedParameterPack()) {
  552. SmallVector<QualType, 2> ExpandedTypes;
  553. SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
  554. for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
  555. ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
  556. ExpandedTInfos.push_back(
  557. getTrivialTypeSourceInfo(ExpandedTypes.back()));
  558. }
  559. Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  560. SourceLocation(),
  561. SourceLocation(),
  562. NTTP->getDepth(),
  563. NTTP->getPosition(), nullptr,
  564. T,
  565. TInfo,
  566. ExpandedTypes.data(),
  567. ExpandedTypes.size(),
  568. ExpandedTInfos.data());
  569. } else {
  570. Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  571. SourceLocation(),
  572. SourceLocation(),
  573. NTTP->getDepth(),
  574. NTTP->getPosition(), nullptr,
  575. T,
  576. NTTP->isParameterPack(),
  577. TInfo);
  578. }
  579. CanonParams.push_back(Param);
  580. } else
  581. CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
  582. cast<TemplateTemplateParmDecl>(*P)));
  583. }
  584. TemplateTemplateParmDecl *CanonTTP
  585. = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  586. SourceLocation(), TTP->getDepth(),
  587. TTP->getPosition(),
  588. TTP->isParameterPack(),
  589. nullptr,
  590. TemplateParameterList::Create(*this, SourceLocation(),
  591. SourceLocation(),
  592. CanonParams.data(),
  593. CanonParams.size(),
  594. SourceLocation()));
  595. // Get the new insert position for the node we care about.
  596. Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
  597. assert(!Canonical && "Shouldn't be in the map!");
  598. (void)Canonical;
  599. // Create the canonical template template parameter entry.
  600. Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
  601. CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
  602. return CanonTTP;
  603. }
  604. CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
  605. if (!LangOpts.CPlusPlus) return nullptr;
  606. switch (T.getCXXABI().getKind()) {
  607. case TargetCXXABI::GenericARM: // Same as Itanium at this level
  608. case TargetCXXABI::iOS:
  609. case TargetCXXABI::iOS64:
  610. case TargetCXXABI::GenericAArch64:
  611. case TargetCXXABI::GenericMIPS:
  612. case TargetCXXABI::GenericItanium:
  613. return CreateItaniumCXXABI(*this);
  614. case TargetCXXABI::Microsoft:
  615. return CreateMicrosoftCXXABI(*this);
  616. }
  617. llvm_unreachable("Invalid CXXABI type!");
  618. }
  619. static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
  620. const LangOptions &LOpts) {
  621. if (LOpts.FakeAddressSpaceMap) {
  622. // The fake address space map must have a distinct entry for each
  623. // language-specific address space.
  624. static const unsigned FakeAddrSpaceMap[] = {
  625. 1, // opencl_global
  626. 2, // opencl_local
  627. 3, // opencl_constant
  628. 4, // opencl_generic
  629. 5, // cuda_device
  630. 6, // cuda_constant
  631. 7 // cuda_shared
  632. };
  633. return &FakeAddrSpaceMap;
  634. } else {
  635. return &T.getAddressSpaceMap();
  636. }
  637. }
  638. static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
  639. const LangOptions &LangOpts) {
  640. switch (LangOpts.getAddressSpaceMapMangling()) {
  641. case LangOptions::ASMM_Target:
  642. return TI.useAddressSpaceMapMangling();
  643. case LangOptions::ASMM_On:
  644. return true;
  645. case LangOptions::ASMM_Off:
  646. return false;
  647. }
  648. llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
  649. }
  650. ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
  651. IdentifierTable &idents, SelectorTable &sels,
  652. Builtin::Context &builtins)
  653. : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
  654. DependentTemplateSpecializationTypes(this_()),
  655. SubstTemplateTemplateParmPacks(this_()),
  656. GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
  657. UInt128Decl(nullptr), Float128StubDecl(nullptr),
  658. BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
  659. ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
  660. CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
  661. FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
  662. ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
  663. BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
  664. FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
  665. SourceMgr(SM), LangOpts(LOpts),
  666. SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
  667. AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
  668. Idents(idents), Selectors(sels), BuiltinInfo(builtins),
  669. DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
  670. Comments(SM), CommentsLoaded(false),
  671. CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
  672. TUDecl = TranslationUnitDecl::Create(*this);
  673. }
  674. ASTContext::~ASTContext() {
  675. ReleaseParentMapEntries();
  676. // Release the DenseMaps associated with DeclContext objects.
  677. // FIXME: Is this the ideal solution?
  678. ReleaseDeclContextMaps();
  679. // Call all of the deallocation functions on all of their targets.
  680. for (DeallocationMap::const_iterator I = Deallocations.begin(),
  681. E = Deallocations.end(); I != E; ++I)
  682. for (unsigned J = 0, N = I->second.size(); J != N; ++J)
  683. (I->first)((I->second)[J]);
  684. // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
  685. // because they can contain DenseMaps.
  686. for (llvm::DenseMap<const ObjCContainerDecl*,
  687. const ASTRecordLayout*>::iterator
  688. I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
  689. // Increment in loop to prevent using deallocated memory.
  690. if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
  691. R->Destroy(*this);
  692. for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
  693. I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
  694. // Increment in loop to prevent using deallocated memory.
  695. if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
  696. R->Destroy(*this);
  697. }
  698. for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
  699. AEnd = DeclAttrs.end();
  700. A != AEnd; ++A)
  701. A->second->~AttrVec();
  702. llvm::DeleteContainerSeconds(MangleNumberingContexts);
  703. }
  704. void ASTContext::ReleaseParentMapEntries() {
  705. if (!AllParents) return;
  706. for (const auto &Entry : *AllParents) {
  707. if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
  708. delete Entry.second.get<ast_type_traits::DynTypedNode *>();
  709. } else {
  710. assert(Entry.second.is<ParentVector *>());
  711. delete Entry.second.get<ParentVector *>();
  712. }
  713. }
  714. }
  715. void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
  716. Deallocations[Callback].push_back(Data);
  717. }
  718. void
  719. ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
  720. ExternalSource = Source;
  721. }
  722. void ASTContext::PrintStats() const {
  723. llvm::errs() << "\n*** AST Context Stats:\n";
  724. llvm::errs() << " " << Types.size() << " types total.\n";
  725. unsigned counts[] = {
  726. #define TYPE(Name, Parent) 0,
  727. #define ABSTRACT_TYPE(Name, Parent)
  728. #include "clang/AST/TypeNodes.def"
  729. 0 // Extra
  730. };
  731. for (unsigned i = 0, e = Types.size(); i != e; ++i) {
  732. Type *T = Types[i];
  733. // HLSL Change Starts - guard against overflows; we can probably prove this is fine, but this is not a sensitive (or retail!) codepath
  734. #if 0
  735. counts[(unsigned)T->getTypeClass()]++;
  736. #else
  737. unsigned offset = (unsigned)T->getTypeClass();
  738. if (offset < _countof(counts)) counts[offset]++;
  739. #endif
  740. // HLSL Change Ends
  741. }
  742. unsigned Idx = 0;
  743. unsigned TotalBytes = 0;
  744. #define TYPE(Name, Parent) \
  745. if (counts[Idx]) \
  746. llvm::errs() << " " << counts[Idx] << " " << #Name \
  747. << " types\n"; \
  748. TotalBytes += counts[Idx] * sizeof(Name##Type); \
  749. ++Idx;
  750. #define ABSTRACT_TYPE(Name, Parent)
  751. #include "clang/AST/TypeNodes.def"
  752. llvm::errs() << "Total bytes = " << TotalBytes << "\n";
  753. // Implicit special member functions.
  754. llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
  755. << NumImplicitDefaultConstructors
  756. << " implicit default constructors created\n";
  757. llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
  758. << NumImplicitCopyConstructors
  759. << " implicit copy constructors created\n";
  760. if (getLangOpts().CPlusPlus)
  761. llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
  762. << NumImplicitMoveConstructors
  763. << " implicit move constructors created\n";
  764. llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
  765. << NumImplicitCopyAssignmentOperators
  766. << " implicit copy assignment operators created\n";
  767. if (getLangOpts().CPlusPlus)
  768. llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
  769. << NumImplicitMoveAssignmentOperators
  770. << " implicit move assignment operators created\n";
  771. llvm::errs() << NumImplicitDestructorsDeclared << "/"
  772. << NumImplicitDestructors
  773. << " implicit destructors created\n";
  774. if (ExternalSource) {
  775. llvm::errs() << "\n";
  776. ExternalSource->PrintStats();
  777. }
  778. BumpAlloc.PrintStats();
  779. }
  780. void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
  781. bool NotifyListeners) {
  782. if (NotifyListeners)
  783. if (auto *Listener = getASTMutationListener())
  784. Listener->RedefinedHiddenDefinition(ND, M);
  785. if (getLangOpts().ModulesLocalVisibility)
  786. MergedDefModules[ND].push_back(M);
  787. else
  788. ND->setHidden(false);
  789. }
  790. void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
  791. auto It = MergedDefModules.find(ND);
  792. if (It == MergedDefModules.end())
  793. return;
  794. auto &Merged = It->second;
  795. llvm::DenseSet<Module*> Found;
  796. for (Module *&M : Merged)
  797. if (!Found.insert(M).second)
  798. M = nullptr;
  799. Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
  800. }
  801. ExternCContextDecl *ASTContext::getExternCContextDecl() const {
  802. if (!ExternCContext)
  803. ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
  804. return ExternCContext;
  805. }
  806. RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
  807. RecordDecl::TagKind TK) const {
  808. SourceLocation Loc;
  809. RecordDecl *NewDecl;
  810. if (getLangOpts().CPlusPlus)
  811. NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
  812. Loc, &Idents.get(Name));
  813. else
  814. NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
  815. &Idents.get(Name));
  816. NewDecl->setImplicit();
  817. NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
  818. const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
  819. return NewDecl;
  820. }
  821. TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
  822. StringRef Name) const {
  823. TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
  824. TypedefDecl *NewDecl = TypedefDecl::Create(
  825. const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
  826. SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
  827. NewDecl->setImplicit();
  828. return NewDecl;
  829. }
  830. TypedefDecl *ASTContext::getInt128Decl() const {
  831. if (!Int128Decl)
  832. Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
  833. return Int128Decl;
  834. }
  835. TypedefDecl *ASTContext::getUInt128Decl() const {
  836. if (!UInt128Decl)
  837. UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
  838. return UInt128Decl;
  839. }
  840. TypeDecl *ASTContext::getFloat128StubType() const {
  841. assert(LangOpts.CPlusPlus && "should only be called for c++");
  842. if (!Float128StubDecl)
  843. Float128StubDecl = buildImplicitRecord("__float128");
  844. return Float128StubDecl;
  845. }
  846. void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
  847. BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
  848. R = CanQualType::CreateUnsafe(QualType(Ty, 0));
  849. Types.push_back(Ty);
  850. }
  851. void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
  852. assert((!this->Target || this->Target == &Target) &&
  853. "Incorrect target reinitialization");
  854. assert(VoidTy.isNull() && "Context reinitialized?");
  855. this->Target = &Target;
  856. ABI.reset(createCXXABI(Target));
  857. AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
  858. AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
  859. // C99 6.2.5p19.
  860. InitBuiltinType(VoidTy, BuiltinType::Void);
  861. // C99 6.2.5p2.
  862. InitBuiltinType(BoolTy, BuiltinType::Bool);
  863. // C99 6.2.5p3.
  864. if (LangOpts.CharIsSigned)
  865. InitBuiltinType(CharTy, BuiltinType::Char_S);
  866. else
  867. InitBuiltinType(CharTy, BuiltinType::Char_U);
  868. // C99 6.2.5p4.
  869. InitBuiltinType(SignedCharTy, BuiltinType::SChar);
  870. InitBuiltinType(ShortTy, BuiltinType::Short);
  871. InitBuiltinType(IntTy, BuiltinType::Int);
  872. InitBuiltinType(LongTy, BuiltinType::Long);
  873. InitBuiltinType(LongLongTy, BuiltinType::LongLong);
  874. // C99 6.2.5p6.
  875. InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
  876. InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
  877. InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
  878. InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
  879. InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
  880. // C99 6.2.5p10.
  881. InitBuiltinType(FloatTy, BuiltinType::Float);
  882. InitBuiltinType(DoubleTy, BuiltinType::Double);
  883. InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
  884. // GNU extension, 128-bit integers.
  885. InitBuiltinType(Int128Ty, BuiltinType::Int128);
  886. InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
  887. // C++ 3.9.1p5
  888. if (TargetInfo::isTypeSigned(Target.getWCharType()))
  889. InitBuiltinType(WCharTy, BuiltinType::WChar_S);
  890. else // -fshort-wchar makes wchar_t be unsigned.
  891. InitBuiltinType(WCharTy, BuiltinType::WChar_U);
  892. if (LangOpts.CPlusPlus && LangOpts.WChar)
  893. WideCharTy = WCharTy;
  894. else {
  895. // C99 (or C++ using -fno-wchar).
  896. WideCharTy = getFromTargetType(Target.getWCharType());
  897. }
  898. WIntTy = getFromTargetType(Target.getWIntType());
  899. if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
  900. InitBuiltinType(Char16Ty, BuiltinType::Char16);
  901. else // C99
  902. Char16Ty = getFromTargetType(Target.getChar16Type());
  903. if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
  904. InitBuiltinType(Char32Ty, BuiltinType::Char32);
  905. else // C99
  906. Char32Ty = getFromTargetType(Target.getChar32Type());
  907. // Placeholder type for type-dependent expressions whose type is
  908. // completely unknown. No code should ever check a type against
  909. // DependentTy and users should never see it; however, it is here to
  910. // help diagnose failures to properly check for type-dependent
  911. // expressions.
  912. InitBuiltinType(DependentTy, BuiltinType::Dependent);
  913. // Placeholder type for functions.
  914. InitBuiltinType(OverloadTy, BuiltinType::Overload);
  915. // Placeholder type for bound members.
  916. InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
  917. // Placeholder type for pseudo-objects.
  918. InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
  919. // "any" type; useful for debugger-like clients.
  920. InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
  921. // Placeholder type for unbridged ARC casts.
  922. InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
  923. // Placeholder type for builtin functions.
  924. InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
  925. // C99 6.2.5p11.
  926. FloatComplexTy = getComplexType(FloatTy);
  927. DoubleComplexTy = getComplexType(DoubleTy);
  928. LongDoubleComplexTy = getComplexType(LongDoubleTy);
  929. // Builtin types for 'id', 'Class', and 'SEL'.
  930. InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
  931. InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
  932. InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
  933. if (LangOpts.OpenCL) {
  934. InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
  935. InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
  936. InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
  937. InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
  938. InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
  939. InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
  940. InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
  941. InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
  942. }
  943. // Builtin type for __objc_yes and __objc_no
  944. ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
  945. SignedCharTy : BoolTy);
  946. ObjCConstantStringType = QualType();
  947. ObjCSuperType = QualType();
  948. // void * type
  949. VoidPtrTy = getPointerType(VoidTy);
  950. // nullptr type (C++0x 2.14.7)
  951. InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
  952. // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
  953. InitBuiltinType(HalfTy, BuiltinType::Half);
  954. // Builtin type used to help define __builtin_va_list.
  955. VaListTagTy = QualType();
  956. // HLSL Change Starts
  957. if (LangOpts.HLSL) {
  958. InitBuiltinType(Min12IntTy, BuiltinType::Min12Int);
  959. InitBuiltinType(Min10FloatTy, BuiltinType::Min10Float);
  960. InitBuiltinType(LitIntTy, BuiltinType::LitInt);
  961. InitBuiltinType(LitFloatTy, BuiltinType::LitFloat);
  962. hlsl::InitializeASTContextForHLSL(*this); // Previously in constructor, guarded by !DelayInitialization
  963. }
  964. // HLSL Change Ends
  965. }
  966. DiagnosticsEngine &ASTContext::getDiagnostics() const {
  967. return SourceMgr.getDiagnostics();
  968. }
  969. AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
  970. AttrVec *&Result = DeclAttrs[D];
  971. if (!Result) {
  972. void *Mem = Allocate(sizeof(AttrVec));
  973. Result = new (Mem) AttrVec;
  974. }
  975. return *Result;
  976. }
  977. /// \brief Erase the attributes corresponding to the given declaration.
  978. void ASTContext::eraseDeclAttrs(const Decl *D) {
  979. llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
  980. if (Pos != DeclAttrs.end()) {
  981. Pos->second->~AttrVec();
  982. DeclAttrs.erase(Pos);
  983. }
  984. }
  985. // FIXME: Remove ?
  986. MemberSpecializationInfo *
  987. ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
  988. assert(Var->isStaticDataMember() && "Not a static data member");
  989. return getTemplateOrSpecializationInfo(Var)
  990. .dyn_cast<MemberSpecializationInfo *>();
  991. }
  992. ASTContext::TemplateOrSpecializationInfo
  993. ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
  994. llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
  995. TemplateOrInstantiation.find(Var);
  996. if (Pos == TemplateOrInstantiation.end())
  997. return TemplateOrSpecializationInfo();
  998. return Pos->second;
  999. }
  1000. void
  1001. ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
  1002. TemplateSpecializationKind TSK,
  1003. SourceLocation PointOfInstantiation) {
  1004. assert(Inst->isStaticDataMember() && "Not a static data member");
  1005. assert(Tmpl->isStaticDataMember() && "Not a static data member");
  1006. setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
  1007. Tmpl, TSK, PointOfInstantiation));
  1008. }
  1009. void
  1010. ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
  1011. TemplateOrSpecializationInfo TSI) {
  1012. assert(!TemplateOrInstantiation[Inst] &&
  1013. "Already noted what the variable was instantiated from");
  1014. TemplateOrInstantiation[Inst] = TSI;
  1015. }
  1016. FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
  1017. const FunctionDecl *FD){
  1018. assert(FD && "Specialization is 0");
  1019. llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
  1020. = ClassScopeSpecializationPattern.find(FD);
  1021. if (Pos == ClassScopeSpecializationPattern.end())
  1022. return nullptr;
  1023. return Pos->second;
  1024. }
  1025. void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
  1026. FunctionDecl *Pattern) {
  1027. assert(FD && "Specialization is 0");
  1028. assert(Pattern && "Class scope specialization pattern is 0");
  1029. ClassScopeSpecializationPattern[FD] = Pattern;
  1030. }
  1031. NamedDecl *
  1032. ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
  1033. llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
  1034. = InstantiatedFromUsingDecl.find(UUD);
  1035. if (Pos == InstantiatedFromUsingDecl.end())
  1036. return nullptr;
  1037. return Pos->second;
  1038. }
  1039. void
  1040. ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
  1041. assert((isa<UsingDecl>(Pattern) ||
  1042. isa<UnresolvedUsingValueDecl>(Pattern) ||
  1043. isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
  1044. "pattern decl is not a using decl");
  1045. assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
  1046. InstantiatedFromUsingDecl[Inst] = Pattern;
  1047. }
  1048. UsingShadowDecl *
  1049. ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
  1050. llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
  1051. = InstantiatedFromUsingShadowDecl.find(Inst);
  1052. if (Pos == InstantiatedFromUsingShadowDecl.end())
  1053. return nullptr;
  1054. return Pos->second;
  1055. }
  1056. void
  1057. ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
  1058. UsingShadowDecl *Pattern) {
  1059. assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
  1060. InstantiatedFromUsingShadowDecl[Inst] = Pattern;
  1061. }
  1062. FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
  1063. llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
  1064. = InstantiatedFromUnnamedFieldDecl.find(Field);
  1065. if (Pos == InstantiatedFromUnnamedFieldDecl.end())
  1066. return nullptr;
  1067. return Pos->second;
  1068. }
  1069. void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
  1070. FieldDecl *Tmpl) {
  1071. assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
  1072. assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
  1073. assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
  1074. "Already noted what unnamed field was instantiated from");
  1075. InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
  1076. }
  1077. ASTContext::overridden_cxx_method_iterator
  1078. ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
  1079. llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
  1080. = OverriddenMethods.find(Method->getCanonicalDecl());
  1081. if (Pos == OverriddenMethods.end())
  1082. return nullptr;
  1083. return Pos->second.begin();
  1084. }
  1085. ASTContext::overridden_cxx_method_iterator
  1086. ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
  1087. llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
  1088. = OverriddenMethods.find(Method->getCanonicalDecl());
  1089. if (Pos == OverriddenMethods.end())
  1090. return nullptr;
  1091. return Pos->second.end();
  1092. }
  1093. unsigned
  1094. ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
  1095. llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
  1096. = OverriddenMethods.find(Method->getCanonicalDecl());
  1097. if (Pos == OverriddenMethods.end())
  1098. return 0;
  1099. return Pos->second.size();
  1100. }
  1101. void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
  1102. const CXXMethodDecl *Overridden) {
  1103. assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
  1104. OverriddenMethods[Method].push_back(Overridden);
  1105. }
  1106. void ASTContext::getOverriddenMethods(
  1107. const NamedDecl *D,
  1108. SmallVectorImpl<const NamedDecl *> &Overridden) const {
  1109. assert(D);
  1110. if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
  1111. Overridden.append(overridden_methods_begin(CXXMethod),
  1112. overridden_methods_end(CXXMethod));
  1113. return;
  1114. }
  1115. const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
  1116. if (!Method)
  1117. return;
  1118. SmallVector<const ObjCMethodDecl *, 8> OverDecls;
  1119. Method->getOverriddenMethods(OverDecls);
  1120. Overridden.append(OverDecls.begin(), OverDecls.end());
  1121. }
  1122. void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
  1123. assert(!Import->NextLocalImport && "Import declaration already in the chain");
  1124. assert(!Import->isFromASTFile() && "Non-local import declaration");
  1125. if (!FirstLocalImport) {
  1126. FirstLocalImport = Import;
  1127. LastLocalImport = Import;
  1128. return;
  1129. }
  1130. LastLocalImport->NextLocalImport = Import;
  1131. LastLocalImport = Import;
  1132. }
  1133. //===----------------------------------------------------------------------===//
  1134. // Type Sizing and Analysis
  1135. //===----------------------------------------------------------------------===//
  1136. /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
  1137. /// scalar floating point type.
  1138. const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
  1139. const BuiltinType *BT = T->getAs<BuiltinType>();
  1140. assert(BT && "Not a floating point type!");
  1141. switch (BT->getKind()) {
  1142. default: llvm_unreachable("Not a floating point type!");
  1143. // HLSL Change Starts
  1144. case BuiltinType::Min10Float:
  1145. // HLSL Change Ends
  1146. case BuiltinType::Half: return Target->getHalfFormat();
  1147. case BuiltinType::Float: return Target->getFloatFormat();
  1148. case BuiltinType::Double: return Target->getDoubleFormat();
  1149. case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
  1150. case BuiltinType::LitFloat: return Target->getDoubleFormat(); // HLSL Change
  1151. }
  1152. }
  1153. CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
  1154. unsigned Align = Target->getCharWidth();
  1155. bool UseAlignAttrOnly = false;
  1156. if (unsigned AlignFromAttr = D->getMaxAlignment()) {
  1157. Align = AlignFromAttr;
  1158. // __attribute__((aligned)) can increase or decrease alignment
  1159. // *except* on a struct or struct member, where it only increases
  1160. // alignment unless 'packed' is also specified.
  1161. //
  1162. // It is an error for alignas to decrease alignment, so we can
  1163. // ignore that possibility; Sema should diagnose it.
  1164. if (isa<FieldDecl>(D)) {
  1165. UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
  1166. cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
  1167. } else {
  1168. UseAlignAttrOnly = true;
  1169. }
  1170. }
  1171. else if (isa<FieldDecl>(D))
  1172. UseAlignAttrOnly =
  1173. D->hasAttr<PackedAttr>() ||
  1174. cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
  1175. // If we're using the align attribute only, just ignore everything
  1176. // else about the declaration and its type.
  1177. if (UseAlignAttrOnly) {
  1178. // do nothing
  1179. } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
  1180. QualType T = VD->getType();
  1181. if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
  1182. if (ForAlignof)
  1183. T = RT->getPointeeType();
  1184. else
  1185. T = getPointerType(RT->getPointeeType());
  1186. }
  1187. QualType BaseT = getBaseElementType(T);
  1188. if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
  1189. // Adjust alignments of declarations with array type by the
  1190. // large-array alignment on the target.
  1191. if (const ArrayType *arrayType = getAsArrayType(T)) {
  1192. unsigned MinWidth = Target->getLargeArrayMinWidth();
  1193. if (!ForAlignof && MinWidth) {
  1194. if (isa<VariableArrayType>(arrayType))
  1195. Align = std::max(Align, Target->getLargeArrayAlign());
  1196. else if (isa<ConstantArrayType>(arrayType) &&
  1197. MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
  1198. Align = std::max(Align, Target->getLargeArrayAlign());
  1199. }
  1200. }
  1201. Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
  1202. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1203. if (VD->hasGlobalStorage() && !ForAlignof)
  1204. Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
  1205. }
  1206. }
  1207. // Fields can be subject to extra alignment constraints, like if
  1208. // the field is packed, the struct is packed, or the struct has a
  1209. // a max-field-alignment constraint (#pragma pack). So calculate
  1210. // the actual alignment of the field within the struct, and then
  1211. // (as we're expected to) constrain that by the alignment of the type.
  1212. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  1213. const RecordDecl *Parent = Field->getParent();
  1214. // We can only produce a sensible answer if the record is valid.
  1215. if (!Parent->isInvalidDecl()) {
  1216. const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
  1217. // Start with the record's overall alignment.
  1218. unsigned FieldAlign = toBits(Layout.getAlignment());
  1219. // Use the GCD of that and the offset within the record.
  1220. uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
  1221. if (Offset > 0) {
  1222. // Alignment is always a power of 2, so the GCD will be a power of 2,
  1223. // which means we get to do this crazy thing instead of Euclid's.
  1224. uint64_t LowBitOfOffset = Offset & (~Offset + 1);
  1225. if (LowBitOfOffset < FieldAlign)
  1226. FieldAlign = static_cast<unsigned>(LowBitOfOffset);
  1227. }
  1228. Align = std::min(Align, FieldAlign);
  1229. }
  1230. }
  1231. }
  1232. return toCharUnitsFromBits(Align);
  1233. }
  1234. // getTypeInfoDataSizeInChars - Return the size of a type, in
  1235. // chars. If the type is a record, its data size is returned. This is
  1236. // the size of the memcpy that's performed when assigning this type
  1237. // using a trivial copy/move assignment operator.
  1238. std::pair<CharUnits, CharUnits>
  1239. ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
  1240. std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
  1241. // In C++, objects can sometimes be allocated into the tail padding
  1242. // of a base-class subobject. We decide whether that's possible
  1243. // during class layout, so here we can just trust the layout results.
  1244. if (getLangOpts().CPlusPlus) {
  1245. if (const RecordType *RT = T->getAs<RecordType>()) {
  1246. const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
  1247. sizeAndAlign.first = layout.getDataSize();
  1248. }
  1249. }
  1250. return sizeAndAlign;
  1251. }
  1252. /// getConstantArrayInfoInChars - Performing the computation in CharUnits
  1253. /// instead of in bits prevents overflowing the uint64_t for some large arrays.
  1254. std::pair<CharUnits, CharUnits>
  1255. static getConstantArrayInfoInChars(const ASTContext &Context,
  1256. const ConstantArrayType *CAT) {
  1257. std::pair<CharUnits, CharUnits> EltInfo =
  1258. Context.getTypeInfoInChars(CAT->getElementType());
  1259. uint64_t Size = CAT->getSize().getZExtValue();
  1260. assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
  1261. (uint64_t)(-1)/Size) &&
  1262. "Overflow in array type char size evaluation");
  1263. uint64_t Width = EltInfo.first.getQuantity() * Size;
  1264. unsigned Align = EltInfo.second.getQuantity();
  1265. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
  1266. Context.getTargetInfo().getPointerWidth(0) == 64)
  1267. Width = llvm::RoundUpToAlignment(Width, Align);
  1268. return std::make_pair(CharUnits::fromQuantity(Width),
  1269. CharUnits::fromQuantity(Align));
  1270. }
  1271. std::pair<CharUnits, CharUnits>
  1272. ASTContext::getTypeInfoInChars(const Type *T) const {
  1273. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
  1274. return getConstantArrayInfoInChars(*this, CAT);
  1275. TypeInfo Info = getTypeInfo(T);
  1276. return std::make_pair(toCharUnitsFromBits(Info.Width),
  1277. toCharUnitsFromBits(Info.Align));
  1278. }
  1279. std::pair<CharUnits, CharUnits>
  1280. ASTContext::getTypeInfoInChars(QualType T) const {
  1281. return getTypeInfoInChars(T.getTypePtr());
  1282. }
  1283. bool ASTContext::isAlignmentRequired(const Type *T) const {
  1284. return getTypeInfo(T).AlignIsRequired;
  1285. }
  1286. bool ASTContext::isAlignmentRequired(QualType T) const {
  1287. return isAlignmentRequired(T.getTypePtr());
  1288. }
  1289. TypeInfo ASTContext::getTypeInfo(const Type *T) const {
  1290. TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
  1291. if (I != MemoizedTypeInfo.end())
  1292. return I->second;
  1293. // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
  1294. TypeInfo TI = getTypeInfoImpl(T);
  1295. MemoizedTypeInfo[T] = TI;
  1296. return TI;
  1297. }
  1298. /// getTypeInfoImpl - Return the size of the specified type, in bits. This
  1299. /// method does not work on incomplete types.
  1300. ///
  1301. /// FIXME: Pointers into different addr spaces could have different sizes and
  1302. /// alignment requirements: getPointerInfo should take an AddrSpace, this
  1303. /// should take a QualType, &c.
  1304. TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
  1305. uint64_t Width = 0;
  1306. unsigned Align = 8;
  1307. bool AlignIsRequired = false;
  1308. // HLSL Change Starts
  1309. if (getLangOpts().HLSL) {
  1310. if (const ExtVectorType *Ty =
  1311. hlsl::ConvertHLSLVecMatTypeToExtVectorType(*this, QualType(T, 0))) {
  1312. T = Ty;
  1313. }
  1314. }
  1315. // HLSL Change Ends
  1316. switch (T->getTypeClass()) {
  1317. #define TYPE(Class, Base)
  1318. #define ABSTRACT_TYPE(Class, Base)
  1319. #define NON_CANONICAL_TYPE(Class, Base)
  1320. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1321. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
  1322. case Type::Class: \
  1323. assert(!T->isDependentType() && "should not see dependent types here"); \
  1324. return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
  1325. #include "clang/AST/TypeNodes.def"
  1326. llvm_unreachable("Should not see dependent types");
  1327. case Type::FunctionNoProto:
  1328. case Type::FunctionProto:
  1329. // GCC extension: alignof(function) = 32 bits
  1330. Width = 0;
  1331. Align = 32;
  1332. break;
  1333. case Type::IncompleteArray:
  1334. case Type::VariableArray:
  1335. Width = 0;
  1336. Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
  1337. break;
  1338. case Type::ConstantArray: {
  1339. const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
  1340. TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
  1341. uint64_t Size = CAT->getSize().getZExtValue();
  1342. assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
  1343. "Overflow in array type bit size evaluation");
  1344. Width = EltInfo.Width * Size;
  1345. Align = EltInfo.Align;
  1346. if (!getTargetInfo().getCXXABI().isMicrosoft() ||
  1347. getTargetInfo().getPointerWidth(0) == 64)
  1348. Width = llvm::RoundUpToAlignment(Width, Align);
  1349. break;
  1350. }
  1351. case Type::ExtVector:
  1352. case Type::Vector: {
  1353. const VectorType *VT = cast<VectorType>(T);
  1354. TypeInfo EltInfo = getTypeInfo(VT->getElementType());
  1355. Width = EltInfo.Width * VT->getNumElements();
  1356. Align = Width;
  1357. // HLSL Change Begins.
  1358. // Vector align to its element.
  1359. if (getLangOpts().HLSL) {
  1360. Align = EltInfo.Align;
  1361. Width = Align * VT->getNumElements();
  1362. }
  1363. // HLSL Change Ends.
  1364. // If the alignment is not a power of 2, round up to the next power of 2.
  1365. // This happens for non-power-of-2 length vectors.
  1366. if (Align & (Align-1)) {
  1367. Align = llvm::NextPowerOf2(Align);
  1368. Width = llvm::RoundUpToAlignment(Width, Align);
  1369. }
  1370. // Adjust the alignment based on the target max.
  1371. uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
  1372. if (TargetVectorAlign && TargetVectorAlign < Align)
  1373. Align = TargetVectorAlign;
  1374. break;
  1375. }
  1376. case Type::Builtin:
  1377. switch (cast<BuiltinType>(T)->getKind()) {
  1378. default: llvm_unreachable("Unknown builtin type!");
  1379. case BuiltinType::Void:
  1380. // GCC extension: alignof(void) = 8 bits.
  1381. Width = 0;
  1382. Align = 8;
  1383. break;
  1384. case BuiltinType::Bool:
  1385. Width = Target->getBoolWidth();
  1386. Align = Target->getBoolAlign();
  1387. break;
  1388. case BuiltinType::Char_S:
  1389. case BuiltinType::Char_U:
  1390. case BuiltinType::UChar:
  1391. case BuiltinType::SChar:
  1392. Width = Target->getCharWidth();
  1393. Align = Target->getCharAlign();
  1394. break;
  1395. case BuiltinType::WChar_S:
  1396. case BuiltinType::WChar_U:
  1397. Width = Target->getWCharWidth();
  1398. Align = Target->getWCharAlign();
  1399. break;
  1400. case BuiltinType::Char16:
  1401. Width = Target->getChar16Width();
  1402. Align = Target->getChar16Align();
  1403. break;
  1404. case BuiltinType::Char32:
  1405. Width = Target->getChar32Width();
  1406. Align = Target->getChar32Align();
  1407. break;
  1408. case BuiltinType::UShort:
  1409. case BuiltinType::Short:
  1410. Width = Target->getShortWidth();
  1411. Align = Target->getShortAlign();
  1412. break;
  1413. case BuiltinType::UInt:
  1414. case BuiltinType::Int:
  1415. Width = Target->getIntWidth();
  1416. Align = Target->getIntAlign();
  1417. break;
  1418. case BuiltinType::ULong:
  1419. case BuiltinType::Long:
  1420. Width = Target->getLongWidth();
  1421. Align = Target->getLongAlign();
  1422. break;
  1423. case BuiltinType::ULongLong:
  1424. case BuiltinType::LongLong:
  1425. Width = Target->getLongLongWidth();
  1426. Align = Target->getLongLongAlign();
  1427. break;
  1428. case BuiltinType::Int128:
  1429. case BuiltinType::UInt128:
  1430. Width = 128;
  1431. Align = 128; // int128_t is 128-bit aligned on all targets.
  1432. break;
  1433. case BuiltinType::Half:
  1434. Width = Target->getHalfWidth();
  1435. Align = Target->getHalfAlign();
  1436. break;
  1437. case BuiltinType::Float:
  1438. Width = Target->getFloatWidth();
  1439. Align = Target->getFloatAlign();
  1440. break;
  1441. case BuiltinType::Double:
  1442. Width = Target->getDoubleWidth();
  1443. Align = Target->getDoubleAlign();
  1444. break;
  1445. // HLSL Change Starts
  1446. case BuiltinType::Min10Float:
  1447. Width = 16;
  1448. Align = 16;
  1449. break;
  1450. case BuiltinType::Min12Int:
  1451. Width = 16;
  1452. Align = 16;
  1453. break;
  1454. // Treat literals as largest size possible here, as it will be used
  1455. // to determine MaxWidth in GetExprRange
  1456. case BuiltinType::LitFloat:
  1457. Width = 64;
  1458. Align = 64;
  1459. break;
  1460. case BuiltinType::LitInt:
  1461. Width = 64;
  1462. Align = 64;
  1463. break;
  1464. // HLSL Change Ends
  1465. case BuiltinType::LongDouble:
  1466. Width = Target->getLongDoubleWidth();
  1467. Align = Target->getLongDoubleAlign();
  1468. break;
  1469. case BuiltinType::NullPtr:
  1470. Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
  1471. Align = Target->getPointerAlign(0); // == sizeof(void*)
  1472. break;
  1473. case BuiltinType::ObjCId:
  1474. case BuiltinType::ObjCClass:
  1475. case BuiltinType::ObjCSel:
  1476. Width = Target->getPointerWidth(0);
  1477. Align = Target->getPointerAlign(0);
  1478. break;
  1479. case BuiltinType::OCLSampler:
  1480. // Samplers are modeled as integers.
  1481. Width = Target->getIntWidth();
  1482. Align = Target->getIntAlign();
  1483. break;
  1484. case BuiltinType::OCLEvent:
  1485. case BuiltinType::OCLImage1d:
  1486. case BuiltinType::OCLImage1dArray:
  1487. case BuiltinType::OCLImage1dBuffer:
  1488. case BuiltinType::OCLImage2d:
  1489. case BuiltinType::OCLImage2dArray:
  1490. case BuiltinType::OCLImage3d:
  1491. // Currently these types are pointers to opaque types.
  1492. Width = Target->getPointerWidth(0);
  1493. Align = Target->getPointerAlign(0);
  1494. break;
  1495. }
  1496. break;
  1497. case Type::ObjCObjectPointer:
  1498. Width = Target->getPointerWidth(0);
  1499. Align = Target->getPointerAlign(0);
  1500. break;
  1501. case Type::BlockPointer: {
  1502. unsigned AS = getTargetAddressSpace(
  1503. cast<BlockPointerType>(T)->getPointeeType());
  1504. Width = Target->getPointerWidth(AS);
  1505. Align = Target->getPointerAlign(AS);
  1506. break;
  1507. }
  1508. case Type::LValueReference:
  1509. case Type::RValueReference: {
  1510. // alignof and sizeof should never enter this code path here, so we go
  1511. // the pointer route.
  1512. unsigned AS = getTargetAddressSpace(
  1513. cast<ReferenceType>(T)->getPointeeType());
  1514. Width = Target->getPointerWidth(AS);
  1515. Align = Target->getPointerAlign(AS);
  1516. break;
  1517. }
  1518. case Type::Pointer: {
  1519. unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
  1520. Width = Target->getPointerWidth(AS);
  1521. Align = Target->getPointerAlign(AS);
  1522. break;
  1523. }
  1524. case Type::MemberPointer: {
  1525. const MemberPointerType *MPT = cast<MemberPointerType>(T);
  1526. std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
  1527. break;
  1528. }
  1529. case Type::Complex: {
  1530. // Complex types have the same alignment as their elements, but twice the
  1531. // size.
  1532. TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
  1533. Width = EltInfo.Width * 2;
  1534. Align = EltInfo.Align;
  1535. break;
  1536. }
  1537. case Type::ObjCObject:
  1538. return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
  1539. case Type::Adjusted:
  1540. case Type::Decayed:
  1541. return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
  1542. case Type::ObjCInterface: {
  1543. const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
  1544. const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
  1545. Width = toBits(Layout.getSize());
  1546. Align = toBits(Layout.getAlignment());
  1547. break;
  1548. }
  1549. case Type::Record:
  1550. case Type::Enum: {
  1551. const TagType *TT = cast<TagType>(T);
  1552. if (TT->getDecl()->isInvalidDecl()) {
  1553. Width = 8;
  1554. Align = 8;
  1555. break;
  1556. }
  1557. if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
  1558. const EnumDecl *ED = ET->getDecl();
  1559. TypeInfo Info =
  1560. getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
  1561. if (unsigned AttrAlign = ED->getMaxAlignment()) {
  1562. Info.Align = AttrAlign;
  1563. Info.AlignIsRequired = true;
  1564. }
  1565. return Info;
  1566. }
  1567. const RecordType *RT = cast<RecordType>(TT);
  1568. const RecordDecl *RD = RT->getDecl();
  1569. const ASTRecordLayout &Layout = getASTRecordLayout(RD);
  1570. Width = toBits(Layout.getSize());
  1571. Align = toBits(Layout.getAlignment());
  1572. AlignIsRequired = RD->hasAttr<AlignedAttr>();
  1573. break;
  1574. }
  1575. case Type::SubstTemplateTypeParm:
  1576. return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
  1577. getReplacementType().getTypePtr());
  1578. case Type::Auto: {
  1579. const AutoType *A = cast<AutoType>(T);
  1580. assert(!A->getDeducedType().isNull() &&
  1581. "cannot request the size of an undeduced or dependent auto type");
  1582. return getTypeInfo(A->getDeducedType().getTypePtr());
  1583. }
  1584. case Type::Paren:
  1585. return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
  1586. case Type::Typedef: {
  1587. const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
  1588. TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
  1589. // If the typedef has an aligned attribute on it, it overrides any computed
  1590. // alignment we have. This violates the GCC documentation (which says that
  1591. // attribute(aligned) can only round up) but matches its implementation.
  1592. if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
  1593. Align = AttrAlign;
  1594. AlignIsRequired = true;
  1595. } else {
  1596. Align = Info.Align;
  1597. AlignIsRequired = Info.AlignIsRequired;
  1598. }
  1599. Width = Info.Width;
  1600. break;
  1601. }
  1602. case Type::Elaborated:
  1603. return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
  1604. case Type::Attributed:
  1605. return getTypeInfo(
  1606. cast<AttributedType>(T)->getEquivalentType().getTypePtr());
  1607. case Type::Atomic: {
  1608. // Start with the base type information.
  1609. TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
  1610. Width = Info.Width;
  1611. Align = Info.Align;
  1612. // If the size of the type doesn't exceed the platform's max
  1613. // atomic promotion width, make the size and alignment more
  1614. // favorable to atomic operations:
  1615. if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
  1616. // Round the size up to a power of 2.
  1617. if (!llvm::isPowerOf2_64(Width))
  1618. Width = llvm::NextPowerOf2(Width);
  1619. // Set the alignment equal to the size.
  1620. Align = static_cast<unsigned>(Width);
  1621. }
  1622. }
  1623. }
  1624. assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
  1625. return TypeInfo(Width, Align, AlignIsRequired);
  1626. }
  1627. unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
  1628. unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
  1629. // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
  1630. if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
  1631. getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
  1632. getTargetInfo().getABI() == "elfv1-qpx" &&
  1633. T->isSpecificBuiltinType(BuiltinType::Double))
  1634. SimdAlign = 256;
  1635. return SimdAlign;
  1636. }
  1637. /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
  1638. CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
  1639. return CharUnits::fromQuantity(BitSize / getCharWidth());
  1640. }
  1641. /// toBits - Convert a size in characters to a size in characters.
  1642. int64_t ASTContext::toBits(CharUnits CharSize) const {
  1643. return CharSize.getQuantity() * getCharWidth();
  1644. }
  1645. /// getTypeSizeInChars - Return the size of the specified type, in characters.
  1646. /// This method does not work on incomplete types.
  1647. CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
  1648. return getTypeInfoInChars(T).first;
  1649. }
  1650. CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
  1651. return getTypeInfoInChars(T).first;
  1652. }
  1653. /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
  1654. /// characters. This method does not work on incomplete types.
  1655. CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
  1656. return toCharUnitsFromBits(getTypeAlign(T));
  1657. }
  1658. CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
  1659. return toCharUnitsFromBits(getTypeAlign(T));
  1660. }
  1661. /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
  1662. /// type for the current target in bits. This can be different than the ABI
  1663. /// alignment in cases where it is beneficial for performance to overalign
  1664. /// a data type.
  1665. unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
  1666. TypeInfo TI = getTypeInfo(T);
  1667. unsigned ABIAlign = TI.Align;
  1668. T = T->getBaseElementTypeUnsafe();
  1669. // The preferred alignment of member pointers is that of a pointer.
  1670. if (T->isMemberPointerType())
  1671. return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
  1672. if (Target->getTriple().getArch() == llvm::Triple::xcore)
  1673. return ABIAlign; // Never overalign on XCore.
  1674. // Double and long long should be naturally aligned if possible.
  1675. if (const ComplexType *CT = T->getAs<ComplexType>())
  1676. T = CT->getElementType().getTypePtr();
  1677. if (const EnumType *ET = T->getAs<EnumType>())
  1678. T = ET->getDecl()->getIntegerType().getTypePtr();
  1679. if (T->isSpecificBuiltinType(BuiltinType::Double) ||
  1680. T->isSpecificBuiltinType(BuiltinType::LongLong) ||
  1681. T->isSpecificBuiltinType(BuiltinType::ULongLong))
  1682. // Don't increase the alignment if an alignment attribute was specified on a
  1683. // typedef declaration.
  1684. if (!TI.AlignIsRequired)
  1685. return std::max(ABIAlign, (unsigned)getTypeSize(T));
  1686. return ABIAlign;
  1687. }
  1688. /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
  1689. /// for __attribute__((aligned)) on this target, to be used if no alignment
  1690. /// value is specified.
  1691. unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
  1692. return getTargetInfo().getDefaultAlignForAttributeAligned();
  1693. }
  1694. /// getAlignOfGlobalVar - Return the alignment in bits that should be given
  1695. /// to a global variable of the specified type.
  1696. unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
  1697. return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
  1698. }
  1699. /// getAlignOfGlobalVarInChars - Return the alignment in characters that
  1700. /// should be given to a global variable of the specified type.
  1701. CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
  1702. return toCharUnitsFromBits(getAlignOfGlobalVar(T));
  1703. }
  1704. CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
  1705. CharUnits Offset = CharUnits::Zero();
  1706. const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
  1707. while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
  1708. Offset += Layout->getBaseClassOffset(Base);
  1709. Layout = &getASTRecordLayout(Base);
  1710. }
  1711. return Offset;
  1712. }
  1713. /// DeepCollectObjCIvars -
  1714. /// This routine first collects all declared, but not synthesized, ivars in
  1715. /// super class and then collects all ivars, including those synthesized for
  1716. /// current class. This routine is used for implementation of current class
  1717. /// when all ivars, declared and synthesized are known.
  1718. ///
  1719. void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
  1720. bool leafClass,
  1721. SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
  1722. if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
  1723. DeepCollectObjCIvars(SuperClass, false, Ivars);
  1724. if (!leafClass) {
  1725. for (const auto *I : OI->ivars())
  1726. Ivars.push_back(I);
  1727. } else {
  1728. ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
  1729. for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
  1730. Iv= Iv->getNextIvar())
  1731. Ivars.push_back(Iv);
  1732. }
  1733. }
  1734. /// CollectInheritedProtocols - Collect all protocols in current class and
  1735. /// those inherited by it.
  1736. void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
  1737. llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
  1738. if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
  1739. // We can use protocol_iterator here instead of
  1740. // all_referenced_protocol_iterator since we are walking all categories.
  1741. for (auto *Proto : OI->all_referenced_protocols()) {
  1742. CollectInheritedProtocols(Proto, Protocols);
  1743. }
  1744. // Categories of this Interface.
  1745. for (const auto *Cat : OI->visible_categories())
  1746. CollectInheritedProtocols(Cat, Protocols);
  1747. if (ObjCInterfaceDecl *SD = OI->getSuperClass())
  1748. while (SD) {
  1749. CollectInheritedProtocols(SD, Protocols);
  1750. SD = SD->getSuperClass();
  1751. }
  1752. } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
  1753. for (auto *Proto : OC->protocols()) {
  1754. CollectInheritedProtocols(Proto, Protocols);
  1755. }
  1756. } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
  1757. // Insert the protocol.
  1758. if (!Protocols.insert(
  1759. const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
  1760. return;
  1761. for (auto *Proto : OP->protocols())
  1762. CollectInheritedProtocols(Proto, Protocols);
  1763. }
  1764. }
  1765. unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
  1766. unsigned count = 0;
  1767. // Count ivars declared in class extension.
  1768. for (const auto *Ext : OI->known_extensions())
  1769. count += Ext->ivar_size();
  1770. // Count ivar defined in this class's implementation. This
  1771. // includes synthesized ivars.
  1772. if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
  1773. count += ImplDecl->ivar_size();
  1774. return count;
  1775. }
  1776. bool ASTContext::isSentinelNullExpr(const Expr *E) {
  1777. if (!E)
  1778. return false;
  1779. // nullptr_t is always treated as null.
  1780. if (E->getType()->isNullPtrType()) return true;
  1781. if (E->getType()->isAnyPointerType() &&
  1782. E->IgnoreParenCasts()->isNullPointerConstant(*this,
  1783. Expr::NPC_ValueDependentIsNull))
  1784. return true;
  1785. // Unfortunately, __null has type 'int'.
  1786. if (isa<GNUNullExpr>(E)) return true;
  1787. return false;
  1788. }
  1789. /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
  1790. ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
  1791. llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
  1792. I = ObjCImpls.find(D);
  1793. if (I != ObjCImpls.end())
  1794. return cast<ObjCImplementationDecl>(I->second);
  1795. return nullptr;
  1796. }
  1797. /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
  1798. ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
  1799. llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
  1800. I = ObjCImpls.find(D);
  1801. if (I != ObjCImpls.end())
  1802. return cast<ObjCCategoryImplDecl>(I->second);
  1803. return nullptr;
  1804. }
  1805. /// \brief Set the implementation of ObjCInterfaceDecl.
  1806. void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
  1807. ObjCImplementationDecl *ImplD) {
  1808. assert(IFaceD && ImplD && "Passed null params");
  1809. ObjCImpls[IFaceD] = ImplD;
  1810. }
  1811. /// \brief Set the implementation of ObjCCategoryDecl.
  1812. void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
  1813. ObjCCategoryImplDecl *ImplD) {
  1814. assert(CatD && ImplD && "Passed null params");
  1815. ObjCImpls[CatD] = ImplD;
  1816. }
  1817. const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
  1818. const NamedDecl *ND) const {
  1819. if (const ObjCInterfaceDecl *ID =
  1820. dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
  1821. return ID;
  1822. if (const ObjCCategoryDecl *CD =
  1823. dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
  1824. return CD->getClassInterface();
  1825. if (const ObjCImplDecl *IMD =
  1826. dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
  1827. return IMD->getClassInterface();
  1828. return nullptr;
  1829. }
  1830. /// \brief Get the copy initialization expression of VarDecl,or NULL if
  1831. /// none exists.
  1832. Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
  1833. assert(VD && "Passed null params");
  1834. assert(VD->hasAttr<BlocksAttr>() &&
  1835. "getBlockVarCopyInits - not __block var");
  1836. llvm::DenseMap<const VarDecl*, Expr*>::iterator
  1837. I = BlockVarCopyInits.find(VD);
  1838. return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
  1839. }
  1840. /// \brief Set the copy inialization expression of a block var decl.
  1841. void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
  1842. assert(VD && Init && "Passed null params");
  1843. assert(VD->hasAttr<BlocksAttr>() &&
  1844. "setBlockVarCopyInits - not __block var");
  1845. BlockVarCopyInits[VD] = Init;
  1846. }
  1847. TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
  1848. unsigned DataSize) const {
  1849. if (!DataSize)
  1850. DataSize = TypeLoc::getFullDataSizeForType(T);
  1851. else
  1852. assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
  1853. "incorrect data size provided to CreateTypeSourceInfo!");
  1854. TypeSourceInfo *TInfo =
  1855. (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
  1856. new (TInfo) TypeSourceInfo(T);
  1857. return TInfo;
  1858. }
  1859. TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
  1860. SourceLocation L) const {
  1861. TypeSourceInfo *DI = CreateTypeSourceInfo(T);
  1862. DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
  1863. return DI;
  1864. }
  1865. const ASTRecordLayout &
  1866. ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
  1867. return getObjCLayout(D, nullptr);
  1868. }
  1869. const ASTRecordLayout &
  1870. ASTContext::getASTObjCImplementationLayout(
  1871. const ObjCImplementationDecl *D) const {
  1872. return getObjCLayout(D->getClassInterface(), D);
  1873. }
  1874. //===----------------------------------------------------------------------===//
  1875. // Type creation/memoization methods
  1876. //===----------------------------------------------------------------------===//
  1877. QualType
  1878. ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
  1879. unsigned fastQuals = quals.getFastQualifiers();
  1880. quals.removeFastQualifiers();
  1881. // Check if we've already instantiated this type.
  1882. llvm::FoldingSetNodeID ID;
  1883. ExtQuals::Profile(ID, baseType, quals);
  1884. void *insertPos = nullptr;
  1885. if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
  1886. assert(eq->getQualifiers() == quals);
  1887. return QualType(eq, fastQuals);
  1888. }
  1889. // If the base type is not canonical, make the appropriate canonical type.
  1890. QualType canon;
  1891. if (!baseType->isCanonicalUnqualified()) {
  1892. SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
  1893. canonSplit.Quals.addConsistentQualifiers(quals);
  1894. canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
  1895. // Re-find the insert position.
  1896. (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
  1897. }
  1898. ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
  1899. ExtQualNodes.InsertNode(eq, insertPos);
  1900. return QualType(eq, fastQuals);
  1901. }
  1902. QualType
  1903. ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
  1904. QualType CanT = getCanonicalType(T);
  1905. if (CanT.getAddressSpace() == AddressSpace)
  1906. return T;
  1907. // If we are composing extended qualifiers together, merge together
  1908. // into one ExtQuals node.
  1909. QualifierCollector Quals;
  1910. const Type *TypeNode = Quals.strip(T);
  1911. // If this type already has an address space specified, it cannot get
  1912. // another one.
  1913. assert(!Quals.hasAddressSpace() &&
  1914. "Type cannot be in multiple addr spaces!");
  1915. Quals.addAddressSpace(AddressSpace);
  1916. return getExtQualType(TypeNode, Quals);
  1917. }
  1918. QualType ASTContext::getObjCGCQualType(QualType T,
  1919. Qualifiers::GC GCAttr) const {
  1920. QualType CanT = getCanonicalType(T);
  1921. if (CanT.getObjCGCAttr() == GCAttr)
  1922. return T;
  1923. if (const PointerType *ptr = T->getAs<PointerType>()) {
  1924. QualType Pointee = ptr->getPointeeType();
  1925. if (Pointee->isAnyPointerType()) {
  1926. QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
  1927. return getPointerType(ResultType);
  1928. }
  1929. }
  1930. // If we are composing extended qualifiers together, merge together
  1931. // into one ExtQuals node.
  1932. QualifierCollector Quals;
  1933. const Type *TypeNode = Quals.strip(T);
  1934. // If this type already has an ObjCGC specified, it cannot get
  1935. // another one.
  1936. assert(!Quals.hasObjCGCAttr() &&
  1937. "Type cannot have multiple ObjCGCs!");
  1938. Quals.addObjCGCAttr(GCAttr);
  1939. return getExtQualType(TypeNode, Quals);
  1940. }
  1941. const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
  1942. FunctionType::ExtInfo Info) {
  1943. if (T->getExtInfo() == Info)
  1944. return T;
  1945. QualType Result;
  1946. if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
  1947. Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
  1948. } else {
  1949. const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
  1950. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  1951. EPI.ExtInfo = Info;
  1952. Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI, FPT->getParamMods());
  1953. }
  1954. return cast<FunctionType>(Result.getTypePtr());
  1955. }
  1956. void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
  1957. QualType ResultType) {
  1958. FD = FD->getMostRecentDecl();
  1959. while (true) {
  1960. const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
  1961. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  1962. FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI, FPT->getParamMods()));
  1963. if (FunctionDecl *Next = FD->getPreviousDecl())
  1964. FD = Next;
  1965. else
  1966. break;
  1967. }
  1968. if (ASTMutationListener *L = getASTMutationListener())
  1969. L->DeducedReturnType(FD, ResultType);
  1970. }
  1971. /// Get a function type and produce the equivalent function type with the
  1972. /// specified exception specification. Type sugar that can be present on a
  1973. /// declaration of a function with an exception specification is permitted
  1974. /// and preserved. Other type sugar (for instance, typedefs) is not.
  1975. static QualType getFunctionTypeWithExceptionSpec(
  1976. ASTContext &Context, QualType Orig,
  1977. const FunctionProtoType::ExceptionSpecInfo &ESI) {
  1978. // Might have some parens.
  1979. if (auto *PT = dyn_cast<ParenType>(Orig))
  1980. return Context.getParenType(
  1981. getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
  1982. // Might have a calling-convention attribute.
  1983. if (auto *AT = dyn_cast<AttributedType>(Orig))
  1984. return Context.getAttributedType(
  1985. AT->getAttrKind(),
  1986. getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
  1987. getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
  1988. ESI));
  1989. // Anything else must be a function type. Rebuild it with the new exception
  1990. // specification.
  1991. const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
  1992. return Context.getFunctionType(
  1993. Proto->getReturnType(), Proto->getParamTypes(),
  1994. Proto->getExtProtoInfo().withExceptionSpec(ESI),
  1995. Proto->getParamMods()); // HLSL Change
  1996. }
  1997. void ASTContext::adjustExceptionSpec(
  1998. FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
  1999. bool AsWritten) {
  2000. // Update the type.
  2001. QualType Updated =
  2002. getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
  2003. FD->setType(Updated);
  2004. if (!AsWritten)
  2005. return;
  2006. // Update the type in the type source information too.
  2007. if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
  2008. // If the type and the type-as-written differ, we may need to update
  2009. // the type-as-written too.
  2010. if (TSInfo->getType() != FD->getType())
  2011. Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
  2012. // FIXME: When we get proper type location information for exceptions,
  2013. // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
  2014. // up the TypeSourceInfo;
  2015. assert(TypeLoc::getFullDataSizeForType(Updated) ==
  2016. TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
  2017. "TypeLoc size mismatch from updating exception specification");
  2018. TSInfo->overrideType(Updated);
  2019. }
  2020. }
  2021. /// getComplexType - Return the uniqued reference to the type for a complex
  2022. /// number with the specified element type.
  2023. QualType ASTContext::getComplexType(QualType T) const {
  2024. // Unique pointers, to guarantee there is only one pointer of a particular
  2025. // structure.
  2026. llvm::FoldingSetNodeID ID;
  2027. ComplexType::Profile(ID, T);
  2028. void *InsertPos = nullptr;
  2029. if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
  2030. return QualType(CT, 0);
  2031. // If the pointee type isn't canonical, this won't be a canonical type either,
  2032. // so fill in the canonical type field.
  2033. QualType Canonical;
  2034. if (!T.isCanonical()) {
  2035. Canonical = getComplexType(getCanonicalType(T));
  2036. // Get the new insert position for the node we care about.
  2037. ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
  2038. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2039. }
  2040. ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
  2041. Types.push_back(New);
  2042. ComplexTypes.InsertNode(New, InsertPos);
  2043. return QualType(New, 0);
  2044. }
  2045. /// getPointerType - Return the uniqued reference to the type for a pointer to
  2046. /// the specified type.
  2047. QualType ASTContext::getPointerType(QualType T) const {
  2048. // Unique pointers, to guarantee there is only one pointer of a particular
  2049. // structure.
  2050. llvm::FoldingSetNodeID ID;
  2051. PointerType::Profile(ID, T);
  2052. void *InsertPos = nullptr;
  2053. if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2054. return QualType(PT, 0);
  2055. // If the pointee type isn't canonical, this won't be a canonical type either,
  2056. // so fill in the canonical type field.
  2057. QualType Canonical;
  2058. if (!T.isCanonical()) {
  2059. Canonical = getPointerType(getCanonicalType(T));
  2060. // Get the new insert position for the node we care about.
  2061. PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2062. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2063. }
  2064. PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
  2065. Types.push_back(New);
  2066. PointerTypes.InsertNode(New, InsertPos);
  2067. return QualType(New, 0);
  2068. }
  2069. QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
  2070. llvm::FoldingSetNodeID ID;
  2071. AdjustedType::Profile(ID, Orig, New);
  2072. void *InsertPos = nullptr;
  2073. AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2074. if (AT)
  2075. return QualType(AT, 0);
  2076. QualType Canonical = getCanonicalType(New);
  2077. // Get the new insert position for the node we care about.
  2078. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2079. assert(!AT && "Shouldn't be in the map!");
  2080. AT = new (*this, TypeAlignment)
  2081. AdjustedType(Type::Adjusted, Orig, New, Canonical);
  2082. Types.push_back(AT);
  2083. AdjustedTypes.InsertNode(AT, InsertPos);
  2084. return QualType(AT, 0);
  2085. }
  2086. QualType ASTContext::getDecayedType(QualType T) const {
  2087. assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
  2088. if (getLangOpts().HLSL) return T; // HLSL Change - no decay for arrays (or anything for that matter)
  2089. QualType Decayed;
  2090. // C99 6.7.5.3p7:
  2091. // A declaration of a parameter as "array of type" shall be
  2092. // adjusted to "qualified pointer to type", where the type
  2093. // qualifiers (if any) are those specified within the [ and ] of
  2094. // the array type derivation.
  2095. if (T->isArrayType())
  2096. Decayed = getArrayDecayedType(T);
  2097. // C99 6.7.5.3p8:
  2098. // A declaration of a parameter as "function returning type"
  2099. // shall be adjusted to "pointer to function returning type", as
  2100. // in 6.3.2.1.
  2101. if (T->isFunctionType())
  2102. Decayed = getPointerType(T);
  2103. llvm::FoldingSetNodeID ID;
  2104. AdjustedType::Profile(ID, T, Decayed);
  2105. void *InsertPos = nullptr;
  2106. AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2107. if (AT)
  2108. return QualType(AT, 0);
  2109. QualType Canonical = getCanonicalType(Decayed);
  2110. // Get the new insert position for the node we care about.
  2111. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2112. assert(!AT && "Shouldn't be in the map!");
  2113. AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
  2114. Types.push_back(AT);
  2115. AdjustedTypes.InsertNode(AT, InsertPos);
  2116. return QualType(AT, 0);
  2117. }
  2118. /// getBlockPointerType - Return the uniqued reference to the type for
  2119. /// a pointer to the specified block.
  2120. QualType ASTContext::getBlockPointerType(QualType T) const {
  2121. assert(T->isFunctionType() && "block of function types only");
  2122. assert(!getLangOpts().HLSL && "HLSL does not support blocks");
  2123. // Unique pointers, to guarantee there is only one block of a particular
  2124. // structure.
  2125. llvm::FoldingSetNodeID ID;
  2126. BlockPointerType::Profile(ID, T);
  2127. void *InsertPos = nullptr;
  2128. if (BlockPointerType *PT =
  2129. BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2130. return QualType(PT, 0);
  2131. // If the block pointee type isn't canonical, this won't be a canonical
  2132. // type either so fill in the canonical type field.
  2133. QualType Canonical;
  2134. if (!T.isCanonical()) {
  2135. Canonical = getBlockPointerType(getCanonicalType(T));
  2136. // Get the new insert position for the node we care about.
  2137. BlockPointerType *NewIP =
  2138. BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2139. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2140. }
  2141. BlockPointerType *New
  2142. = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
  2143. Types.push_back(New);
  2144. BlockPointerTypes.InsertNode(New, InsertPos);
  2145. return QualType(New, 0);
  2146. }
  2147. /// getLValueReferenceType - Return the uniqued reference to the type for an
  2148. /// lvalue reference to the specified type.
  2149. QualType
  2150. ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
  2151. assert(getCanonicalType(T) != OverloadTy &&
  2152. "Unresolved overloaded function type");
  2153. // Unique pointers, to guarantee there is only one pointer of a particular
  2154. // structure.
  2155. llvm::FoldingSetNodeID ID;
  2156. ReferenceType::Profile(ID, T, SpelledAsLValue);
  2157. void *InsertPos = nullptr;
  2158. if (LValueReferenceType *RT =
  2159. LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
  2160. return QualType(RT, 0);
  2161. const ReferenceType *InnerRef = T->getAs<ReferenceType>();
  2162. // If the referencee type isn't canonical, this won't be a canonical type
  2163. // either, so fill in the canonical type field.
  2164. QualType Canonical;
  2165. if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
  2166. QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
  2167. Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
  2168. // Get the new insert position for the node we care about.
  2169. LValueReferenceType *NewIP =
  2170. LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
  2171. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2172. }
  2173. LValueReferenceType *New
  2174. = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
  2175. SpelledAsLValue);
  2176. Types.push_back(New);
  2177. LValueReferenceTypes.InsertNode(New, InsertPos);
  2178. return QualType(New, 0);
  2179. }
  2180. /// getRValueReferenceType - Return the uniqued reference to the type for an
  2181. /// rvalue reference to the specified type.
  2182. QualType ASTContext::getRValueReferenceType(QualType T) const {
  2183. // Unique pointers, to guarantee there is only one pointer of a particular
  2184. // structure.
  2185. llvm::FoldingSetNodeID ID;
  2186. ReferenceType::Profile(ID, T, false);
  2187. void *InsertPos = nullptr;
  2188. if (RValueReferenceType *RT =
  2189. RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
  2190. return QualType(RT, 0);
  2191. const ReferenceType *InnerRef = T->getAs<ReferenceType>();
  2192. // If the referencee type isn't canonical, this won't be a canonical type
  2193. // either, so fill in the canonical type field.
  2194. QualType Canonical;
  2195. if (InnerRef || !T.isCanonical()) {
  2196. QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
  2197. Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
  2198. // Get the new insert position for the node we care about.
  2199. RValueReferenceType *NewIP =
  2200. RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
  2201. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2202. }
  2203. RValueReferenceType *New
  2204. = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
  2205. Types.push_back(New);
  2206. RValueReferenceTypes.InsertNode(New, InsertPos);
  2207. return QualType(New, 0);
  2208. }
  2209. /// getMemberPointerType - Return the uniqued reference to the type for a
  2210. /// member pointer to the specified type, in the specified class.
  2211. QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
  2212. // Unique pointers, to guarantee there is only one pointer of a particular
  2213. // structure.
  2214. llvm::FoldingSetNodeID ID;
  2215. MemberPointerType::Profile(ID, T, Cls);
  2216. void *InsertPos = nullptr;
  2217. if (MemberPointerType *PT =
  2218. MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2219. return QualType(PT, 0);
  2220. // If the pointee or class type isn't canonical, this won't be a canonical
  2221. // type either, so fill in the canonical type field.
  2222. QualType Canonical;
  2223. if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
  2224. Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
  2225. // Get the new insert position for the node we care about.
  2226. MemberPointerType *NewIP =
  2227. MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2228. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2229. }
  2230. MemberPointerType *New
  2231. = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
  2232. Types.push_back(New);
  2233. MemberPointerTypes.InsertNode(New, InsertPos);
  2234. return QualType(New, 0);
  2235. }
  2236. /// getConstantArrayType - Return the unique reference to the type for an
  2237. /// array of the specified element type.
  2238. QualType ASTContext::getConstantArrayType(QualType EltTy,
  2239. const llvm::APInt &ArySizeIn,
  2240. ArrayType::ArraySizeModifier ASM,
  2241. unsigned IndexTypeQuals) const {
  2242. assert((EltTy->isDependentType() ||
  2243. EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
  2244. "Constant array of VLAs is illegal!");
  2245. // Convert the array size into a canonical width matching the pointer size for
  2246. // the target.
  2247. llvm::APInt ArySize(ArySizeIn);
  2248. ArySize =
  2249. ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
  2250. llvm::FoldingSetNodeID ID;
  2251. ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
  2252. void *InsertPos = nullptr;
  2253. if (ConstantArrayType *ATP =
  2254. ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
  2255. return QualType(ATP, 0);
  2256. // If the element type isn't canonical or has qualifiers, this won't
  2257. // be a canonical type either, so fill in the canonical type field.
  2258. QualType Canon;
  2259. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
  2260. SplitQualType canonSplit = getCanonicalType(EltTy).split();
  2261. Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
  2262. ASM, IndexTypeQuals);
  2263. Canon = getQualifiedType(Canon, canonSplit.Quals);
  2264. // Get the new insert position for the node we care about.
  2265. ConstantArrayType *NewIP =
  2266. ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
  2267. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2268. }
  2269. ConstantArrayType *New = new(*this,TypeAlignment)
  2270. ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
  2271. ConstantArrayTypes.InsertNode(New, InsertPos);
  2272. Types.push_back(New);
  2273. return QualType(New, 0);
  2274. }
  2275. /// getVariableArrayDecayedType - Turns the given type, which may be
  2276. /// variably-modified, into the corresponding type with all the known
  2277. /// sizes replaced with [*].
  2278. QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
  2279. // Vastly most common case.
  2280. if (!type->isVariablyModifiedType()) return type;
  2281. QualType result;
  2282. SplitQualType split = type.getSplitDesugaredType();
  2283. const Type *ty = split.Ty;
  2284. switch (ty->getTypeClass()) {
  2285. #define TYPE(Class, Base)
  2286. #define ABSTRACT_TYPE(Class, Base)
  2287. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  2288. #include "clang/AST/TypeNodes.def"
  2289. llvm_unreachable("didn't desugar past all non-canonical types?");
  2290. // These types should never be variably-modified.
  2291. case Type::Builtin:
  2292. case Type::Complex:
  2293. case Type::Vector:
  2294. case Type::ExtVector:
  2295. case Type::DependentSizedExtVector:
  2296. case Type::ObjCObject:
  2297. case Type::ObjCInterface:
  2298. case Type::ObjCObjectPointer:
  2299. case Type::Record:
  2300. case Type::Enum:
  2301. case Type::UnresolvedUsing:
  2302. case Type::TypeOfExpr:
  2303. case Type::TypeOf:
  2304. case Type::Decltype:
  2305. case Type::UnaryTransform:
  2306. case Type::DependentName:
  2307. case Type::InjectedClassName:
  2308. case Type::TemplateSpecialization:
  2309. case Type::DependentTemplateSpecialization:
  2310. case Type::TemplateTypeParm:
  2311. case Type::SubstTemplateTypeParmPack:
  2312. case Type::Auto:
  2313. case Type::PackExpansion:
  2314. llvm_unreachable("type should never be variably-modified");
  2315. // These types can be variably-modified but should never need to
  2316. // further decay.
  2317. case Type::FunctionNoProto:
  2318. case Type::FunctionProto:
  2319. case Type::BlockPointer:
  2320. case Type::MemberPointer:
  2321. return type;
  2322. // These types can be variably-modified. All these modifications
  2323. // preserve structure except as noted by comments.
  2324. // TODO: if we ever care about optimizing VLAs, there are no-op
  2325. // optimizations available here.
  2326. case Type::Pointer:
  2327. result = getPointerType(getVariableArrayDecayedType(
  2328. cast<PointerType>(ty)->getPointeeType()));
  2329. break;
  2330. case Type::LValueReference: {
  2331. const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
  2332. result = getLValueReferenceType(
  2333. getVariableArrayDecayedType(lv->getPointeeType()),
  2334. lv->isSpelledAsLValue());
  2335. break;
  2336. }
  2337. case Type::RValueReference: {
  2338. const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
  2339. result = getRValueReferenceType(
  2340. getVariableArrayDecayedType(lv->getPointeeType()));
  2341. break;
  2342. }
  2343. case Type::Atomic: {
  2344. const AtomicType *at = cast<AtomicType>(ty);
  2345. result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
  2346. break;
  2347. }
  2348. case Type::ConstantArray: {
  2349. const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
  2350. result = getConstantArrayType(
  2351. getVariableArrayDecayedType(cat->getElementType()),
  2352. cat->getSize(),
  2353. cat->getSizeModifier(),
  2354. cat->getIndexTypeCVRQualifiers());
  2355. break;
  2356. }
  2357. case Type::DependentSizedArray: {
  2358. const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
  2359. result = getDependentSizedArrayType(
  2360. getVariableArrayDecayedType(dat->getElementType()),
  2361. dat->getSizeExpr(),
  2362. dat->getSizeModifier(),
  2363. dat->getIndexTypeCVRQualifiers(),
  2364. dat->getBracketsRange());
  2365. break;
  2366. }
  2367. // Turn incomplete types into [*] types.
  2368. case Type::IncompleteArray: {
  2369. const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
  2370. result = getVariableArrayType(
  2371. getVariableArrayDecayedType(iat->getElementType()),
  2372. /*size*/ nullptr,
  2373. ArrayType::Normal,
  2374. iat->getIndexTypeCVRQualifiers(),
  2375. SourceRange());
  2376. break;
  2377. }
  2378. // Turn VLA types into [*] types.
  2379. case Type::VariableArray: {
  2380. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  2381. result = getVariableArrayType(
  2382. getVariableArrayDecayedType(vat->getElementType()),
  2383. /*size*/ nullptr,
  2384. ArrayType::Star,
  2385. vat->getIndexTypeCVRQualifiers(),
  2386. vat->getBracketsRange());
  2387. break;
  2388. }
  2389. }
  2390. // Apply the top-level qualifiers from the original.
  2391. return getQualifiedType(result, split.Quals);
  2392. }
  2393. /// getVariableArrayType - Returns a non-unique reference to the type for a
  2394. /// variable array of the specified element type.
  2395. QualType ASTContext::getVariableArrayType(QualType EltTy,
  2396. Expr *NumElts,
  2397. ArrayType::ArraySizeModifier ASM,
  2398. unsigned IndexTypeQuals,
  2399. SourceRange Brackets) const {
  2400. // Since we don't unique expressions, it isn't possible to unique VLA's
  2401. // that have an expression provided for their size.
  2402. QualType Canon;
  2403. // Be sure to pull qualifiers off the element type.
  2404. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
  2405. SplitQualType canonSplit = getCanonicalType(EltTy).split();
  2406. Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
  2407. IndexTypeQuals, Brackets);
  2408. Canon = getQualifiedType(Canon, canonSplit.Quals);
  2409. }
  2410. VariableArrayType *New = new(*this, TypeAlignment)
  2411. VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
  2412. VariableArrayTypes.push_back(New);
  2413. Types.push_back(New);
  2414. return QualType(New, 0);
  2415. }
  2416. /// getDependentSizedArrayType - Returns a non-unique reference to
  2417. /// the type for a dependently-sized array of the specified element
  2418. /// type.
  2419. QualType ASTContext::getDependentSizedArrayType(QualType elementType,
  2420. Expr *numElements,
  2421. ArrayType::ArraySizeModifier ASM,
  2422. unsigned elementTypeQuals,
  2423. SourceRange brackets) const {
  2424. assert((!numElements || numElements->isTypeDependent() ||
  2425. numElements->isValueDependent()) &&
  2426. "Size must be type- or value-dependent!");
  2427. // Dependently-sized array types that do not have a specified number
  2428. // of elements will have their sizes deduced from a dependent
  2429. // initializer. We do no canonicalization here at all, which is okay
  2430. // because they can't be used in most locations.
  2431. if (!numElements) {
  2432. DependentSizedArrayType *newType
  2433. = new (*this, TypeAlignment)
  2434. DependentSizedArrayType(*this, elementType, QualType(),
  2435. numElements, ASM, elementTypeQuals,
  2436. brackets);
  2437. Types.push_back(newType);
  2438. return QualType(newType, 0);
  2439. }
  2440. // Otherwise, we actually build a new type every time, but we
  2441. // also build a canonical type.
  2442. SplitQualType canonElementType = getCanonicalType(elementType).split();
  2443. void *insertPos = nullptr;
  2444. llvm::FoldingSetNodeID ID;
  2445. DependentSizedArrayType::Profile(ID, *this,
  2446. QualType(canonElementType.Ty, 0),
  2447. ASM, elementTypeQuals, numElements);
  2448. // Look for an existing type with these properties.
  2449. DependentSizedArrayType *canonTy =
  2450. DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
  2451. // If we don't have one, build one.
  2452. if (!canonTy) {
  2453. canonTy = new (*this, TypeAlignment)
  2454. DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
  2455. QualType(), numElements, ASM, elementTypeQuals,
  2456. brackets);
  2457. DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
  2458. Types.push_back(canonTy);
  2459. }
  2460. // Apply qualifiers from the element type to the array.
  2461. QualType canon = getQualifiedType(QualType(canonTy,0),
  2462. canonElementType.Quals);
  2463. // If we didn't need extra canonicalization for the element type,
  2464. // then just use that as our result.
  2465. if (QualType(canonElementType.Ty, 0) == elementType)
  2466. return canon;
  2467. // Otherwise, we need to build a type which follows the spelling
  2468. // of the element type.
  2469. DependentSizedArrayType *sugaredType
  2470. = new (*this, TypeAlignment)
  2471. DependentSizedArrayType(*this, elementType, canon, numElements,
  2472. ASM, elementTypeQuals, brackets);
  2473. Types.push_back(sugaredType);
  2474. return QualType(sugaredType, 0);
  2475. }
  2476. QualType ASTContext::getIncompleteArrayType(QualType elementType,
  2477. ArrayType::ArraySizeModifier ASM,
  2478. unsigned elementTypeQuals) const {
  2479. llvm::FoldingSetNodeID ID;
  2480. IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
  2481. void *insertPos = nullptr;
  2482. if (IncompleteArrayType *iat =
  2483. IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
  2484. return QualType(iat, 0);
  2485. // If the element type isn't canonical, this won't be a canonical type
  2486. // either, so fill in the canonical type field. We also have to pull
  2487. // qualifiers off the element type.
  2488. QualType canon;
  2489. if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
  2490. SplitQualType canonSplit = getCanonicalType(elementType).split();
  2491. canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
  2492. ASM, elementTypeQuals);
  2493. canon = getQualifiedType(canon, canonSplit.Quals);
  2494. // Get the new insert position for the node we care about.
  2495. IncompleteArrayType *existing =
  2496. IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
  2497. assert(!existing && "Shouldn't be in the map!"); (void) existing;
  2498. }
  2499. IncompleteArrayType *newType = new (*this, TypeAlignment)
  2500. IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
  2501. IncompleteArrayTypes.InsertNode(newType, insertPos);
  2502. Types.push_back(newType);
  2503. return QualType(newType, 0);
  2504. }
  2505. /// getVectorType - Return the unique reference to a vector type of
  2506. /// the specified element type and size. VectorType must be a built-in type.
  2507. QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
  2508. VectorType::VectorKind VecKind) const {
  2509. assert(vecType->isBuiltinType());
  2510. // Check if we've already instantiated a vector of this type.
  2511. llvm::FoldingSetNodeID ID;
  2512. VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
  2513. void *InsertPos = nullptr;
  2514. if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
  2515. return QualType(VTP, 0);
  2516. // If the element type isn't canonical, this won't be a canonical type either,
  2517. // so fill in the canonical type field.
  2518. QualType Canonical;
  2519. if (!vecType.isCanonical()) {
  2520. Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
  2521. // Get the new insert position for the node we care about.
  2522. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  2523. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2524. }
  2525. VectorType *New = new (*this, TypeAlignment)
  2526. VectorType(vecType, NumElts, Canonical, VecKind);
  2527. VectorTypes.InsertNode(New, InsertPos);
  2528. Types.push_back(New);
  2529. return QualType(New, 0);
  2530. }
  2531. /// getExtVectorType - Return the unique reference to an extended vector type of
  2532. /// the specified element type and size. VectorType must be a built-in type.
  2533. QualType
  2534. ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
  2535. assert(vecType->isBuiltinType() || vecType->isDependentType());
  2536. // Check if we've already instantiated a vector of this type.
  2537. llvm::FoldingSetNodeID ID;
  2538. VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
  2539. VectorType::GenericVector);
  2540. void *InsertPos = nullptr;
  2541. if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
  2542. return QualType(VTP, 0);
  2543. // If the element type isn't canonical, this won't be a canonical type either,
  2544. // so fill in the canonical type field.
  2545. QualType Canonical;
  2546. if (!vecType.isCanonical()) {
  2547. Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
  2548. // Get the new insert position for the node we care about.
  2549. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  2550. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2551. }
  2552. ExtVectorType *New = new (*this, TypeAlignment)
  2553. ExtVectorType(vecType, NumElts, Canonical);
  2554. VectorTypes.InsertNode(New, InsertPos);
  2555. Types.push_back(New);
  2556. return QualType(New, 0);
  2557. }
  2558. QualType
  2559. ASTContext::getDependentSizedExtVectorType(QualType vecType,
  2560. Expr *SizeExpr,
  2561. SourceLocation AttrLoc) const {
  2562. llvm::FoldingSetNodeID ID;
  2563. DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
  2564. SizeExpr);
  2565. void *InsertPos = nullptr;
  2566. DependentSizedExtVectorType *Canon
  2567. = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  2568. DependentSizedExtVectorType *New;
  2569. if (Canon) {
  2570. // We already have a canonical version of this array type; use it as
  2571. // the canonical type for a newly-built type.
  2572. New = new (*this, TypeAlignment)
  2573. DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
  2574. SizeExpr, AttrLoc);
  2575. } else {
  2576. QualType CanonVecTy = getCanonicalType(vecType);
  2577. if (CanonVecTy == vecType) {
  2578. New = new (*this, TypeAlignment)
  2579. DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
  2580. AttrLoc);
  2581. DependentSizedExtVectorType *CanonCheck
  2582. = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  2583. assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
  2584. (void)CanonCheck;
  2585. DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
  2586. } else {
  2587. QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
  2588. SourceLocation());
  2589. New = new (*this, TypeAlignment)
  2590. DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
  2591. }
  2592. }
  2593. Types.push_back(New);
  2594. return QualType(New, 0);
  2595. }
  2596. /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
  2597. ///
  2598. QualType
  2599. ASTContext::getFunctionNoProtoType(QualType ResultTy,
  2600. const FunctionType::ExtInfo &Info) const {
  2601. const CallingConv CallConv = Info.getCC();
  2602. // Unique functions, to guarantee there is only one function of a particular
  2603. // structure.
  2604. llvm::FoldingSetNodeID ID;
  2605. FunctionNoProtoType::Profile(ID, ResultTy, Info);
  2606. void *InsertPos = nullptr;
  2607. if (FunctionNoProtoType *FT =
  2608. FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
  2609. return QualType(FT, 0);
  2610. QualType Canonical;
  2611. if (!ResultTy.isCanonical()) {
  2612. Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
  2613. // Get the new insert position for the node we care about.
  2614. FunctionNoProtoType *NewIP =
  2615. FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
  2616. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2617. }
  2618. FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
  2619. FunctionNoProtoType *New = new (*this, TypeAlignment)
  2620. FunctionNoProtoType(ResultTy, Canonical, newInfo);
  2621. Types.push_back(New);
  2622. FunctionNoProtoTypes.InsertNode(New, InsertPos);
  2623. return QualType(New, 0);
  2624. }
  2625. /// \brief Determine whether \p T is canonical as the result type of a function.
  2626. static bool isCanonicalResultType(QualType T) {
  2627. return T.isCanonical() &&
  2628. (T.getObjCLifetime() == Qualifiers::OCL_None ||
  2629. T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
  2630. }
  2631. QualType
  2632. ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
  2633. const FunctionProtoType::ExtProtoInfo &EPI,
  2634. ArrayRef<hlsl::ParameterModifier> ParamMods) const { // HLSL Change - param mods
  2635. size_t NumArgs = ArgArray.size();
  2636. // Unique functions, to guarantee there is only one function of a particular
  2637. // structure.
  2638. llvm::FoldingSetNodeID ID;
  2639. FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, ParamMods, // HLSL Change - param mods
  2640. *this);
  2641. void *InsertPos = nullptr;
  2642. if (FunctionProtoType *FTP =
  2643. FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
  2644. return QualType(FTP, 0);
  2645. // Determine whether the type being created is already canonical or not.
  2646. bool isCanonical =
  2647. EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
  2648. !EPI.HasTrailingReturn;
  2649. for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
  2650. if (!ArgArray[i].isCanonicalAsParam() &&
  2651. // HLSL Change Begins.
  2652. // Don't decay array to pointer.
  2653. // But do need to get canonical version of array.
  2654. !(getLangOpts().HLSL && ArgArray[i]->isArrayType() &&
  2655. ArgArray[i].isCanonical()))
  2656. // HLSL Change Ends.
  2657. isCanonical = false;
  2658. // If this type isn't canonical, get the canonical version of it.
  2659. // The exception spec is not part of the canonical type.
  2660. QualType Canonical;
  2661. if (!isCanonical) {
  2662. SmallVector<QualType, 16> CanonicalArgs;
  2663. CanonicalArgs.reserve(NumArgs);
  2664. for (unsigned i = 0; i != NumArgs; ++i)
  2665. CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
  2666. FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
  2667. CanonicalEPI.HasTrailingReturn = false;
  2668. CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
  2669. // Result types do not have ARC lifetime qualifiers.
  2670. QualType CanResultTy = getCanonicalType(ResultTy);
  2671. if (ResultTy.getQualifiers().hasObjCLifetime()) {
  2672. Qualifiers Qs = CanResultTy.getQualifiers();
  2673. Qs.removeObjCLifetime();
  2674. CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
  2675. }
  2676. Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI, ParamMods); // HLSL Change - param mods
  2677. // Get the new insert position for the node we care about.
  2678. FunctionProtoType *NewIP =
  2679. FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
  2680. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2681. }
  2682. // FunctionProtoType objects are allocated with extra bytes after
  2683. // them for three variable size arrays at the end:
  2684. // - parameter types
  2685. // - exception types
  2686. // - consumed-arguments flags
  2687. // Instead of the exception types, there could be a noexcept
  2688. // expression, or information used to resolve the exception
  2689. // specification.
  2690. size_t Size = sizeof(FunctionProtoType) +
  2691. NumArgs * sizeof(QualType);
  2692. if (EPI.ExceptionSpec.Type == EST_Dynamic) {
  2693. Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
  2694. } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
  2695. Size += sizeof(Expr*);
  2696. } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
  2697. Size += 2 * sizeof(FunctionDecl*);
  2698. } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
  2699. Size += sizeof(FunctionDecl*);
  2700. }
  2701. // HLSL Change Starts
  2702. if (getLangOpts().HLSL) {
  2703. assert((Size == sizeof(FunctionProtoType) + NumArgs * sizeof(QualType)) && "else exception spec was added");
  2704. Size += NumArgs * sizeof(hlsl::ParameterModifier);
  2705. }
  2706. // HLSL Change Ends
  2707. if (EPI.ConsumedParameters)
  2708. Size += NumArgs * sizeof(bool);
  2709. FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
  2710. FunctionProtoType::ExtProtoInfo newEPI = EPI;
  2711. new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI, ParamMods); // HLSL - param mods
  2712. Types.push_back(FTP);
  2713. FunctionProtoTypes.InsertNode(FTP, InsertPos);
  2714. return QualType(FTP, 0);
  2715. }
  2716. #ifndef NDEBUG
  2717. static bool NeedsInjectedClassNameType(const RecordDecl *D) {
  2718. if (!isa<CXXRecordDecl>(D)) return false;
  2719. const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
  2720. if (isa<ClassTemplatePartialSpecializationDecl>(RD))
  2721. return true;
  2722. if (RD->getDescribedClassTemplate() &&
  2723. !isa<ClassTemplateSpecializationDecl>(RD))
  2724. return true;
  2725. return false;
  2726. }
  2727. #endif
  2728. /// getInjectedClassNameType - Return the unique reference to the
  2729. /// injected class name type for the specified templated declaration.
  2730. QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
  2731. QualType TST) const {
  2732. assert(NeedsInjectedClassNameType(Decl));
  2733. if (Decl->TypeForDecl) {
  2734. assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
  2735. } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
  2736. assert(PrevDecl->TypeForDecl && "previous declaration has no type");
  2737. Decl->TypeForDecl = PrevDecl->TypeForDecl;
  2738. assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
  2739. } else {
  2740. Type *newType =
  2741. new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
  2742. Decl->TypeForDecl = newType;
  2743. Types.push_back(newType);
  2744. }
  2745. return QualType(Decl->TypeForDecl, 0);
  2746. }
  2747. /// getTypeDeclType - Return the unique reference to the type for the
  2748. /// specified type declaration.
  2749. QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
  2750. assert(Decl && "Passed null for Decl param");
  2751. assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
  2752. if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
  2753. return getTypedefType(Typedef);
  2754. assert(!isa<TemplateTypeParmDecl>(Decl) &&
  2755. "Template type parameter types are always available.");
  2756. if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
  2757. assert(Record->isFirstDecl() && "struct/union has previous declaration");
  2758. assert(!NeedsInjectedClassNameType(Record));
  2759. return getRecordType(Record);
  2760. } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
  2761. assert(Enum->isFirstDecl() && "enum has previous declaration");
  2762. return getEnumType(Enum);
  2763. } else if (const UnresolvedUsingTypenameDecl *Using =
  2764. dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
  2765. Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
  2766. Decl->TypeForDecl = newType;
  2767. Types.push_back(newType);
  2768. } else
  2769. llvm_unreachable("TypeDecl without a type?");
  2770. return QualType(Decl->TypeForDecl, 0);
  2771. }
  2772. /// getTypedefType - Return the unique reference to the type for the
  2773. /// specified typedef name decl.
  2774. QualType
  2775. ASTContext::getTypedefType(const TypedefNameDecl *Decl,
  2776. QualType Canonical) const {
  2777. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  2778. if (Canonical.isNull())
  2779. Canonical = getCanonicalType(Decl->getUnderlyingType());
  2780. TypedefType *newType = new(*this, TypeAlignment)
  2781. TypedefType(Type::Typedef, Decl, Canonical);
  2782. Decl->TypeForDecl = newType;
  2783. Types.push_back(newType);
  2784. return QualType(newType, 0);
  2785. }
  2786. QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
  2787. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  2788. if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
  2789. if (PrevDecl->TypeForDecl)
  2790. return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
  2791. RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
  2792. Decl->TypeForDecl = newType;
  2793. Types.push_back(newType);
  2794. return QualType(newType, 0);
  2795. }
  2796. QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
  2797. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  2798. if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
  2799. if (PrevDecl->TypeForDecl)
  2800. return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
  2801. EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
  2802. Decl->TypeForDecl = newType;
  2803. Types.push_back(newType);
  2804. return QualType(newType, 0);
  2805. }
  2806. QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
  2807. QualType modifiedType,
  2808. QualType equivalentType) {
  2809. llvm::FoldingSetNodeID id;
  2810. AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
  2811. void *insertPos = nullptr;
  2812. AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
  2813. if (type) return QualType(type, 0);
  2814. QualType canon = getCanonicalType(equivalentType);
  2815. type = new (*this, TypeAlignment)
  2816. AttributedType(canon, attrKind, modifiedType, equivalentType);
  2817. Types.push_back(type);
  2818. AttributedTypes.InsertNode(type, insertPos);
  2819. return QualType(type, 0);
  2820. }
  2821. /// \brief Retrieve a substitution-result type.
  2822. QualType
  2823. ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
  2824. QualType Replacement) const {
  2825. assert(Replacement.isCanonical()
  2826. && "replacement types must always be canonical");
  2827. llvm::FoldingSetNodeID ID;
  2828. SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
  2829. void *InsertPos = nullptr;
  2830. SubstTemplateTypeParmType *SubstParm
  2831. = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  2832. if (!SubstParm) {
  2833. SubstParm = new (*this, TypeAlignment)
  2834. SubstTemplateTypeParmType(Parm, Replacement);
  2835. Types.push_back(SubstParm);
  2836. SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
  2837. }
  2838. return QualType(SubstParm, 0);
  2839. }
  2840. /// \brief Retrieve a
  2841. QualType ASTContext::getSubstTemplateTypeParmPackType(
  2842. const TemplateTypeParmType *Parm,
  2843. const TemplateArgument &ArgPack) {
  2844. #ifndef NDEBUG
  2845. for (const auto &P : ArgPack.pack_elements()) {
  2846. assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
  2847. assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
  2848. }
  2849. #endif
  2850. llvm::FoldingSetNodeID ID;
  2851. SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
  2852. void *InsertPos = nullptr;
  2853. if (SubstTemplateTypeParmPackType *SubstParm
  2854. = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
  2855. return QualType(SubstParm, 0);
  2856. QualType Canon;
  2857. if (!Parm->isCanonicalUnqualified()) {
  2858. Canon = getCanonicalType(QualType(Parm, 0));
  2859. Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
  2860. ArgPack);
  2861. SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
  2862. }
  2863. SubstTemplateTypeParmPackType *SubstParm
  2864. = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
  2865. ArgPack);
  2866. Types.push_back(SubstParm);
  2867. SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
  2868. return QualType(SubstParm, 0);
  2869. }
  2870. /// \brief Retrieve the template type parameter type for a template
  2871. /// parameter or parameter pack with the given depth, index, and (optionally)
  2872. /// name.
  2873. QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
  2874. bool ParameterPack,
  2875. TemplateTypeParmDecl *TTPDecl) const {
  2876. llvm::FoldingSetNodeID ID;
  2877. TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
  2878. void *InsertPos = nullptr;
  2879. TemplateTypeParmType *TypeParm
  2880. = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  2881. if (TypeParm)
  2882. return QualType(TypeParm, 0);
  2883. if (TTPDecl) {
  2884. QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
  2885. TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
  2886. TemplateTypeParmType *TypeCheck
  2887. = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  2888. assert(!TypeCheck && "Template type parameter canonical type broken");
  2889. (void)TypeCheck;
  2890. } else
  2891. TypeParm = new (*this, TypeAlignment)
  2892. TemplateTypeParmType(Depth, Index, ParameterPack);
  2893. Types.push_back(TypeParm);
  2894. TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
  2895. return QualType(TypeParm, 0);
  2896. }
  2897. TypeSourceInfo *
  2898. ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
  2899. SourceLocation NameLoc,
  2900. const TemplateArgumentListInfo &Args,
  2901. QualType Underlying) const {
  2902. assert(!Name.getAsDependentTemplateName() &&
  2903. "No dependent template names here!");
  2904. QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
  2905. TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
  2906. TemplateSpecializationTypeLoc TL =
  2907. DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
  2908. TL.setTemplateKeywordLoc(SourceLocation());
  2909. TL.setTemplateNameLoc(NameLoc);
  2910. TL.setLAngleLoc(Args.getLAngleLoc());
  2911. TL.setRAngleLoc(Args.getRAngleLoc());
  2912. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  2913. TL.setArgLocInfo(i, Args[i].getLocInfo());
  2914. return DI;
  2915. }
  2916. QualType
  2917. ASTContext::getTemplateSpecializationType(TemplateName Template,
  2918. const TemplateArgumentListInfo &Args,
  2919. QualType Underlying) const {
  2920. assert(!Template.getAsDependentTemplateName() &&
  2921. "No dependent template names here!");
  2922. unsigned NumArgs = Args.size();
  2923. SmallVector<TemplateArgument, 4> ArgVec;
  2924. ArgVec.reserve(NumArgs);
  2925. for (unsigned i = 0; i != NumArgs; ++i)
  2926. ArgVec.push_back(Args[i].getArgument());
  2927. return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
  2928. Underlying);
  2929. }
  2930. #ifndef NDEBUG
  2931. static bool hasAnyPackExpansions(const TemplateArgument *Args,
  2932. unsigned NumArgs) {
  2933. for (unsigned I = 0; I != NumArgs; ++I)
  2934. if (Args[I].isPackExpansion())
  2935. return true;
  2936. return true;
  2937. }
  2938. #endif
  2939. QualType
  2940. ASTContext::getTemplateSpecializationType(TemplateName Template,
  2941. const TemplateArgument *Args,
  2942. unsigned NumArgs,
  2943. QualType Underlying) const {
  2944. assert(!Template.getAsDependentTemplateName() &&
  2945. "No dependent template names here!");
  2946. // Look through qualified template names.
  2947. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
  2948. Template = TemplateName(QTN->getTemplateDecl());
  2949. bool IsTypeAlias =
  2950. Template.getAsTemplateDecl() &&
  2951. isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
  2952. QualType CanonType;
  2953. if (!Underlying.isNull())
  2954. CanonType = getCanonicalType(Underlying);
  2955. else {
  2956. // We can get here with an alias template when the specialization contains
  2957. // a pack expansion that does not match up with a parameter pack.
  2958. assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
  2959. "Caller must compute aliased type");
  2960. IsTypeAlias = false;
  2961. CanonType = getCanonicalTemplateSpecializationType(Template, Args,
  2962. NumArgs);
  2963. }
  2964. // Allocate the (non-canonical) template specialization type, but don't
  2965. // try to unique it: these types typically have location information that
  2966. // we don't unique and don't want to lose.
  2967. void *Mem = Allocate(sizeof(TemplateSpecializationType) +
  2968. sizeof(TemplateArgument) * NumArgs +
  2969. (IsTypeAlias? sizeof(QualType) : 0),
  2970. TypeAlignment);
  2971. TemplateSpecializationType *Spec
  2972. = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
  2973. IsTypeAlias ? Underlying : QualType());
  2974. Types.push_back(Spec);
  2975. return QualType(Spec, 0);
  2976. }
  2977. QualType
  2978. ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
  2979. const TemplateArgument *Args,
  2980. unsigned NumArgs) const {
  2981. assert(!Template.getAsDependentTemplateName() &&
  2982. "No dependent template names here!");
  2983. // Look through qualified template names.
  2984. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
  2985. Template = TemplateName(QTN->getTemplateDecl());
  2986. // Build the canonical template specialization type.
  2987. TemplateName CanonTemplate = getCanonicalTemplateName(Template);
  2988. SmallVector<TemplateArgument, 4> CanonArgs;
  2989. CanonArgs.reserve(NumArgs);
  2990. for (unsigned I = 0; I != NumArgs; ++I)
  2991. CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
  2992. // Determine whether this canonical template specialization type already
  2993. // exists.
  2994. llvm::FoldingSetNodeID ID;
  2995. TemplateSpecializationType::Profile(ID, CanonTemplate,
  2996. CanonArgs.data(), NumArgs, *this);
  2997. void *InsertPos = nullptr;
  2998. TemplateSpecializationType *Spec
  2999. = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  3000. if (!Spec) {
  3001. // Allocate a new canonical template specialization type.
  3002. void *Mem = Allocate((sizeof(TemplateSpecializationType) +
  3003. sizeof(TemplateArgument) * NumArgs),
  3004. TypeAlignment);
  3005. Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
  3006. CanonArgs.data(), NumArgs,
  3007. QualType(), QualType());
  3008. Types.push_back(Spec);
  3009. TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
  3010. }
  3011. assert(Spec->isDependentType() &&
  3012. "Non-dependent template-id type must have a canonical type");
  3013. return QualType(Spec, 0);
  3014. }
  3015. QualType
  3016. ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
  3017. NestedNameSpecifier *NNS,
  3018. QualType NamedType) const {
  3019. llvm::FoldingSetNodeID ID;
  3020. ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
  3021. void *InsertPos = nullptr;
  3022. ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
  3023. if (T)
  3024. return QualType(T, 0);
  3025. QualType Canon = NamedType;
  3026. if (!Canon.isCanonical()) {
  3027. Canon = getCanonicalType(NamedType);
  3028. ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
  3029. assert(!CheckT && "Elaborated canonical type broken");
  3030. (void)CheckT;
  3031. }
  3032. T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
  3033. Types.push_back(T);
  3034. ElaboratedTypes.InsertNode(T, InsertPos);
  3035. return QualType(T, 0);
  3036. }
  3037. QualType
  3038. ASTContext::getParenType(QualType InnerType) const {
  3039. llvm::FoldingSetNodeID ID;
  3040. ParenType::Profile(ID, InnerType);
  3041. void *InsertPos = nullptr;
  3042. ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
  3043. if (T)
  3044. return QualType(T, 0);
  3045. QualType Canon = InnerType;
  3046. if (!Canon.isCanonical()) {
  3047. Canon = getCanonicalType(InnerType);
  3048. ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
  3049. assert(!CheckT && "Paren canonical type broken");
  3050. (void)CheckT;
  3051. }
  3052. T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
  3053. Types.push_back(T);
  3054. ParenTypes.InsertNode(T, InsertPos);
  3055. return QualType(T, 0);
  3056. }
  3057. QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
  3058. NestedNameSpecifier *NNS,
  3059. const IdentifierInfo *Name,
  3060. QualType Canon) const {
  3061. if (Canon.isNull()) {
  3062. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  3063. ElaboratedTypeKeyword CanonKeyword = Keyword;
  3064. if (Keyword == ETK_None)
  3065. CanonKeyword = ETK_Typename;
  3066. if (CanonNNS != NNS || CanonKeyword != Keyword)
  3067. Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
  3068. }
  3069. llvm::FoldingSetNodeID ID;
  3070. DependentNameType::Profile(ID, Keyword, NNS, Name);
  3071. void *InsertPos = nullptr;
  3072. DependentNameType *T
  3073. = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
  3074. if (T)
  3075. return QualType(T, 0);
  3076. T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
  3077. Types.push_back(T);
  3078. DependentNameTypes.InsertNode(T, InsertPos);
  3079. return QualType(T, 0);
  3080. }
  3081. QualType
  3082. ASTContext::getDependentTemplateSpecializationType(
  3083. ElaboratedTypeKeyword Keyword,
  3084. NestedNameSpecifier *NNS,
  3085. const IdentifierInfo *Name,
  3086. const TemplateArgumentListInfo &Args) const {
  3087. // TODO: avoid this copy
  3088. SmallVector<TemplateArgument, 16> ArgCopy;
  3089. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  3090. ArgCopy.push_back(Args[I].getArgument());
  3091. return getDependentTemplateSpecializationType(Keyword, NNS, Name,
  3092. ArgCopy.size(),
  3093. ArgCopy.data());
  3094. }
  3095. QualType
  3096. ASTContext::getDependentTemplateSpecializationType(
  3097. ElaboratedTypeKeyword Keyword,
  3098. NestedNameSpecifier *NNS,
  3099. const IdentifierInfo *Name,
  3100. unsigned NumArgs,
  3101. const TemplateArgument *Args) const {
  3102. assert((!NNS || NNS->isDependent()) &&
  3103. "nested-name-specifier must be dependent");
  3104. llvm::FoldingSetNodeID ID;
  3105. DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
  3106. Name, NumArgs, Args);
  3107. void *InsertPos = nullptr;
  3108. DependentTemplateSpecializationType *T
  3109. = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  3110. if (T)
  3111. return QualType(T, 0);
  3112. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  3113. ElaboratedTypeKeyword CanonKeyword = Keyword;
  3114. if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
  3115. bool AnyNonCanonArgs = false;
  3116. SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
  3117. for (unsigned I = 0; I != NumArgs; ++I) {
  3118. CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
  3119. if (!CanonArgs[I].structurallyEquals(Args[I]))
  3120. AnyNonCanonArgs = true;
  3121. }
  3122. QualType Canon;
  3123. if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
  3124. Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
  3125. Name, NumArgs,
  3126. CanonArgs.data());
  3127. // Find the insert position again.
  3128. DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  3129. }
  3130. void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
  3131. sizeof(TemplateArgument) * NumArgs),
  3132. TypeAlignment);
  3133. T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
  3134. Name, NumArgs, Args, Canon);
  3135. Types.push_back(T);
  3136. DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
  3137. return QualType(T, 0);
  3138. }
  3139. QualType ASTContext::getPackExpansionType(QualType Pattern,
  3140. Optional<unsigned> NumExpansions) {
  3141. llvm::FoldingSetNodeID ID;
  3142. PackExpansionType::Profile(ID, Pattern, NumExpansions);
  3143. assert(Pattern->containsUnexpandedParameterPack() &&
  3144. "Pack expansions must expand one or more parameter packs");
  3145. void *InsertPos = nullptr;
  3146. PackExpansionType *T
  3147. = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
  3148. if (T)
  3149. return QualType(T, 0);
  3150. QualType Canon;
  3151. if (!Pattern.isCanonical()) {
  3152. Canon = getCanonicalType(Pattern);
  3153. // The canonical type might not contain an unexpanded parameter pack, if it
  3154. // contains an alias template specialization which ignores one of its
  3155. // parameters.
  3156. if (Canon->containsUnexpandedParameterPack()) {
  3157. Canon = getPackExpansionType(Canon, NumExpansions);
  3158. // Find the insert position again, in case we inserted an element into
  3159. // PackExpansionTypes and invalidated our insert position.
  3160. PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
  3161. }
  3162. }
  3163. T = new (*this, TypeAlignment)
  3164. PackExpansionType(Pattern, Canon, NumExpansions);
  3165. Types.push_back(T);
  3166. PackExpansionTypes.InsertNode(T, InsertPos);
  3167. return QualType(T, 0);
  3168. }
  3169. /// CmpProtocolNames - Comparison predicate for sorting protocols
  3170. /// alphabetically.
  3171. static int __cdecl CmpProtocolNames(ObjCProtocolDecl *const *LHS, // HLSL Change - __cdecl
  3172. ObjCProtocolDecl *const *RHS) {
  3173. return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
  3174. }
  3175. static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
  3176. unsigned NumProtocols) {
  3177. if (NumProtocols == 0) return true;
  3178. if (Protocols[0]->getCanonicalDecl() != Protocols[0])
  3179. return false;
  3180. for (unsigned i = 1; i != NumProtocols; ++i)
  3181. if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
  3182. Protocols[i]->getCanonicalDecl() != Protocols[i])
  3183. return false;
  3184. return true;
  3185. }
  3186. static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
  3187. unsigned &NumProtocols) {
  3188. ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
  3189. // Sort protocols, keyed by name.
  3190. llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
  3191. // Canonicalize.
  3192. for (unsigned I = 0, N = NumProtocols; I != N; ++I)
  3193. Protocols[I] = Protocols[I]->getCanonicalDecl();
  3194. // Remove duplicates.
  3195. ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
  3196. NumProtocols = ProtocolsEnd-Protocols;
  3197. }
  3198. QualType ASTContext::getObjCObjectType(QualType BaseType,
  3199. ObjCProtocolDecl * const *Protocols,
  3200. unsigned NumProtocols) const {
  3201. return getObjCObjectType(BaseType, { },
  3202. llvm::makeArrayRef(Protocols, NumProtocols),
  3203. /*isKindOf=*/false);
  3204. }
  3205. QualType ASTContext::getObjCObjectType(
  3206. QualType baseType,
  3207. ArrayRef<QualType> typeArgs,
  3208. ArrayRef<ObjCProtocolDecl *> protocols,
  3209. bool isKindOf) const {
  3210. // If the base type is an interface and there aren't any protocols or
  3211. // type arguments to add, then the interface type will do just fine.
  3212. if (typeArgs.empty() && protocols.empty() && !isKindOf &&
  3213. isa<ObjCInterfaceType>(baseType))
  3214. return baseType;
  3215. // Look in the folding set for an existing type.
  3216. llvm::FoldingSetNodeID ID;
  3217. ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
  3218. void *InsertPos = nullptr;
  3219. if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
  3220. return QualType(QT, 0);
  3221. // Determine the type arguments to be used for canonicalization,
  3222. // which may be explicitly specified here or written on the base
  3223. // type.
  3224. ArrayRef<QualType> effectiveTypeArgs = typeArgs;
  3225. if (effectiveTypeArgs.empty()) {
  3226. if (auto baseObject = baseType->getAs<ObjCObjectType>())
  3227. effectiveTypeArgs = baseObject->getTypeArgs();
  3228. }
  3229. // Build the canonical type, which has the canonical base type and a
  3230. // sorted-and-uniqued list of protocols and the type arguments
  3231. // canonicalized.
  3232. QualType canonical;
  3233. bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
  3234. effectiveTypeArgs.end(),
  3235. [&](QualType type) {
  3236. return type.isCanonical();
  3237. });
  3238. bool protocolsSorted = areSortedAndUniqued(protocols.data(),
  3239. protocols.size());
  3240. if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
  3241. // Determine the canonical type arguments.
  3242. ArrayRef<QualType> canonTypeArgs;
  3243. SmallVector<QualType, 4> canonTypeArgsVec;
  3244. if (!typeArgsAreCanonical) {
  3245. canonTypeArgsVec.reserve(effectiveTypeArgs.size());
  3246. for (auto typeArg : effectiveTypeArgs)
  3247. canonTypeArgsVec.push_back(getCanonicalType(typeArg));
  3248. canonTypeArgs = canonTypeArgsVec;
  3249. } else {
  3250. canonTypeArgs = effectiveTypeArgs;
  3251. }
  3252. ArrayRef<ObjCProtocolDecl *> canonProtocols;
  3253. SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
  3254. if (!protocolsSorted) {
  3255. canonProtocolsVec.insert(canonProtocolsVec.begin(),
  3256. protocols.begin(),
  3257. protocols.end());
  3258. unsigned uniqueCount = protocols.size();
  3259. SortAndUniqueProtocols(&canonProtocolsVec[0], uniqueCount);
  3260. canonProtocols = llvm::makeArrayRef(&canonProtocolsVec[0], uniqueCount);
  3261. } else {
  3262. canonProtocols = protocols;
  3263. }
  3264. canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
  3265. canonProtocols, isKindOf);
  3266. // Regenerate InsertPos.
  3267. ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
  3268. }
  3269. unsigned size = sizeof(ObjCObjectTypeImpl);
  3270. size += typeArgs.size() * sizeof(QualType);
  3271. size += protocols.size() * sizeof(ObjCProtocolDecl *);
  3272. void *mem = Allocate(size, TypeAlignment);
  3273. ObjCObjectTypeImpl *T =
  3274. new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
  3275. isKindOf);
  3276. Types.push_back(T);
  3277. ObjCObjectTypes.InsertNode(T, InsertPos);
  3278. return QualType(T, 0);
  3279. }
  3280. /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
  3281. /// protocol list adopt all protocols in QT's qualified-id protocol
  3282. /// list.
  3283. bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
  3284. ObjCInterfaceDecl *IC) {
  3285. if (!QT->isObjCQualifiedIdType())
  3286. return false;
  3287. if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
  3288. // If both the right and left sides have qualifiers.
  3289. for (auto *Proto : OPT->quals()) {
  3290. if (!IC->ClassImplementsProtocol(Proto, false))
  3291. return false;
  3292. }
  3293. return true;
  3294. }
  3295. return false;
  3296. }
  3297. /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
  3298. /// QT's qualified-id protocol list adopt all protocols in IDecl's list
  3299. /// of protocols.
  3300. bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
  3301. ObjCInterfaceDecl *IDecl) {
  3302. if (!QT->isObjCQualifiedIdType())
  3303. return false;
  3304. const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
  3305. if (!OPT)
  3306. return false;
  3307. if (!IDecl->hasDefinition())
  3308. return false;
  3309. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
  3310. CollectInheritedProtocols(IDecl, InheritedProtocols);
  3311. if (InheritedProtocols.empty())
  3312. return false;
  3313. // Check that if every protocol in list of id<plist> conforms to a protcol
  3314. // of IDecl's, then bridge casting is ok.
  3315. bool Conforms = false;
  3316. for (auto *Proto : OPT->quals()) {
  3317. Conforms = false;
  3318. for (auto *PI : InheritedProtocols) {
  3319. if (ProtocolCompatibleWithProtocol(Proto, PI)) {
  3320. Conforms = true;
  3321. break;
  3322. }
  3323. }
  3324. if (!Conforms)
  3325. break;
  3326. }
  3327. if (Conforms)
  3328. return true;
  3329. for (auto *PI : InheritedProtocols) {
  3330. // If both the right and left sides have qualifiers.
  3331. bool Adopts = false;
  3332. for (auto *Proto : OPT->quals()) {
  3333. // return 'true' if 'PI' is in the inheritance hierarchy of Proto
  3334. if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
  3335. break;
  3336. }
  3337. if (!Adopts)
  3338. return false;
  3339. }
  3340. return true;
  3341. }
  3342. /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
  3343. /// the given object type.
  3344. QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
  3345. llvm::FoldingSetNodeID ID;
  3346. ObjCObjectPointerType::Profile(ID, ObjectT);
  3347. void *InsertPos = nullptr;
  3348. if (ObjCObjectPointerType *QT =
  3349. ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  3350. return QualType(QT, 0);
  3351. // Find the canonical object type.
  3352. QualType Canonical;
  3353. if (!ObjectT.isCanonical()) {
  3354. Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
  3355. // Regenerate InsertPos.
  3356. ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  3357. }
  3358. // No match.
  3359. void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
  3360. ObjCObjectPointerType *QType =
  3361. new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
  3362. Types.push_back(QType);
  3363. ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
  3364. return QualType(QType, 0);
  3365. }
  3366. /// getObjCInterfaceType - Return the unique reference to the type for the
  3367. /// specified ObjC interface decl. The list of protocols is optional.
  3368. QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
  3369. ObjCInterfaceDecl *PrevDecl) const {
  3370. if (Decl->TypeForDecl)
  3371. return QualType(Decl->TypeForDecl, 0);
  3372. if (PrevDecl) {
  3373. assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
  3374. Decl->TypeForDecl = PrevDecl->TypeForDecl;
  3375. return QualType(PrevDecl->TypeForDecl, 0);
  3376. }
  3377. // Prefer the definition, if there is one.
  3378. if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
  3379. Decl = Def;
  3380. void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
  3381. ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
  3382. Decl->TypeForDecl = T;
  3383. Types.push_back(T);
  3384. return QualType(T, 0);
  3385. }
  3386. /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
  3387. /// TypeOfExprType AST's (since expression's are never shared). For example,
  3388. /// multiple declarations that refer to "typeof(x)" all contain different
  3389. /// DeclRefExpr's. This doesn't effect the type checker, since it operates
  3390. /// on canonical type's (which are always unique).
  3391. QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
  3392. TypeOfExprType *toe;
  3393. if (tofExpr->isTypeDependent()) {
  3394. llvm::FoldingSetNodeID ID;
  3395. DependentTypeOfExprType::Profile(ID, *this, tofExpr);
  3396. void *InsertPos = nullptr;
  3397. DependentTypeOfExprType *Canon
  3398. = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
  3399. if (Canon) {
  3400. // We already have a "canonical" version of an identical, dependent
  3401. // typeof(expr) type. Use that as our canonical type.
  3402. toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
  3403. QualType((TypeOfExprType*)Canon, 0));
  3404. } else {
  3405. // Build a new, canonical typeof(expr) type.
  3406. Canon
  3407. = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
  3408. DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
  3409. toe = Canon;
  3410. }
  3411. } else {
  3412. QualType Canonical = getCanonicalType(tofExpr->getType());
  3413. toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
  3414. }
  3415. Types.push_back(toe);
  3416. return QualType(toe, 0);
  3417. }
  3418. /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
  3419. /// TypeOfType nodes. The only motivation to unique these nodes would be
  3420. /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
  3421. /// an issue. This doesn't affect the type checker, since it operates
  3422. /// on canonical types (which are always unique).
  3423. QualType ASTContext::getTypeOfType(QualType tofType) const {
  3424. QualType Canonical = getCanonicalType(tofType);
  3425. TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
  3426. Types.push_back(tot);
  3427. return QualType(tot, 0);
  3428. }
  3429. /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
  3430. /// nodes. This would never be helpful, since each such type has its own
  3431. /// expression, and would not give a significant memory saving, since there
  3432. /// is an Expr tree under each such type.
  3433. QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
  3434. DecltypeType *dt;
  3435. // C++11 [temp.type]p2:
  3436. // If an expression e involves a template parameter, decltype(e) denotes a
  3437. // unique dependent type. Two such decltype-specifiers refer to the same
  3438. // type only if their expressions are equivalent (14.5.6.1).
  3439. if (e->isInstantiationDependent()) {
  3440. llvm::FoldingSetNodeID ID;
  3441. DependentDecltypeType::Profile(ID, *this, e);
  3442. void *InsertPos = nullptr;
  3443. DependentDecltypeType *Canon
  3444. = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
  3445. if (!Canon) {
  3446. // Build a new, canonical typeof(expr) type.
  3447. Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
  3448. DependentDecltypeTypes.InsertNode(Canon, InsertPos);
  3449. }
  3450. dt = new (*this, TypeAlignment)
  3451. DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
  3452. } else {
  3453. dt = new (*this, TypeAlignment)
  3454. DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
  3455. }
  3456. Types.push_back(dt);
  3457. return QualType(dt, 0);
  3458. }
  3459. /// getUnaryTransformationType - We don't unique these, since the memory
  3460. /// savings are minimal and these are rare.
  3461. QualType ASTContext::getUnaryTransformType(QualType BaseType,
  3462. QualType UnderlyingType,
  3463. UnaryTransformType::UTTKind Kind)
  3464. const {
  3465. UnaryTransformType *Ty =
  3466. new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
  3467. Kind,
  3468. UnderlyingType->isDependentType() ?
  3469. QualType() : getCanonicalType(UnderlyingType));
  3470. Types.push_back(Ty);
  3471. return QualType(Ty, 0);
  3472. }
  3473. /// getAutoType - Return the uniqued reference to the 'auto' type which has been
  3474. /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
  3475. /// canonical deduced-but-dependent 'auto' type.
  3476. QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
  3477. bool IsDependent) const {
  3478. if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
  3479. return getAutoDeductType();
  3480. // Look in the folding set for an existing type.
  3481. void *InsertPos = nullptr;
  3482. llvm::FoldingSetNodeID ID;
  3483. AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
  3484. if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
  3485. return QualType(AT, 0);
  3486. AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
  3487. IsDecltypeAuto,
  3488. IsDependent);
  3489. Types.push_back(AT);
  3490. if (InsertPos)
  3491. AutoTypes.InsertNode(AT, InsertPos);
  3492. return QualType(AT, 0);
  3493. }
  3494. /// getAtomicType - Return the uniqued reference to the atomic type for
  3495. /// the given value type.
  3496. QualType ASTContext::getAtomicType(QualType T) const {
  3497. // Unique pointers, to guarantee there is only one pointer of a particular
  3498. // structure.
  3499. llvm::FoldingSetNodeID ID;
  3500. AtomicType::Profile(ID, T);
  3501. void *InsertPos = nullptr;
  3502. if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
  3503. return QualType(AT, 0);
  3504. // If the atomic value type isn't canonical, this won't be a canonical type
  3505. // either, so fill in the canonical type field.
  3506. QualType Canonical;
  3507. if (!T.isCanonical()) {
  3508. Canonical = getAtomicType(getCanonicalType(T));
  3509. // Get the new insert position for the node we care about.
  3510. AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
  3511. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3512. }
  3513. AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
  3514. Types.push_back(New);
  3515. AtomicTypes.InsertNode(New, InsertPos);
  3516. return QualType(New, 0);
  3517. }
  3518. /// getAutoDeductType - Get type pattern for deducing against 'auto'.
  3519. QualType ASTContext::getAutoDeductType() const {
  3520. if (AutoDeductTy.isNull())
  3521. AutoDeductTy = QualType(
  3522. new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
  3523. /*dependent*/false),
  3524. 0);
  3525. return AutoDeductTy;
  3526. }
  3527. /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
  3528. QualType ASTContext::getAutoRRefDeductType() const {
  3529. if (AutoRRefDeductTy.isNull())
  3530. AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
  3531. assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
  3532. return AutoRRefDeductTy;
  3533. }
  3534. /// getTagDeclType - Return the unique reference to the type for the
  3535. /// specified TagDecl (struct/union/class/enum) decl.
  3536. QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
  3537. assert (Decl);
  3538. // FIXME: What is the design on getTagDeclType when it requires casting
  3539. // away const? mutable?
  3540. return getTypeDeclType(const_cast<TagDecl*>(Decl));
  3541. }
  3542. /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
  3543. /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
  3544. /// needs to agree with the definition in <stddef.h>.
  3545. CanQualType ASTContext::getSizeType() const {
  3546. return getFromTargetType(Target->getSizeType());
  3547. }
  3548. /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
  3549. CanQualType ASTContext::getIntMaxType() const {
  3550. return getFromTargetType(Target->getIntMaxType());
  3551. }
  3552. /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
  3553. CanQualType ASTContext::getUIntMaxType() const {
  3554. return getFromTargetType(Target->getUIntMaxType());
  3555. }
  3556. /// getSignedWCharType - Return the type of "signed wchar_t".
  3557. /// Used when in C++, as a GCC extension.
  3558. QualType ASTContext::getSignedWCharType() const {
  3559. // FIXME: derive from "Target" ?
  3560. return WCharTy;
  3561. }
  3562. /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
  3563. /// Used when in C++, as a GCC extension.
  3564. QualType ASTContext::getUnsignedWCharType() const {
  3565. // FIXME: derive from "Target" ?
  3566. return UnsignedIntTy;
  3567. }
  3568. QualType ASTContext::getIntPtrType() const {
  3569. return getFromTargetType(Target->getIntPtrType());
  3570. }
  3571. QualType ASTContext::getUIntPtrType() const {
  3572. return getCorrespondingUnsignedType(getIntPtrType());
  3573. }
  3574. /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
  3575. /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
  3576. QualType ASTContext::getPointerDiffType() const {
  3577. return getFromTargetType(Target->getPtrDiffType(0));
  3578. }
  3579. /// \brief Return the unique type for "pid_t" defined in
  3580. /// <sys/types.h>. We need this to compute the correct type for vfork().
  3581. QualType ASTContext::getProcessIDType() const {
  3582. return getFromTargetType(Target->getProcessIDType());
  3583. }
  3584. //===----------------------------------------------------------------------===//
  3585. // Type Operators
  3586. //===----------------------------------------------------------------------===//
  3587. CanQualType ASTContext::getCanonicalParamType(QualType T) const {
  3588. // Push qualifiers into arrays, and then discard any remaining
  3589. // qualifiers.
  3590. T = getCanonicalType(T);
  3591. T = getVariableArrayDecayedType(T);
  3592. const Type *Ty = T.getTypePtr();
  3593. QualType Result;
  3594. if (isa<ArrayType>(Ty)) {
  3595. // HLSL Change Starts
  3596. if (getLangOpts().HLSL)
  3597. Result = QualType(Ty, 0);
  3598. else
  3599. // HLSL Change Ends
  3600. Result = getArrayDecayedType(QualType(Ty, 0));
  3601. } else if (isa<FunctionType>(Ty)) {
  3602. Result = getPointerType(QualType(Ty, 0));
  3603. } else {
  3604. Result = QualType(Ty, 0);
  3605. }
  3606. return CanQualType::CreateUnsafe(Result);
  3607. }
  3608. QualType ASTContext::getUnqualifiedArrayType(QualType type,
  3609. Qualifiers &quals) {
  3610. SplitQualType splitType = type.getSplitUnqualifiedType();
  3611. // FIXME: getSplitUnqualifiedType() actually walks all the way to
  3612. // the unqualified desugared type and then drops it on the floor.
  3613. // We then have to strip that sugar back off with
  3614. // getUnqualifiedDesugaredType(), which is silly.
  3615. const ArrayType *AT =
  3616. dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
  3617. // If we don't have an array, just use the results in splitType.
  3618. if (!AT) {
  3619. quals = splitType.Quals;
  3620. return QualType(splitType.Ty, 0);
  3621. }
  3622. // Otherwise, recurse on the array's element type.
  3623. QualType elementType = AT->getElementType();
  3624. QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
  3625. // If that didn't change the element type, AT has no qualifiers, so we
  3626. // can just use the results in splitType.
  3627. if (elementType == unqualElementType) {
  3628. assert(quals.empty()); // from the recursive call
  3629. quals = splitType.Quals;
  3630. return QualType(splitType.Ty, 0);
  3631. }
  3632. // Otherwise, add in the qualifiers from the outermost type, then
  3633. // build the type back up.
  3634. quals.addConsistentQualifiers(splitType.Quals);
  3635. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
  3636. return getConstantArrayType(unqualElementType, CAT->getSize(),
  3637. CAT->getSizeModifier(), 0);
  3638. }
  3639. if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
  3640. return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
  3641. }
  3642. if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
  3643. return getVariableArrayType(unqualElementType,
  3644. VAT->getSizeExpr(),
  3645. VAT->getSizeModifier(),
  3646. VAT->getIndexTypeCVRQualifiers(),
  3647. VAT->getBracketsRange());
  3648. }
  3649. const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
  3650. return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
  3651. DSAT->getSizeModifier(), 0,
  3652. SourceRange());
  3653. }
  3654. /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
  3655. /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
  3656. /// they point to and return true. If T1 and T2 aren't pointer types
  3657. /// or pointer-to-member types, or if they are not similar at this
  3658. /// level, returns false and leaves T1 and T2 unchanged. Top-level
  3659. /// qualifiers on T1 and T2 are ignored. This function will typically
  3660. /// be called in a loop that successively "unwraps" pointer and
  3661. /// pointer-to-member types to compare them at each level.
  3662. bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
  3663. const PointerType *T1PtrType = T1->getAs<PointerType>(),
  3664. *T2PtrType = T2->getAs<PointerType>();
  3665. if (T1PtrType && T2PtrType) {
  3666. T1 = T1PtrType->getPointeeType();
  3667. T2 = T2PtrType->getPointeeType();
  3668. return true;
  3669. }
  3670. const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
  3671. *T2MPType = T2->getAs<MemberPointerType>();
  3672. if (T1MPType && T2MPType &&
  3673. hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
  3674. QualType(T2MPType->getClass(), 0))) {
  3675. T1 = T1MPType->getPointeeType();
  3676. T2 = T2MPType->getPointeeType();
  3677. return true;
  3678. }
  3679. if (getLangOpts().ObjC1) {
  3680. const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
  3681. *T2OPType = T2->getAs<ObjCObjectPointerType>();
  3682. if (T1OPType && T2OPType) {
  3683. T1 = T1OPType->getPointeeType();
  3684. T2 = T2OPType->getPointeeType();
  3685. return true;
  3686. }
  3687. }
  3688. // FIXME: Block pointers, too?
  3689. return false;
  3690. }
  3691. DeclarationNameInfo
  3692. ASTContext::getNameForTemplate(TemplateName Name,
  3693. SourceLocation NameLoc) const {
  3694. switch (Name.getKind()) {
  3695. case TemplateName::QualifiedTemplate:
  3696. case TemplateName::Template:
  3697. // DNInfo work in progress: CHECKME: what about DNLoc?
  3698. return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
  3699. NameLoc);
  3700. case TemplateName::OverloadedTemplate: {
  3701. OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
  3702. // DNInfo work in progress: CHECKME: what about DNLoc?
  3703. return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
  3704. }
  3705. case TemplateName::DependentTemplate: {
  3706. DependentTemplateName *DTN = Name.getAsDependentTemplateName();
  3707. DeclarationName DName;
  3708. if (DTN->isIdentifier()) {
  3709. DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
  3710. return DeclarationNameInfo(DName, NameLoc);
  3711. } else {
  3712. DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
  3713. // DNInfo work in progress: FIXME: source locations?
  3714. DeclarationNameLoc DNLoc;
  3715. DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
  3716. DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
  3717. return DeclarationNameInfo(DName, NameLoc, DNLoc);
  3718. }
  3719. }
  3720. case TemplateName::SubstTemplateTemplateParm: {
  3721. SubstTemplateTemplateParmStorage *subst
  3722. = Name.getAsSubstTemplateTemplateParm();
  3723. return DeclarationNameInfo(subst->getParameter()->getDeclName(),
  3724. NameLoc);
  3725. }
  3726. case TemplateName::SubstTemplateTemplateParmPack: {
  3727. SubstTemplateTemplateParmPackStorage *subst
  3728. = Name.getAsSubstTemplateTemplateParmPack();
  3729. return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
  3730. NameLoc);
  3731. }
  3732. }
  3733. llvm_unreachable("bad template name kind!");
  3734. }
  3735. TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
  3736. switch (Name.getKind()) {
  3737. case TemplateName::QualifiedTemplate:
  3738. case TemplateName::Template: {
  3739. TemplateDecl *Template = Name.getAsTemplateDecl();
  3740. if (TemplateTemplateParmDecl *TTP
  3741. = dyn_cast<TemplateTemplateParmDecl>(Template))
  3742. Template = getCanonicalTemplateTemplateParmDecl(TTP);
  3743. // The canonical template name is the canonical template declaration.
  3744. return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
  3745. }
  3746. case TemplateName::OverloadedTemplate:
  3747. llvm_unreachable("cannot canonicalize overloaded template");
  3748. case TemplateName::DependentTemplate: {
  3749. DependentTemplateName *DTN = Name.getAsDependentTemplateName();
  3750. assert(DTN && "Non-dependent template names must refer to template decls.");
  3751. return DTN->CanonicalTemplateName;
  3752. }
  3753. case TemplateName::SubstTemplateTemplateParm: {
  3754. SubstTemplateTemplateParmStorage *subst
  3755. = Name.getAsSubstTemplateTemplateParm();
  3756. return getCanonicalTemplateName(subst->getReplacement());
  3757. }
  3758. case TemplateName::SubstTemplateTemplateParmPack: {
  3759. SubstTemplateTemplateParmPackStorage *subst
  3760. = Name.getAsSubstTemplateTemplateParmPack();
  3761. TemplateTemplateParmDecl *canonParameter
  3762. = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
  3763. TemplateArgument canonArgPack
  3764. = getCanonicalTemplateArgument(subst->getArgumentPack());
  3765. return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
  3766. }
  3767. }
  3768. llvm_unreachable("bad template name!");
  3769. }
  3770. bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
  3771. X = getCanonicalTemplateName(X);
  3772. Y = getCanonicalTemplateName(Y);
  3773. return X.getAsVoidPointer() == Y.getAsVoidPointer();
  3774. }
  3775. TemplateArgument
  3776. ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
  3777. switch (Arg.getKind()) {
  3778. case TemplateArgument::Null:
  3779. return Arg;
  3780. case TemplateArgument::Expression:
  3781. return Arg;
  3782. case TemplateArgument::Declaration: {
  3783. ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
  3784. return TemplateArgument(D, Arg.getParamTypeForDecl());
  3785. }
  3786. case TemplateArgument::NullPtr:
  3787. return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
  3788. /*isNullPtr*/true);
  3789. case TemplateArgument::Template:
  3790. return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
  3791. case TemplateArgument::TemplateExpansion:
  3792. return TemplateArgument(getCanonicalTemplateName(
  3793. Arg.getAsTemplateOrTemplatePattern()),
  3794. Arg.getNumTemplateExpansions());
  3795. case TemplateArgument::Integral:
  3796. return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
  3797. case TemplateArgument::Type:
  3798. return TemplateArgument(getCanonicalType(Arg.getAsType()));
  3799. case TemplateArgument::Pack: {
  3800. if (Arg.pack_size() == 0)
  3801. return Arg;
  3802. TemplateArgument *CanonArgs
  3803. = new (*this) TemplateArgument[Arg.pack_size()];
  3804. unsigned Idx = 0;
  3805. for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
  3806. AEnd = Arg.pack_end();
  3807. A != AEnd; (void)++A, ++Idx)
  3808. CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
  3809. return TemplateArgument(CanonArgs, Arg.pack_size());
  3810. }
  3811. }
  3812. // Silence GCC warning
  3813. llvm_unreachable("Unhandled template argument kind");
  3814. }
  3815. NestedNameSpecifier *
  3816. ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
  3817. if (!NNS)
  3818. return nullptr;
  3819. switch (NNS->getKind()) {
  3820. case NestedNameSpecifier::Identifier:
  3821. // Canonicalize the prefix but keep the identifier the same.
  3822. return NestedNameSpecifier::Create(*this,
  3823. getCanonicalNestedNameSpecifier(NNS->getPrefix()),
  3824. NNS->getAsIdentifier());
  3825. case NestedNameSpecifier::Namespace:
  3826. // A namespace is canonical; build a nested-name-specifier with
  3827. // this namespace and no prefix.
  3828. return NestedNameSpecifier::Create(*this, nullptr,
  3829. NNS->getAsNamespace()->getOriginalNamespace());
  3830. case NestedNameSpecifier::NamespaceAlias:
  3831. // A namespace is canonical; build a nested-name-specifier with
  3832. // this namespace and no prefix.
  3833. return NestedNameSpecifier::Create(*this, nullptr,
  3834. NNS->getAsNamespaceAlias()->getNamespace()
  3835. ->getOriginalNamespace());
  3836. case NestedNameSpecifier::TypeSpec:
  3837. case NestedNameSpecifier::TypeSpecWithTemplate: {
  3838. QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
  3839. // If we have some kind of dependent-named type (e.g., "typename T::type"),
  3840. // break it apart into its prefix and identifier, then reconsititute those
  3841. // as the canonical nested-name-specifier. This is required to canonicalize
  3842. // a dependent nested-name-specifier involving typedefs of dependent-name
  3843. // types, e.g.,
  3844. // typedef typename T::type T1;
  3845. // typedef typename T1::type T2;
  3846. if (const DependentNameType *DNT = T->getAs<DependentNameType>())
  3847. return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
  3848. const_cast<IdentifierInfo *>(DNT->getIdentifier()));
  3849. // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
  3850. // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
  3851. // first place?
  3852. return NestedNameSpecifier::Create(*this, nullptr, false,
  3853. const_cast<Type *>(T.getTypePtr()));
  3854. }
  3855. case NestedNameSpecifier::Global:
  3856. case NestedNameSpecifier::Super:
  3857. // The global specifier and __super specifer are canonical and unique.
  3858. return NNS;
  3859. }
  3860. llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
  3861. }
  3862. const ArrayType *ASTContext::getAsArrayType(QualType T) const {
  3863. // Handle the non-qualified case efficiently.
  3864. if (!T.hasLocalQualifiers()) {
  3865. // Handle the common positive case fast.
  3866. if (const ArrayType *AT = dyn_cast<ArrayType>(T))
  3867. return AT;
  3868. }
  3869. // Handle the common negative case fast.
  3870. if (!isa<ArrayType>(T.getCanonicalType()))
  3871. return nullptr;
  3872. // Apply any qualifiers from the array type to the element type. This
  3873. // implements C99 6.7.3p8: "If the specification of an array type includes
  3874. // any type qualifiers, the element type is so qualified, not the array type."
  3875. // If we get here, we either have type qualifiers on the type, or we have
  3876. // sugar such as a typedef in the way. If we have type qualifiers on the type
  3877. // we must propagate them down into the element type.
  3878. SplitQualType split = T.getSplitDesugaredType();
  3879. Qualifiers qs = split.Quals;
  3880. // If we have a simple case, just return now.
  3881. const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
  3882. if (!ATy || qs.empty())
  3883. return ATy;
  3884. // Otherwise, we have an array and we have qualifiers on it. Push the
  3885. // qualifiers into the array element type and return a new array type.
  3886. QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
  3887. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
  3888. return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
  3889. CAT->getSizeModifier(),
  3890. CAT->getIndexTypeCVRQualifiers()));
  3891. if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
  3892. return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
  3893. IAT->getSizeModifier(),
  3894. IAT->getIndexTypeCVRQualifiers()));
  3895. if (const DependentSizedArrayType *DSAT
  3896. = dyn_cast<DependentSizedArrayType>(ATy))
  3897. return cast<ArrayType>(
  3898. getDependentSizedArrayType(NewEltTy,
  3899. DSAT->getSizeExpr(),
  3900. DSAT->getSizeModifier(),
  3901. DSAT->getIndexTypeCVRQualifiers(),
  3902. DSAT->getBracketsRange()));
  3903. const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
  3904. return cast<ArrayType>(getVariableArrayType(NewEltTy,
  3905. VAT->getSizeExpr(),
  3906. VAT->getSizeModifier(),
  3907. VAT->getIndexTypeCVRQualifiers(),
  3908. VAT->getBracketsRange()));
  3909. }
  3910. QualType ASTContext::getAdjustedParameterType(QualType T) const {
  3911. if (T->isArrayType() || T->isFunctionType())
  3912. return getDecayedType(T);
  3913. return T;
  3914. }
  3915. QualType ASTContext::getSignatureParameterType(QualType T) const {
  3916. T = getVariableArrayDecayedType(T);
  3917. T = getAdjustedParameterType(T);
  3918. return T.getUnqualifiedType();
  3919. }
  3920. QualType ASTContext::getExceptionObjectType(QualType T) const {
  3921. // C++ [except.throw]p3:
  3922. // A throw-expression initializes a temporary object, called the exception
  3923. // object, the type of which is determined by removing any top-level
  3924. // cv-qualifiers from the static type of the operand of throw and adjusting
  3925. // the type from "array of T" or "function returning T" to "pointer to T"
  3926. // or "pointer to function returning T", [...]
  3927. T = getVariableArrayDecayedType(T);
  3928. if (T->isArrayType() || T->isFunctionType())
  3929. T = getDecayedType(T);
  3930. return T.getUnqualifiedType();
  3931. }
  3932. /// getArrayDecayedType - Return the properly qualified result of decaying the
  3933. /// specified array type to a pointer. This operation is non-trivial when
  3934. /// handling typedefs etc. The canonical type of "T" must be an array type,
  3935. /// this returns a pointer to a properly qualified element of the array.
  3936. ///
  3937. /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
  3938. QualType ASTContext::getArrayDecayedType(QualType Ty) const {
  3939. // Get the element type with 'getAsArrayType' so that we don't lose any
  3940. // typedefs in the element type of the array. This also handles propagation
  3941. // of type qualifiers from the array type into the element type if present
  3942. // (C99 6.7.3p8).
  3943. const ArrayType *PrettyArrayType = getAsArrayType(Ty);
  3944. assert(PrettyArrayType && "Not an array type!");
  3945. QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
  3946. // int x[restrict 4] -> int *restrict
  3947. return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
  3948. }
  3949. QualType ASTContext::getBaseElementType(const ArrayType *array) const {
  3950. return getBaseElementType(array->getElementType());
  3951. }
  3952. QualType ASTContext::getBaseElementType(QualType type) const {
  3953. Qualifiers qs;
  3954. while (true) {
  3955. SplitQualType split = type.getSplitDesugaredType();
  3956. const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
  3957. if (!array) break;
  3958. type = array->getElementType();
  3959. qs.addConsistentQualifiers(split.Quals);
  3960. }
  3961. return getQualifiedType(type, qs);
  3962. }
  3963. /// getConstantArrayElementCount - Returns number of constant array elements.
  3964. uint64_t
  3965. ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
  3966. uint64_t ElementCount = 1;
  3967. do {
  3968. ElementCount *= CA->getSize().getZExtValue();
  3969. CA = dyn_cast_or_null<ConstantArrayType>(
  3970. CA->getElementType()->getAsArrayTypeUnsafe());
  3971. } while (CA);
  3972. return ElementCount;
  3973. }
  3974. /// getFloatingRank - Return a relative rank for floating point types.
  3975. /// This routine will assert if passed a built-in type that isn't a float.
  3976. static FloatingRank getFloatingRank(QualType T) {
  3977. if (const ComplexType *CT = T->getAs<ComplexType>())
  3978. return getFloatingRank(CT->getElementType());
  3979. assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
  3980. switch (T->getAs<BuiltinType>()->getKind()) {
  3981. default: llvm_unreachable("getFloatingRank(): not a floating type");
  3982. case BuiltinType::Half: return HalfRank;
  3983. case BuiltinType::Float: return FloatRank;
  3984. case BuiltinType::Double: return DoubleRank;
  3985. case BuiltinType::LongDouble: return LongDoubleRank;
  3986. case BuiltinType::Min10Float: return Min10FloatRank; // HLSL Change
  3987. case BuiltinType::LitFloat: return LitFloatRank; // HLSL Change
  3988. }
  3989. }
  3990. /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
  3991. /// point or a complex type (based on typeDomain/typeSize).
  3992. /// 'typeDomain' is a real floating point or complex type.
  3993. /// 'typeSize' is a real floating point or complex type.
  3994. QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
  3995. QualType Domain) const {
  3996. FloatingRank EltRank = getFloatingRank(Size);
  3997. if (Domain->isComplexType()) {
  3998. switch (EltRank) {
  3999. case HalfRank: llvm_unreachable("Complex half is not supported");
  4000. case FloatRank: return FloatComplexTy;
  4001. case DoubleRank: return DoubleComplexTy;
  4002. case LongDoubleRank: return LongDoubleComplexTy;
  4003. }
  4004. }
  4005. assert(Domain->isRealFloatingType() && "Unknown domain!");
  4006. switch (EltRank) {
  4007. case LitFloatRank: return LitFloatTy; // HLSL Change
  4008. case Min10FloatRank: return Min10FloatTy; // HLSL Change
  4009. case HalfRank: return HalfTy;
  4010. case FloatRank: return FloatTy;
  4011. case DoubleRank: return DoubleTy;
  4012. case LongDoubleRank: return LongDoubleTy;
  4013. }
  4014. llvm_unreachable("getFloatingRank(): illegal value for rank");
  4015. }
  4016. /// getFloatingTypeOrder - Compare the rank of the two specified floating
  4017. /// point types, ignoring the domain of the type (i.e. 'double' ==
  4018. /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
  4019. /// LHS < RHS, return -1.
  4020. int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
  4021. FloatingRank LHSR = getFloatingRank(LHS);
  4022. FloatingRank RHSR = getFloatingRank(RHS);
  4023. if (LHSR == RHSR)
  4024. return 0;
  4025. if (LHSR > RHSR)
  4026. return 1;
  4027. return -1;
  4028. }
  4029. /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
  4030. /// routine will assert if passed a built-in type that isn't an integer or enum,
  4031. /// or if it is not canonicalized.
  4032. unsigned ASTContext::getIntegerRank(const Type *T) const {
  4033. assert(T->isCanonicalUnqualified() && "T should be canonicalized");
  4034. switch (cast<BuiltinType>(T)->getKind()) {
  4035. default: llvm_unreachable("getIntegerRank(): not a built-in integer");
  4036. case BuiltinType::Bool:
  4037. return 1 + (getIntWidth(BoolTy) << 3);
  4038. case BuiltinType::Char_S:
  4039. case BuiltinType::Char_U:
  4040. case BuiltinType::SChar:
  4041. case BuiltinType::UChar:
  4042. return 2 + (getIntWidth(CharTy) << 3);
  4043. case BuiltinType::Short:
  4044. case BuiltinType::UShort:
  4045. return 3 + (getIntWidth(ShortTy) << 3);
  4046. case BuiltinType::LitInt: // HLSL Change
  4047. case BuiltinType::Int:
  4048. case BuiltinType::UInt:
  4049. return 4 + (getIntWidth(IntTy) << 3);
  4050. case BuiltinType::Long:
  4051. case BuiltinType::ULong:
  4052. return 5 + (getIntWidth(LongTy) << 3);
  4053. case BuiltinType::LongLong:
  4054. case BuiltinType::ULongLong:
  4055. return 6 + (getIntWidth(LongLongTy) << 3);
  4056. case BuiltinType::Int128:
  4057. case BuiltinType::UInt128:
  4058. return 7 + (getIntWidth(Int128Ty) << 3);
  4059. }
  4060. }
  4061. /// \brief Whether this is a promotable bitfield reference according
  4062. /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
  4063. ///
  4064. /// \returns the type this bit-field will promote to, or NULL if no
  4065. /// promotion occurs.
  4066. QualType ASTContext::isPromotableBitField(Expr *E) const {
  4067. if (E->isTypeDependent() || E->isValueDependent())
  4068. return QualType();
  4069. // FIXME: We should not do this unless E->refersToBitField() is true. This
  4070. // matters in C where getSourceBitField() will find bit-fields for various
  4071. // cases where the source expression is not a bit-field designator.
  4072. FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
  4073. if (!Field)
  4074. return QualType();
  4075. QualType FT = Field->getType();
  4076. uint64_t BitWidth = Field->getBitWidthValue(*this);
  4077. uint64_t IntSize = getTypeSize(IntTy);
  4078. // C++ [conv.prom]p5:
  4079. // A prvalue for an integral bit-field can be converted to a prvalue of type
  4080. // int if int can represent all the values of the bit-field; otherwise, it
  4081. // can be converted to unsigned int if unsigned int can represent all the
  4082. // values of the bit-field. If the bit-field is larger yet, no integral
  4083. // promotion applies to it.
  4084. // C11 6.3.1.1/2:
  4085. // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
  4086. // If an int can represent all values of the original type (as restricted by
  4087. // the width, for a bit-field), the value is converted to an int; otherwise,
  4088. // it is converted to an unsigned int.
  4089. //
  4090. // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
  4091. // We perform that promotion here to match GCC and C++.
  4092. if (BitWidth < IntSize)
  4093. return IntTy;
  4094. if (BitWidth == IntSize)
  4095. return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
  4096. // Types bigger than int are not subject to promotions, and therefore act
  4097. // like the base type. GCC has some weird bugs in this area that we
  4098. // deliberately do not follow (GCC follows a pre-standard resolution to
  4099. // C's DR315 which treats bit-width as being part of the type, and this leaks
  4100. // into their semantics in some cases).
  4101. return QualType();
  4102. }
  4103. /// getPromotedIntegerType - Returns the type that Promotable will
  4104. /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
  4105. /// integer type.
  4106. QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
  4107. assert(!Promotable.isNull());
  4108. assert(Promotable->isPromotableIntegerType());
  4109. if (const EnumType *ET = Promotable->getAs<EnumType>())
  4110. return ET->getDecl()->getPromotionType();
  4111. if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
  4112. // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
  4113. // (3.9.1) can be converted to a prvalue of the first of the following
  4114. // types that can represent all the values of its underlying type:
  4115. // int, unsigned int, long int, unsigned long int, long long int, or
  4116. // unsigned long long int [...]
  4117. // FIXME: Is there some better way to compute this?
  4118. if (BT->getKind() == BuiltinType::WChar_S ||
  4119. BT->getKind() == BuiltinType::WChar_U ||
  4120. BT->getKind() == BuiltinType::Char16 ||
  4121. BT->getKind() == BuiltinType::Char32) {
  4122. bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
  4123. uint64_t FromSize = getTypeSize(BT);
  4124. QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
  4125. LongLongTy, UnsignedLongLongTy };
  4126. for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
  4127. uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
  4128. if (FromSize < ToSize ||
  4129. (FromSize == ToSize &&
  4130. FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
  4131. return PromoteTypes[Idx];
  4132. }
  4133. llvm_unreachable("char type should fit into long long");
  4134. }
  4135. }
  4136. // At this point, we should have a signed or unsigned integer type.
  4137. if (Promotable->isSignedIntegerType())
  4138. return IntTy;
  4139. uint64_t PromotableSize = getIntWidth(Promotable);
  4140. uint64_t IntSize = getIntWidth(IntTy);
  4141. assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
  4142. return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
  4143. }
  4144. /// \brief Recurses in pointer/array types until it finds an objc retainable
  4145. /// type and returns its ownership.
  4146. Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
  4147. while (!T.isNull()) {
  4148. if (T.getObjCLifetime() != Qualifiers::OCL_None)
  4149. return T.getObjCLifetime();
  4150. if (T->isArrayType())
  4151. T = getBaseElementType(T);
  4152. else if (const PointerType *PT = T->getAs<PointerType>())
  4153. T = PT->getPointeeType();
  4154. else if (const ReferenceType *RT = T->getAs<ReferenceType>())
  4155. T = RT->getPointeeType();
  4156. else
  4157. break;
  4158. }
  4159. return Qualifiers::OCL_None;
  4160. }
  4161. static const Type *getIntegerTypeForEnum(const EnumType *ET) {
  4162. // Incomplete enum types are not treated as integer types.
  4163. // FIXME: In C++, enum types are never integer types.
  4164. if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
  4165. return ET->getDecl()->getIntegerType().getTypePtr();
  4166. return nullptr;
  4167. }
  4168. /// getIntegerTypeOrder - Returns the highest ranked integer type:
  4169. /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
  4170. /// LHS < RHS, return -1.
  4171. int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
  4172. const Type *LHSC = getCanonicalType(LHS).getTypePtr();
  4173. const Type *RHSC = getCanonicalType(RHS).getTypePtr();
  4174. // Unwrap enums to their underlying type.
  4175. if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
  4176. LHSC = getIntegerTypeForEnum(ET);
  4177. if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
  4178. RHSC = getIntegerTypeForEnum(ET);
  4179. if (LHSC == RHSC) return 0;
  4180. bool LHSUnsigned = LHSC->isUnsignedIntegerType();
  4181. bool RHSUnsigned = RHSC->isUnsignedIntegerType();
  4182. unsigned LHSRank = getIntegerRank(LHSC);
  4183. unsigned RHSRank = getIntegerRank(RHSC);
  4184. if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
  4185. if (LHSRank == RHSRank) return 0;
  4186. return LHSRank > RHSRank ? 1 : -1;
  4187. }
  4188. // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
  4189. if (LHSUnsigned) {
  4190. // If the unsigned [LHS] type is larger, return it.
  4191. if (LHSRank >= RHSRank)
  4192. return 1;
  4193. // If the signed type can represent all values of the unsigned type, it
  4194. // wins. Because we are dealing with 2's complement and types that are
  4195. // powers of two larger than each other, this is always safe.
  4196. return -1;
  4197. }
  4198. // If the unsigned [RHS] type is larger, return it.
  4199. if (RHSRank >= LHSRank)
  4200. return -1;
  4201. // If the signed type can represent all values of the unsigned type, it
  4202. // wins. Because we are dealing with 2's complement and types that are
  4203. // powers of two larger than each other, this is always safe.
  4204. return 1;
  4205. }
  4206. // getCFConstantStringType - Return the type used for constant CFStrings.
  4207. QualType ASTContext::getCFConstantStringType() const {
  4208. if (!CFConstantStringTypeDecl) {
  4209. CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
  4210. CFConstantStringTypeDecl->startDefinition();
  4211. QualType FieldTypes[4];
  4212. // const int *isa;
  4213. FieldTypes[0] = getPointerType(IntTy.withConst());
  4214. // int flags;
  4215. FieldTypes[1] = IntTy;
  4216. // const char *str;
  4217. FieldTypes[2] = getPointerType(CharTy.withConst());
  4218. // long length;
  4219. FieldTypes[3] = LongTy;
  4220. // Create fields
  4221. for (unsigned i = 0; i < 4; ++i) {
  4222. FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
  4223. SourceLocation(),
  4224. SourceLocation(), nullptr,
  4225. FieldTypes[i], /*TInfo=*/nullptr,
  4226. /*BitWidth=*/nullptr,
  4227. /*Mutable=*/false,
  4228. ICIS_NoInit);
  4229. Field->setAccess(AS_public);
  4230. CFConstantStringTypeDecl->addDecl(Field);
  4231. }
  4232. CFConstantStringTypeDecl->completeDefinition();
  4233. }
  4234. return getTagDeclType(CFConstantStringTypeDecl);
  4235. }
  4236. QualType ASTContext::getObjCSuperType() const {
  4237. if (ObjCSuperType.isNull()) {
  4238. RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
  4239. TUDecl->addDecl(ObjCSuperTypeDecl);
  4240. ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
  4241. }
  4242. return ObjCSuperType;
  4243. }
  4244. void ASTContext::setCFConstantStringType(QualType T) {
  4245. const RecordType *Rec = T->getAs<RecordType>();
  4246. assert(Rec && "Invalid CFConstantStringType");
  4247. CFConstantStringTypeDecl = Rec->getDecl();
  4248. }
  4249. QualType ASTContext::getBlockDescriptorType() const {
  4250. if (BlockDescriptorType)
  4251. return getTagDeclType(BlockDescriptorType);
  4252. RecordDecl *RD;
  4253. // FIXME: Needs the FlagAppleBlock bit.
  4254. RD = buildImplicitRecord("__block_descriptor");
  4255. RD->startDefinition();
  4256. QualType FieldTypes[] = {
  4257. UnsignedLongTy,
  4258. UnsignedLongTy,
  4259. };
  4260. static const char *const FieldNames[] = {
  4261. "reserved",
  4262. "Size"
  4263. };
  4264. for (size_t i = 0; i < 2; ++i) {
  4265. FieldDecl *Field = FieldDecl::Create(
  4266. *this, RD, SourceLocation(), SourceLocation(),
  4267. &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
  4268. /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
  4269. Field->setAccess(AS_public);
  4270. RD->addDecl(Field);
  4271. }
  4272. RD->completeDefinition();
  4273. BlockDescriptorType = RD;
  4274. return getTagDeclType(BlockDescriptorType);
  4275. }
  4276. QualType ASTContext::getBlockDescriptorExtendedType() const {
  4277. if (BlockDescriptorExtendedType)
  4278. return getTagDeclType(BlockDescriptorExtendedType);
  4279. RecordDecl *RD;
  4280. // FIXME: Needs the FlagAppleBlock bit.
  4281. RD = buildImplicitRecord("__block_descriptor_withcopydispose");
  4282. RD->startDefinition();
  4283. QualType FieldTypes[] = {
  4284. UnsignedLongTy,
  4285. UnsignedLongTy,
  4286. getPointerType(VoidPtrTy),
  4287. getPointerType(VoidPtrTy)
  4288. };
  4289. static const char *const FieldNames[] = {
  4290. "reserved",
  4291. "Size",
  4292. "CopyFuncPtr",
  4293. "DestroyFuncPtr"
  4294. };
  4295. for (size_t i = 0; i < 4; ++i) {
  4296. FieldDecl *Field = FieldDecl::Create(
  4297. *this, RD, SourceLocation(), SourceLocation(),
  4298. &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
  4299. /*BitWidth=*/nullptr,
  4300. /*Mutable=*/false, ICIS_NoInit);
  4301. Field->setAccess(AS_public);
  4302. RD->addDecl(Field);
  4303. }
  4304. RD->completeDefinition();
  4305. BlockDescriptorExtendedType = RD;
  4306. return getTagDeclType(BlockDescriptorExtendedType);
  4307. }
  4308. /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
  4309. /// requires copy/dispose. Note that this must match the logic
  4310. /// in buildByrefHelpers.
  4311. bool ASTContext::BlockRequiresCopying(QualType Ty,
  4312. const VarDecl *D) {
  4313. if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
  4314. const Expr *copyExpr = getBlockVarCopyInits(D);
  4315. if (!copyExpr && record->hasTrivialDestructor()) return false;
  4316. return true;
  4317. }
  4318. if (!Ty->isObjCRetainableType()) return false;
  4319. Qualifiers qs = Ty.getQualifiers();
  4320. // If we have lifetime, that dominates.
  4321. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
  4322. assert(getLangOpts().ObjCAutoRefCount);
  4323. switch (lifetime) {
  4324. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  4325. // These are just bits as far as the runtime is concerned.
  4326. case Qualifiers::OCL_ExplicitNone:
  4327. case Qualifiers::OCL_Autoreleasing:
  4328. return false;
  4329. // Tell the runtime that this is ARC __weak, called by the
  4330. // byref routines.
  4331. case Qualifiers::OCL_Weak:
  4332. // ARC __strong __block variables need to be retained.
  4333. case Qualifiers::OCL_Strong:
  4334. return true;
  4335. }
  4336. llvm_unreachable("fell out of lifetime switch!");
  4337. }
  4338. return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
  4339. Ty->isObjCObjectPointerType());
  4340. }
  4341. bool ASTContext::getByrefLifetime(QualType Ty,
  4342. Qualifiers::ObjCLifetime &LifeTime,
  4343. bool &HasByrefExtendedLayout) const {
  4344. if (!getLangOpts().ObjC1 ||
  4345. getLangOpts().getGC() != LangOptions::NonGC)
  4346. return false;
  4347. HasByrefExtendedLayout = false;
  4348. if (Ty->isRecordType()) {
  4349. HasByrefExtendedLayout = true;
  4350. LifeTime = Qualifiers::OCL_None;
  4351. }
  4352. else if (getLangOpts().ObjCAutoRefCount)
  4353. LifeTime = Ty.getObjCLifetime();
  4354. // MRR.
  4355. else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
  4356. LifeTime = Qualifiers::OCL_ExplicitNone;
  4357. else
  4358. LifeTime = Qualifiers::OCL_None;
  4359. return true;
  4360. }
  4361. TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
  4362. if (!ObjCInstanceTypeDecl)
  4363. ObjCInstanceTypeDecl =
  4364. buildImplicitTypedef(getObjCIdType(), "instancetype");
  4365. return ObjCInstanceTypeDecl;
  4366. }
  4367. // This returns true if a type has been typedefed to BOOL:
  4368. // typedef <type> BOOL;
  4369. static bool isTypeTypedefedAsBOOL(QualType T) {
  4370. if (const TypedefType *TT = dyn_cast<TypedefType>(T))
  4371. if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
  4372. return II->isStr("BOOL");
  4373. return false;
  4374. }
  4375. /// getObjCEncodingTypeSize returns size of type for objective-c encoding
  4376. /// purpose.
  4377. CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
  4378. if (!type->isIncompleteArrayType() && type->isIncompleteType())
  4379. return CharUnits::Zero();
  4380. CharUnits sz = getTypeSizeInChars(type);
  4381. // Make all integer and enum types at least as large as an int
  4382. if (sz.isPositive() && type->isIntegralOrEnumerationType())
  4383. sz = std::max(sz, getTypeSizeInChars(IntTy));
  4384. // Treat arrays as pointers, since that's how they're passed in.
  4385. else if (type->isArrayType())
  4386. sz = getTypeSizeInChars(VoidPtrTy);
  4387. return sz;
  4388. }
  4389. bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
  4390. return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
  4391. VD->getType()->isIntegralOrEnumerationType() &&
  4392. VD->isFirstDecl() && !VD->isOutOfLine() && VD->hasInit();
  4393. }
  4394. static inline
  4395. std::string charUnitsToString(const CharUnits &CU) {
  4396. return llvm::itostr(CU.getQuantity());
  4397. }
  4398. /// getObjCEncodingForBlock - Return the encoded type for this block
  4399. /// declaration.
  4400. std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
  4401. std::string S;
  4402. const BlockDecl *Decl = Expr->getBlockDecl();
  4403. QualType BlockTy =
  4404. Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
  4405. // Encode result type.
  4406. if (getLangOpts().EncodeExtendedBlockSig)
  4407. getObjCEncodingForMethodParameter(
  4408. Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
  4409. true /*Extended*/);
  4410. else
  4411. getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
  4412. // Compute size of all parameters.
  4413. // Start with computing size of a pointer in number of bytes.
  4414. // FIXME: There might(should) be a better way of doing this computation!
  4415. SourceLocation Loc;
  4416. CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
  4417. CharUnits ParmOffset = PtrSize;
  4418. for (auto PI : Decl->params()) {
  4419. QualType PType = PI->getType();
  4420. CharUnits sz = getObjCEncodingTypeSize(PType);
  4421. if (sz.isZero())
  4422. continue;
  4423. assert (sz.isPositive() && "BlockExpr - Incomplete param type");
  4424. ParmOffset += sz;
  4425. }
  4426. // Size of the argument frame
  4427. S += charUnitsToString(ParmOffset);
  4428. // Block pointer and offset.
  4429. S += "@?0";
  4430. // Argument types.
  4431. ParmOffset = PtrSize;
  4432. for (auto PVDecl : Decl->params()) {
  4433. QualType PType = PVDecl->getOriginalType();
  4434. if (const ArrayType *AT =
  4435. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  4436. // Use array's original type only if it has known number of
  4437. // elements.
  4438. if (!isa<ConstantArrayType>(AT))
  4439. PType = PVDecl->getType();
  4440. } else if (PType->isFunctionType())
  4441. PType = PVDecl->getType();
  4442. if (getLangOpts().EncodeExtendedBlockSig)
  4443. getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
  4444. S, true /*Extended*/);
  4445. else
  4446. getObjCEncodingForType(PType, S);
  4447. S += charUnitsToString(ParmOffset);
  4448. ParmOffset += getObjCEncodingTypeSize(PType);
  4449. }
  4450. return S;
  4451. }
  4452. bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
  4453. std::string& S) {
  4454. // Encode result type.
  4455. getObjCEncodingForType(Decl->getReturnType(), S);
  4456. CharUnits ParmOffset;
  4457. // Compute size of all parameters.
  4458. for (auto PI : Decl->params()) {
  4459. QualType PType = PI->getType();
  4460. CharUnits sz = getObjCEncodingTypeSize(PType);
  4461. if (sz.isZero())
  4462. continue;
  4463. assert (sz.isPositive() &&
  4464. "getObjCEncodingForFunctionDecl - Incomplete param type");
  4465. ParmOffset += sz;
  4466. }
  4467. S += charUnitsToString(ParmOffset);
  4468. ParmOffset = CharUnits::Zero();
  4469. // Argument types.
  4470. for (auto PVDecl : Decl->params()) {
  4471. QualType PType = PVDecl->getOriginalType();
  4472. if (const ArrayType *AT =
  4473. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  4474. // Use array's original type only if it has known number of
  4475. // elements.
  4476. if (!isa<ConstantArrayType>(AT))
  4477. PType = PVDecl->getType();
  4478. } else if (PType->isFunctionType())
  4479. PType = PVDecl->getType();
  4480. getObjCEncodingForType(PType, S);
  4481. S += charUnitsToString(ParmOffset);
  4482. ParmOffset += getObjCEncodingTypeSize(PType);
  4483. }
  4484. return false;
  4485. }
  4486. /// getObjCEncodingForMethodParameter - Return the encoded type for a single
  4487. /// method parameter or return type. If Extended, include class names and
  4488. /// block object types.
  4489. void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
  4490. QualType T, std::string& S,
  4491. bool Extended) const {
  4492. // Encode type qualifer, 'in', 'inout', etc. for the parameter.
  4493. getObjCEncodingForTypeQualifier(QT, S);
  4494. // Encode parameter type.
  4495. getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
  4496. true /*OutermostType*/,
  4497. false /*EncodingProperty*/,
  4498. false /*StructField*/,
  4499. Extended /*EncodeBlockParameters*/,
  4500. Extended /*EncodeClassNames*/);
  4501. }
  4502. /// getObjCEncodingForMethodDecl - Return the encoded type for this method
  4503. /// declaration.
  4504. bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
  4505. std::string& S,
  4506. bool Extended) const {
  4507. // FIXME: This is not very efficient.
  4508. // Encode return type.
  4509. getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
  4510. Decl->getReturnType(), S, Extended);
  4511. // Compute size of all parameters.
  4512. // Start with computing size of a pointer in number of bytes.
  4513. // FIXME: There might(should) be a better way of doing this computation!
  4514. SourceLocation Loc;
  4515. CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
  4516. // The first two arguments (self and _cmd) are pointers; account for
  4517. // their size.
  4518. CharUnits ParmOffset = 2 * PtrSize;
  4519. for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
  4520. E = Decl->sel_param_end(); PI != E; ++PI) {
  4521. QualType PType = (*PI)->getType();
  4522. CharUnits sz = getObjCEncodingTypeSize(PType);
  4523. if (sz.isZero())
  4524. continue;
  4525. assert (sz.isPositive() &&
  4526. "getObjCEncodingForMethodDecl - Incomplete param type");
  4527. ParmOffset += sz;
  4528. }
  4529. S += charUnitsToString(ParmOffset);
  4530. S += "@0:";
  4531. S += charUnitsToString(PtrSize);
  4532. // Argument types.
  4533. ParmOffset = 2 * PtrSize;
  4534. for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
  4535. E = Decl->sel_param_end(); PI != E; ++PI) {
  4536. const ParmVarDecl *PVDecl = *PI;
  4537. QualType PType = PVDecl->getOriginalType();
  4538. if (const ArrayType *AT =
  4539. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  4540. // Use array's original type only if it has known number of
  4541. // elements.
  4542. if (!isa<ConstantArrayType>(AT))
  4543. PType = PVDecl->getType();
  4544. } else if (PType->isFunctionType())
  4545. PType = PVDecl->getType();
  4546. getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
  4547. PType, S, Extended);
  4548. S += charUnitsToString(ParmOffset);
  4549. ParmOffset += getObjCEncodingTypeSize(PType);
  4550. }
  4551. return false;
  4552. }
  4553. ObjCPropertyImplDecl *
  4554. ASTContext::getObjCPropertyImplDeclForPropertyDecl(
  4555. const ObjCPropertyDecl *PD,
  4556. const Decl *Container) const {
  4557. if (!Container)
  4558. return nullptr;
  4559. if (const ObjCCategoryImplDecl *CID =
  4560. dyn_cast<ObjCCategoryImplDecl>(Container)) {
  4561. for (auto *PID : CID->property_impls())
  4562. if (PID->getPropertyDecl() == PD)
  4563. return PID;
  4564. } else {
  4565. const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
  4566. for (auto *PID : OID->property_impls())
  4567. if (PID->getPropertyDecl() == PD)
  4568. return PID;
  4569. }
  4570. return nullptr;
  4571. }
  4572. /// getObjCEncodingForPropertyDecl - Return the encoded type for this
  4573. /// property declaration. If non-NULL, Container must be either an
  4574. /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
  4575. /// NULL when getting encodings for protocol properties.
  4576. /// Property attributes are stored as a comma-delimited C string. The simple
  4577. /// attributes readonly and bycopy are encoded as single characters. The
  4578. /// parametrized attributes, getter=name, setter=name, and ivar=name, are
  4579. /// encoded as single characters, followed by an identifier. Property types
  4580. /// are also encoded as a parametrized attribute. The characters used to encode
  4581. /// these attributes are defined by the following enumeration:
  4582. /// @code
  4583. /// enum PropertyAttributes {
  4584. /// kPropertyReadOnly = 'R', // property is read-only.
  4585. /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
  4586. /// kPropertyByref = '&', // property is a reference to the value last assigned
  4587. /// kPropertyDynamic = 'D', // property is dynamic
  4588. /// kPropertyGetter = 'G', // followed by getter selector name
  4589. /// kPropertySetter = 'S', // followed by setter selector name
  4590. /// kPropertyInstanceVariable = 'V' // followed by instance variable name
  4591. /// kPropertyType = 'T' // followed by old-style type encoding.
  4592. /// kPropertyWeak = 'W' // 'weak' property
  4593. /// kPropertyStrong = 'P' // property GC'able
  4594. /// kPropertyNonAtomic = 'N' // property non-atomic
  4595. /// };
  4596. /// @endcode
  4597. void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
  4598. const Decl *Container,
  4599. std::string& S) const {
  4600. // Collect information from the property implementation decl(s).
  4601. bool Dynamic = false;
  4602. ObjCPropertyImplDecl *SynthesizePID = nullptr;
  4603. if (ObjCPropertyImplDecl *PropertyImpDecl =
  4604. getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
  4605. if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  4606. Dynamic = true;
  4607. else
  4608. SynthesizePID = PropertyImpDecl;
  4609. }
  4610. // FIXME: This is not very efficient.
  4611. S = "T";
  4612. // Encode result type.
  4613. // GCC has some special rules regarding encoding of properties which
  4614. // closely resembles encoding of ivars.
  4615. getObjCEncodingForPropertyType(PD->getType(), S);
  4616. if (PD->isReadOnly()) {
  4617. S += ",R";
  4618. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
  4619. S += ",C";
  4620. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
  4621. S += ",&";
  4622. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
  4623. S += ",W";
  4624. } else {
  4625. switch (PD->getSetterKind()) {
  4626. case ObjCPropertyDecl::Assign: break;
  4627. case ObjCPropertyDecl::Copy: S += ",C"; break;
  4628. case ObjCPropertyDecl::Retain: S += ",&"; break;
  4629. case ObjCPropertyDecl::Weak: S += ",W"; break;
  4630. }
  4631. }
  4632. // It really isn't clear at all what this means, since properties
  4633. // are "dynamic by default".
  4634. if (Dynamic)
  4635. S += ",D";
  4636. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
  4637. S += ",N";
  4638. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
  4639. S += ",G";
  4640. S += PD->getGetterName().getAsString();
  4641. }
  4642. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
  4643. S += ",S";
  4644. S += PD->getSetterName().getAsString();
  4645. }
  4646. if (SynthesizePID) {
  4647. const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
  4648. S += ",V";
  4649. S += OID->getNameAsString();
  4650. }
  4651. // FIXME: OBJCGC: weak & strong
  4652. }
  4653. /// getLegacyIntegralTypeEncoding -
  4654. /// Another legacy compatibility encoding: 32-bit longs are encoded as
  4655. /// 'l' or 'L' , but not always. For typedefs, we need to use
  4656. /// 'i' or 'I' instead if encoding a struct field, or a pointer!
  4657. ///
  4658. void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
  4659. if (isa<TypedefType>(PointeeTy.getTypePtr())) {
  4660. if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
  4661. if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
  4662. PointeeTy = UnsignedIntTy;
  4663. else
  4664. if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
  4665. PointeeTy = IntTy;
  4666. }
  4667. }
  4668. }
  4669. void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
  4670. const FieldDecl *Field,
  4671. QualType *NotEncodedT) const {
  4672. // We follow the behavior of gcc, expanding structures which are
  4673. // directly pointed to, and expanding embedded structures. Note that
  4674. // these rules are sufficient to prevent recursive encoding of the
  4675. // same type.
  4676. getObjCEncodingForTypeImpl(T, S, true, true, Field,
  4677. true /* outermost type */, false, false,
  4678. false, false, false, NotEncodedT);
  4679. }
  4680. void ASTContext::getObjCEncodingForPropertyType(QualType T,
  4681. std::string& S) const {
  4682. // Encode result type.
  4683. // GCC has some special rules regarding encoding of properties which
  4684. // closely resembles encoding of ivars.
  4685. getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
  4686. true /* outermost type */,
  4687. true /* encoding property */);
  4688. }
  4689. static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
  4690. BuiltinType::Kind kind) {
  4691. switch (kind) {
  4692. case BuiltinType::Void: return 'v';
  4693. case BuiltinType::Bool: return 'B';
  4694. case BuiltinType::Char_U:
  4695. case BuiltinType::UChar: return 'C';
  4696. case BuiltinType::Char16:
  4697. case BuiltinType::UShort: return 'S';
  4698. case BuiltinType::Char32:
  4699. case BuiltinType::UInt: return 'I';
  4700. case BuiltinType::ULong:
  4701. return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
  4702. case BuiltinType::UInt128: return 'T';
  4703. case BuiltinType::ULongLong: return 'Q';
  4704. case BuiltinType::Char_S:
  4705. case BuiltinType::SChar: return 'c';
  4706. case BuiltinType::Short: return 's';
  4707. case BuiltinType::WChar_S:
  4708. case BuiltinType::WChar_U:
  4709. case BuiltinType::Int: return 'i';
  4710. case BuiltinType::Long:
  4711. return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
  4712. case BuiltinType::LongLong: return 'q';
  4713. case BuiltinType::Int128: return 't';
  4714. case BuiltinType::Float: return 'f';
  4715. case BuiltinType::Double: return 'd';
  4716. case BuiltinType::LongDouble: return 'D';
  4717. case BuiltinType::NullPtr: return '*'; // like char*
  4718. case BuiltinType::Half:
  4719. // FIXME: potentially need @encodes for these!
  4720. return ' ';
  4721. case BuiltinType::ObjCId:
  4722. case BuiltinType::ObjCClass:
  4723. case BuiltinType::ObjCSel:
  4724. llvm_unreachable("@encoding ObjC primitive type");
  4725. // OpenCL and placeholder types don't need @encodings.
  4726. case BuiltinType::OCLImage1d:
  4727. case BuiltinType::OCLImage1dArray:
  4728. case BuiltinType::OCLImage1dBuffer:
  4729. case BuiltinType::OCLImage2d:
  4730. case BuiltinType::OCLImage2dArray:
  4731. case BuiltinType::OCLImage3d:
  4732. case BuiltinType::OCLEvent:
  4733. case BuiltinType::OCLSampler:
  4734. case BuiltinType::Dependent:
  4735. #define BUILTIN_TYPE(KIND, ID)
  4736. #define PLACEHOLDER_TYPE(KIND, ID) \
  4737. case BuiltinType::KIND:
  4738. #include "clang/AST/BuiltinTypes.def"
  4739. llvm_unreachable("invalid builtin type for @encode");
  4740. }
  4741. llvm_unreachable("invalid BuiltinType::Kind value");
  4742. }
  4743. static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
  4744. EnumDecl *Enum = ET->getDecl();
  4745. // The encoding of an non-fixed enum type is always 'i', regardless of size.
  4746. if (!Enum->isFixed())
  4747. return 'i';
  4748. // The encoding of a fixed enum type matches its fixed underlying type.
  4749. const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
  4750. return getObjCEncodingForPrimitiveKind(C, BT->getKind());
  4751. }
  4752. static void EncodeBitField(const ASTContext *Ctx, std::string& S,
  4753. QualType T, const FieldDecl *FD) {
  4754. assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
  4755. S += 'b';
  4756. // The NeXT runtime encodes bit fields as b followed by the number of bits.
  4757. // The GNU runtime requires more information; bitfields are encoded as b,
  4758. // then the offset (in bits) of the first element, then the type of the
  4759. // bitfield, then the size in bits. For example, in this structure:
  4760. //
  4761. // struct
  4762. // {
  4763. // int integer;
  4764. // int flags:2;
  4765. // };
  4766. // On a 32-bit system, the encoding for flags would be b2 for the NeXT
  4767. // runtime, but b32i2 for the GNU runtime. The reason for this extra
  4768. // information is not especially sensible, but we're stuck with it for
  4769. // compatibility with GCC, although providing it breaks anything that
  4770. // actually uses runtime introspection and wants to work on both runtimes...
  4771. if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
  4772. const RecordDecl *RD = FD->getParent();
  4773. const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
  4774. S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
  4775. if (const EnumType *ET = T->getAs<EnumType>())
  4776. S += ObjCEncodingForEnumType(Ctx, ET);
  4777. else {
  4778. const BuiltinType *BT = T->castAs<BuiltinType>();
  4779. S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
  4780. }
  4781. }
  4782. S += llvm::utostr(FD->getBitWidthValue(*Ctx));
  4783. }
  4784. // FIXME: Use SmallString for accumulating string.
  4785. void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
  4786. bool ExpandPointedToStructures,
  4787. bool ExpandStructures,
  4788. const FieldDecl *FD,
  4789. bool OutermostType,
  4790. bool EncodingProperty,
  4791. bool StructField,
  4792. bool EncodeBlockParameters,
  4793. bool EncodeClassNames,
  4794. bool EncodePointerToObjCTypedef,
  4795. QualType *NotEncodedT) const {
  4796. CanQualType CT = getCanonicalType(T);
  4797. switch (CT->getTypeClass()) {
  4798. case Type::Builtin:
  4799. case Type::Enum:
  4800. if (FD && FD->isBitField())
  4801. return EncodeBitField(this, S, T, FD);
  4802. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
  4803. S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
  4804. else
  4805. S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
  4806. return;
  4807. case Type::Complex: {
  4808. const ComplexType *CT = T->castAs<ComplexType>();
  4809. S += 'j';
  4810. getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
  4811. return;
  4812. }
  4813. case Type::Atomic: {
  4814. const AtomicType *AT = T->castAs<AtomicType>();
  4815. S += 'A';
  4816. getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
  4817. return;
  4818. }
  4819. // encoding for pointer or reference types.
  4820. case Type::Pointer:
  4821. case Type::LValueReference:
  4822. case Type::RValueReference: {
  4823. QualType PointeeTy;
  4824. if (isa<PointerType>(CT)) {
  4825. const PointerType *PT = T->castAs<PointerType>();
  4826. if (PT->isObjCSelType()) {
  4827. S += ':';
  4828. return;
  4829. }
  4830. PointeeTy = PT->getPointeeType();
  4831. } else {
  4832. PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
  4833. }
  4834. bool isReadOnly = false;
  4835. // For historical/compatibility reasons, the read-only qualifier of the
  4836. // pointee gets emitted _before_ the '^'. The read-only qualifier of
  4837. // the pointer itself gets ignored, _unless_ we are looking at a typedef!
  4838. // Also, do not emit the 'r' for anything but the outermost type!
  4839. if (isa<TypedefType>(T.getTypePtr())) {
  4840. if (OutermostType && T.isConstQualified()) {
  4841. isReadOnly = true;
  4842. S += 'r';
  4843. }
  4844. } else if (OutermostType) {
  4845. QualType P = PointeeTy;
  4846. while (P->getAs<PointerType>())
  4847. P = P->getAs<PointerType>()->getPointeeType();
  4848. if (P.isConstQualified()) {
  4849. isReadOnly = true;
  4850. S += 'r';
  4851. }
  4852. }
  4853. if (isReadOnly) {
  4854. // Another legacy compatibility encoding. Some ObjC qualifier and type
  4855. // combinations need to be rearranged.
  4856. // Rewrite "in const" from "nr" to "rn"
  4857. if (StringRef(S).endswith("nr"))
  4858. S.replace(S.end()-2, S.end(), "rn");
  4859. }
  4860. if (PointeeTy->isCharType()) {
  4861. // char pointer types should be encoded as '*' unless it is a
  4862. // type that has been typedef'd to 'BOOL'.
  4863. if (!isTypeTypedefedAsBOOL(PointeeTy)) {
  4864. S += '*';
  4865. return;
  4866. }
  4867. } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
  4868. // GCC binary compat: Need to convert "struct objc_class *" to "#".
  4869. if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
  4870. S += '#';
  4871. return;
  4872. }
  4873. // GCC binary compat: Need to convert "struct objc_object *" to "@".
  4874. if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
  4875. S += '@';
  4876. return;
  4877. }
  4878. // fall through...
  4879. }
  4880. S += '^';
  4881. getLegacyIntegralTypeEncoding(PointeeTy);
  4882. getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
  4883. nullptr, false, false, false, false, false, false,
  4884. NotEncodedT);
  4885. return;
  4886. }
  4887. case Type::ConstantArray:
  4888. case Type::IncompleteArray:
  4889. case Type::VariableArray: {
  4890. const ArrayType *AT = cast<ArrayType>(CT);
  4891. if (isa<IncompleteArrayType>(AT) && !StructField) {
  4892. // Incomplete arrays are encoded as a pointer to the array element.
  4893. S += '^';
  4894. getObjCEncodingForTypeImpl(AT->getElementType(), S,
  4895. false, ExpandStructures, FD);
  4896. } else {
  4897. S += '[';
  4898. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
  4899. S += llvm::utostr(CAT->getSize().getZExtValue());
  4900. else {
  4901. //Variable length arrays are encoded as a regular array with 0 elements.
  4902. assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
  4903. "Unknown array type!");
  4904. S += '0';
  4905. }
  4906. getObjCEncodingForTypeImpl(AT->getElementType(), S,
  4907. false, ExpandStructures, FD,
  4908. false, false, false, false, false, false,
  4909. NotEncodedT);
  4910. S += ']';
  4911. }
  4912. return;
  4913. }
  4914. case Type::FunctionNoProto:
  4915. case Type::FunctionProto:
  4916. S += '?';
  4917. return;
  4918. case Type::Record: {
  4919. RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
  4920. S += RDecl->isUnion() ? '(' : '{';
  4921. // Anonymous structures print as '?'
  4922. if (const IdentifierInfo *II = RDecl->getIdentifier()) {
  4923. S += II->getName();
  4924. if (ClassTemplateSpecializationDecl *Spec
  4925. = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
  4926. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  4927. llvm::raw_string_ostream OS(S);
  4928. TemplateSpecializationType::PrintTemplateArgumentList(OS,
  4929. TemplateArgs.data(),
  4930. TemplateArgs.size(),
  4931. (*this).getPrintingPolicy());
  4932. }
  4933. } else {
  4934. S += '?';
  4935. }
  4936. if (ExpandStructures) {
  4937. S += '=';
  4938. if (!RDecl->isUnion()) {
  4939. getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
  4940. } else {
  4941. for (const auto *Field : RDecl->fields()) {
  4942. if (FD) {
  4943. S += '"';
  4944. S += Field->getNameAsString();
  4945. S += '"';
  4946. }
  4947. // Special case bit-fields.
  4948. if (Field->isBitField()) {
  4949. getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
  4950. Field);
  4951. } else {
  4952. QualType qt = Field->getType();
  4953. getLegacyIntegralTypeEncoding(qt);
  4954. getObjCEncodingForTypeImpl(qt, S, false, true,
  4955. FD, /*OutermostType*/false,
  4956. /*EncodingProperty*/false,
  4957. /*StructField*/true,
  4958. false, false, false, NotEncodedT);
  4959. }
  4960. }
  4961. }
  4962. }
  4963. S += RDecl->isUnion() ? ')' : '}';
  4964. return;
  4965. }
  4966. case Type::BlockPointer: {
  4967. const BlockPointerType *BT = T->castAs<BlockPointerType>();
  4968. S += "@?"; // Unlike a pointer-to-function, which is "^?".
  4969. if (EncodeBlockParameters) {
  4970. const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
  4971. S += '<';
  4972. // Block return type
  4973. getObjCEncodingForTypeImpl(
  4974. FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
  4975. FD, false /* OutermostType */, EncodingProperty,
  4976. false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
  4977. NotEncodedT);
  4978. // Block self
  4979. S += "@?";
  4980. // Block parameters
  4981. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
  4982. for (const auto &I : FPT->param_types())
  4983. getObjCEncodingForTypeImpl(
  4984. I, S, ExpandPointedToStructures, ExpandStructures, FD,
  4985. false /* OutermostType */, EncodingProperty,
  4986. false /* StructField */, EncodeBlockParameters, EncodeClassNames,
  4987. false, NotEncodedT);
  4988. }
  4989. S += '>';
  4990. }
  4991. return;
  4992. }
  4993. case Type::ObjCObject: {
  4994. // hack to match legacy encoding of *id and *Class
  4995. QualType Ty = getObjCObjectPointerType(CT);
  4996. if (Ty->isObjCIdType()) {
  4997. S += "{objc_object=}";
  4998. return;
  4999. }
  5000. else if (Ty->isObjCClassType()) {
  5001. S += "{objc_class=}";
  5002. return;
  5003. }
  5004. }
  5005. case Type::ObjCInterface: {
  5006. // Ignore protocol qualifiers when mangling at this level.
  5007. // @encode(class_name)
  5008. ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
  5009. S += '{';
  5010. S += OI->getObjCRuntimeNameAsString();
  5011. S += '=';
  5012. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  5013. DeepCollectObjCIvars(OI, true, Ivars);
  5014. for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
  5015. const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
  5016. if (Field->isBitField())
  5017. getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
  5018. else
  5019. getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
  5020. false, false, false, false, false,
  5021. EncodePointerToObjCTypedef,
  5022. NotEncodedT);
  5023. }
  5024. S += '}';
  5025. return;
  5026. }
  5027. case Type::ObjCObjectPointer: {
  5028. const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
  5029. if (OPT->isObjCIdType()) {
  5030. S += '@';
  5031. return;
  5032. }
  5033. if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
  5034. // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
  5035. // Since this is a binary compatibility issue, need to consult with runtime
  5036. // folks. Fortunately, this is a *very* obsure construct.
  5037. S += '#';
  5038. return;
  5039. }
  5040. if (OPT->isObjCQualifiedIdType()) {
  5041. getObjCEncodingForTypeImpl(getObjCIdType(), S,
  5042. ExpandPointedToStructures,
  5043. ExpandStructures, FD);
  5044. if (FD || EncodingProperty || EncodeClassNames) {
  5045. // Note that we do extended encoding of protocol qualifer list
  5046. // Only when doing ivar or property encoding.
  5047. S += '"';
  5048. for (const auto *I : OPT->quals()) {
  5049. S += '<';
  5050. S += I->getObjCRuntimeNameAsString();
  5051. S += '>';
  5052. }
  5053. S += '"';
  5054. }
  5055. return;
  5056. }
  5057. QualType PointeeTy = OPT->getPointeeType();
  5058. if (!EncodingProperty &&
  5059. isa<TypedefType>(PointeeTy.getTypePtr()) &&
  5060. !EncodePointerToObjCTypedef) {
  5061. // Another historical/compatibility reason.
  5062. // We encode the underlying type which comes out as
  5063. // {...};
  5064. S += '^';
  5065. if (FD && OPT->getInterfaceDecl()) {
  5066. // Prevent recursive encoding of fields in some rare cases.
  5067. ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
  5068. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  5069. DeepCollectObjCIvars(OI, true, Ivars);
  5070. for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
  5071. if (cast<FieldDecl>(Ivars[i]) == FD) {
  5072. S += '{';
  5073. S += OI->getObjCRuntimeNameAsString();
  5074. S += '}';
  5075. return;
  5076. }
  5077. }
  5078. }
  5079. getObjCEncodingForTypeImpl(PointeeTy, S,
  5080. false, ExpandPointedToStructures,
  5081. nullptr,
  5082. false, false, false, false, false,
  5083. /*EncodePointerToObjCTypedef*/true);
  5084. return;
  5085. }
  5086. S += '@';
  5087. if (OPT->getInterfaceDecl() &&
  5088. (FD || EncodingProperty || EncodeClassNames)) {
  5089. S += '"';
  5090. S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
  5091. for (const auto *I : OPT->quals()) {
  5092. S += '<';
  5093. S += I->getObjCRuntimeNameAsString();
  5094. S += '>';
  5095. }
  5096. S += '"';
  5097. }
  5098. return;
  5099. }
  5100. // gcc just blithely ignores member pointers.
  5101. // FIXME: we shoul do better than that. 'M' is available.
  5102. case Type::MemberPointer:
  5103. // This matches gcc's encoding, even though technically it is insufficient.
  5104. //FIXME. We should do a better job than gcc.
  5105. case Type::Vector:
  5106. case Type::ExtVector:
  5107. // Until we have a coherent encoding of these three types, issue warning.
  5108. { if (NotEncodedT)
  5109. *NotEncodedT = T;
  5110. return;
  5111. }
  5112. // We could see an undeduced auto type here during error recovery.
  5113. // Just ignore it.
  5114. case Type::Auto:
  5115. return;
  5116. #define ABSTRACT_TYPE(KIND, BASE)
  5117. #define TYPE(KIND, BASE)
  5118. #define DEPENDENT_TYPE(KIND, BASE) \
  5119. case Type::KIND:
  5120. #define NON_CANONICAL_TYPE(KIND, BASE) \
  5121. case Type::KIND:
  5122. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
  5123. case Type::KIND:
  5124. #include "clang/AST/TypeNodes.def"
  5125. llvm_unreachable("@encode for dependent type!");
  5126. }
  5127. llvm_unreachable("bad type kind!");
  5128. }
  5129. void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
  5130. std::string &S,
  5131. const FieldDecl *FD,
  5132. bool includeVBases,
  5133. QualType *NotEncodedT) const {
  5134. assert(RDecl && "Expected non-null RecordDecl");
  5135. assert(!RDecl->isUnion() && "Should not be called for unions");
  5136. if (!RDecl->getDefinition())
  5137. return;
  5138. CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
  5139. std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
  5140. const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
  5141. if (CXXRec) {
  5142. for (const auto &BI : CXXRec->bases()) {
  5143. if (!BI.isVirtual()) {
  5144. CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
  5145. if (base->isEmpty())
  5146. continue;
  5147. uint64_t offs = toBits(layout.getBaseClassOffset(base));
  5148. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  5149. std::make_pair(offs, base));
  5150. }
  5151. }
  5152. }
  5153. unsigned i = 0;
  5154. for (auto *Field : RDecl->fields()) {
  5155. uint64_t offs = layout.getFieldOffset(i);
  5156. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  5157. std::make_pair(offs, Field));
  5158. ++i;
  5159. }
  5160. if (CXXRec && includeVBases) {
  5161. for (const auto &BI : CXXRec->vbases()) {
  5162. CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
  5163. if (base->isEmpty())
  5164. continue;
  5165. uint64_t offs = toBits(layout.getVBaseClassOffset(base));
  5166. if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
  5167. FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
  5168. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
  5169. std::make_pair(offs, base));
  5170. }
  5171. }
  5172. CharUnits size;
  5173. if (CXXRec) {
  5174. size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
  5175. } else {
  5176. size = layout.getSize();
  5177. }
  5178. #ifndef NDEBUG
  5179. uint64_t CurOffs = 0;
  5180. #endif
  5181. std::multimap<uint64_t, NamedDecl *>::iterator
  5182. CurLayObj = FieldOrBaseOffsets.begin();
  5183. if (CXXRec && CXXRec->isDynamicClass() &&
  5184. (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
  5185. if (FD) {
  5186. S += "\"_vptr$";
  5187. std::string recname = CXXRec->getNameAsString();
  5188. if (recname.empty()) recname = "?";
  5189. S += recname;
  5190. S += '"';
  5191. }
  5192. S += "^^?";
  5193. #ifndef NDEBUG
  5194. CurOffs += getTypeSize(VoidPtrTy);
  5195. #endif
  5196. }
  5197. if (!RDecl->hasFlexibleArrayMember()) {
  5198. // Mark the end of the structure.
  5199. uint64_t offs = toBits(size);
  5200. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  5201. std::make_pair(offs, nullptr));
  5202. }
  5203. for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
  5204. #ifndef NDEBUG
  5205. assert(CurOffs <= CurLayObj->first);
  5206. if (CurOffs < CurLayObj->first) {
  5207. uint64_t padding = CurLayObj->first - CurOffs;
  5208. // FIXME: There doesn't seem to be a way to indicate in the encoding that
  5209. // packing/alignment of members is different that normal, in which case
  5210. // the encoding will be out-of-sync with the real layout.
  5211. // If the runtime switches to just consider the size of types without
  5212. // taking into account alignment, we could make padding explicit in the
  5213. // encoding (e.g. using arrays of chars). The encoding strings would be
  5214. // longer then though.
  5215. CurOffs += padding;
  5216. }
  5217. #endif
  5218. NamedDecl *dcl = CurLayObj->second;
  5219. if (!dcl)
  5220. break; // reached end of structure.
  5221. if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
  5222. // We expand the bases without their virtual bases since those are going
  5223. // in the initial structure. Note that this differs from gcc which
  5224. // expands virtual bases each time one is encountered in the hierarchy,
  5225. // making the encoding type bigger than it really is.
  5226. getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
  5227. NotEncodedT);
  5228. assert(!base->isEmpty());
  5229. #ifndef NDEBUG
  5230. CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
  5231. #endif
  5232. } else {
  5233. FieldDecl *field = cast<FieldDecl>(dcl);
  5234. if (FD) {
  5235. S += '"';
  5236. S += field->getNameAsString();
  5237. S += '"';
  5238. }
  5239. if (field->isBitField()) {
  5240. EncodeBitField(this, S, field->getType(), field);
  5241. #ifndef NDEBUG
  5242. CurOffs += field->getBitWidthValue(*this);
  5243. #endif
  5244. } else {
  5245. QualType qt = field->getType();
  5246. getLegacyIntegralTypeEncoding(qt);
  5247. getObjCEncodingForTypeImpl(qt, S, false, true, FD,
  5248. /*OutermostType*/false,
  5249. /*EncodingProperty*/false,
  5250. /*StructField*/true,
  5251. false, false, false, NotEncodedT);
  5252. #ifndef NDEBUG
  5253. CurOffs += getTypeSize(field->getType());
  5254. #endif
  5255. }
  5256. }
  5257. }
  5258. }
  5259. void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
  5260. std::string& S) const {
  5261. if (QT & Decl::OBJC_TQ_In)
  5262. S += 'n';
  5263. if (QT & Decl::OBJC_TQ_Inout)
  5264. S += 'N';
  5265. if (QT & Decl::OBJC_TQ_Out)
  5266. S += 'o';
  5267. if (QT & Decl::OBJC_TQ_Bycopy)
  5268. S += 'O';
  5269. if (QT & Decl::OBJC_TQ_Byref)
  5270. S += 'R';
  5271. if (QT & Decl::OBJC_TQ_Oneway)
  5272. S += 'V';
  5273. }
  5274. TypedefDecl *ASTContext::getObjCIdDecl() const {
  5275. if (!ObjCIdDecl) {
  5276. QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
  5277. T = getObjCObjectPointerType(T);
  5278. ObjCIdDecl = buildImplicitTypedef(T, "id");
  5279. }
  5280. return ObjCIdDecl;
  5281. }
  5282. TypedefDecl *ASTContext::getObjCSelDecl() const {
  5283. if (!ObjCSelDecl) {
  5284. QualType T = getPointerType(ObjCBuiltinSelTy);
  5285. ObjCSelDecl = buildImplicitTypedef(T, "SEL");
  5286. }
  5287. return ObjCSelDecl;
  5288. }
  5289. TypedefDecl *ASTContext::getObjCClassDecl() const {
  5290. if (!ObjCClassDecl) {
  5291. QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
  5292. T = getObjCObjectPointerType(T);
  5293. ObjCClassDecl = buildImplicitTypedef(T, "Class");
  5294. }
  5295. return ObjCClassDecl;
  5296. }
  5297. ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
  5298. if (!ObjCProtocolClassDecl) {
  5299. ObjCProtocolClassDecl
  5300. = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
  5301. SourceLocation(),
  5302. &Idents.get("Protocol"),
  5303. /*typeParamList=*/nullptr,
  5304. /*PrevDecl=*/nullptr,
  5305. SourceLocation(), true);
  5306. }
  5307. return ObjCProtocolClassDecl;
  5308. }
  5309. //===----------------------------------------------------------------------===//
  5310. // __builtin_va_list Construction Functions
  5311. //===----------------------------------------------------------------------===//
  5312. static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
  5313. // typedef char* __builtin_va_list;
  5314. QualType T = Context->getPointerType(Context->CharTy);
  5315. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  5316. }
  5317. static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
  5318. // typedef void* __builtin_va_list;
  5319. QualType T = Context->getPointerType(Context->VoidTy);
  5320. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  5321. }
  5322. static TypedefDecl *
  5323. CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
  5324. // struct __va_list
  5325. RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
  5326. if (Context->getLangOpts().CPlusPlus) {
  5327. // namespace std { struct __va_list {
  5328. NamespaceDecl *NS;
  5329. NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
  5330. Context->getTranslationUnitDecl(),
  5331. /*Inline*/ false, SourceLocation(),
  5332. SourceLocation(), &Context->Idents.get("std"),
  5333. /*PrevDecl*/ nullptr);
  5334. NS->setImplicit();
  5335. VaListTagDecl->setDeclContext(NS);
  5336. }
  5337. VaListTagDecl->startDefinition();
  5338. const size_t NumFields = 5;
  5339. QualType FieldTypes[NumFields];
  5340. const char *FieldNames[NumFields];
  5341. // void *__stack;
  5342. FieldTypes[0] = Context->getPointerType(Context->VoidTy);
  5343. FieldNames[0] = "__stack";
  5344. // void *__gr_top;
  5345. FieldTypes[1] = Context->getPointerType(Context->VoidTy);
  5346. FieldNames[1] = "__gr_top";
  5347. // void *__vr_top;
  5348. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  5349. FieldNames[2] = "__vr_top";
  5350. // int __gr_offs;
  5351. FieldTypes[3] = Context->IntTy;
  5352. FieldNames[3] = "__gr_offs";
  5353. // int __vr_offs;
  5354. FieldTypes[4] = Context->IntTy;
  5355. FieldNames[4] = "__vr_offs";
  5356. // Create fields
  5357. for (unsigned i = 0; i < NumFields; ++i) {
  5358. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  5359. VaListTagDecl,
  5360. SourceLocation(),
  5361. SourceLocation(),
  5362. &Context->Idents.get(FieldNames[i]),
  5363. FieldTypes[i], /*TInfo=*/nullptr,
  5364. /*BitWidth=*/nullptr,
  5365. /*Mutable=*/false,
  5366. ICIS_NoInit);
  5367. Field->setAccess(AS_public);
  5368. VaListTagDecl->addDecl(Field);
  5369. }
  5370. VaListTagDecl->completeDefinition();
  5371. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  5372. Context->VaListTagTy = VaListTagType;
  5373. // } __builtin_va_list;
  5374. return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
  5375. }
  5376. static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
  5377. // typedef struct __va_list_tag {
  5378. RecordDecl *VaListTagDecl;
  5379. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  5380. VaListTagDecl->startDefinition();
  5381. const size_t NumFields = 5;
  5382. QualType FieldTypes[NumFields];
  5383. const char *FieldNames[NumFields];
  5384. // unsigned char gpr;
  5385. FieldTypes[0] = Context->UnsignedCharTy;
  5386. FieldNames[0] = "gpr";
  5387. // unsigned char fpr;
  5388. FieldTypes[1] = Context->UnsignedCharTy;
  5389. FieldNames[1] = "fpr";
  5390. // unsigned short reserved;
  5391. FieldTypes[2] = Context->UnsignedShortTy;
  5392. FieldNames[2] = "reserved";
  5393. // void* overflow_arg_area;
  5394. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  5395. FieldNames[3] = "overflow_arg_area";
  5396. // void* reg_save_area;
  5397. FieldTypes[4] = Context->getPointerType(Context->VoidTy);
  5398. FieldNames[4] = "reg_save_area";
  5399. // Create fields
  5400. for (unsigned i = 0; i < NumFields; ++i) {
  5401. FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
  5402. SourceLocation(),
  5403. SourceLocation(),
  5404. &Context->Idents.get(FieldNames[i]),
  5405. FieldTypes[i], /*TInfo=*/nullptr,
  5406. /*BitWidth=*/nullptr,
  5407. /*Mutable=*/false,
  5408. ICIS_NoInit);
  5409. Field->setAccess(AS_public);
  5410. VaListTagDecl->addDecl(Field);
  5411. }
  5412. VaListTagDecl->completeDefinition();
  5413. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  5414. Context->VaListTagTy = VaListTagType;
  5415. // } __va_list_tag;
  5416. TypedefDecl *VaListTagTypedefDecl =
  5417. Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
  5418. QualType VaListTagTypedefType =
  5419. Context->getTypedefType(VaListTagTypedefDecl);
  5420. // typedef __va_list_tag __builtin_va_list[1];
  5421. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  5422. QualType VaListTagArrayType
  5423. = Context->getConstantArrayType(VaListTagTypedefType,
  5424. Size, ArrayType::Normal, 0);
  5425. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  5426. }
  5427. static TypedefDecl *
  5428. CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
  5429. // typedef struct __va_list_tag {
  5430. RecordDecl *VaListTagDecl;
  5431. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  5432. VaListTagDecl->startDefinition();
  5433. const size_t NumFields = 4;
  5434. QualType FieldTypes[NumFields];
  5435. const char *FieldNames[NumFields];
  5436. // unsigned gp_offset;
  5437. FieldTypes[0] = Context->UnsignedIntTy;
  5438. FieldNames[0] = "gp_offset";
  5439. // unsigned fp_offset;
  5440. FieldTypes[1] = Context->UnsignedIntTy;
  5441. FieldNames[1] = "fp_offset";
  5442. // void* overflow_arg_area;
  5443. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  5444. FieldNames[2] = "overflow_arg_area";
  5445. // void* reg_save_area;
  5446. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  5447. FieldNames[3] = "reg_save_area";
  5448. // Create fields
  5449. for (unsigned i = 0; i < NumFields; ++i) {
  5450. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  5451. VaListTagDecl,
  5452. SourceLocation(),
  5453. SourceLocation(),
  5454. &Context->Idents.get(FieldNames[i]),
  5455. FieldTypes[i], /*TInfo=*/nullptr,
  5456. /*BitWidth=*/nullptr,
  5457. /*Mutable=*/false,
  5458. ICIS_NoInit);
  5459. Field->setAccess(AS_public);
  5460. VaListTagDecl->addDecl(Field);
  5461. }
  5462. VaListTagDecl->completeDefinition();
  5463. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  5464. Context->VaListTagTy = VaListTagType;
  5465. // } __va_list_tag;
  5466. TypedefDecl *VaListTagTypedefDecl =
  5467. Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
  5468. QualType VaListTagTypedefType =
  5469. Context->getTypedefType(VaListTagTypedefDecl);
  5470. // typedef __va_list_tag __builtin_va_list[1];
  5471. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  5472. QualType VaListTagArrayType
  5473. = Context->getConstantArrayType(VaListTagTypedefType,
  5474. Size, ArrayType::Normal,0);
  5475. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  5476. }
  5477. static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
  5478. // typedef int __builtin_va_list[4];
  5479. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
  5480. QualType IntArrayType
  5481. = Context->getConstantArrayType(Context->IntTy,
  5482. Size, ArrayType::Normal, 0);
  5483. return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
  5484. }
  5485. static TypedefDecl *
  5486. CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
  5487. // struct __va_list
  5488. RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
  5489. if (Context->getLangOpts().CPlusPlus) {
  5490. // namespace std { struct __va_list {
  5491. NamespaceDecl *NS;
  5492. NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
  5493. Context->getTranslationUnitDecl(),
  5494. /*Inline*/false, SourceLocation(),
  5495. SourceLocation(), &Context->Idents.get("std"),
  5496. /*PrevDecl*/ nullptr);
  5497. NS->setImplicit();
  5498. VaListDecl->setDeclContext(NS);
  5499. }
  5500. VaListDecl->startDefinition();
  5501. // void * __ap;
  5502. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  5503. VaListDecl,
  5504. SourceLocation(),
  5505. SourceLocation(),
  5506. &Context->Idents.get("__ap"),
  5507. Context->getPointerType(Context->VoidTy),
  5508. /*TInfo=*/nullptr,
  5509. /*BitWidth=*/nullptr,
  5510. /*Mutable=*/false,
  5511. ICIS_NoInit);
  5512. Field->setAccess(AS_public);
  5513. VaListDecl->addDecl(Field);
  5514. // };
  5515. VaListDecl->completeDefinition();
  5516. // typedef struct __va_list __builtin_va_list;
  5517. QualType T = Context->getRecordType(VaListDecl);
  5518. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  5519. }
  5520. static TypedefDecl *
  5521. CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
  5522. // typedef struct __va_list_tag {
  5523. RecordDecl *VaListTagDecl;
  5524. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  5525. VaListTagDecl->startDefinition();
  5526. const size_t NumFields = 4;
  5527. QualType FieldTypes[NumFields];
  5528. const char *FieldNames[NumFields];
  5529. // long __gpr;
  5530. FieldTypes[0] = Context->LongTy;
  5531. FieldNames[0] = "__gpr";
  5532. // long __fpr;
  5533. FieldTypes[1] = Context->LongTy;
  5534. FieldNames[1] = "__fpr";
  5535. // void *__overflow_arg_area;
  5536. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  5537. FieldNames[2] = "__overflow_arg_area";
  5538. // void *__reg_save_area;
  5539. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  5540. FieldNames[3] = "__reg_save_area";
  5541. // Create fields
  5542. for (unsigned i = 0; i < NumFields; ++i) {
  5543. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  5544. VaListTagDecl,
  5545. SourceLocation(),
  5546. SourceLocation(),
  5547. &Context->Idents.get(FieldNames[i]),
  5548. FieldTypes[i], /*TInfo=*/nullptr,
  5549. /*BitWidth=*/nullptr,
  5550. /*Mutable=*/false,
  5551. ICIS_NoInit);
  5552. Field->setAccess(AS_public);
  5553. VaListTagDecl->addDecl(Field);
  5554. }
  5555. VaListTagDecl->completeDefinition();
  5556. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  5557. Context->VaListTagTy = VaListTagType;
  5558. // } __va_list_tag;
  5559. TypedefDecl *VaListTagTypedefDecl =
  5560. Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
  5561. QualType VaListTagTypedefType =
  5562. Context->getTypedefType(VaListTagTypedefDecl);
  5563. // typedef __va_list_tag __builtin_va_list[1];
  5564. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  5565. QualType VaListTagArrayType
  5566. = Context->getConstantArrayType(VaListTagTypedefType,
  5567. Size, ArrayType::Normal,0);
  5568. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  5569. }
  5570. static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
  5571. TargetInfo::BuiltinVaListKind Kind) {
  5572. switch (Kind) {
  5573. case TargetInfo::CharPtrBuiltinVaList:
  5574. return CreateCharPtrBuiltinVaListDecl(Context);
  5575. case TargetInfo::VoidPtrBuiltinVaList:
  5576. return CreateVoidPtrBuiltinVaListDecl(Context);
  5577. case TargetInfo::AArch64ABIBuiltinVaList:
  5578. return CreateAArch64ABIBuiltinVaListDecl(Context);
  5579. case TargetInfo::PowerABIBuiltinVaList:
  5580. return CreatePowerABIBuiltinVaListDecl(Context);
  5581. case TargetInfo::X86_64ABIBuiltinVaList:
  5582. return CreateX86_64ABIBuiltinVaListDecl(Context);
  5583. case TargetInfo::PNaClABIBuiltinVaList:
  5584. return CreatePNaClABIBuiltinVaListDecl(Context);
  5585. case TargetInfo::AAPCSABIBuiltinVaList:
  5586. return CreateAAPCSABIBuiltinVaListDecl(Context);
  5587. case TargetInfo::SystemZBuiltinVaList:
  5588. return CreateSystemZBuiltinVaListDecl(Context);
  5589. }
  5590. llvm_unreachable("Unhandled __builtin_va_list type kind");
  5591. }
  5592. TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
  5593. if (!BuiltinVaListDecl) {
  5594. BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
  5595. assert(BuiltinVaListDecl->isImplicit());
  5596. }
  5597. return BuiltinVaListDecl;
  5598. }
  5599. QualType ASTContext::getVaListTagType() const {
  5600. // Force the creation of VaListTagTy by building the __builtin_va_list
  5601. // declaration.
  5602. if (VaListTagTy.isNull())
  5603. (void) getBuiltinVaListDecl();
  5604. return VaListTagTy;
  5605. }
  5606. void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
  5607. assert(ObjCConstantStringType.isNull() &&
  5608. "'NSConstantString' type already set!");
  5609. ObjCConstantStringType = getObjCInterfaceType(Decl);
  5610. }
  5611. /// \brief Retrieve the template name that corresponds to a non-empty
  5612. /// lookup.
  5613. TemplateName
  5614. ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
  5615. UnresolvedSetIterator End) const {
  5616. unsigned size = End - Begin;
  5617. assert(size > 1 && "set is not overloaded!");
  5618. void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
  5619. size * sizeof(FunctionTemplateDecl*));
  5620. OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
  5621. NamedDecl **Storage = OT->getStorage();
  5622. for (UnresolvedSetIterator I = Begin; I != End; ++I) {
  5623. NamedDecl *D = *I;
  5624. assert(isa<FunctionTemplateDecl>(D) ||
  5625. (isa<UsingShadowDecl>(D) &&
  5626. isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
  5627. *Storage++ = D;
  5628. }
  5629. return TemplateName(OT);
  5630. }
  5631. /// \brief Retrieve the template name that represents a qualified
  5632. /// template name such as \c std::vector.
  5633. TemplateName
  5634. ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
  5635. bool TemplateKeyword,
  5636. TemplateDecl *Template) const {
  5637. assert(NNS && "Missing nested-name-specifier in qualified template name");
  5638. // FIXME: Canonicalization?
  5639. llvm::FoldingSetNodeID ID;
  5640. QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
  5641. void *InsertPos = nullptr;
  5642. QualifiedTemplateName *QTN =
  5643. QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  5644. if (!QTN) {
  5645. QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
  5646. QualifiedTemplateName(NNS, TemplateKeyword, Template);
  5647. QualifiedTemplateNames.InsertNode(QTN, InsertPos);
  5648. }
  5649. return TemplateName(QTN);
  5650. }
  5651. /// \brief Retrieve the template name that represents a dependent
  5652. /// template name such as \c MetaFun::template apply.
  5653. TemplateName
  5654. ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
  5655. const IdentifierInfo *Name) const {
  5656. assert((!NNS || NNS->isDependent()) &&
  5657. "Nested name specifier must be dependent");
  5658. llvm::FoldingSetNodeID ID;
  5659. DependentTemplateName::Profile(ID, NNS, Name);
  5660. void *InsertPos = nullptr;
  5661. DependentTemplateName *QTN =
  5662. DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  5663. if (QTN)
  5664. return TemplateName(QTN);
  5665. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  5666. if (CanonNNS == NNS) {
  5667. QTN = new (*this, llvm::alignOf<DependentTemplateName>())
  5668. DependentTemplateName(NNS, Name);
  5669. } else {
  5670. TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
  5671. QTN = new (*this, llvm::alignOf<DependentTemplateName>())
  5672. DependentTemplateName(NNS, Name, Canon);
  5673. DependentTemplateName *CheckQTN =
  5674. DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  5675. assert(!CheckQTN && "Dependent type name canonicalization broken");
  5676. (void)CheckQTN;
  5677. }
  5678. DependentTemplateNames.InsertNode(QTN, InsertPos);
  5679. return TemplateName(QTN);
  5680. }
  5681. /// \brief Retrieve the template name that represents a dependent
  5682. /// template name such as \c MetaFun::template operator+.
  5683. TemplateName
  5684. ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
  5685. OverloadedOperatorKind Operator) const {
  5686. assert((!NNS || NNS->isDependent()) &&
  5687. "Nested name specifier must be dependent");
  5688. llvm::FoldingSetNodeID ID;
  5689. DependentTemplateName::Profile(ID, NNS, Operator);
  5690. void *InsertPos = nullptr;
  5691. DependentTemplateName *QTN
  5692. = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  5693. if (QTN)
  5694. return TemplateName(QTN);
  5695. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  5696. if (CanonNNS == NNS) {
  5697. QTN = new (*this, llvm::alignOf<DependentTemplateName>())
  5698. DependentTemplateName(NNS, Operator);
  5699. } else {
  5700. TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
  5701. QTN = new (*this, llvm::alignOf<DependentTemplateName>())
  5702. DependentTemplateName(NNS, Operator, Canon);
  5703. DependentTemplateName *CheckQTN
  5704. = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  5705. assert(!CheckQTN && "Dependent template name canonicalization broken");
  5706. (void)CheckQTN;
  5707. }
  5708. DependentTemplateNames.InsertNode(QTN, InsertPos);
  5709. return TemplateName(QTN);
  5710. }
  5711. TemplateName
  5712. ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
  5713. TemplateName replacement) const {
  5714. llvm::FoldingSetNodeID ID;
  5715. SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
  5716. void *insertPos = nullptr;
  5717. SubstTemplateTemplateParmStorage *subst
  5718. = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
  5719. if (!subst) {
  5720. subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
  5721. SubstTemplateTemplateParms.InsertNode(subst, insertPos);
  5722. }
  5723. return TemplateName(subst);
  5724. }
  5725. TemplateName
  5726. ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
  5727. const TemplateArgument &ArgPack) const {
  5728. ASTContext &Self = const_cast<ASTContext &>(*this);
  5729. llvm::FoldingSetNodeID ID;
  5730. SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
  5731. void *InsertPos = nullptr;
  5732. SubstTemplateTemplateParmPackStorage *Subst
  5733. = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
  5734. if (!Subst) {
  5735. Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
  5736. ArgPack.pack_size(),
  5737. ArgPack.pack_begin());
  5738. SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
  5739. }
  5740. return TemplateName(Subst);
  5741. }
  5742. /// getFromTargetType - Given one of the integer types provided by
  5743. /// TargetInfo, produce the corresponding type. The unsigned @p Type
  5744. /// is actually a value of type @c TargetInfo::IntType.
  5745. CanQualType ASTContext::getFromTargetType(unsigned Type) const {
  5746. switch (Type) {
  5747. case TargetInfo::NoInt: return CanQualType();
  5748. case TargetInfo::SignedChar: return SignedCharTy;
  5749. case TargetInfo::UnsignedChar: return UnsignedCharTy;
  5750. case TargetInfo::SignedShort: return ShortTy;
  5751. case TargetInfo::UnsignedShort: return UnsignedShortTy;
  5752. case TargetInfo::SignedInt: return IntTy;
  5753. case TargetInfo::UnsignedInt: return UnsignedIntTy;
  5754. case TargetInfo::SignedLong: return LongTy;
  5755. case TargetInfo::UnsignedLong: return UnsignedLongTy;
  5756. case TargetInfo::SignedLongLong: return LongLongTy;
  5757. case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
  5758. }
  5759. llvm_unreachable("Unhandled TargetInfo::IntType value");
  5760. }
  5761. //===----------------------------------------------------------------------===//
  5762. // Type Predicates.
  5763. //===----------------------------------------------------------------------===//
  5764. /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
  5765. /// garbage collection attribute.
  5766. ///
  5767. Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
  5768. if (getLangOpts().getGC() == LangOptions::NonGC)
  5769. return Qualifiers::GCNone;
  5770. assert(getLangOpts().ObjC1);
  5771. Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
  5772. // Default behaviour under objective-C's gc is for ObjC pointers
  5773. // (or pointers to them) be treated as though they were declared
  5774. // as __strong.
  5775. if (GCAttrs == Qualifiers::GCNone) {
  5776. if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
  5777. return Qualifiers::Strong;
  5778. else if (Ty->isPointerType())
  5779. return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
  5780. } else {
  5781. // It's not valid to set GC attributes on anything that isn't a
  5782. // pointer.
  5783. #ifndef NDEBUG
  5784. QualType CT = Ty->getCanonicalTypeInternal();
  5785. while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
  5786. CT = AT->getElementType();
  5787. assert(CT->isAnyPointerType() || CT->isBlockPointerType());
  5788. #endif
  5789. }
  5790. return GCAttrs;
  5791. }
  5792. //===----------------------------------------------------------------------===//
  5793. // Type Compatibility Testing
  5794. //===----------------------------------------------------------------------===//
  5795. /// areCompatVectorTypes - Return true if the two specified vector types are
  5796. /// compatible.
  5797. static bool areCompatVectorTypes(const VectorType *LHS,
  5798. const VectorType *RHS) {
  5799. assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
  5800. return LHS->getElementType() == RHS->getElementType() &&
  5801. LHS->getNumElements() == RHS->getNumElements();
  5802. }
  5803. bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
  5804. QualType SecondVec) {
  5805. assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
  5806. assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
  5807. if (hasSameUnqualifiedType(FirstVec, SecondVec))
  5808. return true;
  5809. // Treat Neon vector types and most AltiVec vector types as if they are the
  5810. // equivalent GCC vector types.
  5811. const VectorType *First = FirstVec->getAs<VectorType>();
  5812. const VectorType *Second = SecondVec->getAs<VectorType>();
  5813. if (First->getNumElements() == Second->getNumElements() &&
  5814. hasSameType(First->getElementType(), Second->getElementType()) &&
  5815. First->getVectorKind() != VectorType::AltiVecPixel &&
  5816. First->getVectorKind() != VectorType::AltiVecBool &&
  5817. Second->getVectorKind() != VectorType::AltiVecPixel &&
  5818. Second->getVectorKind() != VectorType::AltiVecBool)
  5819. return true;
  5820. return false;
  5821. }
  5822. //===----------------------------------------------------------------------===//
  5823. // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
  5824. //===----------------------------------------------------------------------===//
  5825. /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
  5826. /// inheritance hierarchy of 'rProto'.
  5827. bool
  5828. ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
  5829. ObjCProtocolDecl *rProto) const {
  5830. if (declaresSameEntity(lProto, rProto))
  5831. return true;
  5832. for (auto *PI : rProto->protocols())
  5833. if (ProtocolCompatibleWithProtocol(lProto, PI))
  5834. return true;
  5835. return false;
  5836. }
  5837. /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
  5838. /// Class<pr1, ...>.
  5839. bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
  5840. QualType rhs) {
  5841. const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
  5842. const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
  5843. assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
  5844. for (auto *lhsProto : lhsQID->quals()) {
  5845. bool match = false;
  5846. for (auto *rhsProto : rhsOPT->quals()) {
  5847. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
  5848. match = true;
  5849. break;
  5850. }
  5851. }
  5852. if (!match)
  5853. return false;
  5854. }
  5855. return true;
  5856. }
  5857. /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
  5858. /// ObjCQualifiedIDType.
  5859. bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
  5860. bool compare) {
  5861. // Allow id<P..> and an 'id' or void* type in all cases.
  5862. if (lhs->isVoidPointerType() ||
  5863. lhs->isObjCIdType() || lhs->isObjCClassType())
  5864. return true;
  5865. else if (rhs->isVoidPointerType() ||
  5866. rhs->isObjCIdType() || rhs->isObjCClassType())
  5867. return true;
  5868. if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
  5869. const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
  5870. if (!rhsOPT) return false;
  5871. if (rhsOPT->qual_empty()) {
  5872. // If the RHS is a unqualified interface pointer "NSString*",
  5873. // make sure we check the class hierarchy.
  5874. if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
  5875. for (auto *I : lhsQID->quals()) {
  5876. // when comparing an id<P> on lhs with a static type on rhs,
  5877. // see if static class implements all of id's protocols, directly or
  5878. // through its super class and categories.
  5879. if (!rhsID->ClassImplementsProtocol(I, true))
  5880. return false;
  5881. }
  5882. }
  5883. // If there are no qualifiers and no interface, we have an 'id'.
  5884. return true;
  5885. }
  5886. // Both the right and left sides have qualifiers.
  5887. for (auto *lhsProto : lhsQID->quals()) {
  5888. bool match = false;
  5889. // when comparing an id<P> on lhs with a static type on rhs,
  5890. // see if static class implements all of id's protocols, directly or
  5891. // through its super class and categories.
  5892. for (auto *rhsProto : rhsOPT->quals()) {
  5893. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  5894. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  5895. match = true;
  5896. break;
  5897. }
  5898. }
  5899. // If the RHS is a qualified interface pointer "NSString<P>*",
  5900. // make sure we check the class hierarchy.
  5901. if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
  5902. for (auto *I : lhsQID->quals()) {
  5903. // when comparing an id<P> on lhs with a static type on rhs,
  5904. // see if static class implements all of id's protocols, directly or
  5905. // through its super class and categories.
  5906. if (rhsID->ClassImplementsProtocol(I, true)) {
  5907. match = true;
  5908. break;
  5909. }
  5910. }
  5911. }
  5912. if (!match)
  5913. return false;
  5914. }
  5915. return true;
  5916. }
  5917. const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
  5918. assert(rhsQID && "One of the LHS/RHS should be id<x>");
  5919. if (const ObjCObjectPointerType *lhsOPT =
  5920. lhs->getAsObjCInterfacePointerType()) {
  5921. // If both the right and left sides have qualifiers.
  5922. for (auto *lhsProto : lhsOPT->quals()) {
  5923. bool match = false;
  5924. // when comparing an id<P> on rhs with a static type on lhs,
  5925. // see if static class implements all of id's protocols, directly or
  5926. // through its super class and categories.
  5927. // First, lhs protocols in the qualifier list must be found, direct
  5928. // or indirect in rhs's qualifier list or it is a mismatch.
  5929. for (auto *rhsProto : rhsQID->quals()) {
  5930. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  5931. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  5932. match = true;
  5933. break;
  5934. }
  5935. }
  5936. if (!match)
  5937. return false;
  5938. }
  5939. // Static class's protocols, or its super class or category protocols
  5940. // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
  5941. if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
  5942. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
  5943. CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
  5944. // This is rather dubious but matches gcc's behavior. If lhs has
  5945. // no type qualifier and its class has no static protocol(s)
  5946. // assume that it is mismatch.
  5947. if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
  5948. return false;
  5949. for (auto *lhsProto : LHSInheritedProtocols) {
  5950. bool match = false;
  5951. for (auto *rhsProto : rhsQID->quals()) {
  5952. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  5953. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  5954. match = true;
  5955. break;
  5956. }
  5957. }
  5958. if (!match)
  5959. return false;
  5960. }
  5961. }
  5962. return true;
  5963. }
  5964. return false;
  5965. }
  5966. /// canAssignObjCInterfaces - Return true if the two interface types are
  5967. /// compatible for assignment from RHS to LHS. This handles validation of any
  5968. /// protocol qualifiers on the LHS or RHS.
  5969. ///
  5970. bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
  5971. const ObjCObjectPointerType *RHSOPT) {
  5972. const ObjCObjectType* LHS = LHSOPT->getObjectType();
  5973. const ObjCObjectType* RHS = RHSOPT->getObjectType();
  5974. // If either type represents the built-in 'id' or 'Class' types, return true.
  5975. if (LHS->isObjCUnqualifiedIdOrClass() ||
  5976. RHS->isObjCUnqualifiedIdOrClass())
  5977. return true;
  5978. // Function object that propagates a successful result or handles
  5979. // __kindof types.
  5980. auto finish = [&](bool succeeded) -> bool {
  5981. if (succeeded)
  5982. return true;
  5983. if (!RHS->isKindOfType())
  5984. return false;
  5985. // Strip off __kindof and protocol qualifiers, then check whether
  5986. // we can assign the other way.
  5987. return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
  5988. LHSOPT->stripObjCKindOfTypeAndQuals(*this));
  5989. };
  5990. if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
  5991. return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
  5992. QualType(RHSOPT,0),
  5993. false));
  5994. }
  5995. if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
  5996. return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
  5997. QualType(RHSOPT,0)));
  5998. }
  5999. // If we have 2 user-defined types, fall into that path.
  6000. if (LHS->getInterface() && RHS->getInterface()) {
  6001. return finish(canAssignObjCInterfaces(LHS, RHS));
  6002. }
  6003. return false;
  6004. }
  6005. /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
  6006. /// for providing type-safety for objective-c pointers used to pass/return
  6007. /// arguments in block literals. When passed as arguments, passing 'A*' where
  6008. /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
  6009. /// not OK. For the return type, the opposite is not OK.
  6010. bool ASTContext::canAssignObjCInterfacesInBlockPointer(
  6011. const ObjCObjectPointerType *LHSOPT,
  6012. const ObjCObjectPointerType *RHSOPT,
  6013. bool BlockReturnType) {
  6014. // Function object that propagates a successful result or handles
  6015. // __kindof types.
  6016. auto finish = [&](bool succeeded) -> bool {
  6017. if (succeeded)
  6018. return true;
  6019. const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
  6020. if (!Expected->isKindOfType())
  6021. return false;
  6022. // Strip off __kindof and protocol qualifiers, then check whether
  6023. // we can assign the other way.
  6024. return canAssignObjCInterfacesInBlockPointer(
  6025. RHSOPT->stripObjCKindOfTypeAndQuals(*this),
  6026. LHSOPT->stripObjCKindOfTypeAndQuals(*this),
  6027. BlockReturnType);
  6028. };
  6029. if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
  6030. return true;
  6031. if (LHSOPT->isObjCBuiltinType()) {
  6032. return finish(RHSOPT->isObjCBuiltinType() ||
  6033. RHSOPT->isObjCQualifiedIdType());
  6034. }
  6035. if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
  6036. return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
  6037. QualType(RHSOPT,0),
  6038. false));
  6039. const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
  6040. const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
  6041. if (LHS && RHS) { // We have 2 user-defined types.
  6042. if (LHS != RHS) {
  6043. if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
  6044. return finish(BlockReturnType);
  6045. if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
  6046. return finish(!BlockReturnType);
  6047. }
  6048. else
  6049. return true;
  6050. }
  6051. return false;
  6052. }
  6053. /// Comparison routine for Objective-C protocols to be used with
  6054. /// llvm::array_pod_sort.
  6055. static int __cdecl compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, // HLSL Change - __cdecl
  6056. ObjCProtocolDecl * const *rhs) {
  6057. return (*lhs)->getName().compare((*rhs)->getName());
  6058. }
  6059. /// getIntersectionOfProtocols - This routine finds the intersection of set
  6060. /// of protocols inherited from two distinct objective-c pointer objects with
  6061. /// the given common base.
  6062. /// It is used to build composite qualifier list of the composite type of
  6063. /// the conditional expression involving two objective-c pointer objects.
  6064. static
  6065. void getIntersectionOfProtocols(ASTContext &Context,
  6066. const ObjCInterfaceDecl *CommonBase,
  6067. const ObjCObjectPointerType *LHSOPT,
  6068. const ObjCObjectPointerType *RHSOPT,
  6069. SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
  6070. const ObjCObjectType* LHS = LHSOPT->getObjectType();
  6071. const ObjCObjectType* RHS = RHSOPT->getObjectType();
  6072. assert(LHS->getInterface() && "LHS must have an interface base");
  6073. assert(RHS->getInterface() && "RHS must have an interface base");
  6074. // Add all of the protocols for the LHS.
  6075. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
  6076. // Start with the protocol qualifiers.
  6077. for (auto proto : LHS->quals()) {
  6078. Context.CollectInheritedProtocols(proto, LHSProtocolSet);
  6079. }
  6080. // Also add the protocols associated with the LHS interface.
  6081. Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
  6082. // Add all of the protocls for the RHS.
  6083. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
  6084. // Start with the protocol qualifiers.
  6085. for (auto proto : RHS->quals()) {
  6086. Context.CollectInheritedProtocols(proto, RHSProtocolSet);
  6087. }
  6088. // Also add the protocols associated with the RHS interface.
  6089. Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
  6090. // Compute the intersection of the collected protocol sets.
  6091. for (auto proto : LHSProtocolSet) {
  6092. if (RHSProtocolSet.count(proto))
  6093. IntersectionSet.push_back(proto);
  6094. }
  6095. // Compute the set of protocols that is implied by either the common type or
  6096. // the protocols within the intersection.
  6097. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
  6098. Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
  6099. // Remove any implied protocols from the list of inherited protocols.
  6100. if (!ImpliedProtocols.empty()) {
  6101. IntersectionSet.erase(
  6102. std::remove_if(IntersectionSet.begin(),
  6103. IntersectionSet.end(),
  6104. [&](ObjCProtocolDecl *proto) -> bool {
  6105. return ImpliedProtocols.count(proto) > 0;
  6106. }),
  6107. IntersectionSet.end());
  6108. }
  6109. // Sort the remaining protocols by name.
  6110. llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
  6111. compareObjCProtocolsByName);
  6112. }
  6113. /// Determine whether the first type is a subtype of the second.
  6114. static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
  6115. QualType rhs) {
  6116. // Common case: two object pointers.
  6117. const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
  6118. const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
  6119. if (lhsOPT && rhsOPT)
  6120. return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
  6121. // Two block pointers.
  6122. const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
  6123. const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
  6124. if (lhsBlock && rhsBlock)
  6125. return ctx.typesAreBlockPointerCompatible(lhs, rhs);
  6126. // If either is an unqualified 'id' and the other is a block, it's
  6127. // acceptable.
  6128. if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
  6129. (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
  6130. return true;
  6131. return false;
  6132. }
  6133. // Check that the given Objective-C type argument lists are equivalent.
  6134. static bool sameObjCTypeArgs(ASTContext &ctx,
  6135. const ObjCInterfaceDecl *iface,
  6136. ArrayRef<QualType> lhsArgs,
  6137. ArrayRef<QualType> rhsArgs,
  6138. bool stripKindOf) {
  6139. if (lhsArgs.size() != rhsArgs.size())
  6140. return false;
  6141. ObjCTypeParamList *typeParams = iface->getTypeParamList();
  6142. for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
  6143. if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
  6144. continue;
  6145. switch (typeParams->begin()[i]->getVariance()) {
  6146. case ObjCTypeParamVariance::Invariant:
  6147. if (!stripKindOf ||
  6148. !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
  6149. rhsArgs[i].stripObjCKindOfType(ctx))) {
  6150. return false;
  6151. }
  6152. break;
  6153. case ObjCTypeParamVariance::Covariant:
  6154. if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
  6155. return false;
  6156. break;
  6157. case ObjCTypeParamVariance::Contravariant:
  6158. if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
  6159. return false;
  6160. break;
  6161. }
  6162. }
  6163. return true;
  6164. }
  6165. QualType ASTContext::areCommonBaseCompatible(
  6166. const ObjCObjectPointerType *Lptr,
  6167. const ObjCObjectPointerType *Rptr) {
  6168. const ObjCObjectType *LHS = Lptr->getObjectType();
  6169. const ObjCObjectType *RHS = Rptr->getObjectType();
  6170. const ObjCInterfaceDecl* LDecl = LHS->getInterface();
  6171. const ObjCInterfaceDecl* RDecl = RHS->getInterface();
  6172. if (!LDecl || !RDecl)
  6173. return QualType();
  6174. // Follow the left-hand side up the class hierarchy until we either hit a
  6175. // root or find the RHS. Record the ancestors in case we don't find it.
  6176. llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
  6177. LHSAncestors;
  6178. while (true) {
  6179. // Record this ancestor. We'll need this if the common type isn't in the
  6180. // path from the LHS to the root.
  6181. LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
  6182. if (declaresSameEntity(LHS->getInterface(), RDecl)) {
  6183. // Get the type arguments.
  6184. ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
  6185. bool anyChanges = false;
  6186. if (LHS->isSpecialized() && RHS->isSpecialized()) {
  6187. // Both have type arguments, compare them.
  6188. if (!sameObjCTypeArgs(*this, LHS->getInterface(),
  6189. LHS->getTypeArgs(), RHS->getTypeArgs(),
  6190. /*stripKindOf=*/true))
  6191. return QualType();
  6192. } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
  6193. // If only one has type arguments, the result will not have type
  6194. // arguments.
  6195. LHSTypeArgs = { };
  6196. anyChanges = true;
  6197. }
  6198. // Compute the intersection of protocols.
  6199. SmallVector<ObjCProtocolDecl *, 8> Protocols;
  6200. getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
  6201. Protocols);
  6202. if (!Protocols.empty())
  6203. anyChanges = true;
  6204. // If anything in the LHS will have changed, build a new result type.
  6205. if (anyChanges) {
  6206. QualType Result = getObjCInterfaceType(LHS->getInterface());
  6207. Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
  6208. LHS->isKindOfType());
  6209. return getObjCObjectPointerType(Result);
  6210. }
  6211. return getObjCObjectPointerType(QualType(LHS, 0));
  6212. }
  6213. // Find the superclass.
  6214. QualType LHSSuperType = LHS->getSuperClassType();
  6215. if (LHSSuperType.isNull())
  6216. break;
  6217. LHS = LHSSuperType->castAs<ObjCObjectType>();
  6218. }
  6219. // We didn't find anything by following the LHS to its root; now check
  6220. // the RHS against the cached set of ancestors.
  6221. while (true) {
  6222. auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
  6223. if (KnownLHS != LHSAncestors.end()) {
  6224. LHS = KnownLHS->second;
  6225. // Get the type arguments.
  6226. ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
  6227. bool anyChanges = false;
  6228. if (LHS->isSpecialized() && RHS->isSpecialized()) {
  6229. // Both have type arguments, compare them.
  6230. if (!sameObjCTypeArgs(*this, LHS->getInterface(),
  6231. LHS->getTypeArgs(), RHS->getTypeArgs(),
  6232. /*stripKindOf=*/true))
  6233. return QualType();
  6234. } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
  6235. // If only one has type arguments, the result will not have type
  6236. // arguments.
  6237. RHSTypeArgs = { };
  6238. anyChanges = true;
  6239. }
  6240. // Compute the intersection of protocols.
  6241. SmallVector<ObjCProtocolDecl *, 8> Protocols;
  6242. getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
  6243. Protocols);
  6244. if (!Protocols.empty())
  6245. anyChanges = true;
  6246. if (anyChanges) {
  6247. QualType Result = getObjCInterfaceType(RHS->getInterface());
  6248. Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
  6249. RHS->isKindOfType());
  6250. return getObjCObjectPointerType(Result);
  6251. }
  6252. return getObjCObjectPointerType(QualType(RHS, 0));
  6253. }
  6254. // Find the superclass of the RHS.
  6255. QualType RHSSuperType = RHS->getSuperClassType();
  6256. if (RHSSuperType.isNull())
  6257. break;
  6258. RHS = RHSSuperType->castAs<ObjCObjectType>();
  6259. }
  6260. return QualType();
  6261. }
  6262. bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
  6263. const ObjCObjectType *RHS) {
  6264. assert(LHS->getInterface() && "LHS is not an interface type");
  6265. assert(RHS->getInterface() && "RHS is not an interface type");
  6266. // Verify that the base decls are compatible: the RHS must be a subclass of
  6267. // the LHS.
  6268. ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
  6269. bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
  6270. if (!IsSuperClass)
  6271. return false;
  6272. // If the LHS has protocol qualifiers, determine whether all of them are
  6273. // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
  6274. // LHS).
  6275. if (LHS->getNumProtocols() > 0) {
  6276. // OK if conversion of LHS to SuperClass results in narrowing of types
  6277. // ; i.e., SuperClass may implement at least one of the protocols
  6278. // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
  6279. // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
  6280. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
  6281. CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
  6282. // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
  6283. // qualifiers.
  6284. for (auto *RHSPI : RHS->quals())
  6285. CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
  6286. // If there is no protocols associated with RHS, it is not a match.
  6287. if (SuperClassInheritedProtocols.empty())
  6288. return false;
  6289. for (const auto *LHSProto : LHS->quals()) {
  6290. bool SuperImplementsProtocol = false;
  6291. for (auto *SuperClassProto : SuperClassInheritedProtocols)
  6292. if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
  6293. SuperImplementsProtocol = true;
  6294. break;
  6295. }
  6296. if (!SuperImplementsProtocol)
  6297. return false;
  6298. }
  6299. }
  6300. // If the LHS is specialized, we may need to check type arguments.
  6301. if (LHS->isSpecialized()) {
  6302. // Follow the superclass chain until we've matched the LHS class in the
  6303. // hierarchy. This substitutes type arguments through.
  6304. const ObjCObjectType *RHSSuper = RHS;
  6305. while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
  6306. RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
  6307. // If the RHS is specializd, compare type arguments.
  6308. if (RHSSuper->isSpecialized() &&
  6309. !sameObjCTypeArgs(*this, LHS->getInterface(),
  6310. LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
  6311. /*stripKindOf=*/true)) {
  6312. return false;
  6313. }
  6314. }
  6315. return true;
  6316. }
  6317. bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
  6318. // get the "pointed to" types
  6319. const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
  6320. const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
  6321. if (!LHSOPT || !RHSOPT)
  6322. return false;
  6323. return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
  6324. canAssignObjCInterfaces(RHSOPT, LHSOPT);
  6325. }
  6326. bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
  6327. return canAssignObjCInterfaces(
  6328. getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
  6329. getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
  6330. }
  6331. /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
  6332. /// both shall have the identically qualified version of a compatible type.
  6333. /// C99 6.2.7p1: Two types have compatible types if their types are the
  6334. /// same. See 6.7.[2,3,5] for additional rules.
  6335. bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
  6336. bool CompareUnqualified) {
  6337. if (getLangOpts().CPlusPlus)
  6338. return hasSameType(LHS, RHS);
  6339. return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
  6340. }
  6341. bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
  6342. return typesAreCompatible(LHS, RHS);
  6343. }
  6344. bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
  6345. return !mergeTypes(LHS, RHS, true).isNull();
  6346. }
  6347. /// mergeTransparentUnionType - if T is a transparent union type and a member
  6348. /// of T is compatible with SubType, return the merged type, else return
  6349. /// QualType()
  6350. QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
  6351. bool OfBlockPointer,
  6352. bool Unqualified) {
  6353. if (const RecordType *UT = T->getAsUnionType()) {
  6354. RecordDecl *UD = UT->getDecl();
  6355. if (UD->hasAttr<TransparentUnionAttr>()) {
  6356. for (const auto *I : UD->fields()) {
  6357. QualType ET = I->getType().getUnqualifiedType();
  6358. QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
  6359. if (!MT.isNull())
  6360. return MT;
  6361. }
  6362. }
  6363. }
  6364. return QualType();
  6365. }
  6366. /// mergeFunctionParameterTypes - merge two types which appear as function
  6367. /// parameter types
  6368. QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
  6369. bool OfBlockPointer,
  6370. bool Unqualified) {
  6371. // GNU extension: two types are compatible if they appear as a function
  6372. // argument, one of the types is a transparent union type and the other
  6373. // type is compatible with a union member
  6374. QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
  6375. Unqualified);
  6376. if (!lmerge.isNull())
  6377. return lmerge;
  6378. QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
  6379. Unqualified);
  6380. if (!rmerge.isNull())
  6381. return rmerge;
  6382. return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
  6383. }
  6384. QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
  6385. bool OfBlockPointer,
  6386. bool Unqualified) {
  6387. const FunctionType *lbase = lhs->getAs<FunctionType>();
  6388. const FunctionType *rbase = rhs->getAs<FunctionType>();
  6389. const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
  6390. const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
  6391. bool allLTypes = true;
  6392. bool allRTypes = true;
  6393. // Check return type
  6394. QualType retType;
  6395. if (OfBlockPointer) {
  6396. QualType RHS = rbase->getReturnType();
  6397. QualType LHS = lbase->getReturnType();
  6398. bool UnqualifiedResult = Unqualified;
  6399. if (!UnqualifiedResult)
  6400. UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
  6401. retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
  6402. }
  6403. else
  6404. retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
  6405. Unqualified);
  6406. if (retType.isNull()) return QualType();
  6407. if (Unqualified)
  6408. retType = retType.getUnqualifiedType();
  6409. CanQualType LRetType = getCanonicalType(lbase->getReturnType());
  6410. CanQualType RRetType = getCanonicalType(rbase->getReturnType());
  6411. if (Unqualified) {
  6412. LRetType = LRetType.getUnqualifiedType();
  6413. RRetType = RRetType.getUnqualifiedType();
  6414. }
  6415. if (getCanonicalType(retType) != LRetType)
  6416. allLTypes = false;
  6417. if (getCanonicalType(retType) != RRetType)
  6418. allRTypes = false;
  6419. // FIXME: double check this
  6420. // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
  6421. // rbase->getRegParmAttr() != 0 &&
  6422. // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
  6423. FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
  6424. FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
  6425. // Compatible functions must have compatible calling conventions
  6426. if (lbaseInfo.getCC() != rbaseInfo.getCC())
  6427. return QualType();
  6428. // Regparm is part of the calling convention.
  6429. if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
  6430. return QualType();
  6431. if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
  6432. return QualType();
  6433. if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
  6434. return QualType();
  6435. // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
  6436. bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
  6437. if (lbaseInfo.getNoReturn() != NoReturn)
  6438. allLTypes = false;
  6439. if (rbaseInfo.getNoReturn() != NoReturn)
  6440. allRTypes = false;
  6441. FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
  6442. if (lproto && rproto) { // two C99 style function prototypes
  6443. assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
  6444. "C++ shouldn't be here");
  6445. // Compatible functions must have the same number of parameters
  6446. if (lproto->getNumParams() != rproto->getNumParams())
  6447. return QualType();
  6448. // Variadic and non-variadic functions aren't compatible
  6449. if (lproto->isVariadic() != rproto->isVariadic())
  6450. return QualType();
  6451. if (lproto->getTypeQuals() != rproto->getTypeQuals())
  6452. return QualType();
  6453. #if 0 // HLSL Change Starts - no ObjC support
  6454. if (LangOpts.ObjCAutoRefCount &&
  6455. !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
  6456. return QualType();
  6457. #endif // HLSL Change Ends - no ObjC support
  6458. // Check parameter type compatibility
  6459. SmallVector<QualType, 10> types;
  6460. for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
  6461. QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
  6462. QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
  6463. QualType paramType = mergeFunctionParameterTypes(
  6464. lParamType, rParamType, OfBlockPointer, Unqualified);
  6465. if (paramType.isNull())
  6466. return QualType();
  6467. if (Unqualified)
  6468. paramType = paramType.getUnqualifiedType();
  6469. types.push_back(paramType);
  6470. if (Unqualified) {
  6471. lParamType = lParamType.getUnqualifiedType();
  6472. rParamType = rParamType.getUnqualifiedType();
  6473. }
  6474. if (getCanonicalType(paramType) != getCanonicalType(lParamType))
  6475. allLTypes = false;
  6476. if (getCanonicalType(paramType) != getCanonicalType(rParamType))
  6477. allRTypes = false;
  6478. }
  6479. if (allLTypes) return lhs;
  6480. if (allRTypes) return rhs;
  6481. FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
  6482. EPI.ExtInfo = einfo;
  6483. return getFunctionType(retType, types, EPI, lproto->getParamMods());
  6484. }
  6485. if (lproto) allRTypes = false;
  6486. if (rproto) allLTypes = false;
  6487. const FunctionProtoType *proto = lproto ? lproto : rproto;
  6488. if (proto) {
  6489. assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
  6490. if (proto->isVariadic()) return QualType();
  6491. // Check that the types are compatible with the types that
  6492. // would result from default argument promotions (C99 6.7.5.3p15).
  6493. // The only types actually affected are promotable integer
  6494. // types and floats, which would be passed as a different
  6495. // type depending on whether the prototype is visible.
  6496. for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
  6497. QualType paramTy = proto->getParamType(i);
  6498. // Look at the converted type of enum types, since that is the type used
  6499. // to pass enum values.
  6500. if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
  6501. paramTy = Enum->getDecl()->getIntegerType();
  6502. if (paramTy.isNull())
  6503. return QualType();
  6504. }
  6505. if (paramTy->isPromotableIntegerType() ||
  6506. getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
  6507. return QualType();
  6508. }
  6509. if (allLTypes) return lhs;
  6510. if (allRTypes) return rhs;
  6511. FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
  6512. EPI.ExtInfo = einfo;
  6513. return getFunctionType(retType, proto->getParamTypes(), EPI, proto->getParamMods());
  6514. }
  6515. if (allLTypes) return lhs;
  6516. if (allRTypes) return rhs;
  6517. return getFunctionNoProtoType(retType, einfo);
  6518. }
  6519. /// Given that we have an enum type and a non-enum type, try to merge them.
  6520. static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
  6521. QualType other, bool isBlockReturnType) {
  6522. // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
  6523. // a signed integer type, or an unsigned integer type.
  6524. // Compatibility is based on the underlying type, not the promotion
  6525. // type.
  6526. QualType underlyingType = ET->getDecl()->getIntegerType();
  6527. if (underlyingType.isNull()) return QualType();
  6528. if (Context.hasSameType(underlyingType, other))
  6529. return other;
  6530. // In block return types, we're more permissive and accept any
  6531. // integral type of the same size.
  6532. if (isBlockReturnType && other->isIntegerType() &&
  6533. Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
  6534. return other;
  6535. return QualType();
  6536. }
  6537. QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
  6538. bool OfBlockPointer,
  6539. bool Unqualified, bool BlockReturnType) {
  6540. // C++ [expr]: If an expression initially has the type "reference to T", the
  6541. // type is adjusted to "T" prior to any further analysis, the expression
  6542. // designates the object or function denoted by the reference, and the
  6543. // expression is an lvalue unless the reference is an rvalue reference and
  6544. // the expression is a function call (possibly inside parentheses).
  6545. assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
  6546. assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
  6547. if (Unqualified) {
  6548. LHS = LHS.getUnqualifiedType();
  6549. RHS = RHS.getUnqualifiedType();
  6550. }
  6551. QualType LHSCan = getCanonicalType(LHS),
  6552. RHSCan = getCanonicalType(RHS);
  6553. // If two types are identical, they are compatible.
  6554. if (LHSCan == RHSCan)
  6555. return LHS;
  6556. // If the qualifiers are different, the types aren't compatible... mostly.
  6557. Qualifiers LQuals = LHSCan.getLocalQualifiers();
  6558. Qualifiers RQuals = RHSCan.getLocalQualifiers();
  6559. if (LQuals != RQuals) {
  6560. // If any of these qualifiers are different, we have a type
  6561. // mismatch.
  6562. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
  6563. LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
  6564. LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
  6565. return QualType();
  6566. // Exactly one GC qualifier difference is allowed: __strong is
  6567. // okay if the other type has no GC qualifier but is an Objective
  6568. // C object pointer (i.e. implicitly strong by default). We fix
  6569. // this by pretending that the unqualified type was actually
  6570. // qualified __strong.
  6571. Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
  6572. Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
  6573. assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
  6574. if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
  6575. return QualType();
  6576. if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
  6577. return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
  6578. }
  6579. if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
  6580. return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
  6581. }
  6582. return QualType();
  6583. }
  6584. // Okay, qualifiers are equal.
  6585. Type::TypeClass LHSClass = LHSCan->getTypeClass();
  6586. Type::TypeClass RHSClass = RHSCan->getTypeClass();
  6587. // We want to consider the two function types to be the same for these
  6588. // comparisons, just force one to the other.
  6589. if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
  6590. if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
  6591. // Same as above for arrays
  6592. if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
  6593. LHSClass = Type::ConstantArray;
  6594. if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
  6595. RHSClass = Type::ConstantArray;
  6596. // ObjCInterfaces are just specialized ObjCObjects.
  6597. if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
  6598. if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
  6599. // Canonicalize ExtVector -> Vector.
  6600. if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
  6601. if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
  6602. // If the canonical type classes don't match.
  6603. if (LHSClass != RHSClass) {
  6604. // Note that we only have special rules for turning block enum
  6605. // returns into block int returns, not vice-versa.
  6606. if (const EnumType* ETy = LHS->getAs<EnumType>()) {
  6607. return mergeEnumWithInteger(*this, ETy, RHS, false);
  6608. }
  6609. if (const EnumType* ETy = RHS->getAs<EnumType>()) {
  6610. return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
  6611. }
  6612. // allow block pointer type to match an 'id' type.
  6613. if (OfBlockPointer && !BlockReturnType) {
  6614. if (LHS->isObjCIdType() && RHS->isBlockPointerType())
  6615. return LHS;
  6616. if (RHS->isObjCIdType() && LHS->isBlockPointerType())
  6617. return RHS;
  6618. }
  6619. return QualType();
  6620. }
  6621. // The canonical type classes match.
  6622. switch (LHSClass) {
  6623. #define TYPE(Class, Base)
  6624. #define ABSTRACT_TYPE(Class, Base)
  6625. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  6626. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  6627. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  6628. #include "clang/AST/TypeNodes.def"
  6629. llvm_unreachable("Non-canonical and dependent types shouldn't get here");
  6630. case Type::Auto:
  6631. case Type::LValueReference:
  6632. case Type::RValueReference:
  6633. case Type::MemberPointer:
  6634. llvm_unreachable("C++ should never be in mergeTypes");
  6635. case Type::ObjCInterface:
  6636. case Type::IncompleteArray:
  6637. case Type::VariableArray:
  6638. case Type::FunctionProto:
  6639. case Type::ExtVector:
  6640. llvm_unreachable("Types are eliminated above");
  6641. case Type::Pointer:
  6642. {
  6643. // Merge two pointer types, while trying to preserve typedef info
  6644. QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
  6645. QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
  6646. if (Unqualified) {
  6647. LHSPointee = LHSPointee.getUnqualifiedType();
  6648. RHSPointee = RHSPointee.getUnqualifiedType();
  6649. }
  6650. QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
  6651. Unqualified);
  6652. if (ResultType.isNull()) return QualType();
  6653. if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
  6654. return LHS;
  6655. if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
  6656. return RHS;
  6657. return getPointerType(ResultType);
  6658. }
  6659. case Type::BlockPointer:
  6660. {
  6661. // Merge two block pointer types, while trying to preserve typedef info
  6662. QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
  6663. QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
  6664. if (Unqualified) {
  6665. LHSPointee = LHSPointee.getUnqualifiedType();
  6666. RHSPointee = RHSPointee.getUnqualifiedType();
  6667. }
  6668. QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
  6669. Unqualified);
  6670. if (ResultType.isNull()) return QualType();
  6671. if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
  6672. return LHS;
  6673. if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
  6674. return RHS;
  6675. return getBlockPointerType(ResultType);
  6676. }
  6677. case Type::Atomic:
  6678. {
  6679. // Merge two pointer types, while trying to preserve typedef info
  6680. QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
  6681. QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
  6682. if (Unqualified) {
  6683. LHSValue = LHSValue.getUnqualifiedType();
  6684. RHSValue = RHSValue.getUnqualifiedType();
  6685. }
  6686. QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
  6687. Unqualified);
  6688. if (ResultType.isNull()) return QualType();
  6689. if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
  6690. return LHS;
  6691. if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
  6692. return RHS;
  6693. return getAtomicType(ResultType);
  6694. }
  6695. case Type::ConstantArray:
  6696. {
  6697. const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
  6698. const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
  6699. if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
  6700. return QualType();
  6701. QualType LHSElem = getAsArrayType(LHS)->getElementType();
  6702. QualType RHSElem = getAsArrayType(RHS)->getElementType();
  6703. if (Unqualified) {
  6704. LHSElem = LHSElem.getUnqualifiedType();
  6705. RHSElem = RHSElem.getUnqualifiedType();
  6706. }
  6707. QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
  6708. if (ResultType.isNull()) return QualType();
  6709. if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
  6710. return LHS;
  6711. if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
  6712. return RHS;
  6713. if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
  6714. ArrayType::ArraySizeModifier(), 0);
  6715. if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
  6716. ArrayType::ArraySizeModifier(), 0);
  6717. const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
  6718. const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
  6719. if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
  6720. return LHS;
  6721. if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
  6722. return RHS;
  6723. if (LVAT) {
  6724. // FIXME: This isn't correct! But tricky to implement because
  6725. // the array's size has to be the size of LHS, but the type
  6726. // has to be different.
  6727. return LHS;
  6728. }
  6729. if (RVAT) {
  6730. // FIXME: This isn't correct! But tricky to implement because
  6731. // the array's size has to be the size of RHS, but the type
  6732. // has to be different.
  6733. return RHS;
  6734. }
  6735. if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
  6736. if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
  6737. return getIncompleteArrayType(ResultType,
  6738. ArrayType::ArraySizeModifier(), 0);
  6739. }
  6740. case Type::FunctionNoProto:
  6741. return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
  6742. case Type::Record:
  6743. case Type::Enum:
  6744. return QualType();
  6745. case Type::Builtin:
  6746. // Only exactly equal builtin types are compatible, which is tested above.
  6747. return QualType();
  6748. case Type::Complex:
  6749. // Distinct complex types are incompatible.
  6750. return QualType();
  6751. case Type::Vector:
  6752. // FIXME: The merged type should be an ExtVector!
  6753. if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
  6754. RHSCan->getAs<VectorType>()))
  6755. return LHS;
  6756. return QualType();
  6757. case Type::ObjCObject: {
  6758. // Check if the types are assignment compatible.
  6759. // FIXME: This should be type compatibility, e.g. whether
  6760. // "LHS x; RHS x;" at global scope is legal.
  6761. const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
  6762. const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
  6763. if (canAssignObjCInterfaces(LHSIface, RHSIface))
  6764. return LHS;
  6765. return QualType();
  6766. }
  6767. case Type::ObjCObjectPointer: {
  6768. if (OfBlockPointer) {
  6769. if (canAssignObjCInterfacesInBlockPointer(
  6770. LHS->getAs<ObjCObjectPointerType>(),
  6771. RHS->getAs<ObjCObjectPointerType>(),
  6772. BlockReturnType))
  6773. return LHS;
  6774. return QualType();
  6775. }
  6776. if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
  6777. RHS->getAs<ObjCObjectPointerType>()))
  6778. return LHS;
  6779. return QualType();
  6780. }
  6781. }
  6782. llvm_unreachable("Invalid Type::Class!");
  6783. }
  6784. bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
  6785. const FunctionProtoType *FromFunctionType,
  6786. const FunctionProtoType *ToFunctionType) {
  6787. if (FromFunctionType->hasAnyConsumedParams() !=
  6788. ToFunctionType->hasAnyConsumedParams())
  6789. return false;
  6790. FunctionProtoType::ExtProtoInfo FromEPI =
  6791. FromFunctionType->getExtProtoInfo();
  6792. FunctionProtoType::ExtProtoInfo ToEPI =
  6793. ToFunctionType->getExtProtoInfo();
  6794. if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
  6795. for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
  6796. if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
  6797. return false;
  6798. }
  6799. return true;
  6800. }
  6801. /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
  6802. /// 'RHS' attributes and returns the merged version; including for function
  6803. /// return types.
  6804. QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
  6805. QualType LHSCan = getCanonicalType(LHS),
  6806. RHSCan = getCanonicalType(RHS);
  6807. // If two types are identical, they are compatible.
  6808. if (LHSCan == RHSCan)
  6809. return LHS;
  6810. if (RHSCan->isFunctionType()) {
  6811. if (!LHSCan->isFunctionType())
  6812. return QualType();
  6813. QualType OldReturnType =
  6814. cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
  6815. QualType NewReturnType =
  6816. cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
  6817. QualType ResReturnType =
  6818. mergeObjCGCQualifiers(NewReturnType, OldReturnType);
  6819. if (ResReturnType.isNull())
  6820. return QualType();
  6821. if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
  6822. // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
  6823. // In either case, use OldReturnType to build the new function type.
  6824. const FunctionType *F = LHS->getAs<FunctionType>();
  6825. if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
  6826. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  6827. EPI.ExtInfo = getFunctionExtInfo(LHS);
  6828. QualType ResultType =
  6829. getFunctionType(OldReturnType, FPT->getParamTypes(), EPI, ArrayRef<hlsl::ParameterModifier>()); // HLSL Change
  6830. return ResultType;
  6831. }
  6832. }
  6833. return QualType();
  6834. }
  6835. // If the qualifiers are different, the types can still be merged.
  6836. Qualifiers LQuals = LHSCan.getLocalQualifiers();
  6837. Qualifiers RQuals = RHSCan.getLocalQualifiers();
  6838. if (LQuals != RQuals) {
  6839. // If any of these qualifiers are different, we have a type mismatch.
  6840. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
  6841. LQuals.getAddressSpace() != RQuals.getAddressSpace())
  6842. return QualType();
  6843. // Exactly one GC qualifier difference is allowed: __strong is
  6844. // okay if the other type has no GC qualifier but is an Objective
  6845. // C object pointer (i.e. implicitly strong by default). We fix
  6846. // this by pretending that the unqualified type was actually
  6847. // qualified __strong.
  6848. Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
  6849. Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
  6850. assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
  6851. if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
  6852. return QualType();
  6853. if (GC_L == Qualifiers::Strong)
  6854. return LHS;
  6855. if (GC_R == Qualifiers::Strong)
  6856. return RHS;
  6857. return QualType();
  6858. }
  6859. if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
  6860. QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
  6861. QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
  6862. QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
  6863. if (ResQT == LHSBaseQT)
  6864. return LHS;
  6865. if (ResQT == RHSBaseQT)
  6866. return RHS;
  6867. }
  6868. return QualType();
  6869. }
  6870. //===----------------------------------------------------------------------===//
  6871. // Integer Predicates
  6872. //===----------------------------------------------------------------------===//
  6873. unsigned ASTContext::getIntWidth(QualType T) const {
  6874. if (const EnumType *ET = T->getAs<EnumType>())
  6875. T = ET->getDecl()->getIntegerType();
  6876. if (T->isBooleanType())
  6877. return 1;
  6878. // For builtin types, just use the standard type sizing method
  6879. return (unsigned)getTypeSize(T);
  6880. }
  6881. QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
  6882. assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
  6883. // Turn <4 x signed int> -> <4 x unsigned int>
  6884. if (const VectorType *VTy = T->getAs<VectorType>())
  6885. return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
  6886. VTy->getNumElements(), VTy->getVectorKind());
  6887. // For enums, we return the unsigned version of the base type.
  6888. if (const EnumType *ETy = T->getAs<EnumType>())
  6889. T = ETy->getDecl()->getIntegerType();
  6890. const BuiltinType *BTy = T->getAs<BuiltinType>();
  6891. assert(BTy && "Unexpected signed integer type");
  6892. switch (BTy->getKind()) {
  6893. case BuiltinType::Char_S:
  6894. case BuiltinType::SChar:
  6895. return UnsignedCharTy;
  6896. case BuiltinType::Short:
  6897. return UnsignedShortTy;
  6898. case BuiltinType::Int:
  6899. return UnsignedIntTy;
  6900. case BuiltinType::Long:
  6901. return UnsignedLongTy;
  6902. case BuiltinType::LongLong:
  6903. return UnsignedLongLongTy;
  6904. case BuiltinType::Int128:
  6905. return UnsignedInt128Ty;
  6906. case BuiltinType::LitInt: // HLSL Change
  6907. return UnsignedIntTy;
  6908. default:
  6909. llvm_unreachable("Unexpected signed integer type");
  6910. }
  6911. }
  6912. ASTMutationListener::~ASTMutationListener() { }
  6913. void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
  6914. QualType ReturnType) {}
  6915. //===----------------------------------------------------------------------===//
  6916. // Builtin Type Computation
  6917. //===----------------------------------------------------------------------===//
  6918. /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
  6919. /// pointer over the consumed characters. This returns the resultant type. If
  6920. /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
  6921. /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
  6922. /// a vector of "i*".
  6923. ///
  6924. /// RequiresICE is filled in on return to indicate whether the value is required
  6925. /// to be an Integer Constant Expression.
  6926. static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
  6927. ASTContext::GetBuiltinTypeError &Error,
  6928. bool &RequiresICE,
  6929. bool AllowTypeModifiers) {
  6930. // Modifiers.
  6931. int HowLong = 0;
  6932. bool Signed = false, Unsigned = false;
  6933. RequiresICE = false;
  6934. // Read the prefixed modifiers first.
  6935. bool Done = false;
  6936. while (!Done) {
  6937. switch (*Str++) {
  6938. default: Done = true; --Str; break;
  6939. case 'I':
  6940. RequiresICE = true;
  6941. break;
  6942. case 'S':
  6943. assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
  6944. assert(!Signed && "Can't use 'S' modifier multiple times!");
  6945. Signed = true;
  6946. break;
  6947. case 'U':
  6948. assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
  6949. assert(!Unsigned && "Can't use 'U' modifier multiple times!");
  6950. Unsigned = true;
  6951. break;
  6952. case 'L':
  6953. assert(HowLong <= 2 && "Can't have LLLL modifier");
  6954. ++HowLong;
  6955. break;
  6956. case 'W':
  6957. // This modifier represents int64 type.
  6958. assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
  6959. switch (Context.getTargetInfo().getInt64Type()) {
  6960. default:
  6961. llvm_unreachable("Unexpected integer type");
  6962. case TargetInfo::SignedLong:
  6963. HowLong = 1;
  6964. break;
  6965. case TargetInfo::SignedLongLong:
  6966. HowLong = 2;
  6967. break;
  6968. }
  6969. }
  6970. }
  6971. QualType Type;
  6972. // Read the base type.
  6973. switch (*Str++) {
  6974. default: llvm_unreachable("Unknown builtin type letter!");
  6975. case 'v':
  6976. assert(HowLong == 0 && !Signed && !Unsigned &&
  6977. "Bad modifiers used with 'v'!");
  6978. Type = Context.VoidTy;
  6979. break;
  6980. case 'h':
  6981. assert(HowLong == 0 && !Signed && !Unsigned &&
  6982. "Bad modifiers used with 'h'!");
  6983. Type = Context.HalfTy;
  6984. break;
  6985. case 'f':
  6986. assert(HowLong == 0 && !Signed && !Unsigned &&
  6987. "Bad modifiers used with 'f'!");
  6988. Type = Context.FloatTy;
  6989. break;
  6990. case 'd':
  6991. assert(HowLong < 2 && !Signed && !Unsigned &&
  6992. "Bad modifiers used with 'd'!");
  6993. if (HowLong)
  6994. Type = Context.LongDoubleTy;
  6995. else
  6996. Type = Context.DoubleTy;
  6997. break;
  6998. case 's':
  6999. assert(HowLong == 0 && "Bad modifiers used with 's'!");
  7000. if (Unsigned)
  7001. Type = Context.UnsignedShortTy;
  7002. else
  7003. Type = Context.ShortTy;
  7004. break;
  7005. case 'i':
  7006. if (HowLong == 3)
  7007. Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
  7008. else if (HowLong == 2)
  7009. Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
  7010. else if (HowLong == 1)
  7011. Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
  7012. else
  7013. Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
  7014. break;
  7015. case 'c':
  7016. assert(HowLong == 0 && "Bad modifiers used with 'c'!");
  7017. if (Signed)
  7018. Type = Context.SignedCharTy;
  7019. else if (Unsigned)
  7020. Type = Context.UnsignedCharTy;
  7021. else
  7022. Type = Context.CharTy;
  7023. break;
  7024. case 'b': // boolean
  7025. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
  7026. Type = Context.BoolTy;
  7027. break;
  7028. case 'z': // size_t.
  7029. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
  7030. Type = Context.getSizeType();
  7031. break;
  7032. case 'F':
  7033. Type = Context.getCFConstantStringType();
  7034. break;
  7035. case 'G':
  7036. Type = Context.getObjCIdType();
  7037. break;
  7038. case 'H':
  7039. Type = Context.getObjCSelType();
  7040. break;
  7041. case 'M':
  7042. Type = Context.getObjCSuperType();
  7043. break;
  7044. case 'a':
  7045. Type = Context.getBuiltinVaListType();
  7046. assert(!Type.isNull() && "builtin va list type not initialized!");
  7047. break;
  7048. case 'A':
  7049. // This is a "reference" to a va_list; however, what exactly
  7050. // this means depends on how va_list is defined. There are two
  7051. // different kinds of va_list: ones passed by value, and ones
  7052. // passed by reference. An example of a by-value va_list is
  7053. // x86, where va_list is a char*. An example of by-ref va_list
  7054. // is x86-64, where va_list is a __va_list_tag[1]. For x86,
  7055. // we want this argument to be a char*&; for x86-64, we want
  7056. // it to be a __va_list_tag*.
  7057. Type = Context.getBuiltinVaListType();
  7058. assert(!Type.isNull() && "builtin va list type not initialized!");
  7059. if (Type->isArrayType())
  7060. Type = Context.getArrayDecayedType(Type);
  7061. else
  7062. Type = Context.getLValueReferenceType(Type);
  7063. break;
  7064. case 'V': {
  7065. char *End;
  7066. unsigned NumElements = strtoul(Str, &End, 10);
  7067. assert(End != Str && "Missing vector size");
  7068. Str = End;
  7069. QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
  7070. RequiresICE, false);
  7071. assert(!RequiresICE && "Can't require vector ICE");
  7072. // TODO: No way to make AltiVec vectors in builtins yet.
  7073. Type = Context.getVectorType(ElementType, NumElements,
  7074. VectorType::GenericVector);
  7075. break;
  7076. }
  7077. case 'E': {
  7078. char *End;
  7079. unsigned NumElements = strtoul(Str, &End, 10);
  7080. assert(End != Str && "Missing vector size");
  7081. Str = End;
  7082. QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
  7083. false);
  7084. Type = Context.getExtVectorType(ElementType, NumElements);
  7085. break;
  7086. }
  7087. case 'X': {
  7088. QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
  7089. false);
  7090. assert(!RequiresICE && "Can't require complex ICE");
  7091. Type = Context.getComplexType(ElementType);
  7092. break;
  7093. }
  7094. case 'Y' : {
  7095. Type = Context.getPointerDiffType();
  7096. break;
  7097. }
  7098. case 'P':
  7099. Type = Context.getFILEType();
  7100. if (Type.isNull()) {
  7101. Error = ASTContext::GE_Missing_stdio;
  7102. return QualType();
  7103. }
  7104. break;
  7105. case 'J':
  7106. if (Signed)
  7107. Type = Context.getsigjmp_bufType();
  7108. else
  7109. Type = Context.getjmp_bufType();
  7110. if (Type.isNull()) {
  7111. Error = ASTContext::GE_Missing_setjmp;
  7112. return QualType();
  7113. }
  7114. break;
  7115. case 'K':
  7116. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
  7117. Type = Context.getucontext_tType();
  7118. if (Type.isNull()) {
  7119. Error = ASTContext::GE_Missing_ucontext;
  7120. return QualType();
  7121. }
  7122. break;
  7123. case 'p':
  7124. Type = Context.getProcessIDType();
  7125. break;
  7126. }
  7127. // If there are modifiers and if we're allowed to parse them, go for it.
  7128. Done = !AllowTypeModifiers;
  7129. while (!Done) {
  7130. switch (char c = *Str++) {
  7131. default: Done = true; --Str; break;
  7132. case '*':
  7133. case '&': {
  7134. // Both pointers and references can have their pointee types
  7135. // qualified with an address space.
  7136. char *End;
  7137. unsigned AddrSpace = strtoul(Str, &End, 10);
  7138. if (End != Str && AddrSpace != 0) {
  7139. Type = Context.getAddrSpaceQualType(Type, AddrSpace);
  7140. Str = End;
  7141. }
  7142. if (c == '*')
  7143. Type = Context.getPointerType(Type);
  7144. else
  7145. Type = Context.getLValueReferenceType(Type);
  7146. break;
  7147. }
  7148. // FIXME: There's no way to have a built-in with an rvalue ref arg.
  7149. case 'C':
  7150. Type = Type.withConst();
  7151. break;
  7152. case 'D':
  7153. Type = Context.getVolatileType(Type);
  7154. break;
  7155. case 'R':
  7156. Type = Type.withRestrict();
  7157. break;
  7158. }
  7159. }
  7160. assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
  7161. "Integer constant 'I' type must be an integer");
  7162. return Type;
  7163. }
  7164. /// GetBuiltinType - Return the type for the specified builtin.
  7165. QualType ASTContext::GetBuiltinType(unsigned Id,
  7166. GetBuiltinTypeError &Error,
  7167. unsigned *IntegerConstantArgs) const {
  7168. const char *TypeStr = BuiltinInfo.GetTypeString(Id);
  7169. SmallVector<QualType, 8> ArgTypes;
  7170. bool RequiresICE = false;
  7171. Error = GE_None;
  7172. QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
  7173. RequiresICE, true);
  7174. if (Error != GE_None)
  7175. return QualType();
  7176. assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
  7177. while (TypeStr[0] && TypeStr[0] != '.') {
  7178. QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
  7179. if (Error != GE_None)
  7180. return QualType();
  7181. // If this argument is required to be an IntegerConstantExpression and the
  7182. // caller cares, fill in the bitmask we return.
  7183. if (RequiresICE && IntegerConstantArgs)
  7184. *IntegerConstantArgs |= 1 << ArgTypes.size();
  7185. // Do array -> pointer decay. The builtin should use the decayed type.
  7186. if (Ty->isArrayType())
  7187. Ty = getArrayDecayedType(Ty);
  7188. ArgTypes.push_back(Ty);
  7189. }
  7190. if (Id == Builtin::BI__GetExceptionInfo)
  7191. return QualType();
  7192. assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
  7193. "'.' should only occur at end of builtin type list!");
  7194. FunctionType::ExtInfo EI(CC_C);
  7195. if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
  7196. bool Variadic = (TypeStr[0] == '.');
  7197. // We really shouldn't be making a no-proto type here, especially in C++.
  7198. if (ArgTypes.empty() && Variadic)
  7199. return getFunctionNoProtoType(ResType, EI);
  7200. FunctionProtoType::ExtProtoInfo EPI;
  7201. EPI.ExtInfo = EI;
  7202. EPI.Variadic = Variadic;
  7203. // HLSL Change: add empty parameter modifier; but this should probably be removed altogether
  7204. return getFunctionType(ResType, ArgTypes, EPI, ArrayRef<hlsl::ParameterModifier>());
  7205. }
  7206. static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
  7207. const FunctionDecl *FD) {
  7208. if (!FD->isExternallyVisible())
  7209. return GVA_Internal;
  7210. GVALinkage External = GVA_StrongExternal;
  7211. switch (FD->getTemplateSpecializationKind()) {
  7212. case TSK_Undeclared:
  7213. case TSK_ExplicitSpecialization:
  7214. External = GVA_StrongExternal;
  7215. break;
  7216. case TSK_ExplicitInstantiationDefinition:
  7217. return GVA_StrongODR;
  7218. // C++11 [temp.explicit]p10:
  7219. // [ Note: The intent is that an inline function that is the subject of
  7220. // an explicit instantiation declaration will still be implicitly
  7221. // instantiated when used so that the body can be considered for
  7222. // inlining, but that no out-of-line copy of the inline function would be
  7223. // generated in the translation unit. -- end note ]
  7224. case TSK_ExplicitInstantiationDeclaration:
  7225. return GVA_AvailableExternally;
  7226. case TSK_ImplicitInstantiation:
  7227. External = GVA_DiscardableODR;
  7228. break;
  7229. }
  7230. if (!FD->isInlined())
  7231. return External;
  7232. if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
  7233. !FD->hasAttr<DLLExportAttr>()) ||
  7234. FD->hasAttr<GNUInlineAttr>()) {
  7235. // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
  7236. // GNU or C99 inline semantics. Determine whether this symbol should be
  7237. // externally visible.
  7238. if (FD->isInlineDefinitionExternallyVisible())
  7239. return External;
  7240. // C99 inline semantics, where the symbol is not externally visible.
  7241. return GVA_AvailableExternally;
  7242. }
  7243. // Functions specified with extern and inline in -fms-compatibility mode
  7244. // forcibly get emitted. While the body of the function cannot be later
  7245. // replaced, the function definition cannot be discarded.
  7246. if (FD->isMSExternInline())
  7247. return GVA_StrongODR;
  7248. return GVA_DiscardableODR;
  7249. }
  7250. static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
  7251. // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
  7252. // dllexport/dllimport on inline functions.
  7253. if (D->hasAttr<DLLImportAttr>()) {
  7254. if (L == GVA_DiscardableODR || L == GVA_StrongODR)
  7255. return GVA_AvailableExternally;
  7256. } else if (D->hasAttr<DLLExportAttr>()) {
  7257. if (L == GVA_DiscardableODR)
  7258. return GVA_StrongODR;
  7259. }
  7260. return L;
  7261. }
  7262. GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
  7263. return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
  7264. FD);
  7265. }
  7266. static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
  7267. const VarDecl *VD) {
  7268. if (!VD->isExternallyVisible())
  7269. return GVA_Internal;
  7270. // HLSL Change Starts - samplers, textures and UAVs should be removed if
  7271. // unused, and fit an 'available externally' model.
  7272. if (hlsl::DXIL::ResourceClass::Invalid !=
  7273. hlsl::GetResourceClassForType(Context, VD->getType())) {
  7274. return GVA_AvailableExternally;
  7275. }
  7276. // HLSL Change Ends
  7277. if (VD->isStaticLocal()) {
  7278. GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
  7279. const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
  7280. while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
  7281. LexicalContext = LexicalContext->getLexicalParent();
  7282. // Let the static local variable inherit its linkage from the nearest
  7283. // enclosing function.
  7284. if (LexicalContext)
  7285. StaticLocalLinkage =
  7286. Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
  7287. // GVA_StrongODR function linkage is stronger than what we need,
  7288. // downgrade to GVA_DiscardableODR.
  7289. // This allows us to discard the variable if we never end up needing it.
  7290. return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
  7291. : StaticLocalLinkage;
  7292. }
  7293. // MSVC treats in-class initialized static data members as definitions.
  7294. // By giving them non-strong linkage, out-of-line definitions won't
  7295. // cause link errors.
  7296. if (Context.isMSStaticDataMemberInlineDefinition(VD))
  7297. return GVA_DiscardableODR;
  7298. switch (VD->getTemplateSpecializationKind()) {
  7299. case TSK_Undeclared:
  7300. case TSK_ExplicitSpecialization:
  7301. return GVA_StrongExternal;
  7302. case TSK_ExplicitInstantiationDefinition:
  7303. return GVA_StrongODR;
  7304. case TSK_ExplicitInstantiationDeclaration:
  7305. return GVA_AvailableExternally;
  7306. case TSK_ImplicitInstantiation:
  7307. return GVA_DiscardableODR;
  7308. }
  7309. llvm_unreachable("Invalid Linkage!");
  7310. }
  7311. GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
  7312. return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
  7313. VD);
  7314. }
  7315. bool ASTContext::DeclMustBeEmitted(const Decl *D) {
  7316. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  7317. if (!VD->isFileVarDecl())
  7318. return false;
  7319. // Global named register variables (GNU extension) are never emitted.
  7320. if (VD->getStorageClass() == SC_Register)
  7321. return false;
  7322. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  7323. // We never need to emit an uninstantiated function template.
  7324. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  7325. return false;
  7326. } else if (isa<OMPThreadPrivateDecl>(D))
  7327. return true;
  7328. else
  7329. return false;
  7330. // If this is a member of a class template, we do not need to emit it.
  7331. if (D->getDeclContext()->isDependentContext())
  7332. return false;
  7333. // Weak references don't produce any output by themselves.
  7334. if (D->hasAttr<WeakRefAttr>())
  7335. return false;
  7336. // Aliases and used decls are required.
  7337. if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
  7338. return true;
  7339. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  7340. // Forward declarations aren't required.
  7341. if (!FD->doesThisDeclarationHaveABody())
  7342. return FD->doesDeclarationForceExternallyVisibleDefinition();
  7343. // Constructors and destructors are required.
  7344. if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
  7345. return true;
  7346. // The key function for a class is required. This rule only comes
  7347. // into play when inline functions can be key functions, though.
  7348. if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  7349. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  7350. const CXXRecordDecl *RD = MD->getParent();
  7351. if (MD->isOutOfLine() && RD->isDynamicClass()) {
  7352. const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
  7353. if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
  7354. return true;
  7355. }
  7356. }
  7357. }
  7358. GVALinkage Linkage = GetGVALinkageForFunction(FD);
  7359. // static, static inline, always_inline, and extern inline functions can
  7360. // always be deferred. Normal inline functions can be deferred in C99/C++.
  7361. // Implicit template instantiations can also be deferred in C++.
  7362. if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
  7363. Linkage == GVA_DiscardableODR)
  7364. return false;
  7365. // HLSL Change Starts
  7366. // Don't just return true because of visibility, unless building a library
  7367. return FD->getName() == getLangOpts().HLSLEntryFunction ||
  7368. IsPatchConstantFunctionDecl(FD) || getLangOpts().IsHLSLLibrary;
  7369. // HLSL Change Ends
  7370. }
  7371. const VarDecl *VD = cast<VarDecl>(D);
  7372. assert(VD->isFileVarDecl() && "Expected file scoped var");
  7373. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
  7374. !isMSStaticDataMemberInlineDefinition(VD))
  7375. return false;
  7376. // Variables that can be needed in other TUs are required.
  7377. GVALinkage L = GetGVALinkageForVariable(VD);
  7378. if (L != GVA_Internal && L != GVA_AvailableExternally &&
  7379. L != GVA_DiscardableODR)
  7380. return true;
  7381. // Variables that have destruction with side-effects are required.
  7382. if (VD->getType().isDestructedType())
  7383. return true;
  7384. // Variables that have initialization with side-effects are required.
  7385. if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
  7386. return true;
  7387. return false;
  7388. }
  7389. CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
  7390. bool IsCXXMethod) const {
  7391. // Pass through to the C++ ABI object
  7392. if (IsCXXMethod)
  7393. return ABI->getDefaultMethodCallConv(IsVariadic);
  7394. if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
  7395. return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
  7396. }
  7397. bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
  7398. // Pass through to the C++ ABI object
  7399. return ABI->isNearlyEmpty(RD);
  7400. }
  7401. VTableContextBase *ASTContext::getVTableContext() {
  7402. if (!VTContext.get()) {
  7403. if (Target->getCXXABI().isMicrosoft())
  7404. VTContext.reset(new MicrosoftVTableContext(*this));
  7405. else
  7406. VTContext.reset(new ItaniumVTableContext(*this));
  7407. }
  7408. return VTContext.get();
  7409. }
  7410. MangleContext *ASTContext::createMangleContext() {
  7411. switch (Target->getCXXABI().getKind()) {
  7412. case TargetCXXABI::GenericAArch64:
  7413. case TargetCXXABI::GenericItanium:
  7414. case TargetCXXABI::GenericARM:
  7415. case TargetCXXABI::GenericMIPS:
  7416. case TargetCXXABI::iOS:
  7417. case TargetCXXABI::iOS64:
  7418. return ItaniumMangleContext::create(*this, getDiagnostics());
  7419. case TargetCXXABI::Microsoft:
  7420. return MicrosoftMangleContext::create(*this, getDiagnostics());
  7421. }
  7422. llvm_unreachable("Unsupported ABI");
  7423. }
  7424. CXXABI::~CXXABI() {}
  7425. size_t ASTContext::getSideTableAllocatedMemory() const {
  7426. return ASTRecordLayouts.getMemorySize() +
  7427. llvm::capacity_in_bytes(ObjCLayouts) +
  7428. llvm::capacity_in_bytes(KeyFunctions) +
  7429. llvm::capacity_in_bytes(ObjCImpls) +
  7430. llvm::capacity_in_bytes(BlockVarCopyInits) +
  7431. llvm::capacity_in_bytes(DeclAttrs) +
  7432. llvm::capacity_in_bytes(TemplateOrInstantiation) +
  7433. llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
  7434. llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
  7435. llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
  7436. llvm::capacity_in_bytes(OverriddenMethods) +
  7437. llvm::capacity_in_bytes(Types) +
  7438. llvm::capacity_in_bytes(VariableArrayTypes) +
  7439. llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
  7440. }
  7441. /// getIntTypeForBitwidth -
  7442. /// sets integer QualTy according to specified details:
  7443. /// bitwidth, signed/unsigned.
  7444. /// Returns empty type if there is no appropriate target types.
  7445. QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
  7446. unsigned Signed) const {
  7447. TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
  7448. CanQualType QualTy = getFromTargetType(Ty);
  7449. if (!QualTy && DestWidth == 128)
  7450. return Signed ? Int128Ty : UnsignedInt128Ty;
  7451. return QualTy;
  7452. }
  7453. /// getRealTypeForBitwidth -
  7454. /// sets floating point QualTy according to specified bitwidth.
  7455. /// Returns empty type if there is no appropriate target types.
  7456. QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
  7457. TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
  7458. switch (Ty) {
  7459. case TargetInfo::Float:
  7460. return FloatTy;
  7461. case TargetInfo::Double:
  7462. return DoubleTy;
  7463. case TargetInfo::LongDouble:
  7464. return LongDoubleTy;
  7465. case TargetInfo::NoFloat:
  7466. return QualType();
  7467. }
  7468. llvm_unreachable("Unhandled TargetInfo::RealType value");
  7469. }
  7470. void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
  7471. if (Number > 1)
  7472. MangleNumbers[ND] = Number;
  7473. }
  7474. unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
  7475. llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
  7476. MangleNumbers.find(ND);
  7477. return I != MangleNumbers.end() ? I->second : 1;
  7478. }
  7479. void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
  7480. if (Number > 1)
  7481. StaticLocalNumbers[VD] = Number;
  7482. }
  7483. unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
  7484. llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
  7485. StaticLocalNumbers.find(VD);
  7486. return I != StaticLocalNumbers.end() ? I->second : 1;
  7487. }
  7488. MangleNumberingContext &
  7489. ASTContext::getManglingNumberContext(const DeclContext *DC) {
  7490. assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
  7491. MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
  7492. if (!MCtx)
  7493. MCtx = createMangleNumberingContext();
  7494. return *MCtx;
  7495. }
  7496. MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
  7497. return ABI->createMangleNumberingContext();
  7498. }
  7499. const CXXConstructorDecl *
  7500. ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
  7501. return ABI->getCopyConstructorForExceptionObject(
  7502. cast<CXXRecordDecl>(RD->getFirstDecl()));
  7503. }
  7504. void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
  7505. CXXConstructorDecl *CD) {
  7506. return ABI->addCopyConstructorForExceptionObject(
  7507. cast<CXXRecordDecl>(RD->getFirstDecl()),
  7508. cast<CXXConstructorDecl>(CD->getFirstDecl()));
  7509. }
  7510. void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
  7511. unsigned ParmIdx, Expr *DAE) {
  7512. ABI->addDefaultArgExprForConstructor(
  7513. cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
  7514. }
  7515. Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
  7516. unsigned ParmIdx) {
  7517. return ABI->getDefaultArgExprForConstructor(
  7518. cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
  7519. }
  7520. void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
  7521. ParamIndices[D] = index;
  7522. }
  7523. unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
  7524. ParameterIndexTable::const_iterator I = ParamIndices.find(D);
  7525. assert(I != ParamIndices.end() &&
  7526. "ParmIndices lacks entry set by ParmVarDecl");
  7527. return I->second;
  7528. }
  7529. APValue *
  7530. ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
  7531. bool MayCreate) {
  7532. assert(E && E->getStorageDuration() == SD_Static &&
  7533. "don't need to cache the computed value for this temporary");
  7534. if (MayCreate)
  7535. return &MaterializedTemporaryValues[E];
  7536. llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
  7537. MaterializedTemporaryValues.find(E);
  7538. return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
  7539. }
  7540. bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
  7541. const llvm::Triple &T = getTargetInfo().getTriple();
  7542. if (!T.isOSDarwin())
  7543. return false;
  7544. if (!(T.isiOS() && T.isOSVersionLT(7)) &&
  7545. !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
  7546. return false;
  7547. QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
  7548. CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
  7549. uint64_t Size = sizeChars.getQuantity();
  7550. CharUnits alignChars = getTypeAlignInChars(AtomicTy);
  7551. unsigned Align = alignChars.getQuantity();
  7552. unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
  7553. return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
  7554. }
  7555. namespace {
  7556. /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
  7557. /// parents as defined by the \c RecursiveASTVisitor.
  7558. ///
  7559. /// Note that the relationship described here is purely in terms of AST
  7560. /// traversal - there are other relationships (for example declaration context)
  7561. /// in the AST that are better modeled by special matchers.
  7562. ///
  7563. /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
  7564. class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
  7565. public:
  7566. /// \brief Builds and returns the translation unit's parent map.
  7567. ///
  7568. /// The caller takes ownership of the returned \c ParentMap.
  7569. static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
  7570. ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
  7571. Visitor.TraverseDecl(&TU);
  7572. return Visitor.Parents;
  7573. }
  7574. private:
  7575. typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
  7576. ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
  7577. }
  7578. bool shouldVisitTemplateInstantiations() const {
  7579. return true;
  7580. }
  7581. bool shouldVisitImplicitCode() const {
  7582. return true;
  7583. }
  7584. // Disables data recursion. We intercept Traverse* methods in the RAV, which
  7585. // are not triggered during data recursion.
  7586. bool shouldUseDataRecursionFor(clang::Stmt *S) const {
  7587. return false;
  7588. }
  7589. template <typename T>
  7590. bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
  7591. if (!Node)
  7592. return true;
  7593. if (ParentStack.size() > 0) {
  7594. // FIXME: Currently we add the same parent multiple times, but only
  7595. // when no memoization data is available for the type.
  7596. // For example when we visit all subexpressions of template
  7597. // instantiations; this is suboptimal, but benign: the only way to
  7598. // visit those is with hasAncestor / hasParent, and those do not create
  7599. // new matches.
  7600. // The plan is to enable DynTypedNode to be storable in a map or hash
  7601. // map. The main problem there is to implement hash functions /
  7602. // comparison operators for all types that DynTypedNode supports that
  7603. // do not have pointer identity.
  7604. auto &NodeOrVector = (*Parents)[Node];
  7605. if (NodeOrVector.isNull()) {
  7606. NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
  7607. } else {
  7608. if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
  7609. auto *Node =
  7610. NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
  7611. auto *Vector = new ASTContext::ParentVector(1, *Node);
  7612. NodeOrVector = Vector;
  7613. delete Node;
  7614. }
  7615. assert(NodeOrVector.template is<ASTContext::ParentVector *>());
  7616. auto *Vector =
  7617. NodeOrVector.template get<ASTContext::ParentVector *>();
  7618. // Skip duplicates for types that have memoization data.
  7619. // We must check that the type has memoization data before calling
  7620. // std::find() because DynTypedNode::operator== can't compare all
  7621. // types.
  7622. bool Found = ParentStack.back().getMemoizationData() &&
  7623. std::find(Vector->begin(), Vector->end(),
  7624. ParentStack.back()) != Vector->end();
  7625. if (!Found)
  7626. Vector->push_back(ParentStack.back());
  7627. }
  7628. }
  7629. ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
  7630. bool Result = (this ->* traverse) (Node);
  7631. ParentStack.pop_back();
  7632. return Result;
  7633. }
  7634. bool TraverseDecl(Decl *DeclNode) {
  7635. return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
  7636. }
  7637. bool TraverseStmt(Stmt *StmtNode) {
  7638. return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
  7639. }
  7640. ASTContext::ParentMap *Parents;
  7641. llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
  7642. friend class RecursiveASTVisitor<ParentMapASTVisitor>;
  7643. };
  7644. } // end namespace
  7645. ArrayRef<ast_type_traits::DynTypedNode>
  7646. ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
  7647. assert(Node.getMemoizationData() &&
  7648. "Invariant broken: only nodes that support memoization may be "
  7649. "used in the parent map.");
  7650. if (!AllParents) {
  7651. // We always need to run over the whole translation unit, as
  7652. // hasAncestor can escape any subtree.
  7653. AllParents.reset(
  7654. ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
  7655. }
  7656. ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
  7657. if (I == AllParents->end()) {
  7658. return None;
  7659. }
  7660. if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
  7661. return llvm::makeArrayRef(N, 1);
  7662. }
  7663. return *I->second.get<ParentVector *>();
  7664. }
  7665. bool
  7666. ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
  7667. const ObjCMethodDecl *MethodImpl) {
  7668. // No point trying to match an unavailable/deprecated mothod.
  7669. if (MethodDecl->hasAttr<UnavailableAttr>()
  7670. || MethodDecl->hasAttr<DeprecatedAttr>())
  7671. return false;
  7672. if (MethodDecl->getObjCDeclQualifier() !=
  7673. MethodImpl->getObjCDeclQualifier())
  7674. return false;
  7675. if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
  7676. return false;
  7677. if (MethodDecl->param_size() != MethodImpl->param_size())
  7678. return false;
  7679. for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
  7680. IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
  7681. EF = MethodDecl->param_end();
  7682. IM != EM && IF != EF; ++IM, ++IF) {
  7683. const ParmVarDecl *DeclVar = (*IF);
  7684. const ParmVarDecl *ImplVar = (*IM);
  7685. if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
  7686. return false;
  7687. if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
  7688. return false;
  7689. }
  7690. return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
  7691. }
  7692. // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
  7693. // doesn't include ASTContext.h
  7694. template
  7695. clang::LazyGenerationalUpdatePtr<
  7696. const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
  7697. clang::LazyGenerationalUpdatePtr<
  7698. const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
  7699. const clang::ASTContext &Ctx, Decl *Value);