SemaExpr.cpp 778 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984
  1. //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for expressions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TreeTransform.h"
  13. #include "UsedDeclVisitor.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/ASTMutationListener.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/EvaluatedExprVisitor.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/ExprObjC.h"
  25. #include "clang/AST/ExprOpenMP.h"
  26. #include "clang/AST/OperationKinds.h"
  27. #include "clang/AST/ParentMapContext.h"
  28. #include "clang/AST/RecursiveASTVisitor.h"
  29. #include "clang/AST/TypeLoc.h"
  30. #include "clang/Basic/Builtins.h"
  31. #include "clang/Basic/DiagnosticSema.h"
  32. #include "clang/Basic/PartialDiagnostic.h"
  33. #include "clang/Basic/SourceManager.h"
  34. #include "clang/Basic/TargetInfo.h"
  35. #include "clang/Lex/LiteralSupport.h"
  36. #include "clang/Lex/Preprocessor.h"
  37. #include "clang/Sema/AnalysisBasedWarnings.h"
  38. #include "clang/Sema/DeclSpec.h"
  39. #include "clang/Sema/DelayedDiagnostic.h"
  40. #include "clang/Sema/Designator.h"
  41. #include "clang/Sema/Initialization.h"
  42. #include "clang/Sema/Lookup.h"
  43. #include "clang/Sema/Overload.h"
  44. #include "clang/Sema/ParsedTemplate.h"
  45. #include "clang/Sema/Scope.h"
  46. #include "clang/Sema/ScopeInfo.h"
  47. #include "clang/Sema/SemaFixItUtils.h"
  48. #include "clang/Sema/SemaInternal.h"
  49. #include "clang/Sema/Template.h"
  50. #include "llvm/ADT/STLExtras.h"
  51. #include "llvm/ADT/StringExtras.h"
  52. #include "llvm/Support/ConvertUTF.h"
  53. #include "llvm/Support/SaveAndRestore.h"
  54. using namespace clang;
  55. using namespace sema;
  56. /// Determine whether the use of this declaration is valid, without
  57. /// emitting diagnostics.
  58. bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
  59. // See if this is an auto-typed variable whose initializer we are parsing.
  60. if (ParsingInitForAutoVars.count(D))
  61. return false;
  62. // See if this is a deleted function.
  63. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  64. if (FD->isDeleted())
  65. return false;
  66. // If the function has a deduced return type, and we can't deduce it,
  67. // then we can't use it either.
  68. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  69. DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
  70. return false;
  71. // See if this is an aligned allocation/deallocation function that is
  72. // unavailable.
  73. if (TreatUnavailableAsInvalid &&
  74. isUnavailableAlignedAllocationFunction(*FD))
  75. return false;
  76. }
  77. // See if this function is unavailable.
  78. if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
  79. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  80. return false;
  81. if (isa<UnresolvedUsingIfExistsDecl>(D))
  82. return false;
  83. return true;
  84. }
  85. static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  86. // Warn if this is used but marked unused.
  87. if (const auto *A = D->getAttr<UnusedAttr>()) {
  88. // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
  89. // should diagnose them.
  90. if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
  91. A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
  92. const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
  93. if (DC && !DC->hasAttr<UnusedAttr>())
  94. S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
  95. }
  96. }
  97. }
  98. /// Emit a note explaining that this function is deleted.
  99. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  100. assert(Decl && Decl->isDeleted());
  101. if (Decl->isDefaulted()) {
  102. // If the method was explicitly defaulted, point at that declaration.
  103. if (!Decl->isImplicit())
  104. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  105. // Try to diagnose why this special member function was implicitly
  106. // deleted. This might fail, if that reason no longer applies.
  107. DiagnoseDeletedDefaultedFunction(Decl);
  108. return;
  109. }
  110. auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
  111. if (Ctor && Ctor->isInheritingConstructor())
  112. return NoteDeletedInheritingConstructor(Ctor);
  113. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  114. << Decl << 1;
  115. }
  116. /// Determine whether a FunctionDecl was ever declared with an
  117. /// explicit storage class.
  118. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  119. for (auto I : D->redecls()) {
  120. if (I->getStorageClass() != SC_None)
  121. return true;
  122. }
  123. return false;
  124. }
  125. /// Check whether we're in an extern inline function and referring to a
  126. /// variable or function with internal linkage (C11 6.7.4p3).
  127. ///
  128. /// This is only a warning because we used to silently accept this code, but
  129. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  130. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  131. /// and so while there may still be user mistakes, most of the time we can't
  132. /// prove that there are errors.
  133. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  134. const NamedDecl *D,
  135. SourceLocation Loc) {
  136. // This is disabled under C++; there are too many ways for this to fire in
  137. // contexts where the warning is a false positive, or where it is technically
  138. // correct but benign.
  139. if (S.getLangOpts().CPlusPlus)
  140. return;
  141. // Check if this is an inlined function or method.
  142. FunctionDecl *Current = S.getCurFunctionDecl();
  143. if (!Current)
  144. return;
  145. if (!Current->isInlined())
  146. return;
  147. if (!Current->isExternallyVisible())
  148. return;
  149. // Check if the decl has internal linkage.
  150. if (D->getFormalLinkage() != InternalLinkage)
  151. return;
  152. // Downgrade from ExtWarn to Extension if
  153. // (1) the supposedly external inline function is in the main file,
  154. // and probably won't be included anywhere else.
  155. // (2) the thing we're referencing is a pure function.
  156. // (3) the thing we're referencing is another inline function.
  157. // This last can give us false negatives, but it's better than warning on
  158. // wrappers for simple C library functions.
  159. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  160. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  161. if (!DowngradeWarning && UsedFn)
  162. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  163. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  164. : diag::ext_internal_in_extern_inline)
  165. << /*IsVar=*/!UsedFn << D;
  166. S.MaybeSuggestAddingStaticToDecl(Current);
  167. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  168. << D;
  169. }
  170. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  171. const FunctionDecl *First = Cur->getFirstDecl();
  172. // Suggest "static" on the function, if possible.
  173. if (!hasAnyExplicitStorageClass(First)) {
  174. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  175. Diag(DeclBegin, diag::note_convert_inline_to_static)
  176. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  177. }
  178. }
  179. /// Determine whether the use of this declaration is valid, and
  180. /// emit any corresponding diagnostics.
  181. ///
  182. /// This routine diagnoses various problems with referencing
  183. /// declarations that can occur when using a declaration. For example,
  184. /// it might warn if a deprecated or unavailable declaration is being
  185. /// used, or produce an error (and return true) if a C++0x deleted
  186. /// function is being used.
  187. ///
  188. /// \returns true if there was an error (this declaration cannot be
  189. /// referenced), false otherwise.
  190. ///
  191. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
  192. const ObjCInterfaceDecl *UnknownObjCClass,
  193. bool ObjCPropertyAccess,
  194. bool AvoidPartialAvailabilityChecks,
  195. ObjCInterfaceDecl *ClassReceiver) {
  196. SourceLocation Loc = Locs.front();
  197. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  198. // If there were any diagnostics suppressed by template argument deduction,
  199. // emit them now.
  200. auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  201. if (Pos != SuppressedDiagnostics.end()) {
  202. for (const PartialDiagnosticAt &Suppressed : Pos->second)
  203. Diag(Suppressed.first, Suppressed.second);
  204. // Clear out the list of suppressed diagnostics, so that we don't emit
  205. // them again for this specialization. However, we don't obsolete this
  206. // entry from the table, because we want to avoid ever emitting these
  207. // diagnostics again.
  208. Pos->second.clear();
  209. }
  210. // C++ [basic.start.main]p3:
  211. // The function 'main' shall not be used within a program.
  212. if (cast<FunctionDecl>(D)->isMain())
  213. Diag(Loc, diag::ext_main_used);
  214. diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
  215. }
  216. // See if this is an auto-typed variable whose initializer we are parsing.
  217. if (ParsingInitForAutoVars.count(D)) {
  218. if (isa<BindingDecl>(D)) {
  219. Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
  220. << D->getDeclName();
  221. } else {
  222. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  223. << D->getDeclName() << cast<VarDecl>(D)->getType();
  224. }
  225. return true;
  226. }
  227. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  228. // See if this is a deleted function.
  229. if (FD->isDeleted()) {
  230. auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
  231. if (Ctor && Ctor->isInheritingConstructor())
  232. Diag(Loc, diag::err_deleted_inherited_ctor_use)
  233. << Ctor->getParent()
  234. << Ctor->getInheritedConstructor().getConstructor()->getParent();
  235. else
  236. Diag(Loc, diag::err_deleted_function_use);
  237. NoteDeletedFunction(FD);
  238. return true;
  239. }
  240. // [expr.prim.id]p4
  241. // A program that refers explicitly or implicitly to a function with a
  242. // trailing requires-clause whose constraint-expression is not satisfied,
  243. // other than to declare it, is ill-formed. [...]
  244. //
  245. // See if this is a function with constraints that need to be satisfied.
  246. // Check this before deducing the return type, as it might instantiate the
  247. // definition.
  248. if (FD->getTrailingRequiresClause()) {
  249. ConstraintSatisfaction Satisfaction;
  250. if (CheckFunctionConstraints(FD, Satisfaction, Loc))
  251. // A diagnostic will have already been generated (non-constant
  252. // constraint expression, for example)
  253. return true;
  254. if (!Satisfaction.IsSatisfied) {
  255. Diag(Loc,
  256. diag::err_reference_to_function_with_unsatisfied_constraints)
  257. << D;
  258. DiagnoseUnsatisfiedConstraint(Satisfaction);
  259. return true;
  260. }
  261. }
  262. // If the function has a deduced return type, and we can't deduce it,
  263. // then we can't use it either.
  264. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  265. DeduceReturnType(FD, Loc))
  266. return true;
  267. if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
  268. return true;
  269. if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
  270. return true;
  271. }
  272. if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  273. // Lambdas are only default-constructible or assignable in C++2a onwards.
  274. if (MD->getParent()->isLambda() &&
  275. ((isa<CXXConstructorDecl>(MD) &&
  276. cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
  277. MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
  278. Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
  279. << !isa<CXXConstructorDecl>(MD);
  280. }
  281. }
  282. auto getReferencedObjCProp = [](const NamedDecl *D) ->
  283. const ObjCPropertyDecl * {
  284. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  285. return MD->findPropertyDecl();
  286. return nullptr;
  287. };
  288. if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
  289. if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
  290. return true;
  291. } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
  292. return true;
  293. }
  294. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  295. // Only the variables omp_in and omp_out are allowed in the combiner.
  296. // Only the variables omp_priv and omp_orig are allowed in the
  297. // initializer-clause.
  298. auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
  299. if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
  300. isa<VarDecl>(D)) {
  301. Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
  302. << getCurFunction()->HasOMPDeclareReductionCombiner;
  303. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  304. return true;
  305. }
  306. // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
  307. // List-items in map clauses on this construct may only refer to the declared
  308. // variable var and entities that could be referenced by a procedure defined
  309. // at the same location
  310. if (LangOpts.OpenMP && isa<VarDecl>(D) &&
  311. !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
  312. Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
  313. << getOpenMPDeclareMapperVarName();
  314. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  315. return true;
  316. }
  317. if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
  318. Diag(Loc, diag::err_use_of_empty_using_if_exists);
  319. Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
  320. return true;
  321. }
  322. DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
  323. AvoidPartialAvailabilityChecks, ClassReceiver);
  324. DiagnoseUnusedOfDecl(*this, D, Loc);
  325. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  326. if (auto *VD = dyn_cast<ValueDecl>(D))
  327. checkTypeSupport(VD->getType(), Loc, VD);
  328. if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
  329. if (!Context.getTargetInfo().isTLSSupported())
  330. if (const auto *VD = dyn_cast<VarDecl>(D))
  331. if (VD->getTLSKind() != VarDecl::TLS_None)
  332. targetDiag(*Locs.begin(), diag::err_thread_unsupported);
  333. }
  334. if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
  335. !isUnevaluatedContext()) {
  336. // C++ [expr.prim.req.nested] p3
  337. // A local parameter shall only appear as an unevaluated operand
  338. // (Clause 8) within the constraint-expression.
  339. Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
  340. << D;
  341. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  342. return true;
  343. }
  344. return false;
  345. }
  346. /// DiagnoseSentinelCalls - This routine checks whether a call or
  347. /// message-send is to a declaration with the sentinel attribute, and
  348. /// if so, it checks that the requirements of the sentinel are
  349. /// satisfied.
  350. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  351. ArrayRef<Expr *> Args) {
  352. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  353. if (!attr)
  354. return;
  355. // The number of formal parameters of the declaration.
  356. unsigned numFormalParams;
  357. // The kind of declaration. This is also an index into a %select in
  358. // the diagnostic.
  359. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  360. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  361. numFormalParams = MD->param_size();
  362. calleeType = CT_Method;
  363. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  364. numFormalParams = FD->param_size();
  365. calleeType = CT_Function;
  366. } else if (isa<VarDecl>(D)) {
  367. QualType type = cast<ValueDecl>(D)->getType();
  368. const FunctionType *fn = nullptr;
  369. if (const PointerType *ptr = type->getAs<PointerType>()) {
  370. fn = ptr->getPointeeType()->getAs<FunctionType>();
  371. if (!fn) return;
  372. calleeType = CT_Function;
  373. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  374. fn = ptr->getPointeeType()->castAs<FunctionType>();
  375. calleeType = CT_Block;
  376. } else {
  377. return;
  378. }
  379. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  380. numFormalParams = proto->getNumParams();
  381. } else {
  382. numFormalParams = 0;
  383. }
  384. } else {
  385. return;
  386. }
  387. // "nullPos" is the number of formal parameters at the end which
  388. // effectively count as part of the variadic arguments. This is
  389. // useful if you would prefer to not have *any* formal parameters,
  390. // but the language forces you to have at least one.
  391. unsigned nullPos = attr->getNullPos();
  392. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  393. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  394. // The number of arguments which should follow the sentinel.
  395. unsigned numArgsAfterSentinel = attr->getSentinel();
  396. // If there aren't enough arguments for all the formal parameters,
  397. // the sentinel, and the args after the sentinel, complain.
  398. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  399. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  400. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  401. return;
  402. }
  403. // Otherwise, find the sentinel expression.
  404. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  405. if (!sentinelExpr) return;
  406. if (sentinelExpr->isValueDependent()) return;
  407. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  408. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  409. // or 'NULL' if those are actually defined in the context. Only use
  410. // 'nil' for ObjC methods, where it's much more likely that the
  411. // variadic arguments form a list of object pointers.
  412. SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
  413. std::string NullValue;
  414. if (calleeType == CT_Method && PP.isMacroDefined("nil"))
  415. NullValue = "nil";
  416. else if (getLangOpts().CPlusPlus11)
  417. NullValue = "nullptr";
  418. else if (PP.isMacroDefined("NULL"))
  419. NullValue = "NULL";
  420. else
  421. NullValue = "(void*) 0";
  422. if (MissingNilLoc.isInvalid())
  423. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  424. else
  425. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  426. << int(calleeType)
  427. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  428. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  429. }
  430. SourceRange Sema::getExprRange(Expr *E) const {
  431. return E ? E->getSourceRange() : SourceRange();
  432. }
  433. //===----------------------------------------------------------------------===//
  434. // Standard Promotions and Conversions
  435. //===----------------------------------------------------------------------===//
  436. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  437. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
  438. // Handle any placeholder expressions which made it here.
  439. if (E->hasPlaceholderType()) {
  440. ExprResult result = CheckPlaceholderExpr(E);
  441. if (result.isInvalid()) return ExprError();
  442. E = result.get();
  443. }
  444. QualType Ty = E->getType();
  445. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  446. if (Ty->isFunctionType()) {
  447. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
  448. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
  449. if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
  450. return ExprError();
  451. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  452. CK_FunctionToPointerDecay).get();
  453. } else if (Ty->isArrayType()) {
  454. // In C90 mode, arrays only promote to pointers if the array expression is
  455. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  456. // type 'array of type' is converted to an expression that has type 'pointer
  457. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  458. // that has type 'array of type' ...". The relevant change is "an lvalue"
  459. // (C90) to "an expression" (C99).
  460. //
  461. // C++ 4.2p1:
  462. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  463. // T" can be converted to an rvalue of type "pointer to T".
  464. //
  465. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
  466. ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  467. CK_ArrayToPointerDecay);
  468. if (Res.isInvalid())
  469. return ExprError();
  470. E = Res.get();
  471. }
  472. }
  473. return E;
  474. }
  475. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  476. // Check to see if we are dereferencing a null pointer. If so,
  477. // and if not volatile-qualified, this is undefined behavior that the
  478. // optimizer will delete, so warn about it. People sometimes try to use this
  479. // to get a deterministic trap and are surprised by clang's behavior. This
  480. // only handles the pattern "*null", which is a very syntactic check.
  481. const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
  482. if (UO && UO->getOpcode() == UO_Deref &&
  483. UO->getSubExpr()->getType()->isPointerType()) {
  484. const LangAS AS =
  485. UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
  486. if ((!isTargetAddressSpace(AS) ||
  487. (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
  488. UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
  489. S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  490. !UO->getType().isVolatileQualified()) {
  491. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  492. S.PDiag(diag::warn_indirection_through_null)
  493. << UO->getSubExpr()->getSourceRange());
  494. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  495. S.PDiag(diag::note_indirection_through_null));
  496. }
  497. }
  498. }
  499. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  500. SourceLocation AssignLoc,
  501. const Expr* RHS) {
  502. const ObjCIvarDecl *IV = OIRE->getDecl();
  503. if (!IV)
  504. return;
  505. DeclarationName MemberName = IV->getDeclName();
  506. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  507. if (!Member || !Member->isStr("isa"))
  508. return;
  509. const Expr *Base = OIRE->getBase();
  510. QualType BaseType = Base->getType();
  511. if (OIRE->isArrow())
  512. BaseType = BaseType->getPointeeType();
  513. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  514. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  515. ObjCInterfaceDecl *ClassDeclared = nullptr;
  516. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  517. if (!ClassDeclared->getSuperClass()
  518. && (*ClassDeclared->ivar_begin()) == IV) {
  519. if (RHS) {
  520. NamedDecl *ObjectSetClass =
  521. S.LookupSingleName(S.TUScope,
  522. &S.Context.Idents.get("object_setClass"),
  523. SourceLocation(), S.LookupOrdinaryName);
  524. if (ObjectSetClass) {
  525. SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
  526. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
  527. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  528. "object_setClass(")
  529. << FixItHint::CreateReplacement(
  530. SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
  531. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  532. }
  533. else
  534. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  535. } else {
  536. NamedDecl *ObjectGetClass =
  537. S.LookupSingleName(S.TUScope,
  538. &S.Context.Idents.get("object_getClass"),
  539. SourceLocation(), S.LookupOrdinaryName);
  540. if (ObjectGetClass)
  541. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
  542. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  543. "object_getClass(")
  544. << FixItHint::CreateReplacement(
  545. SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
  546. else
  547. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  548. }
  549. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  550. }
  551. }
  552. }
  553. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  554. // Handle any placeholder expressions which made it here.
  555. if (E->hasPlaceholderType()) {
  556. ExprResult result = CheckPlaceholderExpr(E);
  557. if (result.isInvalid()) return ExprError();
  558. E = result.get();
  559. }
  560. // C++ [conv.lval]p1:
  561. // A glvalue of a non-function, non-array type T can be
  562. // converted to a prvalue.
  563. if (!E->isGLValue()) return E;
  564. QualType T = E->getType();
  565. assert(!T.isNull() && "r-value conversion on typeless expression?");
  566. // lvalue-to-rvalue conversion cannot be applied to function or array types.
  567. if (T->isFunctionType() || T->isArrayType())
  568. return E;
  569. // We don't want to throw lvalue-to-rvalue casts on top of
  570. // expressions of certain types in C++.
  571. if (getLangOpts().CPlusPlus &&
  572. (E->getType() == Context.OverloadTy ||
  573. T->isDependentType() ||
  574. T->isRecordType()))
  575. return E;
  576. // The C standard is actually really unclear on this point, and
  577. // DR106 tells us what the result should be but not why. It's
  578. // generally best to say that void types just doesn't undergo
  579. // lvalue-to-rvalue at all. Note that expressions of unqualified
  580. // 'void' type are never l-values, but qualified void can be.
  581. if (T->isVoidType())
  582. return E;
  583. // OpenCL usually rejects direct accesses to values of 'half' type.
  584. if (getLangOpts().OpenCL &&
  585. !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
  586. T->isHalfType()) {
  587. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  588. << 0 << T;
  589. return ExprError();
  590. }
  591. CheckForNullPointerDereference(*this, E);
  592. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  593. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  594. &Context.Idents.get("object_getClass"),
  595. SourceLocation(), LookupOrdinaryName);
  596. if (ObjectGetClass)
  597. Diag(E->getExprLoc(), diag::warn_objc_isa_use)
  598. << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
  599. << FixItHint::CreateReplacement(
  600. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  601. else
  602. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  603. }
  604. else if (const ObjCIvarRefExpr *OIRE =
  605. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  606. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  607. // C++ [conv.lval]p1:
  608. // [...] If T is a non-class type, the type of the prvalue is the
  609. // cv-unqualified version of T. Otherwise, the type of the
  610. // rvalue is T.
  611. //
  612. // C99 6.3.2.1p2:
  613. // If the lvalue has qualified type, the value has the unqualified
  614. // version of the type of the lvalue; otherwise, the value has the
  615. // type of the lvalue.
  616. if (T.hasQualifiers())
  617. T = T.getUnqualifiedType();
  618. // Under the MS ABI, lock down the inheritance model now.
  619. if (T->isMemberPointerType() &&
  620. Context.getTargetInfo().getCXXABI().isMicrosoft())
  621. (void)isCompleteType(E->getExprLoc(), T);
  622. ExprResult Res = CheckLValueToRValueConversionOperand(E);
  623. if (Res.isInvalid())
  624. return Res;
  625. E = Res.get();
  626. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  627. // balance that.
  628. if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  629. Cleanup.setExprNeedsCleanups(true);
  630. if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  631. Cleanup.setExprNeedsCleanups(true);
  632. // C++ [conv.lval]p3:
  633. // If T is cv std::nullptr_t, the result is a null pointer constant.
  634. CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
  635. Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
  636. CurFPFeatureOverrides());
  637. // C11 6.3.2.1p2:
  638. // ... if the lvalue has atomic type, the value has the non-atomic version
  639. // of the type of the lvalue ...
  640. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  641. T = Atomic->getValueType().getUnqualifiedType();
  642. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  643. nullptr, VK_PRValue, FPOptionsOverride());
  644. }
  645. return Res;
  646. }
  647. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
  648. ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
  649. if (Res.isInvalid())
  650. return ExprError();
  651. Res = DefaultLvalueConversion(Res.get());
  652. if (Res.isInvalid())
  653. return ExprError();
  654. return Res;
  655. }
  656. /// CallExprUnaryConversions - a special case of an unary conversion
  657. /// performed on a function designator of a call expression.
  658. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  659. QualType Ty = E->getType();
  660. ExprResult Res = E;
  661. // Only do implicit cast for a function type, but not for a pointer
  662. // to function type.
  663. if (Ty->isFunctionType()) {
  664. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  665. CK_FunctionToPointerDecay);
  666. if (Res.isInvalid())
  667. return ExprError();
  668. }
  669. Res = DefaultLvalueConversion(Res.get());
  670. if (Res.isInvalid())
  671. return ExprError();
  672. return Res.get();
  673. }
  674. /// UsualUnaryConversions - Performs various conversions that are common to most
  675. /// operators (C99 6.3). The conversions of array and function types are
  676. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  677. /// apply if the array is an argument to the sizeof or address (&) operators.
  678. /// In these instances, this routine should *not* be called.
  679. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  680. // First, convert to an r-value.
  681. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  682. if (Res.isInvalid())
  683. return ExprError();
  684. E = Res.get();
  685. QualType Ty = E->getType();
  686. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  687. // Half FP have to be promoted to float unless it is natively supported
  688. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  689. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  690. // Try to perform integral promotions if the object has a theoretically
  691. // promotable type.
  692. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  693. // C99 6.3.1.1p2:
  694. //
  695. // The following may be used in an expression wherever an int or
  696. // unsigned int may be used:
  697. // - an object or expression with an integer type whose integer
  698. // conversion rank is less than or equal to the rank of int
  699. // and unsigned int.
  700. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  701. //
  702. // If an int can represent all values of the original type, the
  703. // value is converted to an int; otherwise, it is converted to an
  704. // unsigned int. These are called the integer promotions. All
  705. // other types are unchanged by the integer promotions.
  706. QualType PTy = Context.isPromotableBitField(E);
  707. if (!PTy.isNull()) {
  708. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  709. return E;
  710. }
  711. if (Ty->isPromotableIntegerType()) {
  712. QualType PT = Context.getPromotedIntegerType(Ty);
  713. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  714. return E;
  715. }
  716. }
  717. return E;
  718. }
  719. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  720. /// do not have a prototype. Arguments that have type float or __fp16
  721. /// are promoted to double. All other argument types are converted by
  722. /// UsualUnaryConversions().
  723. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  724. QualType Ty = E->getType();
  725. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  726. ExprResult Res = UsualUnaryConversions(E);
  727. if (Res.isInvalid())
  728. return ExprError();
  729. E = Res.get();
  730. // If this is a 'float' or '__fp16' (CVR qualified or typedef)
  731. // promote to double.
  732. // Note that default argument promotion applies only to float (and
  733. // half/fp16); it does not apply to _Float16.
  734. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  735. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  736. BTy->getKind() == BuiltinType::Float)) {
  737. if (getLangOpts().OpenCL &&
  738. !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
  739. if (BTy->getKind() == BuiltinType::Half) {
  740. E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
  741. }
  742. } else {
  743. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  744. }
  745. }
  746. if (BTy &&
  747. getLangOpts().getExtendIntArgs() ==
  748. LangOptions::ExtendArgsKind::ExtendTo64 &&
  749. Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
  750. Context.getTypeSizeInChars(BTy) <
  751. Context.getTypeSizeInChars(Context.LongLongTy)) {
  752. E = (Ty->isUnsignedIntegerType())
  753. ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
  754. .get()
  755. : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
  756. assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
  757. "Unexpected typesize for LongLongTy");
  758. }
  759. // C++ performs lvalue-to-rvalue conversion as a default argument
  760. // promotion, even on class types, but note:
  761. // C++11 [conv.lval]p2:
  762. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  763. // operand or a subexpression thereof the value contained in the
  764. // referenced object is not accessed. Otherwise, if the glvalue
  765. // has a class type, the conversion copy-initializes a temporary
  766. // of type T from the glvalue and the result of the conversion
  767. // is a prvalue for the temporary.
  768. // FIXME: add some way to gate this entire thing for correctness in
  769. // potentially potentially evaluated contexts.
  770. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  771. ExprResult Temp = PerformCopyInitialization(
  772. InitializedEntity::InitializeTemporary(E->getType()),
  773. E->getExprLoc(), E);
  774. if (Temp.isInvalid())
  775. return ExprError();
  776. E = Temp.get();
  777. }
  778. return E;
  779. }
  780. /// Determine the degree of POD-ness for an expression.
  781. /// Incomplete types are considered POD, since this check can be performed
  782. /// when we're in an unevaluated context.
  783. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  784. if (Ty->isIncompleteType()) {
  785. // C++11 [expr.call]p7:
  786. // After these conversions, if the argument does not have arithmetic,
  787. // enumeration, pointer, pointer to member, or class type, the program
  788. // is ill-formed.
  789. //
  790. // Since we've already performed array-to-pointer and function-to-pointer
  791. // decay, the only such type in C++ is cv void. This also handles
  792. // initializer lists as variadic arguments.
  793. if (Ty->isVoidType())
  794. return VAK_Invalid;
  795. if (Ty->isObjCObjectType())
  796. return VAK_Invalid;
  797. return VAK_Valid;
  798. }
  799. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  800. return VAK_Invalid;
  801. if (Ty.isCXX98PODType(Context))
  802. return VAK_Valid;
  803. // C++11 [expr.call]p7:
  804. // Passing a potentially-evaluated argument of class type (Clause 9)
  805. // having a non-trivial copy constructor, a non-trivial move constructor,
  806. // or a non-trivial destructor, with no corresponding parameter,
  807. // is conditionally-supported with implementation-defined semantics.
  808. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  809. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  810. if (!Record->hasNonTrivialCopyConstructor() &&
  811. !Record->hasNonTrivialMoveConstructor() &&
  812. !Record->hasNonTrivialDestructor())
  813. return VAK_ValidInCXX11;
  814. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  815. return VAK_Valid;
  816. if (Ty->isObjCObjectType())
  817. return VAK_Invalid;
  818. if (getLangOpts().MSVCCompat)
  819. return VAK_MSVCUndefined;
  820. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  821. // permitted to reject them. We should consider doing so.
  822. return VAK_Undefined;
  823. }
  824. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  825. // Don't allow one to pass an Objective-C interface to a vararg.
  826. const QualType &Ty = E->getType();
  827. VarArgKind VAK = isValidVarArgType(Ty);
  828. // Complain about passing non-POD types through varargs.
  829. switch (VAK) {
  830. case VAK_ValidInCXX11:
  831. DiagRuntimeBehavior(
  832. E->getBeginLoc(), nullptr,
  833. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
  834. LLVM_FALLTHROUGH;
  835. case VAK_Valid:
  836. if (Ty->isRecordType()) {
  837. // This is unlikely to be what the user intended. If the class has a
  838. // 'c_str' member function, the user probably meant to call that.
  839. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  840. PDiag(diag::warn_pass_class_arg_to_vararg)
  841. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  842. }
  843. break;
  844. case VAK_Undefined:
  845. case VAK_MSVCUndefined:
  846. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  847. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  848. << getLangOpts().CPlusPlus11 << Ty << CT);
  849. break;
  850. case VAK_Invalid:
  851. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  852. Diag(E->getBeginLoc(),
  853. diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
  854. << Ty << CT;
  855. else if (Ty->isObjCObjectType())
  856. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  857. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  858. << Ty << CT);
  859. else
  860. Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
  861. << isa<InitListExpr>(E) << Ty << CT;
  862. break;
  863. }
  864. }
  865. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  866. /// will create a trap if the resulting type is not a POD type.
  867. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  868. FunctionDecl *FDecl) {
  869. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  870. // Strip the unbridged-cast placeholder expression off, if applicable.
  871. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  872. (CT == VariadicMethod ||
  873. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  874. E = stripARCUnbridgedCast(E);
  875. // Otherwise, do normal placeholder checking.
  876. } else {
  877. ExprResult ExprRes = CheckPlaceholderExpr(E);
  878. if (ExprRes.isInvalid())
  879. return ExprError();
  880. E = ExprRes.get();
  881. }
  882. }
  883. ExprResult ExprRes = DefaultArgumentPromotion(E);
  884. if (ExprRes.isInvalid())
  885. return ExprError();
  886. // Copy blocks to the heap.
  887. if (ExprRes.get()->getType()->isBlockPointerType())
  888. maybeExtendBlockObject(ExprRes);
  889. E = ExprRes.get();
  890. // Diagnostics regarding non-POD argument types are
  891. // emitted along with format string checking in Sema::CheckFunctionCall().
  892. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  893. // Turn this into a trap.
  894. CXXScopeSpec SS;
  895. SourceLocation TemplateKWLoc;
  896. UnqualifiedId Name;
  897. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  898. E->getBeginLoc());
  899. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
  900. /*HasTrailingLParen=*/true,
  901. /*IsAddressOfOperand=*/false);
  902. if (TrapFn.isInvalid())
  903. return ExprError();
  904. ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
  905. None, E->getEndLoc());
  906. if (Call.isInvalid())
  907. return ExprError();
  908. ExprResult Comma =
  909. ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
  910. if (Comma.isInvalid())
  911. return ExprError();
  912. return Comma.get();
  913. }
  914. if (!getLangOpts().CPlusPlus &&
  915. RequireCompleteType(E->getExprLoc(), E->getType(),
  916. diag::err_call_incomplete_argument))
  917. return ExprError();
  918. return E;
  919. }
  920. /// Converts an integer to complex float type. Helper function of
  921. /// UsualArithmeticConversions()
  922. ///
  923. /// \return false if the integer expression is an integer type and is
  924. /// successfully converted to the complex type.
  925. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  926. ExprResult &ComplexExpr,
  927. QualType IntTy,
  928. QualType ComplexTy,
  929. bool SkipCast) {
  930. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  931. if (SkipCast) return false;
  932. if (IntTy->isIntegerType()) {
  933. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  934. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  935. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  936. CK_FloatingRealToComplex);
  937. } else {
  938. assert(IntTy->isComplexIntegerType());
  939. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  940. CK_IntegralComplexToFloatingComplex);
  941. }
  942. return false;
  943. }
  944. /// Handle arithmetic conversion with complex types. Helper function of
  945. /// UsualArithmeticConversions()
  946. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  947. ExprResult &RHS, QualType LHSType,
  948. QualType RHSType,
  949. bool IsCompAssign) {
  950. // if we have an integer operand, the result is the complex type.
  951. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  952. /*skipCast*/false))
  953. return LHSType;
  954. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  955. /*skipCast*/IsCompAssign))
  956. return RHSType;
  957. // This handles complex/complex, complex/float, or float/complex.
  958. // When both operands are complex, the shorter operand is converted to the
  959. // type of the longer, and that is the type of the result. This corresponds
  960. // to what is done when combining two real floating-point operands.
  961. // The fun begins when size promotion occur across type domains.
  962. // From H&S 6.3.4: When one operand is complex and the other is a real
  963. // floating-point type, the less precise type is converted, within it's
  964. // real or complex domain, to the precision of the other type. For example,
  965. // when combining a "long double" with a "double _Complex", the
  966. // "double _Complex" is promoted to "long double _Complex".
  967. // Compute the rank of the two types, regardless of whether they are complex.
  968. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  969. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  970. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  971. QualType LHSElementType =
  972. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  973. QualType RHSElementType =
  974. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  975. QualType ResultType = S.Context.getComplexType(LHSElementType);
  976. if (Order < 0) {
  977. // Promote the precision of the LHS if not an assignment.
  978. ResultType = S.Context.getComplexType(RHSElementType);
  979. if (!IsCompAssign) {
  980. if (LHSComplexType)
  981. LHS =
  982. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  983. else
  984. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  985. }
  986. } else if (Order > 0) {
  987. // Promote the precision of the RHS.
  988. if (RHSComplexType)
  989. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  990. else
  991. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  992. }
  993. return ResultType;
  994. }
  995. /// Handle arithmetic conversion from integer to float. Helper function
  996. /// of UsualArithmeticConversions()
  997. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  998. ExprResult &IntExpr,
  999. QualType FloatTy, QualType IntTy,
  1000. bool ConvertFloat, bool ConvertInt) {
  1001. if (IntTy->isIntegerType()) {
  1002. if (ConvertInt)
  1003. // Convert intExpr to the lhs floating point type.
  1004. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  1005. CK_IntegralToFloating);
  1006. return FloatTy;
  1007. }
  1008. // Convert both sides to the appropriate complex float.
  1009. assert(IntTy->isComplexIntegerType());
  1010. QualType result = S.Context.getComplexType(FloatTy);
  1011. // _Complex int -> _Complex float
  1012. if (ConvertInt)
  1013. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  1014. CK_IntegralComplexToFloatingComplex);
  1015. // float -> _Complex float
  1016. if (ConvertFloat)
  1017. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  1018. CK_FloatingRealToComplex);
  1019. return result;
  1020. }
  1021. /// Handle arithmethic conversion with floating point types. Helper
  1022. /// function of UsualArithmeticConversions()
  1023. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  1024. ExprResult &RHS, QualType LHSType,
  1025. QualType RHSType, bool IsCompAssign) {
  1026. bool LHSFloat = LHSType->isRealFloatingType();
  1027. bool RHSFloat = RHSType->isRealFloatingType();
  1028. // N1169 4.1.4: If one of the operands has a floating type and the other
  1029. // operand has a fixed-point type, the fixed-point operand
  1030. // is converted to the floating type [...]
  1031. if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
  1032. if (LHSFloat)
  1033. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
  1034. else if (!IsCompAssign)
  1035. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
  1036. return LHSFloat ? LHSType : RHSType;
  1037. }
  1038. // If we have two real floating types, convert the smaller operand
  1039. // to the bigger result.
  1040. if (LHSFloat && RHSFloat) {
  1041. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  1042. if (order > 0) {
  1043. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  1044. return LHSType;
  1045. }
  1046. assert(order < 0 && "illegal float comparison");
  1047. if (!IsCompAssign)
  1048. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  1049. return RHSType;
  1050. }
  1051. if (LHSFloat) {
  1052. // Half FP has to be promoted to float unless it is natively supported
  1053. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  1054. LHSType = S.Context.FloatTy;
  1055. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  1056. /*ConvertFloat=*/!IsCompAssign,
  1057. /*ConvertInt=*/ true);
  1058. }
  1059. assert(RHSFloat);
  1060. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  1061. /*ConvertFloat=*/ true,
  1062. /*ConvertInt=*/!IsCompAssign);
  1063. }
  1064. /// Diagnose attempts to convert between __float128, __ibm128 and
  1065. /// long double if there is no support for such conversion.
  1066. /// Helper function of UsualArithmeticConversions().
  1067. static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
  1068. QualType RHSType) {
  1069. // No issue if either is not a floating point type.
  1070. if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
  1071. return false;
  1072. // No issue if both have the same 128-bit float semantics.
  1073. auto *LHSComplex = LHSType->getAs<ComplexType>();
  1074. auto *RHSComplex = RHSType->getAs<ComplexType>();
  1075. QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
  1076. QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
  1077. const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
  1078. const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
  1079. if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
  1080. &RHSSem != &llvm::APFloat::IEEEquad()) &&
  1081. (&LHSSem != &llvm::APFloat::IEEEquad() ||
  1082. &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
  1083. return false;
  1084. return true;
  1085. }
  1086. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  1087. namespace {
  1088. /// These helper callbacks are placed in an anonymous namespace to
  1089. /// permit their use as function template parameters.
  1090. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  1091. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  1092. }
  1093. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  1094. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  1095. CK_IntegralComplexCast);
  1096. }
  1097. }
  1098. /// Handle integer arithmetic conversions. Helper function of
  1099. /// UsualArithmeticConversions()
  1100. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  1101. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  1102. ExprResult &RHS, QualType LHSType,
  1103. QualType RHSType, bool IsCompAssign) {
  1104. // The rules for this case are in C99 6.3.1.8
  1105. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  1106. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  1107. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  1108. if (LHSSigned == RHSSigned) {
  1109. // Same signedness; use the higher-ranked type
  1110. if (order >= 0) {
  1111. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1112. return LHSType;
  1113. } else if (!IsCompAssign)
  1114. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1115. return RHSType;
  1116. } else if (order != (LHSSigned ? 1 : -1)) {
  1117. // The unsigned type has greater than or equal rank to the
  1118. // signed type, so use the unsigned type
  1119. if (RHSSigned) {
  1120. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1121. return LHSType;
  1122. } else if (!IsCompAssign)
  1123. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1124. return RHSType;
  1125. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1126. // The two types are different widths; if we are here, that
  1127. // means the signed type is larger than the unsigned type, so
  1128. // use the signed type.
  1129. if (LHSSigned) {
  1130. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1131. return LHSType;
  1132. } else if (!IsCompAssign)
  1133. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1134. return RHSType;
  1135. } else {
  1136. // The signed type is higher-ranked than the unsigned type,
  1137. // but isn't actually any bigger (like unsigned int and long
  1138. // on most 32-bit systems). Use the unsigned type corresponding
  1139. // to the signed type.
  1140. QualType result =
  1141. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1142. RHS = (*doRHSCast)(S, RHS.get(), result);
  1143. if (!IsCompAssign)
  1144. LHS = (*doLHSCast)(S, LHS.get(), result);
  1145. return result;
  1146. }
  1147. }
  1148. /// Handle conversions with GCC complex int extension. Helper function
  1149. /// of UsualArithmeticConversions()
  1150. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1151. ExprResult &RHS, QualType LHSType,
  1152. QualType RHSType,
  1153. bool IsCompAssign) {
  1154. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1155. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1156. if (LHSComplexInt && RHSComplexInt) {
  1157. QualType LHSEltType = LHSComplexInt->getElementType();
  1158. QualType RHSEltType = RHSComplexInt->getElementType();
  1159. QualType ScalarType =
  1160. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1161. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1162. return S.Context.getComplexType(ScalarType);
  1163. }
  1164. if (LHSComplexInt) {
  1165. QualType LHSEltType = LHSComplexInt->getElementType();
  1166. QualType ScalarType =
  1167. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1168. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1169. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1170. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1171. CK_IntegralRealToComplex);
  1172. return ComplexType;
  1173. }
  1174. assert(RHSComplexInt);
  1175. QualType RHSEltType = RHSComplexInt->getElementType();
  1176. QualType ScalarType =
  1177. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1178. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1179. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1180. if (!IsCompAssign)
  1181. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1182. CK_IntegralRealToComplex);
  1183. return ComplexType;
  1184. }
  1185. /// Return the rank of a given fixed point or integer type. The value itself
  1186. /// doesn't matter, but the values must be increasing with proper increasing
  1187. /// rank as described in N1169 4.1.1.
  1188. static unsigned GetFixedPointRank(QualType Ty) {
  1189. const auto *BTy = Ty->getAs<BuiltinType>();
  1190. assert(BTy && "Expected a builtin type.");
  1191. switch (BTy->getKind()) {
  1192. case BuiltinType::ShortFract:
  1193. case BuiltinType::UShortFract:
  1194. case BuiltinType::SatShortFract:
  1195. case BuiltinType::SatUShortFract:
  1196. return 1;
  1197. case BuiltinType::Fract:
  1198. case BuiltinType::UFract:
  1199. case BuiltinType::SatFract:
  1200. case BuiltinType::SatUFract:
  1201. return 2;
  1202. case BuiltinType::LongFract:
  1203. case BuiltinType::ULongFract:
  1204. case BuiltinType::SatLongFract:
  1205. case BuiltinType::SatULongFract:
  1206. return 3;
  1207. case BuiltinType::ShortAccum:
  1208. case BuiltinType::UShortAccum:
  1209. case BuiltinType::SatShortAccum:
  1210. case BuiltinType::SatUShortAccum:
  1211. return 4;
  1212. case BuiltinType::Accum:
  1213. case BuiltinType::UAccum:
  1214. case BuiltinType::SatAccum:
  1215. case BuiltinType::SatUAccum:
  1216. return 5;
  1217. case BuiltinType::LongAccum:
  1218. case BuiltinType::ULongAccum:
  1219. case BuiltinType::SatLongAccum:
  1220. case BuiltinType::SatULongAccum:
  1221. return 6;
  1222. default:
  1223. if (BTy->isInteger())
  1224. return 0;
  1225. llvm_unreachable("Unexpected fixed point or integer type");
  1226. }
  1227. }
  1228. /// handleFixedPointConversion - Fixed point operations between fixed
  1229. /// point types and integers or other fixed point types do not fall under
  1230. /// usual arithmetic conversion since these conversions could result in loss
  1231. /// of precsision (N1169 4.1.4). These operations should be calculated with
  1232. /// the full precision of their result type (N1169 4.1.6.2.1).
  1233. static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
  1234. QualType RHSTy) {
  1235. assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
  1236. "Expected at least one of the operands to be a fixed point type");
  1237. assert((LHSTy->isFixedPointOrIntegerType() ||
  1238. RHSTy->isFixedPointOrIntegerType()) &&
  1239. "Special fixed point arithmetic operation conversions are only "
  1240. "applied to ints or other fixed point types");
  1241. // If one operand has signed fixed-point type and the other operand has
  1242. // unsigned fixed-point type, then the unsigned fixed-point operand is
  1243. // converted to its corresponding signed fixed-point type and the resulting
  1244. // type is the type of the converted operand.
  1245. if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
  1246. LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
  1247. else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
  1248. RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
  1249. // The result type is the type with the highest rank, whereby a fixed-point
  1250. // conversion rank is always greater than an integer conversion rank; if the
  1251. // type of either of the operands is a saturating fixedpoint type, the result
  1252. // type shall be the saturating fixed-point type corresponding to the type
  1253. // with the highest rank; the resulting value is converted (taking into
  1254. // account rounding and overflow) to the precision of the resulting type.
  1255. // Same ranks between signed and unsigned types are resolved earlier, so both
  1256. // types are either signed or both unsigned at this point.
  1257. unsigned LHSTyRank = GetFixedPointRank(LHSTy);
  1258. unsigned RHSTyRank = GetFixedPointRank(RHSTy);
  1259. QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
  1260. if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
  1261. ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
  1262. return ResultTy;
  1263. }
  1264. /// Check that the usual arithmetic conversions can be performed on this pair of
  1265. /// expressions that might be of enumeration type.
  1266. static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
  1267. SourceLocation Loc,
  1268. Sema::ArithConvKind ACK) {
  1269. // C++2a [expr.arith.conv]p1:
  1270. // If one operand is of enumeration type and the other operand is of a
  1271. // different enumeration type or a floating-point type, this behavior is
  1272. // deprecated ([depr.arith.conv.enum]).
  1273. //
  1274. // Warn on this in all language modes. Produce a deprecation warning in C++20.
  1275. // Eventually we will presumably reject these cases (in C++23 onwards?).
  1276. QualType L = LHS->getType(), R = RHS->getType();
  1277. bool LEnum = L->isUnscopedEnumerationType(),
  1278. REnum = R->isUnscopedEnumerationType();
  1279. bool IsCompAssign = ACK == Sema::ACK_CompAssign;
  1280. if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
  1281. (REnum && L->isFloatingType())) {
  1282. S.Diag(Loc, S.getLangOpts().CPlusPlus20
  1283. ? diag::warn_arith_conv_enum_float_cxx20
  1284. : diag::warn_arith_conv_enum_float)
  1285. << LHS->getSourceRange() << RHS->getSourceRange()
  1286. << (int)ACK << LEnum << L << R;
  1287. } else if (!IsCompAssign && LEnum && REnum &&
  1288. !S.Context.hasSameUnqualifiedType(L, R)) {
  1289. unsigned DiagID;
  1290. if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
  1291. !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
  1292. // If either enumeration type is unnamed, it's less likely that the
  1293. // user cares about this, but this situation is still deprecated in
  1294. // C++2a. Use a different warning group.
  1295. DiagID = S.getLangOpts().CPlusPlus20
  1296. ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
  1297. : diag::warn_arith_conv_mixed_anon_enum_types;
  1298. } else if (ACK == Sema::ACK_Conditional) {
  1299. // Conditional expressions are separated out because they have
  1300. // historically had a different warning flag.
  1301. DiagID = S.getLangOpts().CPlusPlus20
  1302. ? diag::warn_conditional_mixed_enum_types_cxx20
  1303. : diag::warn_conditional_mixed_enum_types;
  1304. } else if (ACK == Sema::ACK_Comparison) {
  1305. // Comparison expressions are separated out because they have
  1306. // historically had a different warning flag.
  1307. DiagID = S.getLangOpts().CPlusPlus20
  1308. ? diag::warn_comparison_mixed_enum_types_cxx20
  1309. : diag::warn_comparison_mixed_enum_types;
  1310. } else {
  1311. DiagID = S.getLangOpts().CPlusPlus20
  1312. ? diag::warn_arith_conv_mixed_enum_types_cxx20
  1313. : diag::warn_arith_conv_mixed_enum_types;
  1314. }
  1315. S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
  1316. << (int)ACK << L << R;
  1317. }
  1318. }
  1319. /// UsualArithmeticConversions - Performs various conversions that are common to
  1320. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1321. /// routine returns the first non-arithmetic type found. The client is
  1322. /// responsible for emitting appropriate error diagnostics.
  1323. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1324. SourceLocation Loc,
  1325. ArithConvKind ACK) {
  1326. checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
  1327. if (ACK != ACK_CompAssign) {
  1328. LHS = UsualUnaryConversions(LHS.get());
  1329. if (LHS.isInvalid())
  1330. return QualType();
  1331. }
  1332. RHS = UsualUnaryConversions(RHS.get());
  1333. if (RHS.isInvalid())
  1334. return QualType();
  1335. // For conversion purposes, we ignore any qualifiers.
  1336. // For example, "const float" and "float" are equivalent.
  1337. QualType LHSType =
  1338. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1339. QualType RHSType =
  1340. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1341. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1342. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1343. LHSType = AtomicLHS->getValueType();
  1344. // If both types are identical, no conversion is needed.
  1345. if (LHSType == RHSType)
  1346. return LHSType;
  1347. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1348. // The caller can deal with this (e.g. pointer + int).
  1349. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1350. return QualType();
  1351. // Apply unary and bitfield promotions to the LHS's type.
  1352. QualType LHSUnpromotedType = LHSType;
  1353. if (LHSType->isPromotableIntegerType())
  1354. LHSType = Context.getPromotedIntegerType(LHSType);
  1355. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1356. if (!LHSBitfieldPromoteTy.isNull())
  1357. LHSType = LHSBitfieldPromoteTy;
  1358. if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
  1359. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1360. // If both types are identical, no conversion is needed.
  1361. if (LHSType == RHSType)
  1362. return LHSType;
  1363. // At this point, we have two different arithmetic types.
  1364. // Diagnose attempts to convert between __ibm128, __float128 and long double
  1365. // where such conversions currently can't be handled.
  1366. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  1367. return QualType();
  1368. // Handle complex types first (C99 6.3.1.8p1).
  1369. if (LHSType->isComplexType() || RHSType->isComplexType())
  1370. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1371. ACK == ACK_CompAssign);
  1372. // Now handle "real" floating types (i.e. float, double, long double).
  1373. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1374. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1375. ACK == ACK_CompAssign);
  1376. // Handle GCC complex int extension.
  1377. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1378. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1379. ACK == ACK_CompAssign);
  1380. if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
  1381. return handleFixedPointConversion(*this, LHSType, RHSType);
  1382. // Finally, we have two differing integer types.
  1383. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1384. (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
  1385. }
  1386. //===----------------------------------------------------------------------===//
  1387. // Semantic Analysis for various Expression Types
  1388. //===----------------------------------------------------------------------===//
  1389. ExprResult
  1390. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1391. SourceLocation DefaultLoc,
  1392. SourceLocation RParenLoc,
  1393. Expr *ControllingExpr,
  1394. ArrayRef<ParsedType> ArgTypes,
  1395. ArrayRef<Expr *> ArgExprs) {
  1396. unsigned NumAssocs = ArgTypes.size();
  1397. assert(NumAssocs == ArgExprs.size());
  1398. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1399. for (unsigned i = 0; i < NumAssocs; ++i) {
  1400. if (ArgTypes[i])
  1401. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1402. else
  1403. Types[i] = nullptr;
  1404. }
  1405. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1406. ControllingExpr,
  1407. llvm::makeArrayRef(Types, NumAssocs),
  1408. ArgExprs);
  1409. delete [] Types;
  1410. return ER;
  1411. }
  1412. ExprResult
  1413. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1414. SourceLocation DefaultLoc,
  1415. SourceLocation RParenLoc,
  1416. Expr *ControllingExpr,
  1417. ArrayRef<TypeSourceInfo *> Types,
  1418. ArrayRef<Expr *> Exprs) {
  1419. unsigned NumAssocs = Types.size();
  1420. assert(NumAssocs == Exprs.size());
  1421. // Decay and strip qualifiers for the controlling expression type, and handle
  1422. // placeholder type replacement. See committee discussion from WG14 DR423.
  1423. {
  1424. EnterExpressionEvaluationContext Unevaluated(
  1425. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  1426. ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
  1427. if (R.isInvalid())
  1428. return ExprError();
  1429. ControllingExpr = R.get();
  1430. }
  1431. // The controlling expression is an unevaluated operand, so side effects are
  1432. // likely unintended.
  1433. if (!inTemplateInstantiation() &&
  1434. ControllingExpr->HasSideEffects(Context, false))
  1435. Diag(ControllingExpr->getExprLoc(),
  1436. diag::warn_side_effects_unevaluated_context);
  1437. bool TypeErrorFound = false,
  1438. IsResultDependent = ControllingExpr->isTypeDependent(),
  1439. ContainsUnexpandedParameterPack
  1440. = ControllingExpr->containsUnexpandedParameterPack();
  1441. for (unsigned i = 0; i < NumAssocs; ++i) {
  1442. if (Exprs[i]->containsUnexpandedParameterPack())
  1443. ContainsUnexpandedParameterPack = true;
  1444. if (Types[i]) {
  1445. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1446. ContainsUnexpandedParameterPack = true;
  1447. if (Types[i]->getType()->isDependentType()) {
  1448. IsResultDependent = true;
  1449. } else {
  1450. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1451. // complete object type other than a variably modified type."
  1452. unsigned D = 0;
  1453. if (Types[i]->getType()->isIncompleteType())
  1454. D = diag::err_assoc_type_incomplete;
  1455. else if (!Types[i]->getType()->isObjectType())
  1456. D = diag::err_assoc_type_nonobject;
  1457. else if (Types[i]->getType()->isVariablyModifiedType())
  1458. D = diag::err_assoc_type_variably_modified;
  1459. if (D != 0) {
  1460. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1461. << Types[i]->getTypeLoc().getSourceRange()
  1462. << Types[i]->getType();
  1463. TypeErrorFound = true;
  1464. }
  1465. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1466. // selection shall specify compatible types."
  1467. for (unsigned j = i+1; j < NumAssocs; ++j)
  1468. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1469. Context.typesAreCompatible(Types[i]->getType(),
  1470. Types[j]->getType())) {
  1471. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1472. diag::err_assoc_compatible_types)
  1473. << Types[j]->getTypeLoc().getSourceRange()
  1474. << Types[j]->getType()
  1475. << Types[i]->getType();
  1476. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1477. diag::note_compat_assoc)
  1478. << Types[i]->getTypeLoc().getSourceRange()
  1479. << Types[i]->getType();
  1480. TypeErrorFound = true;
  1481. }
  1482. }
  1483. }
  1484. }
  1485. if (TypeErrorFound)
  1486. return ExprError();
  1487. // If we determined that the generic selection is result-dependent, don't
  1488. // try to compute the result expression.
  1489. if (IsResultDependent)
  1490. return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
  1491. Exprs, DefaultLoc, RParenLoc,
  1492. ContainsUnexpandedParameterPack);
  1493. SmallVector<unsigned, 1> CompatIndices;
  1494. unsigned DefaultIndex = -1U;
  1495. for (unsigned i = 0; i < NumAssocs; ++i) {
  1496. if (!Types[i])
  1497. DefaultIndex = i;
  1498. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1499. Types[i]->getType()))
  1500. CompatIndices.push_back(i);
  1501. }
  1502. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1503. // type compatible with at most one of the types named in its generic
  1504. // association list."
  1505. if (CompatIndices.size() > 1) {
  1506. // We strip parens here because the controlling expression is typically
  1507. // parenthesized in macro definitions.
  1508. ControllingExpr = ControllingExpr->IgnoreParens();
  1509. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
  1510. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1511. << (unsigned)CompatIndices.size();
  1512. for (unsigned I : CompatIndices) {
  1513. Diag(Types[I]->getTypeLoc().getBeginLoc(),
  1514. diag::note_compat_assoc)
  1515. << Types[I]->getTypeLoc().getSourceRange()
  1516. << Types[I]->getType();
  1517. }
  1518. return ExprError();
  1519. }
  1520. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1521. // its controlling expression shall have type compatible with exactly one of
  1522. // the types named in its generic association list."
  1523. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1524. // We strip parens here because the controlling expression is typically
  1525. // parenthesized in macro definitions.
  1526. ControllingExpr = ControllingExpr->IgnoreParens();
  1527. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
  1528. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1529. return ExprError();
  1530. }
  1531. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1532. // type name that is compatible with the type of the controlling expression,
  1533. // then the result expression of the generic selection is the expression
  1534. // in that generic association. Otherwise, the result expression of the
  1535. // generic selection is the expression in the default generic association."
  1536. unsigned ResultIndex =
  1537. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1538. return GenericSelectionExpr::Create(
  1539. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1540. ContainsUnexpandedParameterPack, ResultIndex);
  1541. }
  1542. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1543. /// location of the token and the offset of the ud-suffix within it.
  1544. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1545. unsigned Offset) {
  1546. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1547. S.getLangOpts());
  1548. }
  1549. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1550. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1551. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1552. IdentifierInfo *UDSuffix,
  1553. SourceLocation UDSuffixLoc,
  1554. ArrayRef<Expr*> Args,
  1555. SourceLocation LitEndLoc) {
  1556. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1557. QualType ArgTy[2];
  1558. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1559. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1560. if (ArgTy[ArgIdx]->isArrayType())
  1561. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1562. }
  1563. DeclarationName OpName =
  1564. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1565. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1566. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1567. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1568. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1569. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1570. /*AllowStringTemplatePack*/ false,
  1571. /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
  1572. return ExprError();
  1573. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1574. }
  1575. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1576. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1577. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1578. /// multiple tokens. However, the common case is that StringToks points to one
  1579. /// string.
  1580. ///
  1581. ExprResult
  1582. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1583. assert(!StringToks.empty() && "Must have at least one string!");
  1584. StringLiteralParser Literal(StringToks, PP);
  1585. if (Literal.hadError)
  1586. return ExprError();
  1587. SmallVector<SourceLocation, 4> StringTokLocs;
  1588. for (const Token &Tok : StringToks)
  1589. StringTokLocs.push_back(Tok.getLocation());
  1590. QualType CharTy = Context.CharTy;
  1591. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1592. if (Literal.isWide()) {
  1593. CharTy = Context.getWideCharType();
  1594. Kind = StringLiteral::Wide;
  1595. } else if (Literal.isUTF8()) {
  1596. if (getLangOpts().Char8)
  1597. CharTy = Context.Char8Ty;
  1598. Kind = StringLiteral::UTF8;
  1599. } else if (Literal.isUTF16()) {
  1600. CharTy = Context.Char16Ty;
  1601. Kind = StringLiteral::UTF16;
  1602. } else if (Literal.isUTF32()) {
  1603. CharTy = Context.Char32Ty;
  1604. Kind = StringLiteral::UTF32;
  1605. } else if (Literal.isPascal()) {
  1606. CharTy = Context.UnsignedCharTy;
  1607. }
  1608. // Warn on initializing an array of char from a u8 string literal; this
  1609. // becomes ill-formed in C++2a.
  1610. if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
  1611. !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
  1612. Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
  1613. // Create removals for all 'u8' prefixes in the string literal(s). This
  1614. // ensures C++2a compatibility (but may change the program behavior when
  1615. // built by non-Clang compilers for which the execution character set is
  1616. // not always UTF-8).
  1617. auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
  1618. SourceLocation RemovalDiagLoc;
  1619. for (const Token &Tok : StringToks) {
  1620. if (Tok.getKind() == tok::utf8_string_literal) {
  1621. if (RemovalDiagLoc.isInvalid())
  1622. RemovalDiagLoc = Tok.getLocation();
  1623. RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
  1624. Tok.getLocation(),
  1625. Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
  1626. getSourceManager(), getLangOpts())));
  1627. }
  1628. }
  1629. Diag(RemovalDiagLoc, RemovalDiag);
  1630. }
  1631. QualType StrTy =
  1632. Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
  1633. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1634. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1635. Kind, Literal.Pascal, StrTy,
  1636. &StringTokLocs[0],
  1637. StringTokLocs.size());
  1638. if (Literal.getUDSuffix().empty())
  1639. return Lit;
  1640. // We're building a user-defined literal.
  1641. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1642. SourceLocation UDSuffixLoc =
  1643. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1644. Literal.getUDSuffixOffset());
  1645. // Make sure we're allowed user-defined literals here.
  1646. if (!UDLScope)
  1647. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1648. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1649. // operator "" X (str, len)
  1650. QualType SizeType = Context.getSizeType();
  1651. DeclarationName OpName =
  1652. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1653. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1654. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1655. QualType ArgTy[] = {
  1656. Context.getArrayDecayedType(StrTy), SizeType
  1657. };
  1658. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1659. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1660. /*AllowRaw*/ false, /*AllowTemplate*/ true,
  1661. /*AllowStringTemplatePack*/ true,
  1662. /*DiagnoseMissing*/ true, Lit)) {
  1663. case LOLR_Cooked: {
  1664. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1665. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1666. StringTokLocs[0]);
  1667. Expr *Args[] = { Lit, LenArg };
  1668. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1669. }
  1670. case LOLR_Template: {
  1671. TemplateArgumentListInfo ExplicitArgs;
  1672. TemplateArgument Arg(Lit);
  1673. TemplateArgumentLocInfo ArgInfo(Lit);
  1674. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1675. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1676. &ExplicitArgs);
  1677. }
  1678. case LOLR_StringTemplatePack: {
  1679. TemplateArgumentListInfo ExplicitArgs;
  1680. unsigned CharBits = Context.getIntWidth(CharTy);
  1681. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1682. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1683. TemplateArgument TypeArg(CharTy);
  1684. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1685. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1686. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1687. Value = Lit->getCodeUnit(I);
  1688. TemplateArgument Arg(Context, Value, CharTy);
  1689. TemplateArgumentLocInfo ArgInfo;
  1690. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1691. }
  1692. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1693. &ExplicitArgs);
  1694. }
  1695. case LOLR_Raw:
  1696. case LOLR_ErrorNoDiagnostic:
  1697. llvm_unreachable("unexpected literal operator lookup result");
  1698. case LOLR_Error:
  1699. return ExprError();
  1700. }
  1701. llvm_unreachable("unexpected literal operator lookup result");
  1702. }
  1703. DeclRefExpr *
  1704. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1705. SourceLocation Loc,
  1706. const CXXScopeSpec *SS) {
  1707. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1708. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1709. }
  1710. DeclRefExpr *
  1711. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1712. const DeclarationNameInfo &NameInfo,
  1713. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1714. SourceLocation TemplateKWLoc,
  1715. const TemplateArgumentListInfo *TemplateArgs) {
  1716. NestedNameSpecifierLoc NNS =
  1717. SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
  1718. return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
  1719. TemplateArgs);
  1720. }
  1721. // CUDA/HIP: Check whether a captured reference variable is referencing a
  1722. // host variable in a device or host device lambda.
  1723. static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
  1724. VarDecl *VD) {
  1725. if (!S.getLangOpts().CUDA || !VD->hasInit())
  1726. return false;
  1727. assert(VD->getType()->isReferenceType());
  1728. // Check whether the reference variable is referencing a host variable.
  1729. auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
  1730. if (!DRE)
  1731. return false;
  1732. auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
  1733. if (!Referee || !Referee->hasGlobalStorage() ||
  1734. Referee->hasAttr<CUDADeviceAttr>())
  1735. return false;
  1736. // Check whether the current function is a device or host device lambda.
  1737. // Check whether the reference variable is a capture by getDeclContext()
  1738. // since refersToEnclosingVariableOrCapture() is not ready at this point.
  1739. auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
  1740. if (MD && MD->getParent()->isLambda() &&
  1741. MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
  1742. VD->getDeclContext() != MD)
  1743. return true;
  1744. return false;
  1745. }
  1746. NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
  1747. // A declaration named in an unevaluated operand never constitutes an odr-use.
  1748. if (isUnevaluatedContext())
  1749. return NOUR_Unevaluated;
  1750. // C++2a [basic.def.odr]p4:
  1751. // A variable x whose name appears as a potentially-evaluated expression e
  1752. // is odr-used by e unless [...] x is a reference that is usable in
  1753. // constant expressions.
  1754. // CUDA/HIP:
  1755. // If a reference variable referencing a host variable is captured in a
  1756. // device or host device lambda, the value of the referee must be copied
  1757. // to the capture and the reference variable must be treated as odr-use
  1758. // since the value of the referee is not known at compile time and must
  1759. // be loaded from the captured.
  1760. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1761. if (VD->getType()->isReferenceType() &&
  1762. !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
  1763. !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
  1764. VD->isUsableInConstantExpressions(Context))
  1765. return NOUR_Constant;
  1766. }
  1767. // All remaining non-variable cases constitute an odr-use. For variables, we
  1768. // need to wait and see how the expression is used.
  1769. return NOUR_None;
  1770. }
  1771. /// BuildDeclRefExpr - Build an expression that references a
  1772. /// declaration that does not require a closure capture.
  1773. DeclRefExpr *
  1774. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1775. const DeclarationNameInfo &NameInfo,
  1776. NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
  1777. SourceLocation TemplateKWLoc,
  1778. const TemplateArgumentListInfo *TemplateArgs) {
  1779. bool RefersToCapturedVariable =
  1780. isa<VarDecl>(D) &&
  1781. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1782. DeclRefExpr *E = DeclRefExpr::Create(
  1783. Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
  1784. VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
  1785. MarkDeclRefReferenced(E);
  1786. // C++ [except.spec]p17:
  1787. // An exception-specification is considered to be needed when:
  1788. // - in an expression, the function is the unique lookup result or
  1789. // the selected member of a set of overloaded functions.
  1790. //
  1791. // We delay doing this until after we've built the function reference and
  1792. // marked it as used so that:
  1793. // a) if the function is defaulted, we get errors from defining it before /
  1794. // instead of errors from computing its exception specification, and
  1795. // b) if the function is a defaulted comparison, we can use the body we
  1796. // build when defining it as input to the exception specification
  1797. // computation rather than computing a new body.
  1798. if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
  1799. if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
  1800. if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
  1801. E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
  1802. }
  1803. }
  1804. if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
  1805. Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
  1806. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
  1807. getCurFunction()->recordUseOfWeak(E);
  1808. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1809. if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
  1810. FD = IFD->getAnonField();
  1811. if (FD) {
  1812. UnusedPrivateFields.remove(FD);
  1813. // Just in case we're building an illegal pointer-to-member.
  1814. if (FD->isBitField())
  1815. E->setObjectKind(OK_BitField);
  1816. }
  1817. // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
  1818. // designates a bit-field.
  1819. if (auto *BD = dyn_cast<BindingDecl>(D))
  1820. if (auto *BE = BD->getBinding())
  1821. E->setObjectKind(BE->getObjectKind());
  1822. return E;
  1823. }
  1824. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1825. /// possibly a list of template arguments.
  1826. ///
  1827. /// If this produces template arguments, it is permitted to call
  1828. /// DecomposeTemplateName.
  1829. ///
  1830. /// This actually loses a lot of source location information for
  1831. /// non-standard name kinds; we should consider preserving that in
  1832. /// some way.
  1833. void
  1834. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1835. TemplateArgumentListInfo &Buffer,
  1836. DeclarationNameInfo &NameInfo,
  1837. const TemplateArgumentListInfo *&TemplateArgs) {
  1838. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
  1839. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1840. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1841. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1842. Id.TemplateId->NumArgs);
  1843. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1844. TemplateName TName = Id.TemplateId->Template.get();
  1845. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1846. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1847. TemplateArgs = &Buffer;
  1848. } else {
  1849. NameInfo = GetNameFromUnqualifiedId(Id);
  1850. TemplateArgs = nullptr;
  1851. }
  1852. }
  1853. static void emitEmptyLookupTypoDiagnostic(
  1854. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1855. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1856. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1857. DeclContext *Ctx =
  1858. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1859. if (!TC) {
  1860. // Emit a special diagnostic for failed member lookups.
  1861. // FIXME: computing the declaration context might fail here (?)
  1862. if (Ctx)
  1863. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1864. << SS.getRange();
  1865. else
  1866. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1867. return;
  1868. }
  1869. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1870. bool DroppedSpecifier =
  1871. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1872. unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
  1873. ? diag::note_implicit_param_decl
  1874. : diag::note_previous_decl;
  1875. if (!Ctx)
  1876. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1877. SemaRef.PDiag(NoteID));
  1878. else
  1879. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1880. << Typo << Ctx << DroppedSpecifier
  1881. << SS.getRange(),
  1882. SemaRef.PDiag(NoteID));
  1883. }
  1884. /// Diagnose a lookup that found results in an enclosing class during error
  1885. /// recovery. This usually indicates that the results were found in a dependent
  1886. /// base class that could not be searched as part of a template definition.
  1887. /// Always issues a diagnostic (though this may be only a warning in MS
  1888. /// compatibility mode).
  1889. ///
  1890. /// Return \c true if the error is unrecoverable, or \c false if the caller
  1891. /// should attempt to recover using these lookup results.
  1892. bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
  1893. // During a default argument instantiation the CurContext points
  1894. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1895. // function parameter list, hence add an explicit check.
  1896. bool isDefaultArgument =
  1897. !CodeSynthesisContexts.empty() &&
  1898. CodeSynthesisContexts.back().Kind ==
  1899. CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
  1900. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1901. bool isInstance = CurMethod && CurMethod->isInstance() &&
  1902. R.getNamingClass() == CurMethod->getParent() &&
  1903. !isDefaultArgument;
  1904. // There are two ways we can find a class-scope declaration during template
  1905. // instantiation that we did not find in the template definition: if it is a
  1906. // member of a dependent base class, or if it is declared after the point of
  1907. // use in the same class. Distinguish these by comparing the class in which
  1908. // the member was found to the naming class of the lookup.
  1909. unsigned DiagID = diag::err_found_in_dependent_base;
  1910. unsigned NoteID = diag::note_member_declared_at;
  1911. if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
  1912. DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
  1913. : diag::err_found_later_in_class;
  1914. } else if (getLangOpts().MSVCCompat) {
  1915. DiagID = diag::ext_found_in_dependent_base;
  1916. NoteID = diag::note_dependent_member_use;
  1917. }
  1918. if (isInstance) {
  1919. // Give a code modification hint to insert 'this->'.
  1920. Diag(R.getNameLoc(), DiagID)
  1921. << R.getLookupName()
  1922. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1923. CheckCXXThisCapture(R.getNameLoc());
  1924. } else {
  1925. // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
  1926. // they're not shadowed).
  1927. Diag(R.getNameLoc(), DiagID) << R.getLookupName();
  1928. }
  1929. for (NamedDecl *D : R)
  1930. Diag(D->getLocation(), NoteID);
  1931. // Return true if we are inside a default argument instantiation
  1932. // and the found name refers to an instance member function, otherwise
  1933. // the caller will try to create an implicit member call and this is wrong
  1934. // for default arguments.
  1935. //
  1936. // FIXME: Is this special case necessary? We could allow the caller to
  1937. // diagnose this.
  1938. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1939. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1940. return true;
  1941. }
  1942. // Tell the callee to try to recover.
  1943. return false;
  1944. }
  1945. /// Diagnose an empty lookup.
  1946. ///
  1947. /// \return false if new lookup candidates were found
  1948. bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1949. CorrectionCandidateCallback &CCC,
  1950. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1951. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1952. DeclarationName Name = R.getLookupName();
  1953. unsigned diagnostic = diag::err_undeclared_var_use;
  1954. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1955. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1956. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1957. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1958. diagnostic = diag::err_undeclared_use;
  1959. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1960. }
  1961. // If the original lookup was an unqualified lookup, fake an
  1962. // unqualified lookup. This is useful when (for example) the
  1963. // original lookup would not have found something because it was a
  1964. // dependent name.
  1965. DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
  1966. while (DC) {
  1967. if (isa<CXXRecordDecl>(DC)) {
  1968. LookupQualifiedName(R, DC);
  1969. if (!R.empty()) {
  1970. // Don't give errors about ambiguities in this lookup.
  1971. R.suppressDiagnostics();
  1972. // If there's a best viable function among the results, only mention
  1973. // that one in the notes.
  1974. OverloadCandidateSet Candidates(R.getNameLoc(),
  1975. OverloadCandidateSet::CSK_Normal);
  1976. AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
  1977. OverloadCandidateSet::iterator Best;
  1978. if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
  1979. OR_Success) {
  1980. R.clear();
  1981. R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
  1982. R.resolveKind();
  1983. }
  1984. return DiagnoseDependentMemberLookup(R);
  1985. }
  1986. R.clear();
  1987. }
  1988. DC = DC->getLookupParent();
  1989. }
  1990. // We didn't find anything, so try to correct for a typo.
  1991. TypoCorrection Corrected;
  1992. if (S && Out) {
  1993. SourceLocation TypoLoc = R.getNameLoc();
  1994. assert(!ExplicitTemplateArgs &&
  1995. "Diagnosing an empty lookup with explicit template args!");
  1996. *Out = CorrectTypoDelayed(
  1997. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
  1998. [=](const TypoCorrection &TC) {
  1999. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  2000. diagnostic, diagnostic_suggest);
  2001. },
  2002. nullptr, CTK_ErrorRecovery);
  2003. if (*Out)
  2004. return true;
  2005. } else if (S &&
  2006. (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
  2007. S, &SS, CCC, CTK_ErrorRecovery))) {
  2008. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  2009. bool DroppedSpecifier =
  2010. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  2011. R.setLookupName(Corrected.getCorrection());
  2012. bool AcceptableWithRecovery = false;
  2013. bool AcceptableWithoutRecovery = false;
  2014. NamedDecl *ND = Corrected.getFoundDecl();
  2015. if (ND) {
  2016. if (Corrected.isOverloaded()) {
  2017. OverloadCandidateSet OCS(R.getNameLoc(),
  2018. OverloadCandidateSet::CSK_Normal);
  2019. OverloadCandidateSet::iterator Best;
  2020. for (NamedDecl *CD : Corrected) {
  2021. if (FunctionTemplateDecl *FTD =
  2022. dyn_cast<FunctionTemplateDecl>(CD))
  2023. AddTemplateOverloadCandidate(
  2024. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  2025. Args, OCS);
  2026. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  2027. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  2028. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  2029. Args, OCS);
  2030. }
  2031. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  2032. case OR_Success:
  2033. ND = Best->FoundDecl;
  2034. Corrected.setCorrectionDecl(ND);
  2035. break;
  2036. default:
  2037. // FIXME: Arbitrarily pick the first declaration for the note.
  2038. Corrected.setCorrectionDecl(ND);
  2039. break;
  2040. }
  2041. }
  2042. R.addDecl(ND);
  2043. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  2044. CXXRecordDecl *Record = nullptr;
  2045. if (Corrected.getCorrectionSpecifier()) {
  2046. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  2047. Record = Ty->getAsCXXRecordDecl();
  2048. }
  2049. if (!Record)
  2050. Record = cast<CXXRecordDecl>(
  2051. ND->getDeclContext()->getRedeclContext());
  2052. R.setNamingClass(Record);
  2053. }
  2054. auto *UnderlyingND = ND->getUnderlyingDecl();
  2055. AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
  2056. isa<FunctionTemplateDecl>(UnderlyingND);
  2057. // FIXME: If we ended up with a typo for a type name or
  2058. // Objective-C class name, we're in trouble because the parser
  2059. // is in the wrong place to recover. Suggest the typo
  2060. // correction, but don't make it a fix-it since we're not going
  2061. // to recover well anyway.
  2062. AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
  2063. getAsTypeTemplateDecl(UnderlyingND) ||
  2064. isa<ObjCInterfaceDecl>(UnderlyingND);
  2065. } else {
  2066. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  2067. // because we aren't able to recover.
  2068. AcceptableWithoutRecovery = true;
  2069. }
  2070. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  2071. unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
  2072. ? diag::note_implicit_param_decl
  2073. : diag::note_previous_decl;
  2074. if (SS.isEmpty())
  2075. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  2076. PDiag(NoteID), AcceptableWithRecovery);
  2077. else
  2078. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  2079. << Name << computeDeclContext(SS, false)
  2080. << DroppedSpecifier << SS.getRange(),
  2081. PDiag(NoteID), AcceptableWithRecovery);
  2082. // Tell the callee whether to try to recover.
  2083. return !AcceptableWithRecovery;
  2084. }
  2085. }
  2086. R.clear();
  2087. // Emit a special diagnostic for failed member lookups.
  2088. // FIXME: computing the declaration context might fail here (?)
  2089. if (!SS.isEmpty()) {
  2090. Diag(R.getNameLoc(), diag::err_no_member)
  2091. << Name << computeDeclContext(SS, false)
  2092. << SS.getRange();
  2093. return true;
  2094. }
  2095. // Give up, we can't recover.
  2096. Diag(R.getNameLoc(), diagnostic) << Name;
  2097. return true;
  2098. }
  2099. /// In Microsoft mode, if we are inside a template class whose parent class has
  2100. /// dependent base classes, and we can't resolve an unqualified identifier, then
  2101. /// assume the identifier is a member of a dependent base class. We can only
  2102. /// recover successfully in static methods, instance methods, and other contexts
  2103. /// where 'this' is available. This doesn't precisely match MSVC's
  2104. /// instantiation model, but it's close enough.
  2105. static Expr *
  2106. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  2107. DeclarationNameInfo &NameInfo,
  2108. SourceLocation TemplateKWLoc,
  2109. const TemplateArgumentListInfo *TemplateArgs) {
  2110. // Only try to recover from lookup into dependent bases in static methods or
  2111. // contexts where 'this' is available.
  2112. QualType ThisType = S.getCurrentThisType();
  2113. const CXXRecordDecl *RD = nullptr;
  2114. if (!ThisType.isNull())
  2115. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  2116. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  2117. RD = MD->getParent();
  2118. if (!RD || !RD->hasAnyDependentBases())
  2119. return nullptr;
  2120. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  2121. // is available, suggest inserting 'this->' as a fixit.
  2122. SourceLocation Loc = NameInfo.getLoc();
  2123. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  2124. DB << NameInfo.getName() << RD;
  2125. if (!ThisType.isNull()) {
  2126. DB << FixItHint::CreateInsertion(Loc, "this->");
  2127. return CXXDependentScopeMemberExpr::Create(
  2128. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  2129. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  2130. /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
  2131. }
  2132. // Synthesize a fake NNS that points to the derived class. This will
  2133. // perform name lookup during template instantiation.
  2134. CXXScopeSpec SS;
  2135. auto *NNS =
  2136. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  2137. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  2138. return DependentScopeDeclRefExpr::Create(
  2139. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  2140. TemplateArgs);
  2141. }
  2142. ExprResult
  2143. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  2144. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  2145. bool HasTrailingLParen, bool IsAddressOfOperand,
  2146. CorrectionCandidateCallback *CCC,
  2147. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  2148. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  2149. "cannot be direct & operand and have a trailing lparen");
  2150. if (SS.isInvalid())
  2151. return ExprError();
  2152. TemplateArgumentListInfo TemplateArgsBuffer;
  2153. // Decompose the UnqualifiedId into the following data.
  2154. DeclarationNameInfo NameInfo;
  2155. const TemplateArgumentListInfo *TemplateArgs;
  2156. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  2157. DeclarationName Name = NameInfo.getName();
  2158. IdentifierInfo *II = Name.getAsIdentifierInfo();
  2159. SourceLocation NameLoc = NameInfo.getLoc();
  2160. if (II && II->isEditorPlaceholder()) {
  2161. // FIXME: When typed placeholders are supported we can create a typed
  2162. // placeholder expression node.
  2163. return ExprError();
  2164. }
  2165. // C++ [temp.dep.expr]p3:
  2166. // An id-expression is type-dependent if it contains:
  2167. // -- an identifier that was declared with a dependent type,
  2168. // (note: handled after lookup)
  2169. // -- a template-id that is dependent,
  2170. // (note: handled in BuildTemplateIdExpr)
  2171. // -- a conversion-function-id that specifies a dependent type,
  2172. // -- a nested-name-specifier that contains a class-name that
  2173. // names a dependent type.
  2174. // Determine whether this is a member of an unknown specialization;
  2175. // we need to handle these differently.
  2176. bool DependentID = false;
  2177. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  2178. Name.getCXXNameType()->isDependentType()) {
  2179. DependentID = true;
  2180. } else if (SS.isSet()) {
  2181. if (DeclContext *DC = computeDeclContext(SS, false)) {
  2182. if (RequireCompleteDeclContext(SS, DC))
  2183. return ExprError();
  2184. } else {
  2185. DependentID = true;
  2186. }
  2187. }
  2188. if (DependentID)
  2189. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  2190. IsAddressOfOperand, TemplateArgs);
  2191. // Perform the required lookup.
  2192. LookupResult R(*this, NameInfo,
  2193. (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
  2194. ? LookupObjCImplicitSelfParam
  2195. : LookupOrdinaryName);
  2196. if (TemplateKWLoc.isValid() || TemplateArgs) {
  2197. // Lookup the template name again to correctly establish the context in
  2198. // which it was found. This is really unfortunate as we already did the
  2199. // lookup to determine that it was a template name in the first place. If
  2200. // this becomes a performance hit, we can work harder to preserve those
  2201. // results until we get here but it's likely not worth it.
  2202. bool MemberOfUnknownSpecialization;
  2203. AssumedTemplateKind AssumedTemplate;
  2204. if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  2205. MemberOfUnknownSpecialization, TemplateKWLoc,
  2206. &AssumedTemplate))
  2207. return ExprError();
  2208. if (MemberOfUnknownSpecialization ||
  2209. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  2210. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  2211. IsAddressOfOperand, TemplateArgs);
  2212. } else {
  2213. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  2214. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  2215. // If the result might be in a dependent base class, this is a dependent
  2216. // id-expression.
  2217. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2218. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  2219. IsAddressOfOperand, TemplateArgs);
  2220. // If this reference is in an Objective-C method, then we need to do
  2221. // some special Objective-C lookup, too.
  2222. if (IvarLookupFollowUp) {
  2223. ExprResult E(LookupInObjCMethod(R, S, II, true));
  2224. if (E.isInvalid())
  2225. return ExprError();
  2226. if (Expr *Ex = E.getAs<Expr>())
  2227. return Ex;
  2228. }
  2229. }
  2230. if (R.isAmbiguous())
  2231. return ExprError();
  2232. // This could be an implicitly declared function reference (legal in C90,
  2233. // extension in C99, forbidden in C++).
  2234. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  2235. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  2236. if (D) R.addDecl(D);
  2237. }
  2238. // Determine whether this name might be a candidate for
  2239. // argument-dependent lookup.
  2240. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  2241. if (R.empty() && !ADL) {
  2242. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  2243. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  2244. TemplateKWLoc, TemplateArgs))
  2245. return E;
  2246. }
  2247. // Don't diagnose an empty lookup for inline assembly.
  2248. if (IsInlineAsmIdentifier)
  2249. return ExprError();
  2250. // If this name wasn't predeclared and if this is not a function
  2251. // call, diagnose the problem.
  2252. TypoExpr *TE = nullptr;
  2253. DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
  2254. : nullptr);
  2255. DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
  2256. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  2257. "Typo correction callback misconfigured");
  2258. if (CCC) {
  2259. // Make sure the callback knows what the typo being diagnosed is.
  2260. CCC->setTypoName(II);
  2261. if (SS.isValid())
  2262. CCC->setTypoNNS(SS.getScopeRep());
  2263. }
  2264. // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
  2265. // a template name, but we happen to have always already looked up the name
  2266. // before we get here if it must be a template name.
  2267. if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
  2268. None, &TE)) {
  2269. if (TE && KeywordReplacement) {
  2270. auto &State = getTypoExprState(TE);
  2271. auto BestTC = State.Consumer->getNextCorrection();
  2272. if (BestTC.isKeyword()) {
  2273. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  2274. if (State.DiagHandler)
  2275. State.DiagHandler(BestTC);
  2276. KeywordReplacement->startToken();
  2277. KeywordReplacement->setKind(II->getTokenID());
  2278. KeywordReplacement->setIdentifierInfo(II);
  2279. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  2280. // Clean up the state associated with the TypoExpr, since it has
  2281. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  2282. clearDelayedTypo(TE);
  2283. // Signal that a correction to a keyword was performed by returning a
  2284. // valid-but-null ExprResult.
  2285. return (Expr*)nullptr;
  2286. }
  2287. State.Consumer->resetCorrectionStream();
  2288. }
  2289. return TE ? TE : ExprError();
  2290. }
  2291. assert(!R.empty() &&
  2292. "DiagnoseEmptyLookup returned false but added no results");
  2293. // If we found an Objective-C instance variable, let
  2294. // LookupInObjCMethod build the appropriate expression to
  2295. // reference the ivar.
  2296. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  2297. R.clear();
  2298. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  2299. // In a hopelessly buggy code, Objective-C instance variable
  2300. // lookup fails and no expression will be built to reference it.
  2301. if (!E.isInvalid() && !E.get())
  2302. return ExprError();
  2303. return E;
  2304. }
  2305. }
  2306. // This is guaranteed from this point on.
  2307. assert(!R.empty() || ADL);
  2308. // Check whether this might be a C++ implicit instance member access.
  2309. // C++ [class.mfct.non-static]p3:
  2310. // When an id-expression that is not part of a class member access
  2311. // syntax and not used to form a pointer to member is used in the
  2312. // body of a non-static member function of class X, if name lookup
  2313. // resolves the name in the id-expression to a non-static non-type
  2314. // member of some class C, the id-expression is transformed into a
  2315. // class member access expression using (*this) as the
  2316. // postfix-expression to the left of the . operator.
  2317. //
  2318. // But we don't actually need to do this for '&' operands if R
  2319. // resolved to a function or overloaded function set, because the
  2320. // expression is ill-formed if it actually works out to be a
  2321. // non-static member function:
  2322. //
  2323. // C++ [expr.ref]p4:
  2324. // Otherwise, if E1.E2 refers to a non-static member function. . .
  2325. // [t]he expression can be used only as the left-hand operand of a
  2326. // member function call.
  2327. //
  2328. // There are other safeguards against such uses, but it's important
  2329. // to get this right here so that we don't end up making a
  2330. // spuriously dependent expression if we're inside a dependent
  2331. // instance method.
  2332. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  2333. bool MightBeImplicitMember;
  2334. if (!IsAddressOfOperand)
  2335. MightBeImplicitMember = true;
  2336. else if (!SS.isEmpty())
  2337. MightBeImplicitMember = false;
  2338. else if (R.isOverloadedResult())
  2339. MightBeImplicitMember = false;
  2340. else if (R.isUnresolvableResult())
  2341. MightBeImplicitMember = true;
  2342. else
  2343. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  2344. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  2345. isa<MSPropertyDecl>(R.getFoundDecl());
  2346. if (MightBeImplicitMember)
  2347. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  2348. R, TemplateArgs, S);
  2349. }
  2350. if (TemplateArgs || TemplateKWLoc.isValid()) {
  2351. // In C++1y, if this is a variable template id, then check it
  2352. // in BuildTemplateIdExpr().
  2353. // The single lookup result must be a variable template declaration.
  2354. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
  2355. Id.TemplateId->Kind == TNK_Var_template) {
  2356. assert(R.getAsSingle<VarTemplateDecl>() &&
  2357. "There should only be one declaration found.");
  2358. }
  2359. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  2360. }
  2361. return BuildDeclarationNameExpr(SS, R, ADL);
  2362. }
  2363. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2364. /// declaration name, generally during template instantiation.
  2365. /// There's a large number of things which don't need to be done along
  2366. /// this path.
  2367. ExprResult Sema::BuildQualifiedDeclarationNameExpr(
  2368. CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
  2369. bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
  2370. DeclContext *DC = computeDeclContext(SS, false);
  2371. if (!DC)
  2372. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2373. NameInfo, /*TemplateArgs=*/nullptr);
  2374. if (RequireCompleteDeclContext(SS, DC))
  2375. return ExprError();
  2376. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2377. LookupQualifiedName(R, DC);
  2378. if (R.isAmbiguous())
  2379. return ExprError();
  2380. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2381. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2382. NameInfo, /*TemplateArgs=*/nullptr);
  2383. if (R.empty()) {
  2384. // Don't diagnose problems with invalid record decl, the secondary no_member
  2385. // diagnostic during template instantiation is likely bogus, e.g. if a class
  2386. // is invalid because it's derived from an invalid base class, then missing
  2387. // members were likely supposed to be inherited.
  2388. if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
  2389. if (CD->isInvalidDecl())
  2390. return ExprError();
  2391. Diag(NameInfo.getLoc(), diag::err_no_member)
  2392. << NameInfo.getName() << DC << SS.getRange();
  2393. return ExprError();
  2394. }
  2395. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2396. // Diagnose a missing typename if this resolved unambiguously to a type in
  2397. // a dependent context. If we can recover with a type, downgrade this to
  2398. // a warning in Microsoft compatibility mode.
  2399. unsigned DiagID = diag::err_typename_missing;
  2400. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2401. DiagID = diag::ext_typename_missing;
  2402. SourceLocation Loc = SS.getBeginLoc();
  2403. auto D = Diag(Loc, DiagID);
  2404. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2405. << SourceRange(Loc, NameInfo.getEndLoc());
  2406. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2407. // context.
  2408. if (!RecoveryTSI)
  2409. return ExprError();
  2410. // Only issue the fixit if we're prepared to recover.
  2411. D << FixItHint::CreateInsertion(Loc, "typename ");
  2412. // Recover by pretending this was an elaborated type.
  2413. QualType Ty = Context.getTypeDeclType(TD);
  2414. TypeLocBuilder TLB;
  2415. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2416. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2417. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2418. QTL.setElaboratedKeywordLoc(SourceLocation());
  2419. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2420. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2421. return ExprEmpty();
  2422. }
  2423. // Defend against this resolving to an implicit member access. We usually
  2424. // won't get here if this might be a legitimate a class member (we end up in
  2425. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2426. // a pointer-to-member or in an unevaluated context in C++11.
  2427. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2428. return BuildPossibleImplicitMemberExpr(SS,
  2429. /*TemplateKWLoc=*/SourceLocation(),
  2430. R, /*TemplateArgs=*/nullptr, S);
  2431. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2432. }
  2433. /// The parser has read a name in, and Sema has detected that we're currently
  2434. /// inside an ObjC method. Perform some additional checks and determine if we
  2435. /// should form a reference to an ivar.
  2436. ///
  2437. /// Ideally, most of this would be done by lookup, but there's
  2438. /// actually quite a lot of extra work involved.
  2439. DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
  2440. IdentifierInfo *II) {
  2441. SourceLocation Loc = Lookup.getNameLoc();
  2442. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2443. // Check for error condition which is already reported.
  2444. if (!CurMethod)
  2445. return DeclResult(true);
  2446. // There are two cases to handle here. 1) scoped lookup could have failed,
  2447. // in which case we should look for an ivar. 2) scoped lookup could have
  2448. // found a decl, but that decl is outside the current instance method (i.e.
  2449. // a global variable). In these two cases, we do a lookup for an ivar with
  2450. // this name, if the lookup sucedes, we replace it our current decl.
  2451. // If we're in a class method, we don't normally want to look for
  2452. // ivars. But if we don't find anything else, and there's an
  2453. // ivar, that's an error.
  2454. bool IsClassMethod = CurMethod->isClassMethod();
  2455. bool LookForIvars;
  2456. if (Lookup.empty())
  2457. LookForIvars = true;
  2458. else if (IsClassMethod)
  2459. LookForIvars = false;
  2460. else
  2461. LookForIvars = (Lookup.isSingleResult() &&
  2462. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2463. ObjCInterfaceDecl *IFace = nullptr;
  2464. if (LookForIvars) {
  2465. IFace = CurMethod->getClassInterface();
  2466. ObjCInterfaceDecl *ClassDeclared;
  2467. ObjCIvarDecl *IV = nullptr;
  2468. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2469. // Diagnose using an ivar in a class method.
  2470. if (IsClassMethod) {
  2471. Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
  2472. return DeclResult(true);
  2473. }
  2474. // Diagnose the use of an ivar outside of the declaring class.
  2475. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2476. !declaresSameEntity(ClassDeclared, IFace) &&
  2477. !getLangOpts().DebuggerSupport)
  2478. Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
  2479. // Success.
  2480. return IV;
  2481. }
  2482. } else if (CurMethod->isInstanceMethod()) {
  2483. // We should warn if a local variable hides an ivar.
  2484. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2485. ObjCInterfaceDecl *ClassDeclared;
  2486. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2487. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2488. declaresSameEntity(IFace, ClassDeclared))
  2489. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2490. }
  2491. }
  2492. } else if (Lookup.isSingleResult() &&
  2493. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2494. // If accessing a stand-alone ivar in a class method, this is an error.
  2495. if (const ObjCIvarDecl *IV =
  2496. dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
  2497. Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
  2498. return DeclResult(true);
  2499. }
  2500. }
  2501. // Didn't encounter an error, didn't find an ivar.
  2502. return DeclResult(false);
  2503. }
  2504. ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
  2505. ObjCIvarDecl *IV) {
  2506. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2507. assert(CurMethod && CurMethod->isInstanceMethod() &&
  2508. "should not reference ivar from this context");
  2509. ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
  2510. assert(IFace && "should not reference ivar from this context");
  2511. // If we're referencing an invalid decl, just return this as a silent
  2512. // error node. The error diagnostic was already emitted on the decl.
  2513. if (IV->isInvalidDecl())
  2514. return ExprError();
  2515. // Check if referencing a field with __attribute__((deprecated)).
  2516. if (DiagnoseUseOfDecl(IV, Loc))
  2517. return ExprError();
  2518. // FIXME: This should use a new expr for a direct reference, don't
  2519. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2520. IdentifierInfo &II = Context.Idents.get("self");
  2521. UnqualifiedId SelfName;
  2522. SelfName.setImplicitSelfParam(&II);
  2523. CXXScopeSpec SelfScopeSpec;
  2524. SourceLocation TemplateKWLoc;
  2525. ExprResult SelfExpr =
  2526. ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
  2527. /*HasTrailingLParen=*/false,
  2528. /*IsAddressOfOperand=*/false);
  2529. if (SelfExpr.isInvalid())
  2530. return ExprError();
  2531. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2532. if (SelfExpr.isInvalid())
  2533. return ExprError();
  2534. MarkAnyDeclReferenced(Loc, IV, true);
  2535. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2536. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2537. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2538. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2539. ObjCIvarRefExpr *Result = new (Context)
  2540. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2541. IV->getLocation(), SelfExpr.get(), true, true);
  2542. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2543. if (!isUnevaluatedContext() &&
  2544. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2545. getCurFunction()->recordUseOfWeak(Result);
  2546. }
  2547. if (getLangOpts().ObjCAutoRefCount)
  2548. if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
  2549. ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
  2550. return Result;
  2551. }
  2552. /// The parser has read a name in, and Sema has detected that we're currently
  2553. /// inside an ObjC method. Perform some additional checks and determine if we
  2554. /// should form a reference to an ivar. If so, build an expression referencing
  2555. /// that ivar.
  2556. ExprResult
  2557. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2558. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2559. // FIXME: Integrate this lookup step into LookupParsedName.
  2560. DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
  2561. if (Ivar.isInvalid())
  2562. return ExprError();
  2563. if (Ivar.isUsable())
  2564. return BuildIvarRefExpr(S, Lookup.getNameLoc(),
  2565. cast<ObjCIvarDecl>(Ivar.get()));
  2566. if (Lookup.empty() && II && AllowBuiltinCreation)
  2567. LookupBuiltin(Lookup);
  2568. // Sentinel value saying that we didn't do anything special.
  2569. return ExprResult(false);
  2570. }
  2571. /// Cast a base object to a member's actual type.
  2572. ///
  2573. /// There are two relevant checks:
  2574. ///
  2575. /// C++ [class.access.base]p7:
  2576. ///
  2577. /// If a class member access operator [...] is used to access a non-static
  2578. /// data member or non-static member function, the reference is ill-formed if
  2579. /// the left operand [...] cannot be implicitly converted to a pointer to the
  2580. /// naming class of the right operand.
  2581. ///
  2582. /// C++ [expr.ref]p7:
  2583. ///
  2584. /// If E2 is a non-static data member or a non-static member function, the
  2585. /// program is ill-formed if the class of which E2 is directly a member is an
  2586. /// ambiguous base (11.8) of the naming class (11.9.3) of E2.
  2587. ///
  2588. /// Note that the latter check does not consider access; the access of the
  2589. /// "real" base class is checked as appropriate when checking the access of the
  2590. /// member name.
  2591. ExprResult
  2592. Sema::PerformObjectMemberConversion(Expr *From,
  2593. NestedNameSpecifier *Qualifier,
  2594. NamedDecl *FoundDecl,
  2595. NamedDecl *Member) {
  2596. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2597. if (!RD)
  2598. return From;
  2599. QualType DestRecordType;
  2600. QualType DestType;
  2601. QualType FromRecordType;
  2602. QualType FromType = From->getType();
  2603. bool PointerConversions = false;
  2604. if (isa<FieldDecl>(Member)) {
  2605. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2606. auto FromPtrType = FromType->getAs<PointerType>();
  2607. DestRecordType = Context.getAddrSpaceQualType(
  2608. DestRecordType, FromPtrType
  2609. ? FromType->getPointeeType().getAddressSpace()
  2610. : FromType.getAddressSpace());
  2611. if (FromPtrType) {
  2612. DestType = Context.getPointerType(DestRecordType);
  2613. FromRecordType = FromPtrType->getPointeeType();
  2614. PointerConversions = true;
  2615. } else {
  2616. DestType = DestRecordType;
  2617. FromRecordType = FromType;
  2618. }
  2619. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2620. if (Method->isStatic())
  2621. return From;
  2622. DestType = Method->getThisType();
  2623. DestRecordType = DestType->getPointeeType();
  2624. if (FromType->getAs<PointerType>()) {
  2625. FromRecordType = FromType->getPointeeType();
  2626. PointerConversions = true;
  2627. } else {
  2628. FromRecordType = FromType;
  2629. DestType = DestRecordType;
  2630. }
  2631. LangAS FromAS = FromRecordType.getAddressSpace();
  2632. LangAS DestAS = DestRecordType.getAddressSpace();
  2633. if (FromAS != DestAS) {
  2634. QualType FromRecordTypeWithoutAS =
  2635. Context.removeAddrSpaceQualType(FromRecordType);
  2636. QualType FromTypeWithDestAS =
  2637. Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
  2638. if (PointerConversions)
  2639. FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
  2640. From = ImpCastExprToType(From, FromTypeWithDestAS,
  2641. CK_AddressSpaceConversion, From->getValueKind())
  2642. .get();
  2643. }
  2644. } else {
  2645. // No conversion necessary.
  2646. return From;
  2647. }
  2648. if (DestType->isDependentType() || FromType->isDependentType())
  2649. return From;
  2650. // If the unqualified types are the same, no conversion is necessary.
  2651. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2652. return From;
  2653. SourceRange FromRange = From->getSourceRange();
  2654. SourceLocation FromLoc = FromRange.getBegin();
  2655. ExprValueKind VK = From->getValueKind();
  2656. // C++ [class.member.lookup]p8:
  2657. // [...] Ambiguities can often be resolved by qualifying a name with its
  2658. // class name.
  2659. //
  2660. // If the member was a qualified name and the qualified referred to a
  2661. // specific base subobject type, we'll cast to that intermediate type
  2662. // first and then to the object in which the member is declared. That allows
  2663. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2664. //
  2665. // class Base { public: int x; };
  2666. // class Derived1 : public Base { };
  2667. // class Derived2 : public Base { };
  2668. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2669. //
  2670. // void VeryDerived::f() {
  2671. // x = 17; // error: ambiguous base subobjects
  2672. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2673. // }
  2674. if (Qualifier && Qualifier->getAsType()) {
  2675. QualType QType = QualType(Qualifier->getAsType(), 0);
  2676. assert(QType->isRecordType() && "lookup done with non-record type");
  2677. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2678. // In C++98, the qualifier type doesn't actually have to be a base
  2679. // type of the object type, in which case we just ignore it.
  2680. // Otherwise build the appropriate casts.
  2681. if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
  2682. CXXCastPath BasePath;
  2683. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2684. FromLoc, FromRange, &BasePath))
  2685. return ExprError();
  2686. if (PointerConversions)
  2687. QType = Context.getPointerType(QType);
  2688. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2689. VK, &BasePath).get();
  2690. FromType = QType;
  2691. FromRecordType = QRecordType;
  2692. // If the qualifier type was the same as the destination type,
  2693. // we're done.
  2694. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2695. return From;
  2696. }
  2697. }
  2698. CXXCastPath BasePath;
  2699. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2700. FromLoc, FromRange, &BasePath,
  2701. /*IgnoreAccess=*/true))
  2702. return ExprError();
  2703. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2704. VK, &BasePath);
  2705. }
  2706. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2707. const LookupResult &R,
  2708. bool HasTrailingLParen) {
  2709. // Only when used directly as the postfix-expression of a call.
  2710. if (!HasTrailingLParen)
  2711. return false;
  2712. // Never if a scope specifier was provided.
  2713. if (SS.isSet())
  2714. return false;
  2715. // Only in C++ or ObjC++.
  2716. if (!getLangOpts().CPlusPlus)
  2717. return false;
  2718. // Turn off ADL when we find certain kinds of declarations during
  2719. // normal lookup:
  2720. for (NamedDecl *D : R) {
  2721. // C++0x [basic.lookup.argdep]p3:
  2722. // -- a declaration of a class member
  2723. // Since using decls preserve this property, we check this on the
  2724. // original decl.
  2725. if (D->isCXXClassMember())
  2726. return false;
  2727. // C++0x [basic.lookup.argdep]p3:
  2728. // -- a block-scope function declaration that is not a
  2729. // using-declaration
  2730. // NOTE: we also trigger this for function templates (in fact, we
  2731. // don't check the decl type at all, since all other decl types
  2732. // turn off ADL anyway).
  2733. if (isa<UsingShadowDecl>(D))
  2734. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2735. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2736. return false;
  2737. // C++0x [basic.lookup.argdep]p3:
  2738. // -- a declaration that is neither a function or a function
  2739. // template
  2740. // And also for builtin functions.
  2741. if (isa<FunctionDecl>(D)) {
  2742. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2743. // But also builtin functions.
  2744. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2745. return false;
  2746. } else if (!isa<FunctionTemplateDecl>(D))
  2747. return false;
  2748. }
  2749. return true;
  2750. }
  2751. /// Diagnoses obvious problems with the use of the given declaration
  2752. /// as an expression. This is only actually called for lookups that
  2753. /// were not overloaded, and it doesn't promise that the declaration
  2754. /// will in fact be used.
  2755. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2756. if (D->isInvalidDecl())
  2757. return true;
  2758. if (isa<TypedefNameDecl>(D)) {
  2759. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2760. return true;
  2761. }
  2762. if (isa<ObjCInterfaceDecl>(D)) {
  2763. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2764. return true;
  2765. }
  2766. if (isa<NamespaceDecl>(D)) {
  2767. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2768. return true;
  2769. }
  2770. return false;
  2771. }
  2772. // Certain multiversion types should be treated as overloaded even when there is
  2773. // only one result.
  2774. static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
  2775. assert(R.isSingleResult() && "Expected only a single result");
  2776. const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  2777. return FD &&
  2778. (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
  2779. }
  2780. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2781. LookupResult &R, bool NeedsADL,
  2782. bool AcceptInvalidDecl) {
  2783. // If this is a single, fully-resolved result and we don't need ADL,
  2784. // just build an ordinary singleton decl ref.
  2785. if (!NeedsADL && R.isSingleResult() &&
  2786. !R.getAsSingle<FunctionTemplateDecl>() &&
  2787. !ShouldLookupResultBeMultiVersionOverload(R))
  2788. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2789. R.getRepresentativeDecl(), nullptr,
  2790. AcceptInvalidDecl);
  2791. // We only need to check the declaration if there's exactly one
  2792. // result, because in the overloaded case the results can only be
  2793. // functions and function templates.
  2794. if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
  2795. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2796. return ExprError();
  2797. // Otherwise, just build an unresolved lookup expression. Suppress
  2798. // any lookup-related diagnostics; we'll hash these out later, when
  2799. // we've picked a target.
  2800. R.suppressDiagnostics();
  2801. UnresolvedLookupExpr *ULE
  2802. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2803. SS.getWithLocInContext(Context),
  2804. R.getLookupNameInfo(),
  2805. NeedsADL, R.isOverloadedResult(),
  2806. R.begin(), R.end());
  2807. return ULE;
  2808. }
  2809. static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  2810. ValueDecl *var);
  2811. /// Complete semantic analysis for a reference to the given declaration.
  2812. ExprResult Sema::BuildDeclarationNameExpr(
  2813. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2814. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2815. bool AcceptInvalidDecl) {
  2816. assert(D && "Cannot refer to a NULL declaration");
  2817. assert(!isa<FunctionTemplateDecl>(D) &&
  2818. "Cannot refer unambiguously to a function template");
  2819. SourceLocation Loc = NameInfo.getLoc();
  2820. if (CheckDeclInExpr(*this, Loc, D))
  2821. return ExprError();
  2822. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2823. // Specifically diagnose references to class templates that are missing
  2824. // a template argument list.
  2825. diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
  2826. return ExprError();
  2827. }
  2828. // Make sure that we're referring to a value.
  2829. if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
  2830. Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
  2831. Diag(D->getLocation(), diag::note_declared_at);
  2832. return ExprError();
  2833. }
  2834. // Check whether this declaration can be used. Note that we suppress
  2835. // this check when we're going to perform argument-dependent lookup
  2836. // on this function name, because this might not be the function
  2837. // that overload resolution actually selects.
  2838. if (DiagnoseUseOfDecl(D, Loc))
  2839. return ExprError();
  2840. auto *VD = cast<ValueDecl>(D);
  2841. // Only create DeclRefExpr's for valid Decl's.
  2842. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2843. return ExprError();
  2844. // Handle members of anonymous structs and unions. If we got here,
  2845. // and the reference is to a class member indirect field, then this
  2846. // must be the subject of a pointer-to-member expression.
  2847. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2848. if (!indirectField->isCXXClassMember())
  2849. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2850. indirectField);
  2851. QualType type = VD->getType();
  2852. if (type.isNull())
  2853. return ExprError();
  2854. ExprValueKind valueKind = VK_PRValue;
  2855. // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
  2856. // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
  2857. // is expanded by some outer '...' in the context of the use.
  2858. type = type.getNonPackExpansionType();
  2859. switch (D->getKind()) {
  2860. // Ignore all the non-ValueDecl kinds.
  2861. #define ABSTRACT_DECL(kind)
  2862. #define VALUE(type, base)
  2863. #define DECL(type, base) case Decl::type:
  2864. #include "clang/AST/DeclNodes.inc"
  2865. llvm_unreachable("invalid value decl kind");
  2866. // These shouldn't make it here.
  2867. case Decl::ObjCAtDefsField:
  2868. llvm_unreachable("forming non-member reference to ivar?");
  2869. // Enum constants are always r-values and never references.
  2870. // Unresolved using declarations are dependent.
  2871. case Decl::EnumConstant:
  2872. case Decl::UnresolvedUsingValue:
  2873. case Decl::OMPDeclareReduction:
  2874. case Decl::OMPDeclareMapper:
  2875. valueKind = VK_PRValue;
  2876. break;
  2877. // Fields and indirect fields that got here must be for
  2878. // pointer-to-member expressions; we just call them l-values for
  2879. // internal consistency, because this subexpression doesn't really
  2880. // exist in the high-level semantics.
  2881. case Decl::Field:
  2882. case Decl::IndirectField:
  2883. case Decl::ObjCIvar:
  2884. assert(getLangOpts().CPlusPlus && "building reference to field in C?");
  2885. // These can't have reference type in well-formed programs, but
  2886. // for internal consistency we do this anyway.
  2887. type = type.getNonReferenceType();
  2888. valueKind = VK_LValue;
  2889. break;
  2890. // Non-type template parameters are either l-values or r-values
  2891. // depending on the type.
  2892. case Decl::NonTypeTemplateParm: {
  2893. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2894. type = reftype->getPointeeType();
  2895. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2896. break;
  2897. }
  2898. // [expr.prim.id.unqual]p2:
  2899. // If the entity is a template parameter object for a template
  2900. // parameter of type T, the type of the expression is const T.
  2901. // [...] The expression is an lvalue if the entity is a [...] template
  2902. // parameter object.
  2903. if (type->isRecordType()) {
  2904. type = type.getUnqualifiedType().withConst();
  2905. valueKind = VK_LValue;
  2906. break;
  2907. }
  2908. // For non-references, we need to strip qualifiers just in case
  2909. // the template parameter was declared as 'const int' or whatever.
  2910. valueKind = VK_PRValue;
  2911. type = type.getUnqualifiedType();
  2912. break;
  2913. }
  2914. case Decl::Var:
  2915. case Decl::VarTemplateSpecialization:
  2916. case Decl::VarTemplatePartialSpecialization:
  2917. case Decl::Decomposition:
  2918. case Decl::OMPCapturedExpr:
  2919. // In C, "extern void blah;" is valid and is an r-value.
  2920. if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
  2921. type->isVoidType()) {
  2922. valueKind = VK_PRValue;
  2923. break;
  2924. }
  2925. LLVM_FALLTHROUGH;
  2926. case Decl::ImplicitParam:
  2927. case Decl::ParmVar: {
  2928. // These are always l-values.
  2929. valueKind = VK_LValue;
  2930. type = type.getNonReferenceType();
  2931. // FIXME: Does the addition of const really only apply in
  2932. // potentially-evaluated contexts? Since the variable isn't actually
  2933. // captured in an unevaluated context, it seems that the answer is no.
  2934. if (!isUnevaluatedContext()) {
  2935. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2936. if (!CapturedType.isNull())
  2937. type = CapturedType;
  2938. }
  2939. break;
  2940. }
  2941. case Decl::Binding: {
  2942. // These are always lvalues.
  2943. valueKind = VK_LValue;
  2944. type = type.getNonReferenceType();
  2945. // FIXME: Support lambda-capture of BindingDecls, once CWG actually
  2946. // decides how that's supposed to work.
  2947. auto *BD = cast<BindingDecl>(VD);
  2948. if (BD->getDeclContext() != CurContext) {
  2949. auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
  2950. if (DD && DD->hasLocalStorage())
  2951. diagnoseUncapturableValueReference(*this, Loc, BD);
  2952. }
  2953. break;
  2954. }
  2955. case Decl::Function: {
  2956. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2957. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2958. type = Context.BuiltinFnTy;
  2959. valueKind = VK_PRValue;
  2960. break;
  2961. }
  2962. }
  2963. const FunctionType *fty = type->castAs<FunctionType>();
  2964. // If we're referring to a function with an __unknown_anytype
  2965. // result type, make the entire expression __unknown_anytype.
  2966. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2967. type = Context.UnknownAnyTy;
  2968. valueKind = VK_PRValue;
  2969. break;
  2970. }
  2971. // Functions are l-values in C++.
  2972. if (getLangOpts().CPlusPlus) {
  2973. valueKind = VK_LValue;
  2974. break;
  2975. }
  2976. // C99 DR 316 says that, if a function type comes from a
  2977. // function definition (without a prototype), that type is only
  2978. // used for checking compatibility. Therefore, when referencing
  2979. // the function, we pretend that we don't have the full function
  2980. // type.
  2981. if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
  2982. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2983. fty->getExtInfo());
  2984. // Functions are r-values in C.
  2985. valueKind = VK_PRValue;
  2986. break;
  2987. }
  2988. case Decl::CXXDeductionGuide:
  2989. llvm_unreachable("building reference to deduction guide");
  2990. case Decl::MSProperty:
  2991. case Decl::MSGuid:
  2992. case Decl::TemplateParamObject:
  2993. // FIXME: Should MSGuidDecl and template parameter objects be subject to
  2994. // capture in OpenMP, or duplicated between host and device?
  2995. valueKind = VK_LValue;
  2996. break;
  2997. case Decl::CXXMethod:
  2998. // If we're referring to a method with an __unknown_anytype
  2999. // result type, make the entire expression __unknown_anytype.
  3000. // This should only be possible with a type written directly.
  3001. if (const FunctionProtoType *proto =
  3002. dyn_cast<FunctionProtoType>(VD->getType()))
  3003. if (proto->getReturnType() == Context.UnknownAnyTy) {
  3004. type = Context.UnknownAnyTy;
  3005. valueKind = VK_PRValue;
  3006. break;
  3007. }
  3008. // C++ methods are l-values if static, r-values if non-static.
  3009. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  3010. valueKind = VK_LValue;
  3011. break;
  3012. }
  3013. LLVM_FALLTHROUGH;
  3014. case Decl::CXXConversion:
  3015. case Decl::CXXDestructor:
  3016. case Decl::CXXConstructor:
  3017. valueKind = VK_PRValue;
  3018. break;
  3019. }
  3020. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  3021. /*FIXME: TemplateKWLoc*/ SourceLocation(),
  3022. TemplateArgs);
  3023. }
  3024. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  3025. SmallString<32> &Target) {
  3026. Target.resize(CharByteWidth * (Source.size() + 1));
  3027. char *ResultPtr = &Target[0];
  3028. const llvm::UTF8 *ErrorPtr;
  3029. bool success =
  3030. llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  3031. (void)success;
  3032. assert(success);
  3033. Target.resize(ResultPtr - &Target[0]);
  3034. }
  3035. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  3036. PredefinedExpr::IdentKind IK) {
  3037. // Pick the current block, lambda, captured statement or function.
  3038. Decl *currentDecl = nullptr;
  3039. if (const BlockScopeInfo *BSI = getCurBlock())
  3040. currentDecl = BSI->TheDecl;
  3041. else if (const LambdaScopeInfo *LSI = getCurLambda())
  3042. currentDecl = LSI->CallOperator;
  3043. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  3044. currentDecl = CSI->TheCapturedDecl;
  3045. else
  3046. currentDecl = getCurFunctionOrMethodDecl();
  3047. if (!currentDecl) {
  3048. Diag(Loc, diag::ext_predef_outside_function);
  3049. currentDecl = Context.getTranslationUnitDecl();
  3050. }
  3051. QualType ResTy;
  3052. StringLiteral *SL = nullptr;
  3053. if (cast<DeclContext>(currentDecl)->isDependentContext())
  3054. ResTy = Context.DependentTy;
  3055. else {
  3056. // Pre-defined identifiers are of type char[x], where x is the length of
  3057. // the string.
  3058. auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
  3059. unsigned Length = Str.length();
  3060. llvm::APInt LengthI(32, Length + 1);
  3061. if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
  3062. ResTy =
  3063. Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
  3064. SmallString<32> RawChars;
  3065. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  3066. Str, RawChars);
  3067. ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
  3068. ArrayType::Normal,
  3069. /*IndexTypeQuals*/ 0);
  3070. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  3071. /*Pascal*/ false, ResTy, Loc);
  3072. } else {
  3073. ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
  3074. ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
  3075. ArrayType::Normal,
  3076. /*IndexTypeQuals*/ 0);
  3077. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  3078. /*Pascal*/ false, ResTy, Loc);
  3079. }
  3080. }
  3081. return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
  3082. }
  3083. ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
  3084. SourceLocation LParen,
  3085. SourceLocation RParen,
  3086. TypeSourceInfo *TSI) {
  3087. return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
  3088. }
  3089. ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
  3090. SourceLocation LParen,
  3091. SourceLocation RParen,
  3092. ParsedType ParsedTy) {
  3093. TypeSourceInfo *TSI = nullptr;
  3094. QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
  3095. if (Ty.isNull())
  3096. return ExprError();
  3097. if (!TSI)
  3098. TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
  3099. return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
  3100. }
  3101. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  3102. PredefinedExpr::IdentKind IK;
  3103. switch (Kind) {
  3104. default: llvm_unreachable("Unknown simple primary expr!");
  3105. case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  3106. case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
  3107. case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
  3108. case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
  3109. case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
  3110. case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
  3111. case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
  3112. }
  3113. return BuildPredefinedExpr(Loc, IK);
  3114. }
  3115. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  3116. SmallString<16> CharBuffer;
  3117. bool Invalid = false;
  3118. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  3119. if (Invalid)
  3120. return ExprError();
  3121. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  3122. PP, Tok.getKind());
  3123. if (Literal.hadError())
  3124. return ExprError();
  3125. QualType Ty;
  3126. if (Literal.isWide())
  3127. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  3128. else if (Literal.isUTF8() && getLangOpts().Char8)
  3129. Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
  3130. else if (Literal.isUTF16())
  3131. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  3132. else if (Literal.isUTF32())
  3133. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  3134. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  3135. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  3136. else
  3137. Ty = Context.CharTy; // 'x' -> char in C++
  3138. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  3139. if (Literal.isWide())
  3140. Kind = CharacterLiteral::Wide;
  3141. else if (Literal.isUTF16())
  3142. Kind = CharacterLiteral::UTF16;
  3143. else if (Literal.isUTF32())
  3144. Kind = CharacterLiteral::UTF32;
  3145. else if (Literal.isUTF8())
  3146. Kind = CharacterLiteral::UTF8;
  3147. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  3148. Tok.getLocation());
  3149. if (Literal.getUDSuffix().empty())
  3150. return Lit;
  3151. // We're building a user-defined literal.
  3152. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  3153. SourceLocation UDSuffixLoc =
  3154. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  3155. // Make sure we're allowed user-defined literals here.
  3156. if (!UDLScope)
  3157. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  3158. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  3159. // operator "" X (ch)
  3160. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  3161. Lit, Tok.getLocation());
  3162. }
  3163. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  3164. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3165. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  3166. Context.IntTy, Loc);
  3167. }
  3168. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  3169. QualType Ty, SourceLocation Loc) {
  3170. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  3171. using llvm::APFloat;
  3172. APFloat Val(Format);
  3173. APFloat::opStatus result = Literal.GetFloatValue(Val);
  3174. // Overflow is always an error, but underflow is only an error if
  3175. // we underflowed to zero (APFloat reports denormals as underflow).
  3176. if ((result & APFloat::opOverflow) ||
  3177. ((result & APFloat::opUnderflow) && Val.isZero())) {
  3178. unsigned diagnostic;
  3179. SmallString<20> buffer;
  3180. if (result & APFloat::opOverflow) {
  3181. diagnostic = diag::warn_float_overflow;
  3182. APFloat::getLargest(Format).toString(buffer);
  3183. } else {
  3184. diagnostic = diag::warn_float_underflow;
  3185. APFloat::getSmallest(Format).toString(buffer);
  3186. }
  3187. S.Diag(Loc, diagnostic)
  3188. << Ty
  3189. << StringRef(buffer.data(), buffer.size());
  3190. }
  3191. bool isExact = (result == APFloat::opOK);
  3192. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  3193. }
  3194. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  3195. assert(E && "Invalid expression");
  3196. if (E->isValueDependent())
  3197. return false;
  3198. QualType QT = E->getType();
  3199. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  3200. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  3201. return true;
  3202. }
  3203. llvm::APSInt ValueAPS;
  3204. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  3205. if (R.isInvalid())
  3206. return true;
  3207. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  3208. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  3209. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  3210. << toString(ValueAPS, 10) << ValueIsPositive;
  3211. return true;
  3212. }
  3213. return false;
  3214. }
  3215. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  3216. // Fast path for a single digit (which is quite common). A single digit
  3217. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  3218. if (Tok.getLength() == 1) {
  3219. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  3220. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  3221. }
  3222. SmallString<128> SpellingBuffer;
  3223. // NumericLiteralParser wants to overread by one character. Add padding to
  3224. // the buffer in case the token is copied to the buffer. If getSpelling()
  3225. // returns a StringRef to the memory buffer, it should have a null char at
  3226. // the EOF, so it is also safe.
  3227. SpellingBuffer.resize(Tok.getLength() + 1);
  3228. // Get the spelling of the token, which eliminates trigraphs, etc.
  3229. bool Invalid = false;
  3230. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  3231. if (Invalid)
  3232. return ExprError();
  3233. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
  3234. PP.getSourceManager(), PP.getLangOpts(),
  3235. PP.getTargetInfo(), PP.getDiagnostics());
  3236. if (Literal.hadError)
  3237. return ExprError();
  3238. if (Literal.hasUDSuffix()) {
  3239. // We're building a user-defined literal.
  3240. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  3241. SourceLocation UDSuffixLoc =
  3242. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  3243. // Make sure we're allowed user-defined literals here.
  3244. if (!UDLScope)
  3245. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  3246. QualType CookedTy;
  3247. if (Literal.isFloatingLiteral()) {
  3248. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  3249. // long double, the literal is treated as a call of the form
  3250. // operator "" X (f L)
  3251. CookedTy = Context.LongDoubleTy;
  3252. } else {
  3253. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  3254. // unsigned long long, the literal is treated as a call of the form
  3255. // operator "" X (n ULL)
  3256. CookedTy = Context.UnsignedLongLongTy;
  3257. }
  3258. DeclarationName OpName =
  3259. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  3260. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  3261. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  3262. SourceLocation TokLoc = Tok.getLocation();
  3263. // Perform literal operator lookup to determine if we're building a raw
  3264. // literal or a cooked one.
  3265. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  3266. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  3267. /*AllowRaw*/ true, /*AllowTemplate*/ true,
  3268. /*AllowStringTemplatePack*/ false,
  3269. /*DiagnoseMissing*/ !Literal.isImaginary)) {
  3270. case LOLR_ErrorNoDiagnostic:
  3271. // Lookup failure for imaginary constants isn't fatal, there's still the
  3272. // GNU extension producing _Complex types.
  3273. break;
  3274. case LOLR_Error:
  3275. return ExprError();
  3276. case LOLR_Cooked: {
  3277. Expr *Lit;
  3278. if (Literal.isFloatingLiteral()) {
  3279. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  3280. } else {
  3281. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  3282. if (Literal.GetIntegerValue(ResultVal))
  3283. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3284. << /* Unsigned */ 1;
  3285. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  3286. Tok.getLocation());
  3287. }
  3288. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3289. }
  3290. case LOLR_Raw: {
  3291. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  3292. // literal is treated as a call of the form
  3293. // operator "" X ("n")
  3294. unsigned Length = Literal.getUDSuffixOffset();
  3295. QualType StrTy = Context.getConstantArrayType(
  3296. Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
  3297. llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
  3298. Expr *Lit = StringLiteral::Create(
  3299. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  3300. /*Pascal*/false, StrTy, &TokLoc, 1);
  3301. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3302. }
  3303. case LOLR_Template: {
  3304. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  3305. // template), L is treated as a call fo the form
  3306. // operator "" X <'c1', 'c2', ... 'ck'>()
  3307. // where n is the source character sequence c1 c2 ... ck.
  3308. TemplateArgumentListInfo ExplicitArgs;
  3309. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  3310. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  3311. llvm::APSInt Value(CharBits, CharIsUnsigned);
  3312. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  3313. Value = TokSpelling[I];
  3314. TemplateArgument Arg(Context, Value, Context.CharTy);
  3315. TemplateArgumentLocInfo ArgInfo;
  3316. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  3317. }
  3318. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  3319. &ExplicitArgs);
  3320. }
  3321. case LOLR_StringTemplatePack:
  3322. llvm_unreachable("unexpected literal operator lookup result");
  3323. }
  3324. }
  3325. Expr *Res;
  3326. if (Literal.isFixedPointLiteral()) {
  3327. QualType Ty;
  3328. if (Literal.isAccum) {
  3329. if (Literal.isHalf) {
  3330. Ty = Context.ShortAccumTy;
  3331. } else if (Literal.isLong) {
  3332. Ty = Context.LongAccumTy;
  3333. } else {
  3334. Ty = Context.AccumTy;
  3335. }
  3336. } else if (Literal.isFract) {
  3337. if (Literal.isHalf) {
  3338. Ty = Context.ShortFractTy;
  3339. } else if (Literal.isLong) {
  3340. Ty = Context.LongFractTy;
  3341. } else {
  3342. Ty = Context.FractTy;
  3343. }
  3344. }
  3345. if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
  3346. bool isSigned = !Literal.isUnsigned;
  3347. unsigned scale = Context.getFixedPointScale(Ty);
  3348. unsigned bit_width = Context.getTypeInfo(Ty).Width;
  3349. llvm::APInt Val(bit_width, 0, isSigned);
  3350. bool Overflowed = Literal.GetFixedPointValue(Val, scale);
  3351. bool ValIsZero = Val.isZero() && !Overflowed;
  3352. auto MaxVal = Context.getFixedPointMax(Ty).getValue();
  3353. if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
  3354. // Clause 6.4.4 - The value of a constant shall be in the range of
  3355. // representable values for its type, with exception for constants of a
  3356. // fract type with a value of exactly 1; such a constant shall denote
  3357. // the maximal value for the type.
  3358. --Val;
  3359. else if (Val.ugt(MaxVal) || Overflowed)
  3360. Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
  3361. Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
  3362. Tok.getLocation(), scale);
  3363. } else if (Literal.isFloatingLiteral()) {
  3364. QualType Ty;
  3365. if (Literal.isHalf){
  3366. if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
  3367. Ty = Context.HalfTy;
  3368. else {
  3369. Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
  3370. return ExprError();
  3371. }
  3372. } else if (Literal.isFloat)
  3373. Ty = Context.FloatTy;
  3374. else if (Literal.isLong)
  3375. Ty = Context.LongDoubleTy;
  3376. else if (Literal.isFloat16)
  3377. Ty = Context.Float16Ty;
  3378. else if (Literal.isFloat128)
  3379. Ty = Context.Float128Ty;
  3380. else
  3381. Ty = Context.DoubleTy;
  3382. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  3383. if (Ty == Context.DoubleTy) {
  3384. if (getLangOpts().SinglePrecisionConstants) {
  3385. if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
  3386. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3387. }
  3388. } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
  3389. "cl_khr_fp64", getLangOpts())) {
  3390. // Impose single-precision float type when cl_khr_fp64 is not enabled.
  3391. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
  3392. << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
  3393. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3394. }
  3395. }
  3396. } else if (!Literal.isIntegerLiteral()) {
  3397. return ExprError();
  3398. } else {
  3399. QualType Ty;
  3400. // 'long long' is a C99 or C++11 feature.
  3401. if (!getLangOpts().C99 && Literal.isLongLong) {
  3402. if (getLangOpts().CPlusPlus)
  3403. Diag(Tok.getLocation(),
  3404. getLangOpts().CPlusPlus11 ?
  3405. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  3406. else
  3407. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  3408. }
  3409. // 'z/uz' literals are a C++2b feature.
  3410. if (Literal.isSizeT)
  3411. Diag(Tok.getLocation(), getLangOpts().CPlusPlus
  3412. ? getLangOpts().CPlusPlus2b
  3413. ? diag::warn_cxx20_compat_size_t_suffix
  3414. : diag::ext_cxx2b_size_t_suffix
  3415. : diag::err_cxx2b_size_t_suffix);
  3416. // Get the value in the widest-possible width.
  3417. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  3418. llvm::APInt ResultVal(MaxWidth, 0);
  3419. if (Literal.GetIntegerValue(ResultVal)) {
  3420. // If this value didn't fit into uintmax_t, error and force to ull.
  3421. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3422. << /* Unsigned */ 1;
  3423. Ty = Context.UnsignedLongLongTy;
  3424. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  3425. "long long is not intmax_t?");
  3426. } else {
  3427. // If this value fits into a ULL, try to figure out what else it fits into
  3428. // according to the rules of C99 6.4.4.1p5.
  3429. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  3430. // be an unsigned int.
  3431. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  3432. // Check from smallest to largest, picking the smallest type we can.
  3433. unsigned Width = 0;
  3434. // Microsoft specific integer suffixes are explicitly sized.
  3435. if (Literal.MicrosoftInteger) {
  3436. if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  3437. Width = 8;
  3438. Ty = Context.CharTy;
  3439. } else {
  3440. Width = Literal.MicrosoftInteger;
  3441. Ty = Context.getIntTypeForBitwidth(Width,
  3442. /*Signed=*/!Literal.isUnsigned);
  3443. }
  3444. }
  3445. // Check C++2b size_t literals.
  3446. if (Literal.isSizeT) {
  3447. assert(!Literal.MicrosoftInteger &&
  3448. "size_t literals can't be Microsoft literals");
  3449. unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
  3450. Context.getTargetInfo().getSizeType());
  3451. // Does it fit in size_t?
  3452. if (ResultVal.isIntN(SizeTSize)) {
  3453. // Does it fit in ssize_t?
  3454. if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
  3455. Ty = Context.getSignedSizeType();
  3456. else if (AllowUnsigned)
  3457. Ty = Context.getSizeType();
  3458. Width = SizeTSize;
  3459. }
  3460. }
  3461. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
  3462. !Literal.isSizeT) {
  3463. // Are int/unsigned possibilities?
  3464. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3465. // Does it fit in a unsigned int?
  3466. if (ResultVal.isIntN(IntSize)) {
  3467. // Does it fit in a signed int?
  3468. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  3469. Ty = Context.IntTy;
  3470. else if (AllowUnsigned)
  3471. Ty = Context.UnsignedIntTy;
  3472. Width = IntSize;
  3473. }
  3474. }
  3475. // Are long/unsigned long possibilities?
  3476. if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
  3477. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  3478. // Does it fit in a unsigned long?
  3479. if (ResultVal.isIntN(LongSize)) {
  3480. // Does it fit in a signed long?
  3481. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  3482. Ty = Context.LongTy;
  3483. else if (AllowUnsigned)
  3484. Ty = Context.UnsignedLongTy;
  3485. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  3486. // is compatible.
  3487. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3488. const unsigned LongLongSize =
  3489. Context.getTargetInfo().getLongLongWidth();
  3490. Diag(Tok.getLocation(),
  3491. getLangOpts().CPlusPlus
  3492. ? Literal.isLong
  3493. ? diag::warn_old_implicitly_unsigned_long_cxx
  3494. : /*C++98 UB*/ diag::
  3495. ext_old_implicitly_unsigned_long_cxx
  3496. : diag::warn_old_implicitly_unsigned_long)
  3497. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3498. : /*will be ill-formed*/ 1);
  3499. Ty = Context.UnsignedLongTy;
  3500. }
  3501. Width = LongSize;
  3502. }
  3503. }
  3504. // Check long long if needed.
  3505. if (Ty.isNull() && !Literal.isSizeT) {
  3506. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3507. // Does it fit in a unsigned long long?
  3508. if (ResultVal.isIntN(LongLongSize)) {
  3509. // Does it fit in a signed long long?
  3510. // To be compatible with MSVC, hex integer literals ending with the
  3511. // LL or i64 suffix are always signed in Microsoft mode.
  3512. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3513. (getLangOpts().MSVCCompat && Literal.isLongLong)))
  3514. Ty = Context.LongLongTy;
  3515. else if (AllowUnsigned)
  3516. Ty = Context.UnsignedLongLongTy;
  3517. Width = LongLongSize;
  3518. }
  3519. }
  3520. // If we still couldn't decide a type, we either have 'size_t' literal
  3521. // that is out of range, or a decimal literal that does not fit in a
  3522. // signed long long and has no U suffix.
  3523. if (Ty.isNull()) {
  3524. if (Literal.isSizeT)
  3525. Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
  3526. << Literal.isUnsigned;
  3527. else
  3528. Diag(Tok.getLocation(),
  3529. diag::ext_integer_literal_too_large_for_signed);
  3530. Ty = Context.UnsignedLongLongTy;
  3531. Width = Context.getTargetInfo().getLongLongWidth();
  3532. }
  3533. if (ResultVal.getBitWidth() != Width)
  3534. ResultVal = ResultVal.trunc(Width);
  3535. }
  3536. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3537. }
  3538. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3539. if (Literal.isImaginary) {
  3540. Res = new (Context) ImaginaryLiteral(Res,
  3541. Context.getComplexType(Res->getType()));
  3542. Diag(Tok.getLocation(), diag::ext_imaginary_constant);
  3543. }
  3544. return Res;
  3545. }
  3546. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3547. assert(E && "ActOnParenExpr() missing expr");
  3548. QualType ExprTy = E->getType();
  3549. if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
  3550. !E->isLValue() && ExprTy->hasFloatingRepresentation())
  3551. return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
  3552. return new (Context) ParenExpr(L, R, E);
  3553. }
  3554. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3555. SourceLocation Loc,
  3556. SourceRange ArgRange) {
  3557. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3558. // scalar or vector data type argument..."
  3559. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3560. // type (C99 6.2.5p18) or void.
  3561. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3562. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3563. << T << ArgRange;
  3564. return true;
  3565. }
  3566. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3567. "Scalar types should always be complete");
  3568. return false;
  3569. }
  3570. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3571. SourceLocation Loc,
  3572. SourceRange ArgRange,
  3573. UnaryExprOrTypeTrait TraitKind) {
  3574. // Invalid types must be hard errors for SFINAE in C++.
  3575. if (S.LangOpts.CPlusPlus)
  3576. return true;
  3577. // C99 6.5.3.4p1:
  3578. if (T->isFunctionType() &&
  3579. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
  3580. TraitKind == UETT_PreferredAlignOf)) {
  3581. // sizeof(function)/alignof(function) is allowed as an extension.
  3582. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3583. << getTraitSpelling(TraitKind) << ArgRange;
  3584. return false;
  3585. }
  3586. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3587. // this is an error (OpenCL v1.1 s6.3.k)
  3588. if (T->isVoidType()) {
  3589. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3590. : diag::ext_sizeof_alignof_void_type;
  3591. S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
  3592. return false;
  3593. }
  3594. return true;
  3595. }
  3596. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3597. SourceLocation Loc,
  3598. SourceRange ArgRange,
  3599. UnaryExprOrTypeTrait TraitKind) {
  3600. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3601. // runtime doesn't allow it.
  3602. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3603. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3604. << T << (TraitKind == UETT_SizeOf)
  3605. << ArgRange;
  3606. return true;
  3607. }
  3608. return false;
  3609. }
  3610. /// Check whether E is a pointer from a decayed array type (the decayed
  3611. /// pointer type is equal to T) and emit a warning if it is.
  3612. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3613. Expr *E) {
  3614. // Don't warn if the operation changed the type.
  3615. if (T != E->getType())
  3616. return;
  3617. // Now look for array decays.
  3618. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3619. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3620. return;
  3621. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3622. << ICE->getType()
  3623. << ICE->getSubExpr()->getType();
  3624. }
  3625. /// Check the constraints on expression operands to unary type expression
  3626. /// and type traits.
  3627. ///
  3628. /// Completes any types necessary and validates the constraints on the operand
  3629. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3630. /// the expression as it completes the type for that expression through template
  3631. /// instantiation, etc.
  3632. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3633. UnaryExprOrTypeTrait ExprKind) {
  3634. QualType ExprTy = E->getType();
  3635. assert(!ExprTy->isReferenceType());
  3636. bool IsUnevaluatedOperand =
  3637. (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
  3638. ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
  3639. if (IsUnevaluatedOperand) {
  3640. ExprResult Result = CheckUnevaluatedOperand(E);
  3641. if (Result.isInvalid())
  3642. return true;
  3643. E = Result.get();
  3644. }
  3645. // The operand for sizeof and alignof is in an unevaluated expression context,
  3646. // so side effects could result in unintended consequences.
  3647. // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
  3648. // used to build SFINAE gadgets.
  3649. // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
  3650. if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
  3651. !E->isInstantiationDependent() &&
  3652. E->HasSideEffects(Context, false))
  3653. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3654. if (ExprKind == UETT_VecStep)
  3655. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3656. E->getSourceRange());
  3657. // Explicitly list some types as extensions.
  3658. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3659. E->getSourceRange(), ExprKind))
  3660. return false;
  3661. // 'alignof' applied to an expression only requires the base element type of
  3662. // the expression to be complete. 'sizeof' requires the expression's type to
  3663. // be complete (and will attempt to complete it if it's an array of unknown
  3664. // bound).
  3665. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3666. if (RequireCompleteSizedType(
  3667. E->getExprLoc(), Context.getBaseElementType(E->getType()),
  3668. diag::err_sizeof_alignof_incomplete_or_sizeless_type,
  3669. getTraitSpelling(ExprKind), E->getSourceRange()))
  3670. return true;
  3671. } else {
  3672. if (RequireCompleteSizedExprType(
  3673. E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
  3674. getTraitSpelling(ExprKind), E->getSourceRange()))
  3675. return true;
  3676. }
  3677. // Completing the expression's type may have changed it.
  3678. ExprTy = E->getType();
  3679. assert(!ExprTy->isReferenceType());
  3680. if (ExprTy->isFunctionType()) {
  3681. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3682. << getTraitSpelling(ExprKind) << E->getSourceRange();
  3683. return true;
  3684. }
  3685. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3686. E->getSourceRange(), ExprKind))
  3687. return true;
  3688. if (ExprKind == UETT_SizeOf) {
  3689. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3690. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3691. QualType OType = PVD->getOriginalType();
  3692. QualType Type = PVD->getType();
  3693. if (Type->isPointerType() && OType->isArrayType()) {
  3694. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3695. << Type << OType;
  3696. Diag(PVD->getLocation(), diag::note_declared_at);
  3697. }
  3698. }
  3699. }
  3700. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3701. // decays into a pointer and returns an unintended result. This is most
  3702. // likely a typo for "sizeof(array) op x".
  3703. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3704. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3705. BO->getLHS());
  3706. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3707. BO->getRHS());
  3708. }
  3709. }
  3710. return false;
  3711. }
  3712. /// Check the constraints on operands to unary expression and type
  3713. /// traits.
  3714. ///
  3715. /// This will complete any types necessary, and validate the various constraints
  3716. /// on those operands.
  3717. ///
  3718. /// The UsualUnaryConversions() function is *not* called by this routine.
  3719. /// C99 6.3.2.1p[2-4] all state:
  3720. /// Except when it is the operand of the sizeof operator ...
  3721. ///
  3722. /// C++ [expr.sizeof]p4
  3723. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3724. /// standard conversions are not applied to the operand of sizeof.
  3725. ///
  3726. /// This policy is followed for all of the unary trait expressions.
  3727. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3728. SourceLocation OpLoc,
  3729. SourceRange ExprRange,
  3730. UnaryExprOrTypeTrait ExprKind) {
  3731. if (ExprType->isDependentType())
  3732. return false;
  3733. // C++ [expr.sizeof]p2:
  3734. // When applied to a reference or a reference type, the result
  3735. // is the size of the referenced type.
  3736. // C++11 [expr.alignof]p3:
  3737. // When alignof is applied to a reference type, the result
  3738. // shall be the alignment of the referenced type.
  3739. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3740. ExprType = Ref->getPointeeType();
  3741. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3742. // When alignof or _Alignof is applied to an array type, the result
  3743. // is the alignment of the element type.
  3744. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
  3745. ExprKind == UETT_OpenMPRequiredSimdAlign)
  3746. ExprType = Context.getBaseElementType(ExprType);
  3747. if (ExprKind == UETT_VecStep)
  3748. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3749. // Explicitly list some types as extensions.
  3750. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3751. ExprKind))
  3752. return false;
  3753. if (RequireCompleteSizedType(
  3754. OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
  3755. getTraitSpelling(ExprKind), ExprRange))
  3756. return true;
  3757. if (ExprType->isFunctionType()) {
  3758. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3759. << getTraitSpelling(ExprKind) << ExprRange;
  3760. return true;
  3761. }
  3762. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3763. ExprKind))
  3764. return true;
  3765. return false;
  3766. }
  3767. static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
  3768. // Cannot know anything else if the expression is dependent.
  3769. if (E->isTypeDependent())
  3770. return false;
  3771. if (E->getObjectKind() == OK_BitField) {
  3772. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
  3773. << 1 << E->getSourceRange();
  3774. return true;
  3775. }
  3776. ValueDecl *D = nullptr;
  3777. Expr *Inner = E->IgnoreParens();
  3778. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
  3779. D = DRE->getDecl();
  3780. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
  3781. D = ME->getMemberDecl();
  3782. }
  3783. // If it's a field, require the containing struct to have a
  3784. // complete definition so that we can compute the layout.
  3785. //
  3786. // This can happen in C++11 onwards, either by naming the member
  3787. // in a way that is not transformed into a member access expression
  3788. // (in an unevaluated operand, for instance), or by naming the member
  3789. // in a trailing-return-type.
  3790. //
  3791. // For the record, since __alignof__ on expressions is a GCC
  3792. // extension, GCC seems to permit this but always gives the
  3793. // nonsensical answer 0.
  3794. //
  3795. // We don't really need the layout here --- we could instead just
  3796. // directly check for all the appropriate alignment-lowing
  3797. // attributes --- but that would require duplicating a lot of
  3798. // logic that just isn't worth duplicating for such a marginal
  3799. // use-case.
  3800. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3801. // Fast path this check, since we at least know the record has a
  3802. // definition if we can find a member of it.
  3803. if (!FD->getParent()->isCompleteDefinition()) {
  3804. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3805. << E->getSourceRange();
  3806. return true;
  3807. }
  3808. // Otherwise, if it's a field, and the field doesn't have
  3809. // reference type, then it must have a complete type (or be a
  3810. // flexible array member, which we explicitly want to
  3811. // white-list anyway), which makes the following checks trivial.
  3812. if (!FD->getType()->isReferenceType())
  3813. return false;
  3814. }
  3815. return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
  3816. }
  3817. bool Sema::CheckVecStepExpr(Expr *E) {
  3818. E = E->IgnoreParens();
  3819. // Cannot know anything else if the expression is dependent.
  3820. if (E->isTypeDependent())
  3821. return false;
  3822. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3823. }
  3824. static void captureVariablyModifiedType(ASTContext &Context, QualType T,
  3825. CapturingScopeInfo *CSI) {
  3826. assert(T->isVariablyModifiedType());
  3827. assert(CSI != nullptr);
  3828. // We're going to walk down into the type and look for VLA expressions.
  3829. do {
  3830. const Type *Ty = T.getTypePtr();
  3831. switch (Ty->getTypeClass()) {
  3832. #define TYPE(Class, Base)
  3833. #define ABSTRACT_TYPE(Class, Base)
  3834. #define NON_CANONICAL_TYPE(Class, Base)
  3835. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  3836. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  3837. #include "clang/AST/TypeNodes.inc"
  3838. T = QualType();
  3839. break;
  3840. // These types are never variably-modified.
  3841. case Type::Builtin:
  3842. case Type::Complex:
  3843. case Type::Vector:
  3844. case Type::ExtVector:
  3845. case Type::ConstantMatrix:
  3846. case Type::Record:
  3847. case Type::Enum:
  3848. case Type::Elaborated:
  3849. case Type::TemplateSpecialization:
  3850. case Type::ObjCObject:
  3851. case Type::ObjCInterface:
  3852. case Type::ObjCObjectPointer:
  3853. case Type::ObjCTypeParam:
  3854. case Type::Pipe:
  3855. case Type::BitInt:
  3856. llvm_unreachable("type class is never variably-modified!");
  3857. case Type::Adjusted:
  3858. T = cast<AdjustedType>(Ty)->getOriginalType();
  3859. break;
  3860. case Type::Decayed:
  3861. T = cast<DecayedType>(Ty)->getPointeeType();
  3862. break;
  3863. case Type::Pointer:
  3864. T = cast<PointerType>(Ty)->getPointeeType();
  3865. break;
  3866. case Type::BlockPointer:
  3867. T = cast<BlockPointerType>(Ty)->getPointeeType();
  3868. break;
  3869. case Type::LValueReference:
  3870. case Type::RValueReference:
  3871. T = cast<ReferenceType>(Ty)->getPointeeType();
  3872. break;
  3873. case Type::MemberPointer:
  3874. T = cast<MemberPointerType>(Ty)->getPointeeType();
  3875. break;
  3876. case Type::ConstantArray:
  3877. case Type::IncompleteArray:
  3878. // Losing element qualification here is fine.
  3879. T = cast<ArrayType>(Ty)->getElementType();
  3880. break;
  3881. case Type::VariableArray: {
  3882. // Losing element qualification here is fine.
  3883. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  3884. // Unknown size indication requires no size computation.
  3885. // Otherwise, evaluate and record it.
  3886. auto Size = VAT->getSizeExpr();
  3887. if (Size && !CSI->isVLATypeCaptured(VAT) &&
  3888. (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
  3889. CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
  3890. T = VAT->getElementType();
  3891. break;
  3892. }
  3893. case Type::FunctionProto:
  3894. case Type::FunctionNoProto:
  3895. T = cast<FunctionType>(Ty)->getReturnType();
  3896. break;
  3897. case Type::Paren:
  3898. case Type::TypeOf:
  3899. case Type::UnaryTransform:
  3900. case Type::Attributed:
  3901. case Type::SubstTemplateTypeParm:
  3902. case Type::MacroQualified:
  3903. // Keep walking after single level desugaring.
  3904. T = T.getSingleStepDesugaredType(Context);
  3905. break;
  3906. case Type::Typedef:
  3907. T = cast<TypedefType>(Ty)->desugar();
  3908. break;
  3909. case Type::Decltype:
  3910. T = cast<DecltypeType>(Ty)->desugar();
  3911. break;
  3912. case Type::Using:
  3913. T = cast<UsingType>(Ty)->desugar();
  3914. break;
  3915. case Type::Auto:
  3916. case Type::DeducedTemplateSpecialization:
  3917. T = cast<DeducedType>(Ty)->getDeducedType();
  3918. break;
  3919. case Type::TypeOfExpr:
  3920. T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  3921. break;
  3922. case Type::Atomic:
  3923. T = cast<AtomicType>(Ty)->getValueType();
  3924. break;
  3925. }
  3926. } while (!T.isNull() && T->isVariablyModifiedType());
  3927. }
  3928. /// Build a sizeof or alignof expression given a type operand.
  3929. ExprResult
  3930. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3931. SourceLocation OpLoc,
  3932. UnaryExprOrTypeTrait ExprKind,
  3933. SourceRange R) {
  3934. if (!TInfo)
  3935. return ExprError();
  3936. QualType T = TInfo->getType();
  3937. if (!T->isDependentType() &&
  3938. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3939. return ExprError();
  3940. if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
  3941. if (auto *TT = T->getAs<TypedefType>()) {
  3942. for (auto I = FunctionScopes.rbegin(),
  3943. E = std::prev(FunctionScopes.rend());
  3944. I != E; ++I) {
  3945. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  3946. if (CSI == nullptr)
  3947. break;
  3948. DeclContext *DC = nullptr;
  3949. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  3950. DC = LSI->CallOperator;
  3951. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  3952. DC = CRSI->TheCapturedDecl;
  3953. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  3954. DC = BSI->TheDecl;
  3955. if (DC) {
  3956. if (DC->containsDecl(TT->getDecl()))
  3957. break;
  3958. captureVariablyModifiedType(Context, T, CSI);
  3959. }
  3960. }
  3961. }
  3962. }
  3963. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3964. if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
  3965. TInfo->getType()->isVariablyModifiedType())
  3966. TInfo = TransformToPotentiallyEvaluated(TInfo);
  3967. return new (Context) UnaryExprOrTypeTraitExpr(
  3968. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3969. }
  3970. /// Build a sizeof or alignof expression given an expression
  3971. /// operand.
  3972. ExprResult
  3973. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3974. UnaryExprOrTypeTrait ExprKind) {
  3975. ExprResult PE = CheckPlaceholderExpr(E);
  3976. if (PE.isInvalid())
  3977. return ExprError();
  3978. E = PE.get();
  3979. // Verify that the operand is valid.
  3980. bool isInvalid = false;
  3981. if (E->isTypeDependent()) {
  3982. // Delay type-checking for type-dependent expressions.
  3983. } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3984. isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
  3985. } else if (ExprKind == UETT_VecStep) {
  3986. isInvalid = CheckVecStepExpr(E);
  3987. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3988. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3989. isInvalid = true;
  3990. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3991. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
  3992. isInvalid = true;
  3993. } else {
  3994. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3995. }
  3996. if (isInvalid)
  3997. return ExprError();
  3998. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3999. PE = TransformToPotentiallyEvaluated(E);
  4000. if (PE.isInvalid()) return ExprError();
  4001. E = PE.get();
  4002. }
  4003. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  4004. return new (Context) UnaryExprOrTypeTraitExpr(
  4005. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  4006. }
  4007. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  4008. /// expr and the same for @c alignof and @c __alignof
  4009. /// Note that the ArgRange is invalid if isType is false.
  4010. ExprResult
  4011. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  4012. UnaryExprOrTypeTrait ExprKind, bool IsType,
  4013. void *TyOrEx, SourceRange ArgRange) {
  4014. // If error parsing type, ignore.
  4015. if (!TyOrEx) return ExprError();
  4016. if (IsType) {
  4017. TypeSourceInfo *TInfo;
  4018. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  4019. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  4020. }
  4021. Expr *ArgEx = (Expr *)TyOrEx;
  4022. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  4023. return Result;
  4024. }
  4025. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  4026. bool IsReal) {
  4027. if (V.get()->isTypeDependent())
  4028. return S.Context.DependentTy;
  4029. // _Real and _Imag are only l-values for normal l-values.
  4030. if (V.get()->getObjectKind() != OK_Ordinary) {
  4031. V = S.DefaultLvalueConversion(V.get());
  4032. if (V.isInvalid())
  4033. return QualType();
  4034. }
  4035. // These operators return the element type of a complex type.
  4036. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  4037. return CT->getElementType();
  4038. // Otherwise they pass through real integer and floating point types here.
  4039. if (V.get()->getType()->isArithmeticType())
  4040. return V.get()->getType();
  4041. // Test for placeholders.
  4042. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  4043. if (PR.isInvalid()) return QualType();
  4044. if (PR.get() != V.get()) {
  4045. V = PR;
  4046. return CheckRealImagOperand(S, V, Loc, IsReal);
  4047. }
  4048. // Reject anything else.
  4049. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  4050. << (IsReal ? "__real" : "__imag");
  4051. return QualType();
  4052. }
  4053. ExprResult
  4054. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  4055. tok::TokenKind Kind, Expr *Input) {
  4056. UnaryOperatorKind Opc;
  4057. switch (Kind) {
  4058. default: llvm_unreachable("Unknown unary op!");
  4059. case tok::plusplus: Opc = UO_PostInc; break;
  4060. case tok::minusminus: Opc = UO_PostDec; break;
  4061. }
  4062. // Since this might is a postfix expression, get rid of ParenListExprs.
  4063. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  4064. if (Result.isInvalid()) return ExprError();
  4065. Input = Result.get();
  4066. return BuildUnaryOp(S, OpLoc, Opc, Input);
  4067. }
  4068. /// Diagnose if arithmetic on the given ObjC pointer is illegal.
  4069. ///
  4070. /// \return true on error
  4071. static bool checkArithmeticOnObjCPointer(Sema &S,
  4072. SourceLocation opLoc,
  4073. Expr *op) {
  4074. assert(op->getType()->isObjCObjectPointerType());
  4075. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  4076. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  4077. return false;
  4078. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  4079. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  4080. << op->getSourceRange();
  4081. return true;
  4082. }
  4083. static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
  4084. auto *BaseNoParens = Base->IgnoreParens();
  4085. if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
  4086. return MSProp->getPropertyDecl()->getType()->isArrayType();
  4087. return isa<MSPropertySubscriptExpr>(BaseNoParens);
  4088. }
  4089. // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
  4090. // Typically this is DependentTy, but can sometimes be more precise.
  4091. //
  4092. // There are cases when we could determine a non-dependent type:
  4093. // - LHS and RHS may have non-dependent types despite being type-dependent
  4094. // (e.g. unbounded array static members of the current instantiation)
  4095. // - one may be a dependent-sized array with known element type
  4096. // - one may be a dependent-typed valid index (enum in current instantiation)
  4097. //
  4098. // We *always* return a dependent type, in such cases it is DependentTy.
  4099. // This avoids creating type-dependent expressions with non-dependent types.
  4100. // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
  4101. static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
  4102. const ASTContext &Ctx) {
  4103. assert(LHS->isTypeDependent() || RHS->isTypeDependent());
  4104. QualType LTy = LHS->getType(), RTy = RHS->getType();
  4105. QualType Result = Ctx.DependentTy;
  4106. if (RTy->isIntegralOrUnscopedEnumerationType()) {
  4107. if (const PointerType *PT = LTy->getAs<PointerType>())
  4108. Result = PT->getPointeeType();
  4109. else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
  4110. Result = AT->getElementType();
  4111. } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
  4112. if (const PointerType *PT = RTy->getAs<PointerType>())
  4113. Result = PT->getPointeeType();
  4114. else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
  4115. Result = AT->getElementType();
  4116. }
  4117. // Ensure we return a dependent type.
  4118. return Result->isDependentType() ? Result : Ctx.DependentTy;
  4119. }
  4120. ExprResult
  4121. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  4122. Expr *idx, SourceLocation rbLoc) {
  4123. if (base && !base->getType().isNull() &&
  4124. base->hasPlaceholderType(BuiltinType::OMPArraySection))
  4125. return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
  4126. SourceLocation(), /*Length*/ nullptr,
  4127. /*Stride=*/nullptr, rbLoc);
  4128. // Since this might be a postfix expression, get rid of ParenListExprs.
  4129. if (isa<ParenListExpr>(base)) {
  4130. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  4131. if (result.isInvalid()) return ExprError();
  4132. base = result.get();
  4133. }
  4134. // Check if base and idx form a MatrixSubscriptExpr.
  4135. //
  4136. // Helper to check for comma expressions, which are not allowed as indices for
  4137. // matrix subscript expressions.
  4138. auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
  4139. if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
  4140. Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
  4141. << SourceRange(base->getBeginLoc(), rbLoc);
  4142. return true;
  4143. }
  4144. return false;
  4145. };
  4146. // The matrix subscript operator ([][])is considered a single operator.
  4147. // Separating the index expressions by parenthesis is not allowed.
  4148. if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
  4149. !isa<MatrixSubscriptExpr>(base)) {
  4150. Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
  4151. << SourceRange(base->getBeginLoc(), rbLoc);
  4152. return ExprError();
  4153. }
  4154. // If the base is a MatrixSubscriptExpr, try to create a new
  4155. // MatrixSubscriptExpr.
  4156. auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
  4157. if (matSubscriptE) {
  4158. if (CheckAndReportCommaError(idx))
  4159. return ExprError();
  4160. assert(matSubscriptE->isIncomplete() &&
  4161. "base has to be an incomplete matrix subscript");
  4162. return CreateBuiltinMatrixSubscriptExpr(
  4163. matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
  4164. }
  4165. // Handle any non-overload placeholder types in the base and index
  4166. // expressions. We can't handle overloads here because the other
  4167. // operand might be an overloadable type, in which case the overload
  4168. // resolution for the operator overload should get the first crack
  4169. // at the overload.
  4170. bool IsMSPropertySubscript = false;
  4171. if (base->getType()->isNonOverloadPlaceholderType()) {
  4172. IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
  4173. if (!IsMSPropertySubscript) {
  4174. ExprResult result = CheckPlaceholderExpr(base);
  4175. if (result.isInvalid())
  4176. return ExprError();
  4177. base = result.get();
  4178. }
  4179. }
  4180. // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
  4181. if (base->getType()->isMatrixType()) {
  4182. if (CheckAndReportCommaError(idx))
  4183. return ExprError();
  4184. return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
  4185. }
  4186. // A comma-expression as the index is deprecated in C++2a onwards.
  4187. if (getLangOpts().CPlusPlus20 &&
  4188. ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
  4189. (isa<CXXOperatorCallExpr>(idx) &&
  4190. cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
  4191. Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
  4192. << SourceRange(base->getBeginLoc(), rbLoc);
  4193. }
  4194. if (idx->getType()->isNonOverloadPlaceholderType()) {
  4195. ExprResult result = CheckPlaceholderExpr(idx);
  4196. if (result.isInvalid()) return ExprError();
  4197. idx = result.get();
  4198. }
  4199. // Build an unanalyzed expression if either operand is type-dependent.
  4200. if (getLangOpts().CPlusPlus &&
  4201. (base->isTypeDependent() || idx->isTypeDependent())) {
  4202. return new (Context) ArraySubscriptExpr(
  4203. base, idx, getDependentArraySubscriptType(base, idx, getASTContext()),
  4204. VK_LValue, OK_Ordinary, rbLoc);
  4205. }
  4206. // MSDN, property (C++)
  4207. // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
  4208. // This attribute can also be used in the declaration of an empty array in a
  4209. // class or structure definition. For example:
  4210. // __declspec(property(get=GetX, put=PutX)) int x[];
  4211. // The above statement indicates that x[] can be used with one or more array
  4212. // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
  4213. // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
  4214. if (IsMSPropertySubscript) {
  4215. // Build MS property subscript expression if base is MS property reference
  4216. // or MS property subscript.
  4217. return new (Context) MSPropertySubscriptExpr(
  4218. base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
  4219. }
  4220. // Use C++ overloaded-operator rules if either operand has record
  4221. // type. The spec says to do this if either type is *overloadable*,
  4222. // but enum types can't declare subscript operators or conversion
  4223. // operators, so there's nothing interesting for overload resolution
  4224. // to do if there aren't any record types involved.
  4225. //
  4226. // ObjC pointers have their own subscripting logic that is not tied
  4227. // to overload resolution and so should not take this path.
  4228. if (getLangOpts().CPlusPlus &&
  4229. (base->getType()->isRecordType() ||
  4230. (!base->getType()->isObjCObjectPointerType() &&
  4231. idx->getType()->isRecordType()))) {
  4232. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  4233. }
  4234. ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  4235. if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
  4236. CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
  4237. return Res;
  4238. }
  4239. ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
  4240. InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
  4241. InitializationKind Kind =
  4242. InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
  4243. InitializationSequence InitSeq(*this, Entity, Kind, E);
  4244. return InitSeq.Perform(*this, Entity, Kind, E);
  4245. }
  4246. ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
  4247. Expr *ColumnIdx,
  4248. SourceLocation RBLoc) {
  4249. ExprResult BaseR = CheckPlaceholderExpr(Base);
  4250. if (BaseR.isInvalid())
  4251. return BaseR;
  4252. Base = BaseR.get();
  4253. ExprResult RowR = CheckPlaceholderExpr(RowIdx);
  4254. if (RowR.isInvalid())
  4255. return RowR;
  4256. RowIdx = RowR.get();
  4257. if (!ColumnIdx)
  4258. return new (Context) MatrixSubscriptExpr(
  4259. Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
  4260. // Build an unanalyzed expression if any of the operands is type-dependent.
  4261. if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
  4262. ColumnIdx->isTypeDependent())
  4263. return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
  4264. Context.DependentTy, RBLoc);
  4265. ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
  4266. if (ColumnR.isInvalid())
  4267. return ColumnR;
  4268. ColumnIdx = ColumnR.get();
  4269. // Check that IndexExpr is an integer expression. If it is a constant
  4270. // expression, check that it is less than Dim (= the number of elements in the
  4271. // corresponding dimension).
  4272. auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
  4273. bool IsColumnIdx) -> Expr * {
  4274. if (!IndexExpr->getType()->isIntegerType() &&
  4275. !IndexExpr->isTypeDependent()) {
  4276. Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
  4277. << IsColumnIdx;
  4278. return nullptr;
  4279. }
  4280. if (Optional<llvm::APSInt> Idx =
  4281. IndexExpr->getIntegerConstantExpr(Context)) {
  4282. if ((*Idx < 0 || *Idx >= Dim)) {
  4283. Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
  4284. << IsColumnIdx << Dim;
  4285. return nullptr;
  4286. }
  4287. }
  4288. ExprResult ConvExpr =
  4289. tryConvertExprToType(IndexExpr, Context.getSizeType());
  4290. assert(!ConvExpr.isInvalid() &&
  4291. "should be able to convert any integer type to size type");
  4292. return ConvExpr.get();
  4293. };
  4294. auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
  4295. RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
  4296. ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
  4297. if (!RowIdx || !ColumnIdx)
  4298. return ExprError();
  4299. return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
  4300. MTy->getElementType(), RBLoc);
  4301. }
  4302. void Sema::CheckAddressOfNoDeref(const Expr *E) {
  4303. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  4304. const Expr *StrippedExpr = E->IgnoreParenImpCasts();
  4305. // For expressions like `&(*s).b`, the base is recorded and what should be
  4306. // checked.
  4307. const MemberExpr *Member = nullptr;
  4308. while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
  4309. StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
  4310. LastRecord.PossibleDerefs.erase(StrippedExpr);
  4311. }
  4312. void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
  4313. if (isUnevaluatedContext())
  4314. return;
  4315. QualType ResultTy = E->getType();
  4316. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  4317. // Bail if the element is an array since it is not memory access.
  4318. if (isa<ArrayType>(ResultTy))
  4319. return;
  4320. if (ResultTy->hasAttr(attr::NoDeref)) {
  4321. LastRecord.PossibleDerefs.insert(E);
  4322. return;
  4323. }
  4324. // Check if the base type is a pointer to a member access of a struct
  4325. // marked with noderef.
  4326. const Expr *Base = E->getBase();
  4327. QualType BaseTy = Base->getType();
  4328. if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
  4329. // Not a pointer access
  4330. return;
  4331. const MemberExpr *Member = nullptr;
  4332. while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
  4333. Member->isArrow())
  4334. Base = Member->getBase();
  4335. if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
  4336. if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
  4337. LastRecord.PossibleDerefs.insert(E);
  4338. }
  4339. }
  4340. ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
  4341. Expr *LowerBound,
  4342. SourceLocation ColonLocFirst,
  4343. SourceLocation ColonLocSecond,
  4344. Expr *Length, Expr *Stride,
  4345. SourceLocation RBLoc) {
  4346. if (Base->hasPlaceholderType() &&
  4347. !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
  4348. ExprResult Result = CheckPlaceholderExpr(Base);
  4349. if (Result.isInvalid())
  4350. return ExprError();
  4351. Base = Result.get();
  4352. }
  4353. if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
  4354. ExprResult Result = CheckPlaceholderExpr(LowerBound);
  4355. if (Result.isInvalid())
  4356. return ExprError();
  4357. Result = DefaultLvalueConversion(Result.get());
  4358. if (Result.isInvalid())
  4359. return ExprError();
  4360. LowerBound = Result.get();
  4361. }
  4362. if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
  4363. ExprResult Result = CheckPlaceholderExpr(Length);
  4364. if (Result.isInvalid())
  4365. return ExprError();
  4366. Result = DefaultLvalueConversion(Result.get());
  4367. if (Result.isInvalid())
  4368. return ExprError();
  4369. Length = Result.get();
  4370. }
  4371. if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
  4372. ExprResult Result = CheckPlaceholderExpr(Stride);
  4373. if (Result.isInvalid())
  4374. return ExprError();
  4375. Result = DefaultLvalueConversion(Result.get());
  4376. if (Result.isInvalid())
  4377. return ExprError();
  4378. Stride = Result.get();
  4379. }
  4380. // Build an unanalyzed expression if either operand is type-dependent.
  4381. if (Base->isTypeDependent() ||
  4382. (LowerBound &&
  4383. (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
  4384. (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
  4385. (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
  4386. return new (Context) OMPArraySectionExpr(
  4387. Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
  4388. OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
  4389. }
  4390. // Perform default conversions.
  4391. QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
  4392. QualType ResultTy;
  4393. if (OriginalTy->isAnyPointerType()) {
  4394. ResultTy = OriginalTy->getPointeeType();
  4395. } else if (OriginalTy->isArrayType()) {
  4396. ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
  4397. } else {
  4398. return ExprError(
  4399. Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
  4400. << Base->getSourceRange());
  4401. }
  4402. // C99 6.5.2.1p1
  4403. if (LowerBound) {
  4404. auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
  4405. LowerBound);
  4406. if (Res.isInvalid())
  4407. return ExprError(Diag(LowerBound->getExprLoc(),
  4408. diag::err_omp_typecheck_section_not_integer)
  4409. << 0 << LowerBound->getSourceRange());
  4410. LowerBound = Res.get();
  4411. if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  4412. LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  4413. Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
  4414. << 0 << LowerBound->getSourceRange();
  4415. }
  4416. if (Length) {
  4417. auto Res =
  4418. PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
  4419. if (Res.isInvalid())
  4420. return ExprError(Diag(Length->getExprLoc(),
  4421. diag::err_omp_typecheck_section_not_integer)
  4422. << 1 << Length->getSourceRange());
  4423. Length = Res.get();
  4424. if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  4425. Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  4426. Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
  4427. << 1 << Length->getSourceRange();
  4428. }
  4429. if (Stride) {
  4430. ExprResult Res =
  4431. PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
  4432. if (Res.isInvalid())
  4433. return ExprError(Diag(Stride->getExprLoc(),
  4434. diag::err_omp_typecheck_section_not_integer)
  4435. << 1 << Stride->getSourceRange());
  4436. Stride = Res.get();
  4437. if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  4438. Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  4439. Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
  4440. << 1 << Stride->getSourceRange();
  4441. }
  4442. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  4443. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  4444. // type. Note that functions are not objects, and that (in C99 parlance)
  4445. // incomplete types are not object types.
  4446. if (ResultTy->isFunctionType()) {
  4447. Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
  4448. << ResultTy << Base->getSourceRange();
  4449. return ExprError();
  4450. }
  4451. if (RequireCompleteType(Base->getExprLoc(), ResultTy,
  4452. diag::err_omp_section_incomplete_type, Base))
  4453. return ExprError();
  4454. if (LowerBound && !OriginalTy->isAnyPointerType()) {
  4455. Expr::EvalResult Result;
  4456. if (LowerBound->EvaluateAsInt(Result, Context)) {
  4457. // OpenMP 5.0, [2.1.5 Array Sections]
  4458. // The array section must be a subset of the original array.
  4459. llvm::APSInt LowerBoundValue = Result.Val.getInt();
  4460. if (LowerBoundValue.isNegative()) {
  4461. Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
  4462. << LowerBound->getSourceRange();
  4463. return ExprError();
  4464. }
  4465. }
  4466. }
  4467. if (Length) {
  4468. Expr::EvalResult Result;
  4469. if (Length->EvaluateAsInt(Result, Context)) {
  4470. // OpenMP 5.0, [2.1.5 Array Sections]
  4471. // The length must evaluate to non-negative integers.
  4472. llvm::APSInt LengthValue = Result.Val.getInt();
  4473. if (LengthValue.isNegative()) {
  4474. Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
  4475. << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
  4476. << Length->getSourceRange();
  4477. return ExprError();
  4478. }
  4479. }
  4480. } else if (ColonLocFirst.isValid() &&
  4481. (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
  4482. !OriginalTy->isVariableArrayType()))) {
  4483. // OpenMP 5.0, [2.1.5 Array Sections]
  4484. // When the size of the array dimension is not known, the length must be
  4485. // specified explicitly.
  4486. Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
  4487. << (!OriginalTy.isNull() && OriginalTy->isArrayType());
  4488. return ExprError();
  4489. }
  4490. if (Stride) {
  4491. Expr::EvalResult Result;
  4492. if (Stride->EvaluateAsInt(Result, Context)) {
  4493. // OpenMP 5.0, [2.1.5 Array Sections]
  4494. // The stride must evaluate to a positive integer.
  4495. llvm::APSInt StrideValue = Result.Val.getInt();
  4496. if (!StrideValue.isStrictlyPositive()) {
  4497. Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
  4498. << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
  4499. << Stride->getSourceRange();
  4500. return ExprError();
  4501. }
  4502. }
  4503. }
  4504. if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
  4505. ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
  4506. if (Result.isInvalid())
  4507. return ExprError();
  4508. Base = Result.get();
  4509. }
  4510. return new (Context) OMPArraySectionExpr(
  4511. Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
  4512. OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
  4513. }
  4514. ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
  4515. SourceLocation RParenLoc,
  4516. ArrayRef<Expr *> Dims,
  4517. ArrayRef<SourceRange> Brackets) {
  4518. if (Base->hasPlaceholderType()) {
  4519. ExprResult Result = CheckPlaceholderExpr(Base);
  4520. if (Result.isInvalid())
  4521. return ExprError();
  4522. Result = DefaultLvalueConversion(Result.get());
  4523. if (Result.isInvalid())
  4524. return ExprError();
  4525. Base = Result.get();
  4526. }
  4527. QualType BaseTy = Base->getType();
  4528. // Delay analysis of the types/expressions if instantiation/specialization is
  4529. // required.
  4530. if (!BaseTy->isPointerType() && Base->isTypeDependent())
  4531. return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
  4532. LParenLoc, RParenLoc, Dims, Brackets);
  4533. if (!BaseTy->isPointerType() ||
  4534. (!Base->isTypeDependent() &&
  4535. BaseTy->getPointeeType()->isIncompleteType()))
  4536. return ExprError(Diag(Base->getExprLoc(),
  4537. diag::err_omp_non_pointer_type_array_shaping_base)
  4538. << Base->getSourceRange());
  4539. SmallVector<Expr *, 4> NewDims;
  4540. bool ErrorFound = false;
  4541. for (Expr *Dim : Dims) {
  4542. if (Dim->hasPlaceholderType()) {
  4543. ExprResult Result = CheckPlaceholderExpr(Dim);
  4544. if (Result.isInvalid()) {
  4545. ErrorFound = true;
  4546. continue;
  4547. }
  4548. Result = DefaultLvalueConversion(Result.get());
  4549. if (Result.isInvalid()) {
  4550. ErrorFound = true;
  4551. continue;
  4552. }
  4553. Dim = Result.get();
  4554. }
  4555. if (!Dim->isTypeDependent()) {
  4556. ExprResult Result =
  4557. PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
  4558. if (Result.isInvalid()) {
  4559. ErrorFound = true;
  4560. Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
  4561. << Dim->getSourceRange();
  4562. continue;
  4563. }
  4564. Dim = Result.get();
  4565. Expr::EvalResult EvResult;
  4566. if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
  4567. // OpenMP 5.0, [2.1.4 Array Shaping]
  4568. // Each si is an integral type expression that must evaluate to a
  4569. // positive integer.
  4570. llvm::APSInt Value = EvResult.Val.getInt();
  4571. if (!Value.isStrictlyPositive()) {
  4572. Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
  4573. << toString(Value, /*Radix=*/10, /*Signed=*/true)
  4574. << Dim->getSourceRange();
  4575. ErrorFound = true;
  4576. continue;
  4577. }
  4578. }
  4579. }
  4580. NewDims.push_back(Dim);
  4581. }
  4582. if (ErrorFound)
  4583. return ExprError();
  4584. return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
  4585. LParenLoc, RParenLoc, NewDims, Brackets);
  4586. }
  4587. ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
  4588. SourceLocation LLoc, SourceLocation RLoc,
  4589. ArrayRef<OMPIteratorData> Data) {
  4590. SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
  4591. bool IsCorrect = true;
  4592. for (const OMPIteratorData &D : Data) {
  4593. TypeSourceInfo *TInfo = nullptr;
  4594. SourceLocation StartLoc;
  4595. QualType DeclTy;
  4596. if (!D.Type.getAsOpaquePtr()) {
  4597. // OpenMP 5.0, 2.1.6 Iterators
  4598. // In an iterator-specifier, if the iterator-type is not specified then
  4599. // the type of that iterator is of int type.
  4600. DeclTy = Context.IntTy;
  4601. StartLoc = D.DeclIdentLoc;
  4602. } else {
  4603. DeclTy = GetTypeFromParser(D.Type, &TInfo);
  4604. StartLoc = TInfo->getTypeLoc().getBeginLoc();
  4605. }
  4606. bool IsDeclTyDependent = DeclTy->isDependentType() ||
  4607. DeclTy->containsUnexpandedParameterPack() ||
  4608. DeclTy->isInstantiationDependentType();
  4609. if (!IsDeclTyDependent) {
  4610. if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
  4611. // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
  4612. // The iterator-type must be an integral or pointer type.
  4613. Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
  4614. << DeclTy;
  4615. IsCorrect = false;
  4616. continue;
  4617. }
  4618. if (DeclTy.isConstant(Context)) {
  4619. // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
  4620. // The iterator-type must not be const qualified.
  4621. Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
  4622. << DeclTy;
  4623. IsCorrect = false;
  4624. continue;
  4625. }
  4626. }
  4627. // Iterator declaration.
  4628. assert(D.DeclIdent && "Identifier expected.");
  4629. // Always try to create iterator declarator to avoid extra error messages
  4630. // about unknown declarations use.
  4631. auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
  4632. D.DeclIdent, DeclTy, TInfo, SC_None);
  4633. VD->setImplicit();
  4634. if (S) {
  4635. // Check for conflicting previous declaration.
  4636. DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
  4637. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4638. ForVisibleRedeclaration);
  4639. Previous.suppressDiagnostics();
  4640. LookupName(Previous, S);
  4641. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
  4642. /*AllowInlineNamespace=*/false);
  4643. if (!Previous.empty()) {
  4644. NamedDecl *Old = Previous.getRepresentativeDecl();
  4645. Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
  4646. Diag(Old->getLocation(), diag::note_previous_definition);
  4647. } else {
  4648. PushOnScopeChains(VD, S);
  4649. }
  4650. } else {
  4651. CurContext->addDecl(VD);
  4652. }
  4653. Expr *Begin = D.Range.Begin;
  4654. if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
  4655. ExprResult BeginRes =
  4656. PerformImplicitConversion(Begin, DeclTy, AA_Converting);
  4657. Begin = BeginRes.get();
  4658. }
  4659. Expr *End = D.Range.End;
  4660. if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
  4661. ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
  4662. End = EndRes.get();
  4663. }
  4664. Expr *Step = D.Range.Step;
  4665. if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
  4666. if (!Step->getType()->isIntegralType(Context)) {
  4667. Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
  4668. << Step << Step->getSourceRange();
  4669. IsCorrect = false;
  4670. continue;
  4671. }
  4672. Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
  4673. // OpenMP 5.0, 2.1.6 Iterators, Restrictions
  4674. // If the step expression of a range-specification equals zero, the
  4675. // behavior is unspecified.
  4676. if (Result && Result->isZero()) {
  4677. Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
  4678. << Step << Step->getSourceRange();
  4679. IsCorrect = false;
  4680. continue;
  4681. }
  4682. }
  4683. if (!Begin || !End || !IsCorrect) {
  4684. IsCorrect = false;
  4685. continue;
  4686. }
  4687. OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
  4688. IDElem.IteratorDecl = VD;
  4689. IDElem.AssignmentLoc = D.AssignLoc;
  4690. IDElem.Range.Begin = Begin;
  4691. IDElem.Range.End = End;
  4692. IDElem.Range.Step = Step;
  4693. IDElem.ColonLoc = D.ColonLoc;
  4694. IDElem.SecondColonLoc = D.SecColonLoc;
  4695. }
  4696. if (!IsCorrect) {
  4697. // Invalidate all created iterator declarations if error is found.
  4698. for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
  4699. if (Decl *ID = D.IteratorDecl)
  4700. ID->setInvalidDecl();
  4701. }
  4702. return ExprError();
  4703. }
  4704. SmallVector<OMPIteratorHelperData, 4> Helpers;
  4705. if (!CurContext->isDependentContext()) {
  4706. // Build number of ityeration for each iteration range.
  4707. // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
  4708. // ((Begini-Stepi-1-Endi) / -Stepi);
  4709. for (OMPIteratorExpr::IteratorDefinition &D : ID) {
  4710. // (Endi - Begini)
  4711. ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
  4712. D.Range.Begin);
  4713. if(!Res.isUsable()) {
  4714. IsCorrect = false;
  4715. continue;
  4716. }
  4717. ExprResult St, St1;
  4718. if (D.Range.Step) {
  4719. St = D.Range.Step;
  4720. // (Endi - Begini) + Stepi
  4721. Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
  4722. if (!Res.isUsable()) {
  4723. IsCorrect = false;
  4724. continue;
  4725. }
  4726. // (Endi - Begini) + Stepi - 1
  4727. Res =
  4728. CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
  4729. ActOnIntegerConstant(D.AssignmentLoc, 1).get());
  4730. if (!Res.isUsable()) {
  4731. IsCorrect = false;
  4732. continue;
  4733. }
  4734. // ((Endi - Begini) + Stepi - 1) / Stepi
  4735. Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
  4736. if (!Res.isUsable()) {
  4737. IsCorrect = false;
  4738. continue;
  4739. }
  4740. St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
  4741. // (Begini - Endi)
  4742. ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
  4743. D.Range.Begin, D.Range.End);
  4744. if (!Res1.isUsable()) {
  4745. IsCorrect = false;
  4746. continue;
  4747. }
  4748. // (Begini - Endi) - Stepi
  4749. Res1 =
  4750. CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
  4751. if (!Res1.isUsable()) {
  4752. IsCorrect = false;
  4753. continue;
  4754. }
  4755. // (Begini - Endi) - Stepi - 1
  4756. Res1 =
  4757. CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
  4758. ActOnIntegerConstant(D.AssignmentLoc, 1).get());
  4759. if (!Res1.isUsable()) {
  4760. IsCorrect = false;
  4761. continue;
  4762. }
  4763. // ((Begini - Endi) - Stepi - 1) / (-Stepi)
  4764. Res1 =
  4765. CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
  4766. if (!Res1.isUsable()) {
  4767. IsCorrect = false;
  4768. continue;
  4769. }
  4770. // Stepi > 0.
  4771. ExprResult CmpRes =
  4772. CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
  4773. ActOnIntegerConstant(D.AssignmentLoc, 0).get());
  4774. if (!CmpRes.isUsable()) {
  4775. IsCorrect = false;
  4776. continue;
  4777. }
  4778. Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
  4779. Res.get(), Res1.get());
  4780. if (!Res.isUsable()) {
  4781. IsCorrect = false;
  4782. continue;
  4783. }
  4784. }
  4785. Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
  4786. if (!Res.isUsable()) {
  4787. IsCorrect = false;
  4788. continue;
  4789. }
  4790. // Build counter update.
  4791. // Build counter.
  4792. auto *CounterVD =
  4793. VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
  4794. D.IteratorDecl->getBeginLoc(), nullptr,
  4795. Res.get()->getType(), nullptr, SC_None);
  4796. CounterVD->setImplicit();
  4797. ExprResult RefRes =
  4798. BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
  4799. D.IteratorDecl->getBeginLoc());
  4800. // Build counter update.
  4801. // I = Begini + counter * Stepi;
  4802. ExprResult UpdateRes;
  4803. if (D.Range.Step) {
  4804. UpdateRes = CreateBuiltinBinOp(
  4805. D.AssignmentLoc, BO_Mul,
  4806. DefaultLvalueConversion(RefRes.get()).get(), St.get());
  4807. } else {
  4808. UpdateRes = DefaultLvalueConversion(RefRes.get());
  4809. }
  4810. if (!UpdateRes.isUsable()) {
  4811. IsCorrect = false;
  4812. continue;
  4813. }
  4814. UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
  4815. UpdateRes.get());
  4816. if (!UpdateRes.isUsable()) {
  4817. IsCorrect = false;
  4818. continue;
  4819. }
  4820. ExprResult VDRes =
  4821. BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
  4822. cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
  4823. D.IteratorDecl->getBeginLoc());
  4824. UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
  4825. UpdateRes.get());
  4826. if (!UpdateRes.isUsable()) {
  4827. IsCorrect = false;
  4828. continue;
  4829. }
  4830. UpdateRes =
  4831. ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
  4832. if (!UpdateRes.isUsable()) {
  4833. IsCorrect = false;
  4834. continue;
  4835. }
  4836. ExprResult CounterUpdateRes =
  4837. CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
  4838. if (!CounterUpdateRes.isUsable()) {
  4839. IsCorrect = false;
  4840. continue;
  4841. }
  4842. CounterUpdateRes =
  4843. ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
  4844. if (!CounterUpdateRes.isUsable()) {
  4845. IsCorrect = false;
  4846. continue;
  4847. }
  4848. OMPIteratorHelperData &HD = Helpers.emplace_back();
  4849. HD.CounterVD = CounterVD;
  4850. HD.Upper = Res.get();
  4851. HD.Update = UpdateRes.get();
  4852. HD.CounterUpdate = CounterUpdateRes.get();
  4853. }
  4854. } else {
  4855. Helpers.assign(ID.size(), {});
  4856. }
  4857. if (!IsCorrect) {
  4858. // Invalidate all created iterator declarations if error is found.
  4859. for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
  4860. if (Decl *ID = D.IteratorDecl)
  4861. ID->setInvalidDecl();
  4862. }
  4863. return ExprError();
  4864. }
  4865. return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
  4866. LLoc, RLoc, ID, Helpers);
  4867. }
  4868. ExprResult
  4869. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  4870. Expr *Idx, SourceLocation RLoc) {
  4871. Expr *LHSExp = Base;
  4872. Expr *RHSExp = Idx;
  4873. ExprValueKind VK = VK_LValue;
  4874. ExprObjectKind OK = OK_Ordinary;
  4875. // Per C++ core issue 1213, the result is an xvalue if either operand is
  4876. // a non-lvalue array, and an lvalue otherwise.
  4877. if (getLangOpts().CPlusPlus11) {
  4878. for (auto *Op : {LHSExp, RHSExp}) {
  4879. Op = Op->IgnoreImplicit();
  4880. if (Op->getType()->isArrayType() && !Op->isLValue())
  4881. VK = VK_XValue;
  4882. }
  4883. }
  4884. // Perform default conversions.
  4885. if (!LHSExp->getType()->getAs<VectorType>()) {
  4886. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  4887. if (Result.isInvalid())
  4888. return ExprError();
  4889. LHSExp = Result.get();
  4890. }
  4891. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  4892. if (Result.isInvalid())
  4893. return ExprError();
  4894. RHSExp = Result.get();
  4895. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  4896. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  4897. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  4898. // in the subscript position. As a result, we need to derive the array base
  4899. // and index from the expression types.
  4900. Expr *BaseExpr, *IndexExpr;
  4901. QualType ResultType;
  4902. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  4903. BaseExpr = LHSExp;
  4904. IndexExpr = RHSExp;
  4905. ResultType =
  4906. getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
  4907. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  4908. BaseExpr = LHSExp;
  4909. IndexExpr = RHSExp;
  4910. ResultType = PTy->getPointeeType();
  4911. } else if (const ObjCObjectPointerType *PTy =
  4912. LHSTy->getAs<ObjCObjectPointerType>()) {
  4913. BaseExpr = LHSExp;
  4914. IndexExpr = RHSExp;
  4915. // Use custom logic if this should be the pseudo-object subscript
  4916. // expression.
  4917. if (!LangOpts.isSubscriptPointerArithmetic())
  4918. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  4919. nullptr);
  4920. ResultType = PTy->getPointeeType();
  4921. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  4922. // Handle the uncommon case of "123[Ptr]".
  4923. BaseExpr = RHSExp;
  4924. IndexExpr = LHSExp;
  4925. ResultType = PTy->getPointeeType();
  4926. } else if (const ObjCObjectPointerType *PTy =
  4927. RHSTy->getAs<ObjCObjectPointerType>()) {
  4928. // Handle the uncommon case of "123[Ptr]".
  4929. BaseExpr = RHSExp;
  4930. IndexExpr = LHSExp;
  4931. ResultType = PTy->getPointeeType();
  4932. if (!LangOpts.isSubscriptPointerArithmetic()) {
  4933. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  4934. << ResultType << BaseExpr->getSourceRange();
  4935. return ExprError();
  4936. }
  4937. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  4938. BaseExpr = LHSExp; // vectors: V[123]
  4939. IndexExpr = RHSExp;
  4940. // We apply C++ DR1213 to vector subscripting too.
  4941. if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
  4942. ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
  4943. if (Materialized.isInvalid())
  4944. return ExprError();
  4945. LHSExp = Materialized.get();
  4946. }
  4947. VK = LHSExp->getValueKind();
  4948. if (VK != VK_PRValue)
  4949. OK = OK_VectorComponent;
  4950. ResultType = VTy->getElementType();
  4951. QualType BaseType = BaseExpr->getType();
  4952. Qualifiers BaseQuals = BaseType.getQualifiers();
  4953. Qualifiers MemberQuals = ResultType.getQualifiers();
  4954. Qualifiers Combined = BaseQuals + MemberQuals;
  4955. if (Combined != MemberQuals)
  4956. ResultType = Context.getQualifiedType(ResultType, Combined);
  4957. } else if (LHSTy->isArrayType()) {
  4958. // If we see an array that wasn't promoted by
  4959. // DefaultFunctionArrayLvalueConversion, it must be an array that
  4960. // wasn't promoted because of the C90 rule that doesn't
  4961. // allow promoting non-lvalue arrays. Warn, then
  4962. // force the promotion here.
  4963. Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  4964. << LHSExp->getSourceRange();
  4965. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  4966. CK_ArrayToPointerDecay).get();
  4967. LHSTy = LHSExp->getType();
  4968. BaseExpr = LHSExp;
  4969. IndexExpr = RHSExp;
  4970. ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
  4971. } else if (RHSTy->isArrayType()) {
  4972. // Same as previous, except for 123[f().a] case
  4973. Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  4974. << RHSExp->getSourceRange();
  4975. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  4976. CK_ArrayToPointerDecay).get();
  4977. RHSTy = RHSExp->getType();
  4978. BaseExpr = RHSExp;
  4979. IndexExpr = LHSExp;
  4980. ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
  4981. } else {
  4982. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  4983. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  4984. }
  4985. // C99 6.5.2.1p1
  4986. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  4987. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  4988. << IndexExpr->getSourceRange());
  4989. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  4990. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  4991. && !IndexExpr->isTypeDependent())
  4992. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  4993. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  4994. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  4995. // type. Note that Functions are not objects, and that (in C99 parlance)
  4996. // incomplete types are not object types.
  4997. if (ResultType->isFunctionType()) {
  4998. Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
  4999. << ResultType << BaseExpr->getSourceRange();
  5000. return ExprError();
  5001. }
  5002. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  5003. // GNU extension: subscripting on pointer to void
  5004. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  5005. << BaseExpr->getSourceRange();
  5006. // C forbids expressions of unqualified void type from being l-values.
  5007. // See IsCForbiddenLValueType.
  5008. if (!ResultType.hasQualifiers())
  5009. VK = VK_PRValue;
  5010. } else if (!ResultType->isDependentType() &&
  5011. RequireCompleteSizedType(
  5012. LLoc, ResultType,
  5013. diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
  5014. return ExprError();
  5015. assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
  5016. !ResultType.isCForbiddenLValueType());
  5017. if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
  5018. FunctionScopes.size() > 1) {
  5019. if (auto *TT =
  5020. LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
  5021. for (auto I = FunctionScopes.rbegin(),
  5022. E = std::prev(FunctionScopes.rend());
  5023. I != E; ++I) {
  5024. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  5025. if (CSI == nullptr)
  5026. break;
  5027. DeclContext *DC = nullptr;
  5028. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  5029. DC = LSI->CallOperator;
  5030. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  5031. DC = CRSI->TheCapturedDecl;
  5032. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  5033. DC = BSI->TheDecl;
  5034. if (DC) {
  5035. if (DC->containsDecl(TT->getDecl()))
  5036. break;
  5037. captureVariablyModifiedType(
  5038. Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
  5039. }
  5040. }
  5041. }
  5042. }
  5043. return new (Context)
  5044. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  5045. }
  5046. bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
  5047. ParmVarDecl *Param) {
  5048. if (Param->hasUnparsedDefaultArg()) {
  5049. // If we've already cleared out the location for the default argument,
  5050. // that means we're parsing it right now.
  5051. if (!UnparsedDefaultArgLocs.count(Param)) {
  5052. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  5053. Diag(CallLoc, diag::note_recursive_default_argument_used_here);
  5054. Param->setInvalidDecl();
  5055. return true;
  5056. }
  5057. Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
  5058. << FD << cast<CXXRecordDecl>(FD->getDeclContext());
  5059. Diag(UnparsedDefaultArgLocs[Param],
  5060. diag::note_default_argument_declared_here);
  5061. return true;
  5062. }
  5063. if (Param->hasUninstantiatedDefaultArg() &&
  5064. InstantiateDefaultArgument(CallLoc, FD, Param))
  5065. return true;
  5066. assert(Param->hasInit() && "default argument but no initializer?");
  5067. // If the default expression creates temporaries, we need to
  5068. // push them to the current stack of expression temporaries so they'll
  5069. // be properly destroyed.
  5070. // FIXME: We should really be rebuilding the default argument with new
  5071. // bound temporaries; see the comment in PR5810.
  5072. // We don't need to do that with block decls, though, because
  5073. // blocks in default argument expression can never capture anything.
  5074. if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
  5075. // Set the "needs cleanups" bit regardless of whether there are
  5076. // any explicit objects.
  5077. Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
  5078. // Append all the objects to the cleanup list. Right now, this
  5079. // should always be a no-op, because blocks in default argument
  5080. // expressions should never be able to capture anything.
  5081. assert(!Init->getNumObjects() &&
  5082. "default argument expression has capturing blocks?");
  5083. }
  5084. // We already type-checked the argument, so we know it works.
  5085. // Just mark all of the declarations in this potentially-evaluated expression
  5086. // as being "referenced".
  5087. EnterExpressionEvaluationContext EvalContext(
  5088. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  5089. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  5090. /*SkipLocalVariables=*/true);
  5091. return false;
  5092. }
  5093. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  5094. FunctionDecl *FD, ParmVarDecl *Param) {
  5095. assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
  5096. if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
  5097. return ExprError();
  5098. return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
  5099. }
  5100. Sema::VariadicCallType
  5101. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  5102. Expr *Fn) {
  5103. if (Proto && Proto->isVariadic()) {
  5104. if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
  5105. return VariadicConstructor;
  5106. else if (Fn && Fn->getType()->isBlockPointerType())
  5107. return VariadicBlock;
  5108. else if (FDecl) {
  5109. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  5110. if (Method->isInstance())
  5111. return VariadicMethod;
  5112. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  5113. return VariadicMethod;
  5114. return VariadicFunction;
  5115. }
  5116. return VariadicDoesNotApply;
  5117. }
  5118. namespace {
  5119. class FunctionCallCCC final : public FunctionCallFilterCCC {
  5120. public:
  5121. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  5122. unsigned NumArgs, MemberExpr *ME)
  5123. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  5124. FunctionName(FuncName) {}
  5125. bool ValidateCandidate(const TypoCorrection &candidate) override {
  5126. if (!candidate.getCorrectionSpecifier() ||
  5127. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  5128. return false;
  5129. }
  5130. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  5131. }
  5132. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  5133. return std::make_unique<FunctionCallCCC>(*this);
  5134. }
  5135. private:
  5136. const IdentifierInfo *const FunctionName;
  5137. };
  5138. }
  5139. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  5140. FunctionDecl *FDecl,
  5141. ArrayRef<Expr *> Args) {
  5142. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  5143. DeclarationName FuncName = FDecl->getDeclName();
  5144. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
  5145. FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
  5146. if (TypoCorrection Corrected = S.CorrectTypo(
  5147. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  5148. S.getScopeForContext(S.CurContext), nullptr, CCC,
  5149. Sema::CTK_ErrorRecovery)) {
  5150. if (NamedDecl *ND = Corrected.getFoundDecl()) {
  5151. if (Corrected.isOverloaded()) {
  5152. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  5153. OverloadCandidateSet::iterator Best;
  5154. for (NamedDecl *CD : Corrected) {
  5155. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  5156. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  5157. OCS);
  5158. }
  5159. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  5160. case OR_Success:
  5161. ND = Best->FoundDecl;
  5162. Corrected.setCorrectionDecl(ND);
  5163. break;
  5164. default:
  5165. break;
  5166. }
  5167. }
  5168. ND = ND->getUnderlyingDecl();
  5169. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
  5170. return Corrected;
  5171. }
  5172. }
  5173. return TypoCorrection();
  5174. }
  5175. /// ConvertArgumentsForCall - Converts the arguments specified in
  5176. /// Args/NumArgs to the parameter types of the function FDecl with
  5177. /// function prototype Proto. Call is the call expression itself, and
  5178. /// Fn is the function expression. For a C++ member function, this
  5179. /// routine does not attempt to convert the object argument. Returns
  5180. /// true if the call is ill-formed.
  5181. bool
  5182. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  5183. FunctionDecl *FDecl,
  5184. const FunctionProtoType *Proto,
  5185. ArrayRef<Expr *> Args,
  5186. SourceLocation RParenLoc,
  5187. bool IsExecConfig) {
  5188. // Bail out early if calling a builtin with custom typechecking.
  5189. if (FDecl)
  5190. if (unsigned ID = FDecl->getBuiltinID())
  5191. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  5192. return false;
  5193. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  5194. // assignment, to the types of the corresponding parameter, ...
  5195. unsigned NumParams = Proto->getNumParams();
  5196. bool Invalid = false;
  5197. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  5198. unsigned FnKind = Fn->getType()->isBlockPointerType()
  5199. ? 1 /* block */
  5200. : (IsExecConfig ? 3 /* kernel function (exec config) */
  5201. : 0 /* function */);
  5202. // If too few arguments are available (and we don't have default
  5203. // arguments for the remaining parameters), don't make the call.
  5204. if (Args.size() < NumParams) {
  5205. if (Args.size() < MinArgs) {
  5206. TypoCorrection TC;
  5207. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  5208. unsigned diag_id =
  5209. MinArgs == NumParams && !Proto->isVariadic()
  5210. ? diag::err_typecheck_call_too_few_args_suggest
  5211. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  5212. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  5213. << static_cast<unsigned>(Args.size())
  5214. << TC.getCorrectionRange());
  5215. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  5216. Diag(RParenLoc,
  5217. MinArgs == NumParams && !Proto->isVariadic()
  5218. ? diag::err_typecheck_call_too_few_args_one
  5219. : diag::err_typecheck_call_too_few_args_at_least_one)
  5220. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  5221. else
  5222. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  5223. ? diag::err_typecheck_call_too_few_args
  5224. : diag::err_typecheck_call_too_few_args_at_least)
  5225. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  5226. << Fn->getSourceRange();
  5227. // Emit the location of the prototype.
  5228. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  5229. Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
  5230. return true;
  5231. }
  5232. // We reserve space for the default arguments when we create
  5233. // the call expression, before calling ConvertArgumentsForCall.
  5234. assert((Call->getNumArgs() == NumParams) &&
  5235. "We should have reserved space for the default arguments before!");
  5236. }
  5237. // If too many are passed and not variadic, error on the extras and drop
  5238. // them.
  5239. if (Args.size() > NumParams) {
  5240. if (!Proto->isVariadic()) {
  5241. TypoCorrection TC;
  5242. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  5243. unsigned diag_id =
  5244. MinArgs == NumParams && !Proto->isVariadic()
  5245. ? diag::err_typecheck_call_too_many_args_suggest
  5246. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  5247. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  5248. << static_cast<unsigned>(Args.size())
  5249. << TC.getCorrectionRange());
  5250. } else if (NumParams == 1 && FDecl &&
  5251. FDecl->getParamDecl(0)->getDeclName())
  5252. Diag(Args[NumParams]->getBeginLoc(),
  5253. MinArgs == NumParams
  5254. ? diag::err_typecheck_call_too_many_args_one
  5255. : diag::err_typecheck_call_too_many_args_at_most_one)
  5256. << FnKind << FDecl->getParamDecl(0)
  5257. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  5258. << SourceRange(Args[NumParams]->getBeginLoc(),
  5259. Args.back()->getEndLoc());
  5260. else
  5261. Diag(Args[NumParams]->getBeginLoc(),
  5262. MinArgs == NumParams
  5263. ? diag::err_typecheck_call_too_many_args
  5264. : diag::err_typecheck_call_too_many_args_at_most)
  5265. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  5266. << Fn->getSourceRange()
  5267. << SourceRange(Args[NumParams]->getBeginLoc(),
  5268. Args.back()->getEndLoc());
  5269. // Emit the location of the prototype.
  5270. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  5271. Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
  5272. // This deletes the extra arguments.
  5273. Call->shrinkNumArgs(NumParams);
  5274. return true;
  5275. }
  5276. }
  5277. SmallVector<Expr *, 8> AllArgs;
  5278. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  5279. Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
  5280. AllArgs, CallType);
  5281. if (Invalid)
  5282. return true;
  5283. unsigned TotalNumArgs = AllArgs.size();
  5284. for (unsigned i = 0; i < TotalNumArgs; ++i)
  5285. Call->setArg(i, AllArgs[i]);
  5286. Call->computeDependence();
  5287. return false;
  5288. }
  5289. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  5290. const FunctionProtoType *Proto,
  5291. unsigned FirstParam, ArrayRef<Expr *> Args,
  5292. SmallVectorImpl<Expr *> &AllArgs,
  5293. VariadicCallType CallType, bool AllowExplicit,
  5294. bool IsListInitialization) {
  5295. unsigned NumParams = Proto->getNumParams();
  5296. bool Invalid = false;
  5297. size_t ArgIx = 0;
  5298. // Continue to check argument types (even if we have too few/many args).
  5299. for (unsigned i = FirstParam; i < NumParams; i++) {
  5300. QualType ProtoArgType = Proto->getParamType(i);
  5301. Expr *Arg;
  5302. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  5303. if (ArgIx < Args.size()) {
  5304. Arg = Args[ArgIx++];
  5305. if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
  5306. diag::err_call_incomplete_argument, Arg))
  5307. return true;
  5308. // Strip the unbridged-cast placeholder expression off, if applicable.
  5309. bool CFAudited = false;
  5310. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  5311. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  5312. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  5313. Arg = stripARCUnbridgedCast(Arg);
  5314. else if (getLangOpts().ObjCAutoRefCount &&
  5315. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  5316. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  5317. CFAudited = true;
  5318. if (Proto->getExtParameterInfo(i).isNoEscape() &&
  5319. ProtoArgType->isBlockPointerType())
  5320. if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
  5321. BE->getBlockDecl()->setDoesNotEscape();
  5322. InitializedEntity Entity =
  5323. Param ? InitializedEntity::InitializeParameter(Context, Param,
  5324. ProtoArgType)
  5325. : InitializedEntity::InitializeParameter(
  5326. Context, ProtoArgType, Proto->isParamConsumed(i));
  5327. // Remember that parameter belongs to a CF audited API.
  5328. if (CFAudited)
  5329. Entity.setParameterCFAudited();
  5330. ExprResult ArgE = PerformCopyInitialization(
  5331. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  5332. if (ArgE.isInvalid())
  5333. return true;
  5334. Arg = ArgE.getAs<Expr>();
  5335. } else {
  5336. assert(Param && "can't use default arguments without a known callee");
  5337. ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  5338. if (ArgExpr.isInvalid())
  5339. return true;
  5340. Arg = ArgExpr.getAs<Expr>();
  5341. }
  5342. // Check for array bounds violations for each argument to the call. This
  5343. // check only triggers warnings when the argument isn't a more complex Expr
  5344. // with its own checking, such as a BinaryOperator.
  5345. CheckArrayAccess(Arg);
  5346. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  5347. CheckStaticArrayArgument(CallLoc, Param, Arg);
  5348. AllArgs.push_back(Arg);
  5349. }
  5350. // If this is a variadic call, handle args passed through "...".
  5351. if (CallType != VariadicDoesNotApply) {
  5352. // Assume that extern "C" functions with variadic arguments that
  5353. // return __unknown_anytype aren't *really* variadic.
  5354. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  5355. FDecl->isExternC()) {
  5356. for (Expr *A : Args.slice(ArgIx)) {
  5357. QualType paramType; // ignored
  5358. ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
  5359. Invalid |= arg.isInvalid();
  5360. AllArgs.push_back(arg.get());
  5361. }
  5362. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  5363. } else {
  5364. for (Expr *A : Args.slice(ArgIx)) {
  5365. ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
  5366. Invalid |= Arg.isInvalid();
  5367. AllArgs.push_back(Arg.get());
  5368. }
  5369. }
  5370. // Check for array bounds violations.
  5371. for (Expr *A : Args.slice(ArgIx))
  5372. CheckArrayAccess(A);
  5373. }
  5374. return Invalid;
  5375. }
  5376. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  5377. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  5378. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  5379. TL = DTL.getOriginalLoc();
  5380. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  5381. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  5382. << ATL.getLocalSourceRange();
  5383. }
  5384. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  5385. /// array parameter, check that it is non-null, and that if it is formed by
  5386. /// array-to-pointer decay, the underlying array is sufficiently large.
  5387. ///
  5388. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  5389. /// array type derivation, then for each call to the function, the value of the
  5390. /// corresponding actual argument shall provide access to the first element of
  5391. /// an array with at least as many elements as specified by the size expression.
  5392. void
  5393. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  5394. ParmVarDecl *Param,
  5395. const Expr *ArgExpr) {
  5396. // Static array parameters are not supported in C++.
  5397. if (!Param || getLangOpts().CPlusPlus)
  5398. return;
  5399. QualType OrigTy = Param->getOriginalType();
  5400. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  5401. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  5402. return;
  5403. if (ArgExpr->isNullPointerConstant(Context,
  5404. Expr::NPC_NeverValueDependent)) {
  5405. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  5406. DiagnoseCalleeStaticArrayParam(*this, Param);
  5407. return;
  5408. }
  5409. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  5410. if (!CAT)
  5411. return;
  5412. const ConstantArrayType *ArgCAT =
  5413. Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
  5414. if (!ArgCAT)
  5415. return;
  5416. if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
  5417. ArgCAT->getElementType())) {
  5418. if (ArgCAT->getSize().ult(CAT->getSize())) {
  5419. Diag(CallLoc, diag::warn_static_array_too_small)
  5420. << ArgExpr->getSourceRange()
  5421. << (unsigned)ArgCAT->getSize().getZExtValue()
  5422. << (unsigned)CAT->getSize().getZExtValue() << 0;
  5423. DiagnoseCalleeStaticArrayParam(*this, Param);
  5424. }
  5425. return;
  5426. }
  5427. Optional<CharUnits> ArgSize =
  5428. getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
  5429. Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
  5430. if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
  5431. Diag(CallLoc, diag::warn_static_array_too_small)
  5432. << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
  5433. << (unsigned)ParmSize->getQuantity() << 1;
  5434. DiagnoseCalleeStaticArrayParam(*this, Param);
  5435. }
  5436. }
  5437. /// Given a function expression of unknown-any type, try to rebuild it
  5438. /// to have a function type.
  5439. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  5440. /// Is the given type a placeholder that we need to lower out
  5441. /// immediately during argument processing?
  5442. static bool isPlaceholderToRemoveAsArg(QualType type) {
  5443. // Placeholders are never sugared.
  5444. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  5445. if (!placeholder) return false;
  5446. switch (placeholder->getKind()) {
  5447. // Ignore all the non-placeholder types.
  5448. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  5449. case BuiltinType::Id:
  5450. #include "clang/Basic/OpenCLImageTypes.def"
  5451. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  5452. case BuiltinType::Id:
  5453. #include "clang/Basic/OpenCLExtensionTypes.def"
  5454. // In practice we'll never use this, since all SVE types are sugared
  5455. // via TypedefTypes rather than exposed directly as BuiltinTypes.
  5456. #define SVE_TYPE(Name, Id, SingletonId) \
  5457. case BuiltinType::Id:
  5458. #include "clang/Basic/AArch64SVEACLETypes.def"
  5459. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  5460. case BuiltinType::Id:
  5461. #include "clang/Basic/PPCTypes.def"
  5462. #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
  5463. #include "clang/Basic/RISCVVTypes.def"
  5464. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  5465. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  5466. #include "clang/AST/BuiltinTypes.def"
  5467. return false;
  5468. // We cannot lower out overload sets; they might validly be resolved
  5469. // by the call machinery.
  5470. case BuiltinType::Overload:
  5471. return false;
  5472. // Unbridged casts in ARC can be handled in some call positions and
  5473. // should be left in place.
  5474. case BuiltinType::ARCUnbridgedCast:
  5475. return false;
  5476. // Pseudo-objects should be converted as soon as possible.
  5477. case BuiltinType::PseudoObject:
  5478. return true;
  5479. // The debugger mode could theoretically but currently does not try
  5480. // to resolve unknown-typed arguments based on known parameter types.
  5481. case BuiltinType::UnknownAny:
  5482. return true;
  5483. // These are always invalid as call arguments and should be reported.
  5484. case BuiltinType::BoundMember:
  5485. case BuiltinType::BuiltinFn:
  5486. case BuiltinType::IncompleteMatrixIdx:
  5487. case BuiltinType::OMPArraySection:
  5488. case BuiltinType::OMPArrayShaping:
  5489. case BuiltinType::OMPIterator:
  5490. return true;
  5491. }
  5492. llvm_unreachable("bad builtin type kind");
  5493. }
  5494. /// Check an argument list for placeholders that we won't try to
  5495. /// handle later.
  5496. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  5497. // Apply this processing to all the arguments at once instead of
  5498. // dying at the first failure.
  5499. bool hasInvalid = false;
  5500. for (size_t i = 0, e = args.size(); i != e; i++) {
  5501. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  5502. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  5503. if (result.isInvalid()) hasInvalid = true;
  5504. else args[i] = result.get();
  5505. }
  5506. }
  5507. return hasInvalid;
  5508. }
  5509. /// If a builtin function has a pointer argument with no explicit address
  5510. /// space, then it should be able to accept a pointer to any address
  5511. /// space as input. In order to do this, we need to replace the
  5512. /// standard builtin declaration with one that uses the same address space
  5513. /// as the call.
  5514. ///
  5515. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  5516. /// it does not contain any pointer arguments without
  5517. /// an address space qualifer. Otherwise the rewritten
  5518. /// FunctionDecl is returned.
  5519. /// TODO: Handle pointer return types.
  5520. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  5521. FunctionDecl *FDecl,
  5522. MultiExprArg ArgExprs) {
  5523. QualType DeclType = FDecl->getType();
  5524. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  5525. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
  5526. ArgExprs.size() < FT->getNumParams())
  5527. return nullptr;
  5528. bool NeedsNewDecl = false;
  5529. unsigned i = 0;
  5530. SmallVector<QualType, 8> OverloadParams;
  5531. for (QualType ParamType : FT->param_types()) {
  5532. // Convert array arguments to pointer to simplify type lookup.
  5533. ExprResult ArgRes =
  5534. Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
  5535. if (ArgRes.isInvalid())
  5536. return nullptr;
  5537. Expr *Arg = ArgRes.get();
  5538. QualType ArgType = Arg->getType();
  5539. if (!ParamType->isPointerType() ||
  5540. ParamType.hasAddressSpace() ||
  5541. !ArgType->isPointerType() ||
  5542. !ArgType->getPointeeType().hasAddressSpace()) {
  5543. OverloadParams.push_back(ParamType);
  5544. continue;
  5545. }
  5546. QualType PointeeType = ParamType->getPointeeType();
  5547. if (PointeeType.hasAddressSpace())
  5548. continue;
  5549. NeedsNewDecl = true;
  5550. LangAS AS = ArgType->getPointeeType().getAddressSpace();
  5551. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  5552. OverloadParams.push_back(Context.getPointerType(PointeeType));
  5553. }
  5554. if (!NeedsNewDecl)
  5555. return nullptr;
  5556. FunctionProtoType::ExtProtoInfo EPI;
  5557. EPI.Variadic = FT->isVariadic();
  5558. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  5559. OverloadParams, EPI);
  5560. DeclContext *Parent = FDecl->getParent();
  5561. FunctionDecl *OverloadDecl = FunctionDecl::Create(
  5562. Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
  5563. FDecl->getIdentifier(), OverloadTy,
  5564. /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
  5565. false,
  5566. /*hasPrototype=*/true);
  5567. SmallVector<ParmVarDecl*, 16> Params;
  5568. FT = cast<FunctionProtoType>(OverloadTy);
  5569. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  5570. QualType ParamType = FT->getParamType(i);
  5571. ParmVarDecl *Parm =
  5572. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  5573. SourceLocation(), nullptr, ParamType,
  5574. /*TInfo=*/nullptr, SC_None, nullptr);
  5575. Parm->setScopeInfo(0, i);
  5576. Params.push_back(Parm);
  5577. }
  5578. OverloadDecl->setParams(Params);
  5579. Sema->mergeDeclAttributes(OverloadDecl, FDecl);
  5580. return OverloadDecl;
  5581. }
  5582. static void checkDirectCallValidity(Sema &S, const Expr *Fn,
  5583. FunctionDecl *Callee,
  5584. MultiExprArg ArgExprs) {
  5585. // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
  5586. // similar attributes) really don't like it when functions are called with an
  5587. // invalid number of args.
  5588. if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
  5589. /*PartialOverloading=*/false) &&
  5590. !Callee->isVariadic())
  5591. return;
  5592. if (Callee->getMinRequiredArguments() > ArgExprs.size())
  5593. return;
  5594. if (const EnableIfAttr *Attr =
  5595. S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
  5596. S.Diag(Fn->getBeginLoc(),
  5597. isa<CXXMethodDecl>(Callee)
  5598. ? diag::err_ovl_no_viable_member_function_in_call
  5599. : diag::err_ovl_no_viable_function_in_call)
  5600. << Callee << Callee->getSourceRange();
  5601. S.Diag(Callee->getLocation(),
  5602. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  5603. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  5604. return;
  5605. }
  5606. }
  5607. static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
  5608. const UnresolvedMemberExpr *const UME, Sema &S) {
  5609. const auto GetFunctionLevelDCIfCXXClass =
  5610. [](Sema &S) -> const CXXRecordDecl * {
  5611. const DeclContext *const DC = S.getFunctionLevelDeclContext();
  5612. if (!DC || !DC->getParent())
  5613. return nullptr;
  5614. // If the call to some member function was made from within a member
  5615. // function body 'M' return return 'M's parent.
  5616. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  5617. return MD->getParent()->getCanonicalDecl();
  5618. // else the call was made from within a default member initializer of a
  5619. // class, so return the class.
  5620. if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
  5621. return RD->getCanonicalDecl();
  5622. return nullptr;
  5623. };
  5624. // If our DeclContext is neither a member function nor a class (in the
  5625. // case of a lambda in a default member initializer), we can't have an
  5626. // enclosing 'this'.
  5627. const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
  5628. if (!CurParentClass)
  5629. return false;
  5630. // The naming class for implicit member functions call is the class in which
  5631. // name lookup starts.
  5632. const CXXRecordDecl *const NamingClass =
  5633. UME->getNamingClass()->getCanonicalDecl();
  5634. assert(NamingClass && "Must have naming class even for implicit access");
  5635. // If the unresolved member functions were found in a 'naming class' that is
  5636. // related (either the same or derived from) to the class that contains the
  5637. // member function that itself contained the implicit member access.
  5638. return CurParentClass == NamingClass ||
  5639. CurParentClass->isDerivedFrom(NamingClass);
  5640. }
  5641. static void
  5642. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  5643. Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
  5644. if (!UME)
  5645. return;
  5646. LambdaScopeInfo *const CurLSI = S.getCurLambda();
  5647. // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
  5648. // already been captured, or if this is an implicit member function call (if
  5649. // it isn't, an attempt to capture 'this' should already have been made).
  5650. if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
  5651. !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
  5652. return;
  5653. // Check if the naming class in which the unresolved members were found is
  5654. // related (same as or is a base of) to the enclosing class.
  5655. if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
  5656. return;
  5657. DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
  5658. // If the enclosing function is not dependent, then this lambda is
  5659. // capture ready, so if we can capture this, do so.
  5660. if (!EnclosingFunctionCtx->isDependentContext()) {
  5661. // If the current lambda and all enclosing lambdas can capture 'this' -
  5662. // then go ahead and capture 'this' (since our unresolved overload set
  5663. // contains at least one non-static member function).
  5664. if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
  5665. S.CheckCXXThisCapture(CallLoc);
  5666. } else if (S.CurContext->isDependentContext()) {
  5667. // ... since this is an implicit member reference, that might potentially
  5668. // involve a 'this' capture, mark 'this' for potential capture in
  5669. // enclosing lambdas.
  5670. if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
  5671. CurLSI->addPotentialThisCapture(CallLoc);
  5672. }
  5673. }
  5674. ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  5675. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  5676. Expr *ExecConfig) {
  5677. ExprResult Call =
  5678. BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
  5679. /*IsExecConfig=*/false, /*AllowRecovery=*/true);
  5680. if (Call.isInvalid())
  5681. return Call;
  5682. // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
  5683. // language modes.
  5684. if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
  5685. if (ULE->hasExplicitTemplateArgs() &&
  5686. ULE->decls_begin() == ULE->decls_end()) {
  5687. Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
  5688. ? diag::warn_cxx17_compat_adl_only_template_id
  5689. : diag::ext_adl_only_template_id)
  5690. << ULE->getName();
  5691. }
  5692. }
  5693. if (LangOpts.OpenMP)
  5694. Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
  5695. ExecConfig);
  5696. return Call;
  5697. }
  5698. /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
  5699. /// This provides the location of the left/right parens and a list of comma
  5700. /// locations.
  5701. ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  5702. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  5703. Expr *ExecConfig, bool IsExecConfig,
  5704. bool AllowRecovery) {
  5705. // Since this might be a postfix expression, get rid of ParenListExprs.
  5706. ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
  5707. if (Result.isInvalid()) return ExprError();
  5708. Fn = Result.get();
  5709. if (checkArgsForPlaceholders(*this, ArgExprs))
  5710. return ExprError();
  5711. if (getLangOpts().CPlusPlus) {
  5712. // If this is a pseudo-destructor expression, build the call immediately.
  5713. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  5714. if (!ArgExprs.empty()) {
  5715. // Pseudo-destructor calls should not have any arguments.
  5716. Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
  5717. << FixItHint::CreateRemoval(
  5718. SourceRange(ArgExprs.front()->getBeginLoc(),
  5719. ArgExprs.back()->getEndLoc()));
  5720. }
  5721. return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
  5722. VK_PRValue, RParenLoc, CurFPFeatureOverrides());
  5723. }
  5724. if (Fn->getType() == Context.PseudoObjectTy) {
  5725. ExprResult result = CheckPlaceholderExpr(Fn);
  5726. if (result.isInvalid()) return ExprError();
  5727. Fn = result.get();
  5728. }
  5729. // Determine whether this is a dependent call inside a C++ template,
  5730. // in which case we won't do any semantic analysis now.
  5731. if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
  5732. if (ExecConfig) {
  5733. return CUDAKernelCallExpr::Create(Context, Fn,
  5734. cast<CallExpr>(ExecConfig), ArgExprs,
  5735. Context.DependentTy, VK_PRValue,
  5736. RParenLoc, CurFPFeatureOverrides());
  5737. } else {
  5738. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  5739. *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
  5740. Fn->getBeginLoc());
  5741. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  5742. VK_PRValue, RParenLoc, CurFPFeatureOverrides());
  5743. }
  5744. }
  5745. // Determine whether this is a call to an object (C++ [over.call.object]).
  5746. if (Fn->getType()->isRecordType())
  5747. return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
  5748. RParenLoc);
  5749. if (Fn->getType() == Context.UnknownAnyTy) {
  5750. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  5751. if (result.isInvalid()) return ExprError();
  5752. Fn = result.get();
  5753. }
  5754. if (Fn->getType() == Context.BoundMemberTy) {
  5755. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  5756. RParenLoc, ExecConfig, IsExecConfig,
  5757. AllowRecovery);
  5758. }
  5759. }
  5760. // Check for overloaded calls. This can happen even in C due to extensions.
  5761. if (Fn->getType() == Context.OverloadTy) {
  5762. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  5763. // We aren't supposed to apply this logic if there's an '&' involved.
  5764. if (!find.HasFormOfMemberPointer) {
  5765. if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  5766. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  5767. VK_PRValue, RParenLoc, CurFPFeatureOverrides());
  5768. OverloadExpr *ovl = find.Expression;
  5769. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
  5770. return BuildOverloadedCallExpr(
  5771. Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
  5772. /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
  5773. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  5774. RParenLoc, ExecConfig, IsExecConfig,
  5775. AllowRecovery);
  5776. }
  5777. }
  5778. // If we're directly calling a function, get the appropriate declaration.
  5779. if (Fn->getType() == Context.UnknownAnyTy) {
  5780. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  5781. if (result.isInvalid()) return ExprError();
  5782. Fn = result.get();
  5783. }
  5784. Expr *NakedFn = Fn->IgnoreParens();
  5785. bool CallingNDeclIndirectly = false;
  5786. NamedDecl *NDecl = nullptr;
  5787. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
  5788. if (UnOp->getOpcode() == UO_AddrOf) {
  5789. CallingNDeclIndirectly = true;
  5790. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  5791. }
  5792. }
  5793. if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
  5794. NDecl = DRE->getDecl();
  5795. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  5796. if (FDecl && FDecl->getBuiltinID()) {
  5797. // Rewrite the function decl for this builtin by replacing parameters
  5798. // with no explicit address space with the address space of the arguments
  5799. // in ArgExprs.
  5800. if ((FDecl =
  5801. rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  5802. NDecl = FDecl;
  5803. Fn = DeclRefExpr::Create(
  5804. Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
  5805. SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
  5806. nullptr, DRE->isNonOdrUse());
  5807. }
  5808. }
  5809. } else if (isa<MemberExpr>(NakedFn))
  5810. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  5811. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  5812. if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
  5813. FD, /*Complain=*/true, Fn->getBeginLoc()))
  5814. return ExprError();
  5815. checkDirectCallValidity(*this, Fn, FD, ArgExprs);
  5816. // If this expression is a call to a builtin function in HIP device
  5817. // compilation, allow a pointer-type argument to default address space to be
  5818. // passed as a pointer-type parameter to a non-default address space.
  5819. // If Arg is declared in the default address space and Param is declared
  5820. // in a non-default address space, perform an implicit address space cast to
  5821. // the parameter type.
  5822. if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
  5823. FD->getBuiltinID()) {
  5824. for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
  5825. ParmVarDecl *Param = FD->getParamDecl(Idx);
  5826. if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
  5827. !ArgExprs[Idx]->getType()->isPointerType())
  5828. continue;
  5829. auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
  5830. auto ArgTy = ArgExprs[Idx]->getType();
  5831. auto ArgPtTy = ArgTy->getPointeeType();
  5832. auto ArgAS = ArgPtTy.getAddressSpace();
  5833. // Add address space cast if target address spaces are different
  5834. bool NeedImplicitASC =
  5835. ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
  5836. ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
  5837. // or from specific AS which has target AS matching that of Param.
  5838. getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
  5839. if (!NeedImplicitASC)
  5840. continue;
  5841. // First, ensure that the Arg is an RValue.
  5842. if (ArgExprs[Idx]->isGLValue()) {
  5843. ArgExprs[Idx] = ImplicitCastExpr::Create(
  5844. Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
  5845. nullptr, VK_PRValue, FPOptionsOverride());
  5846. }
  5847. // Construct a new arg type with address space of Param
  5848. Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
  5849. ArgPtQuals.setAddressSpace(ParamAS);
  5850. auto NewArgPtTy =
  5851. Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
  5852. auto NewArgTy =
  5853. Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
  5854. ArgTy.getQualifiers());
  5855. // Finally perform an implicit address space cast
  5856. ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
  5857. CK_AddressSpaceConversion)
  5858. .get();
  5859. }
  5860. }
  5861. }
  5862. if (Context.isDependenceAllowed() &&
  5863. (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
  5864. assert(!getLangOpts().CPlusPlus);
  5865. assert((Fn->containsErrors() ||
  5866. llvm::any_of(ArgExprs,
  5867. [](clang::Expr *E) { return E->containsErrors(); })) &&
  5868. "should only occur in error-recovery path.");
  5869. QualType ReturnType =
  5870. llvm::isa_and_nonnull<FunctionDecl>(NDecl)
  5871. ? cast<FunctionDecl>(NDecl)->getCallResultType()
  5872. : Context.DependentTy;
  5873. return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
  5874. Expr::getValueKindForType(ReturnType), RParenLoc,
  5875. CurFPFeatureOverrides());
  5876. }
  5877. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  5878. ExecConfig, IsExecConfig);
  5879. }
  5880. /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
  5881. // with the specified CallArgs
  5882. Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
  5883. MultiExprArg CallArgs) {
  5884. StringRef Name = Context.BuiltinInfo.getName(Id);
  5885. LookupResult R(*this, &Context.Idents.get(Name), Loc,
  5886. Sema::LookupOrdinaryName);
  5887. LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
  5888. auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
  5889. assert(BuiltInDecl && "failed to find builtin declaration");
  5890. ExprResult DeclRef =
  5891. BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
  5892. assert(DeclRef.isUsable() && "Builtin reference cannot fail");
  5893. ExprResult Call =
  5894. BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
  5895. assert(!Call.isInvalid() && "Call to builtin cannot fail!");
  5896. return Call.get();
  5897. }
  5898. /// Parse a __builtin_astype expression.
  5899. ///
  5900. /// __builtin_astype( value, dst type )
  5901. ///
  5902. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  5903. SourceLocation BuiltinLoc,
  5904. SourceLocation RParenLoc) {
  5905. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  5906. return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
  5907. }
  5908. /// Create a new AsTypeExpr node (bitcast) from the arguments.
  5909. ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
  5910. SourceLocation BuiltinLoc,
  5911. SourceLocation RParenLoc) {
  5912. ExprValueKind VK = VK_PRValue;
  5913. ExprObjectKind OK = OK_Ordinary;
  5914. QualType SrcTy = E->getType();
  5915. if (!SrcTy->isDependentType() &&
  5916. Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
  5917. return ExprError(
  5918. Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
  5919. << DestTy << SrcTy << E->getSourceRange());
  5920. return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
  5921. }
  5922. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  5923. /// provided arguments.
  5924. ///
  5925. /// __builtin_convertvector( value, dst type )
  5926. ///
  5927. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  5928. SourceLocation BuiltinLoc,
  5929. SourceLocation RParenLoc) {
  5930. TypeSourceInfo *TInfo;
  5931. GetTypeFromParser(ParsedDestTy, &TInfo);
  5932. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  5933. }
  5934. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  5935. /// i.e. an expression not of \p OverloadTy. The expression should
  5936. /// unary-convert to an expression of function-pointer or
  5937. /// block-pointer type.
  5938. ///
  5939. /// \param NDecl the declaration being called, if available
  5940. ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  5941. SourceLocation LParenLoc,
  5942. ArrayRef<Expr *> Args,
  5943. SourceLocation RParenLoc, Expr *Config,
  5944. bool IsExecConfig, ADLCallKind UsesADL) {
  5945. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  5946. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  5947. // Functions with 'interrupt' attribute cannot be called directly.
  5948. if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
  5949. Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
  5950. return ExprError();
  5951. }
  5952. // Interrupt handlers don't save off the VFP regs automatically on ARM,
  5953. // so there's some risk when calling out to non-interrupt handler functions
  5954. // that the callee might not preserve them. This is easy to diagnose here,
  5955. // but can be very challenging to debug.
  5956. // Likewise, X86 interrupt handlers may only call routines with attribute
  5957. // no_caller_saved_registers since there is no efficient way to
  5958. // save and restore the non-GPR state.
  5959. if (auto *Caller = getCurFunctionDecl()) {
  5960. if (Caller->hasAttr<ARMInterruptAttr>()) {
  5961. bool VFP = Context.getTargetInfo().hasFeature("vfp");
  5962. if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
  5963. Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
  5964. if (FDecl)
  5965. Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
  5966. }
  5967. }
  5968. if (Caller->hasAttr<AnyX86InterruptAttr>() &&
  5969. ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
  5970. Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
  5971. if (FDecl)
  5972. Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
  5973. }
  5974. }
  5975. // Promote the function operand.
  5976. // We special-case function promotion here because we only allow promoting
  5977. // builtin functions to function pointers in the callee of a call.
  5978. ExprResult Result;
  5979. QualType ResultTy;
  5980. if (BuiltinID &&
  5981. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  5982. // Extract the return type from the (builtin) function pointer type.
  5983. // FIXME Several builtins still have setType in
  5984. // Sema::CheckBuiltinFunctionCall. One should review their definitions in
  5985. // Builtins.def to ensure they are correct before removing setType calls.
  5986. QualType FnPtrTy = Context.getPointerType(FDecl->getType());
  5987. Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
  5988. ResultTy = FDecl->getCallResultType();
  5989. } else {
  5990. Result = CallExprUnaryConversions(Fn);
  5991. ResultTy = Context.BoolTy;
  5992. }
  5993. if (Result.isInvalid())
  5994. return ExprError();
  5995. Fn = Result.get();
  5996. // Check for a valid function type, but only if it is not a builtin which
  5997. // requires custom type checking. These will be handled by
  5998. // CheckBuiltinFunctionCall below just after creation of the call expression.
  5999. const FunctionType *FuncT = nullptr;
  6000. if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
  6001. retry:
  6002. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  6003. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  6004. // have type pointer to function".
  6005. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  6006. if (!FuncT)
  6007. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  6008. << Fn->getType() << Fn->getSourceRange());
  6009. } else if (const BlockPointerType *BPT =
  6010. Fn->getType()->getAs<BlockPointerType>()) {
  6011. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  6012. } else {
  6013. // Handle calls to expressions of unknown-any type.
  6014. if (Fn->getType() == Context.UnknownAnyTy) {
  6015. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  6016. if (rewrite.isInvalid())
  6017. return ExprError();
  6018. Fn = rewrite.get();
  6019. goto retry;
  6020. }
  6021. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  6022. << Fn->getType() << Fn->getSourceRange());
  6023. }
  6024. }
  6025. // Get the number of parameters in the function prototype, if any.
  6026. // We will allocate space for max(Args.size(), NumParams) arguments
  6027. // in the call expression.
  6028. const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
  6029. unsigned NumParams = Proto ? Proto->getNumParams() : 0;
  6030. CallExpr *TheCall;
  6031. if (Config) {
  6032. assert(UsesADL == ADLCallKind::NotADL &&
  6033. "CUDAKernelCallExpr should not use ADL");
  6034. TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
  6035. Args, ResultTy, VK_PRValue, RParenLoc,
  6036. CurFPFeatureOverrides(), NumParams);
  6037. } else {
  6038. TheCall =
  6039. CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
  6040. CurFPFeatureOverrides(), NumParams, UsesADL);
  6041. }
  6042. if (!Context.isDependenceAllowed()) {
  6043. // Forget about the nulled arguments since typo correction
  6044. // do not handle them well.
  6045. TheCall->shrinkNumArgs(Args.size());
  6046. // C cannot always handle TypoExpr nodes in builtin calls and direct
  6047. // function calls as their argument checking don't necessarily handle
  6048. // dependent types properly, so make sure any TypoExprs have been
  6049. // dealt with.
  6050. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  6051. if (!Result.isUsable()) return ExprError();
  6052. CallExpr *TheOldCall = TheCall;
  6053. TheCall = dyn_cast<CallExpr>(Result.get());
  6054. bool CorrectedTypos = TheCall != TheOldCall;
  6055. if (!TheCall) return Result;
  6056. Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
  6057. // A new call expression node was created if some typos were corrected.
  6058. // However it may not have been constructed with enough storage. In this
  6059. // case, rebuild the node with enough storage. The waste of space is
  6060. // immaterial since this only happens when some typos were corrected.
  6061. if (CorrectedTypos && Args.size() < NumParams) {
  6062. if (Config)
  6063. TheCall = CUDAKernelCallExpr::Create(
  6064. Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
  6065. RParenLoc, CurFPFeatureOverrides(), NumParams);
  6066. else
  6067. TheCall =
  6068. CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
  6069. CurFPFeatureOverrides(), NumParams, UsesADL);
  6070. }
  6071. // We can now handle the nulled arguments for the default arguments.
  6072. TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
  6073. }
  6074. // Bail out early if calling a builtin with custom type checking.
  6075. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  6076. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  6077. if (getLangOpts().CUDA) {
  6078. if (Config) {
  6079. // CUDA: Kernel calls must be to global functions
  6080. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  6081. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  6082. << FDecl << Fn->getSourceRange());
  6083. // CUDA: Kernel function must have 'void' return type
  6084. if (!FuncT->getReturnType()->isVoidType() &&
  6085. !FuncT->getReturnType()->getAs<AutoType>() &&
  6086. !FuncT->getReturnType()->isInstantiationDependentType())
  6087. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  6088. << Fn->getType() << Fn->getSourceRange());
  6089. } else {
  6090. // CUDA: Calls to global functions must be configured
  6091. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  6092. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  6093. << FDecl << Fn->getSourceRange());
  6094. }
  6095. }
  6096. // Check for a valid return type
  6097. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
  6098. FDecl))
  6099. return ExprError();
  6100. // We know the result type of the call, set it.
  6101. TheCall->setType(FuncT->getCallResultType(Context));
  6102. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  6103. if (Proto) {
  6104. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  6105. IsExecConfig))
  6106. return ExprError();
  6107. } else {
  6108. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  6109. if (FDecl) {
  6110. // Check if we have too few/too many template arguments, based
  6111. // on our knowledge of the function definition.
  6112. const FunctionDecl *Def = nullptr;
  6113. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  6114. Proto = Def->getType()->getAs<FunctionProtoType>();
  6115. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  6116. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  6117. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  6118. }
  6119. // If the function we're calling isn't a function prototype, but we have
  6120. // a function prototype from a prior declaratiom, use that prototype.
  6121. if (!FDecl->hasPrototype())
  6122. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  6123. }
  6124. // Promote the arguments (C99 6.5.2.2p6).
  6125. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  6126. Expr *Arg = Args[i];
  6127. if (Proto && i < Proto->getNumParams()) {
  6128. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  6129. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  6130. ExprResult ArgE =
  6131. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  6132. if (ArgE.isInvalid())
  6133. return true;
  6134. Arg = ArgE.getAs<Expr>();
  6135. } else {
  6136. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  6137. if (ArgE.isInvalid())
  6138. return true;
  6139. Arg = ArgE.getAs<Expr>();
  6140. }
  6141. if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
  6142. diag::err_call_incomplete_argument, Arg))
  6143. return ExprError();
  6144. TheCall->setArg(i, Arg);
  6145. }
  6146. TheCall->computeDependence();
  6147. }
  6148. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  6149. if (!Method->isStatic())
  6150. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  6151. << Fn->getSourceRange());
  6152. // Check for sentinels
  6153. if (NDecl)
  6154. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  6155. // Warn for unions passing across security boundary (CMSE).
  6156. if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
  6157. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  6158. if (const auto *RT =
  6159. dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
  6160. if (RT->getDecl()->isOrContainsUnion())
  6161. Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
  6162. << 0 << i;
  6163. }
  6164. }
  6165. }
  6166. // Do special checking on direct calls to functions.
  6167. if (FDecl) {
  6168. if (CheckFunctionCall(FDecl, TheCall, Proto))
  6169. return ExprError();
  6170. checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
  6171. if (BuiltinID)
  6172. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  6173. } else if (NDecl) {
  6174. if (CheckPointerCall(NDecl, TheCall, Proto))
  6175. return ExprError();
  6176. } else {
  6177. if (CheckOtherCall(TheCall, Proto))
  6178. return ExprError();
  6179. }
  6180. return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
  6181. }
  6182. ExprResult
  6183. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  6184. SourceLocation RParenLoc, Expr *InitExpr) {
  6185. assert(Ty && "ActOnCompoundLiteral(): missing type");
  6186. assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
  6187. TypeSourceInfo *TInfo;
  6188. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  6189. if (!TInfo)
  6190. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  6191. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  6192. }
  6193. ExprResult
  6194. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  6195. SourceLocation RParenLoc, Expr *LiteralExpr) {
  6196. QualType literalType = TInfo->getType();
  6197. if (literalType->isArrayType()) {
  6198. if (RequireCompleteSizedType(
  6199. LParenLoc, Context.getBaseElementType(literalType),
  6200. diag::err_array_incomplete_or_sizeless_type,
  6201. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  6202. return ExprError();
  6203. if (literalType->isVariableArrayType()) {
  6204. if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
  6205. diag::err_variable_object_no_init)) {
  6206. return ExprError();
  6207. }
  6208. }
  6209. } else if (!literalType->isDependentType() &&
  6210. RequireCompleteType(LParenLoc, literalType,
  6211. diag::err_typecheck_decl_incomplete_type,
  6212. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  6213. return ExprError();
  6214. InitializedEntity Entity
  6215. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  6216. InitializationKind Kind
  6217. = InitializationKind::CreateCStyleCast(LParenLoc,
  6218. SourceRange(LParenLoc, RParenLoc),
  6219. /*InitList=*/true);
  6220. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  6221. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  6222. &literalType);
  6223. if (Result.isInvalid())
  6224. return ExprError();
  6225. LiteralExpr = Result.get();
  6226. bool isFileScope = !CurContext->isFunctionOrMethod();
  6227. // In C, compound literals are l-values for some reason.
  6228. // For GCC compatibility, in C++, file-scope array compound literals with
  6229. // constant initializers are also l-values, and compound literals are
  6230. // otherwise prvalues.
  6231. //
  6232. // (GCC also treats C++ list-initialized file-scope array prvalues with
  6233. // constant initializers as l-values, but that's non-conforming, so we don't
  6234. // follow it there.)
  6235. //
  6236. // FIXME: It would be better to handle the lvalue cases as materializing and
  6237. // lifetime-extending a temporary object, but our materialized temporaries
  6238. // representation only supports lifetime extension from a variable, not "out
  6239. // of thin air".
  6240. // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
  6241. // is bound to the result of applying array-to-pointer decay to the compound
  6242. // literal.
  6243. // FIXME: GCC supports compound literals of reference type, which should
  6244. // obviously have a value kind derived from the kind of reference involved.
  6245. ExprValueKind VK =
  6246. (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
  6247. ? VK_PRValue
  6248. : VK_LValue;
  6249. if (isFileScope)
  6250. if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
  6251. for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
  6252. Expr *Init = ILE->getInit(i);
  6253. ILE->setInit(i, ConstantExpr::Create(Context, Init));
  6254. }
  6255. auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  6256. VK, LiteralExpr, isFileScope);
  6257. if (isFileScope) {
  6258. if (!LiteralExpr->isTypeDependent() &&
  6259. !LiteralExpr->isValueDependent() &&
  6260. !literalType->isDependentType()) // C99 6.5.2.5p3
  6261. if (CheckForConstantInitializer(LiteralExpr, literalType))
  6262. return ExprError();
  6263. } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
  6264. literalType.getAddressSpace() != LangAS::Default) {
  6265. // Embedded-C extensions to C99 6.5.2.5:
  6266. // "If the compound literal occurs inside the body of a function, the
  6267. // type name shall not be qualified by an address-space qualifier."
  6268. Diag(LParenLoc, diag::err_compound_literal_with_address_space)
  6269. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
  6270. return ExprError();
  6271. }
  6272. if (!isFileScope && !getLangOpts().CPlusPlus) {
  6273. // Compound literals that have automatic storage duration are destroyed at
  6274. // the end of the scope in C; in C++, they're just temporaries.
  6275. // Emit diagnostics if it is or contains a C union type that is non-trivial
  6276. // to destruct.
  6277. if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
  6278. checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
  6279. NTCUC_CompoundLiteral, NTCUK_Destruct);
  6280. // Diagnose jumps that enter or exit the lifetime of the compound literal.
  6281. if (literalType.isDestructedType()) {
  6282. Cleanup.setExprNeedsCleanups(true);
  6283. ExprCleanupObjects.push_back(E);
  6284. getCurFunction()->setHasBranchProtectedScope();
  6285. }
  6286. }
  6287. if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  6288. E->getType().hasNonTrivialToPrimitiveCopyCUnion())
  6289. checkNonTrivialCUnionInInitializer(E->getInitializer(),
  6290. E->getInitializer()->getExprLoc());
  6291. return MaybeBindToTemporary(E);
  6292. }
  6293. ExprResult
  6294. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  6295. SourceLocation RBraceLoc) {
  6296. // Only produce each kind of designated initialization diagnostic once.
  6297. SourceLocation FirstDesignator;
  6298. bool DiagnosedArrayDesignator = false;
  6299. bool DiagnosedNestedDesignator = false;
  6300. bool DiagnosedMixedDesignator = false;
  6301. // Check that any designated initializers are syntactically valid in the
  6302. // current language mode.
  6303. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  6304. if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
  6305. if (FirstDesignator.isInvalid())
  6306. FirstDesignator = DIE->getBeginLoc();
  6307. if (!getLangOpts().CPlusPlus)
  6308. break;
  6309. if (!DiagnosedNestedDesignator && DIE->size() > 1) {
  6310. DiagnosedNestedDesignator = true;
  6311. Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
  6312. << DIE->getDesignatorsSourceRange();
  6313. }
  6314. for (auto &Desig : DIE->designators()) {
  6315. if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
  6316. DiagnosedArrayDesignator = true;
  6317. Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
  6318. << Desig.getSourceRange();
  6319. }
  6320. }
  6321. if (!DiagnosedMixedDesignator &&
  6322. !isa<DesignatedInitExpr>(InitArgList[0])) {
  6323. DiagnosedMixedDesignator = true;
  6324. Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
  6325. << DIE->getSourceRange();
  6326. Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
  6327. << InitArgList[0]->getSourceRange();
  6328. }
  6329. } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
  6330. isa<DesignatedInitExpr>(InitArgList[0])) {
  6331. DiagnosedMixedDesignator = true;
  6332. auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
  6333. Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
  6334. << DIE->getSourceRange();
  6335. Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
  6336. << InitArgList[I]->getSourceRange();
  6337. }
  6338. }
  6339. if (FirstDesignator.isValid()) {
  6340. // Only diagnose designated initiaization as a C++20 extension if we didn't
  6341. // already diagnose use of (non-C++20) C99 designator syntax.
  6342. if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
  6343. !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
  6344. Diag(FirstDesignator, getLangOpts().CPlusPlus20
  6345. ? diag::warn_cxx17_compat_designated_init
  6346. : diag::ext_cxx_designated_init);
  6347. } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
  6348. Diag(FirstDesignator, diag::ext_designated_init);
  6349. }
  6350. }
  6351. return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
  6352. }
  6353. ExprResult
  6354. Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  6355. SourceLocation RBraceLoc) {
  6356. // Semantic analysis for initializers is done by ActOnDeclarator() and
  6357. // CheckInitializer() - it requires knowledge of the object being initialized.
  6358. // Immediately handle non-overload placeholders. Overloads can be
  6359. // resolved contextually, but everything else here can't.
  6360. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  6361. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  6362. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  6363. // Ignore failures; dropping the entire initializer list because
  6364. // of one failure would be terrible for indexing/etc.
  6365. if (result.isInvalid()) continue;
  6366. InitArgList[I] = result.get();
  6367. }
  6368. }
  6369. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  6370. RBraceLoc);
  6371. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  6372. return E;
  6373. }
  6374. /// Do an explicit extend of the given block pointer if we're in ARC.
  6375. void Sema::maybeExtendBlockObject(ExprResult &E) {
  6376. assert(E.get()->getType()->isBlockPointerType());
  6377. assert(E.get()->isPRValue());
  6378. // Only do this in an r-value context.
  6379. if (!getLangOpts().ObjCAutoRefCount) return;
  6380. E = ImplicitCastExpr::Create(
  6381. Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
  6382. /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
  6383. Cleanup.setExprNeedsCleanups(true);
  6384. }
  6385. /// Prepare a conversion of the given expression to an ObjC object
  6386. /// pointer type.
  6387. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  6388. QualType type = E.get()->getType();
  6389. if (type->isObjCObjectPointerType()) {
  6390. return CK_BitCast;
  6391. } else if (type->isBlockPointerType()) {
  6392. maybeExtendBlockObject(E);
  6393. return CK_BlockPointerToObjCPointerCast;
  6394. } else {
  6395. assert(type->isPointerType());
  6396. return CK_CPointerToObjCPointerCast;
  6397. }
  6398. }
  6399. /// Prepares for a scalar cast, performing all the necessary stages
  6400. /// except the final cast and returning the kind required.
  6401. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  6402. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  6403. // Also, callers should have filtered out the invalid cases with
  6404. // pointers. Everything else should be possible.
  6405. QualType SrcTy = Src.get()->getType();
  6406. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  6407. return CK_NoOp;
  6408. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  6409. case Type::STK_MemberPointer:
  6410. llvm_unreachable("member pointer type in C");
  6411. case Type::STK_CPointer:
  6412. case Type::STK_BlockPointer:
  6413. case Type::STK_ObjCObjectPointer:
  6414. switch (DestTy->getScalarTypeKind()) {
  6415. case Type::STK_CPointer: {
  6416. LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
  6417. LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
  6418. if (SrcAS != DestAS)
  6419. return CK_AddressSpaceConversion;
  6420. if (Context.hasCvrSimilarType(SrcTy, DestTy))
  6421. return CK_NoOp;
  6422. return CK_BitCast;
  6423. }
  6424. case Type::STK_BlockPointer:
  6425. return (SrcKind == Type::STK_BlockPointer
  6426. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  6427. case Type::STK_ObjCObjectPointer:
  6428. if (SrcKind == Type::STK_ObjCObjectPointer)
  6429. return CK_BitCast;
  6430. if (SrcKind == Type::STK_CPointer)
  6431. return CK_CPointerToObjCPointerCast;
  6432. maybeExtendBlockObject(Src);
  6433. return CK_BlockPointerToObjCPointerCast;
  6434. case Type::STK_Bool:
  6435. return CK_PointerToBoolean;
  6436. case Type::STK_Integral:
  6437. return CK_PointerToIntegral;
  6438. case Type::STK_Floating:
  6439. case Type::STK_FloatingComplex:
  6440. case Type::STK_IntegralComplex:
  6441. case Type::STK_MemberPointer:
  6442. case Type::STK_FixedPoint:
  6443. llvm_unreachable("illegal cast from pointer");
  6444. }
  6445. llvm_unreachable("Should have returned before this");
  6446. case Type::STK_FixedPoint:
  6447. switch (DestTy->getScalarTypeKind()) {
  6448. case Type::STK_FixedPoint:
  6449. return CK_FixedPointCast;
  6450. case Type::STK_Bool:
  6451. return CK_FixedPointToBoolean;
  6452. case Type::STK_Integral:
  6453. return CK_FixedPointToIntegral;
  6454. case Type::STK_Floating:
  6455. return CK_FixedPointToFloating;
  6456. case Type::STK_IntegralComplex:
  6457. case Type::STK_FloatingComplex:
  6458. Diag(Src.get()->getExprLoc(),
  6459. diag::err_unimplemented_conversion_with_fixed_point_type)
  6460. << DestTy;
  6461. return CK_IntegralCast;
  6462. case Type::STK_CPointer:
  6463. case Type::STK_ObjCObjectPointer:
  6464. case Type::STK_BlockPointer:
  6465. case Type::STK_MemberPointer:
  6466. llvm_unreachable("illegal cast to pointer type");
  6467. }
  6468. llvm_unreachable("Should have returned before this");
  6469. case Type::STK_Bool: // casting from bool is like casting from an integer
  6470. case Type::STK_Integral:
  6471. switch (DestTy->getScalarTypeKind()) {
  6472. case Type::STK_CPointer:
  6473. case Type::STK_ObjCObjectPointer:
  6474. case Type::STK_BlockPointer:
  6475. if (Src.get()->isNullPointerConstant(Context,
  6476. Expr::NPC_ValueDependentIsNull))
  6477. return CK_NullToPointer;
  6478. return CK_IntegralToPointer;
  6479. case Type::STK_Bool:
  6480. return CK_IntegralToBoolean;
  6481. case Type::STK_Integral:
  6482. return CK_IntegralCast;
  6483. case Type::STK_Floating:
  6484. return CK_IntegralToFloating;
  6485. case Type::STK_IntegralComplex:
  6486. Src = ImpCastExprToType(Src.get(),
  6487. DestTy->castAs<ComplexType>()->getElementType(),
  6488. CK_IntegralCast);
  6489. return CK_IntegralRealToComplex;
  6490. case Type::STK_FloatingComplex:
  6491. Src = ImpCastExprToType(Src.get(),
  6492. DestTy->castAs<ComplexType>()->getElementType(),
  6493. CK_IntegralToFloating);
  6494. return CK_FloatingRealToComplex;
  6495. case Type::STK_MemberPointer:
  6496. llvm_unreachable("member pointer type in C");
  6497. case Type::STK_FixedPoint:
  6498. return CK_IntegralToFixedPoint;
  6499. }
  6500. llvm_unreachable("Should have returned before this");
  6501. case Type::STK_Floating:
  6502. switch (DestTy->getScalarTypeKind()) {
  6503. case Type::STK_Floating:
  6504. return CK_FloatingCast;
  6505. case Type::STK_Bool:
  6506. return CK_FloatingToBoolean;
  6507. case Type::STK_Integral:
  6508. return CK_FloatingToIntegral;
  6509. case Type::STK_FloatingComplex:
  6510. Src = ImpCastExprToType(Src.get(),
  6511. DestTy->castAs<ComplexType>()->getElementType(),
  6512. CK_FloatingCast);
  6513. return CK_FloatingRealToComplex;
  6514. case Type::STK_IntegralComplex:
  6515. Src = ImpCastExprToType(Src.get(),
  6516. DestTy->castAs<ComplexType>()->getElementType(),
  6517. CK_FloatingToIntegral);
  6518. return CK_IntegralRealToComplex;
  6519. case Type::STK_CPointer:
  6520. case Type::STK_ObjCObjectPointer:
  6521. case Type::STK_BlockPointer:
  6522. llvm_unreachable("valid float->pointer cast?");
  6523. case Type::STK_MemberPointer:
  6524. llvm_unreachable("member pointer type in C");
  6525. case Type::STK_FixedPoint:
  6526. return CK_FloatingToFixedPoint;
  6527. }
  6528. llvm_unreachable("Should have returned before this");
  6529. case Type::STK_FloatingComplex:
  6530. switch (DestTy->getScalarTypeKind()) {
  6531. case Type::STK_FloatingComplex:
  6532. return CK_FloatingComplexCast;
  6533. case Type::STK_IntegralComplex:
  6534. return CK_FloatingComplexToIntegralComplex;
  6535. case Type::STK_Floating: {
  6536. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  6537. if (Context.hasSameType(ET, DestTy))
  6538. return CK_FloatingComplexToReal;
  6539. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  6540. return CK_FloatingCast;
  6541. }
  6542. case Type::STK_Bool:
  6543. return CK_FloatingComplexToBoolean;
  6544. case Type::STK_Integral:
  6545. Src = ImpCastExprToType(Src.get(),
  6546. SrcTy->castAs<ComplexType>()->getElementType(),
  6547. CK_FloatingComplexToReal);
  6548. return CK_FloatingToIntegral;
  6549. case Type::STK_CPointer:
  6550. case Type::STK_ObjCObjectPointer:
  6551. case Type::STK_BlockPointer:
  6552. llvm_unreachable("valid complex float->pointer cast?");
  6553. case Type::STK_MemberPointer:
  6554. llvm_unreachable("member pointer type in C");
  6555. case Type::STK_FixedPoint:
  6556. Diag(Src.get()->getExprLoc(),
  6557. diag::err_unimplemented_conversion_with_fixed_point_type)
  6558. << SrcTy;
  6559. return CK_IntegralCast;
  6560. }
  6561. llvm_unreachable("Should have returned before this");
  6562. case Type::STK_IntegralComplex:
  6563. switch (DestTy->getScalarTypeKind()) {
  6564. case Type::STK_FloatingComplex:
  6565. return CK_IntegralComplexToFloatingComplex;
  6566. case Type::STK_IntegralComplex:
  6567. return CK_IntegralComplexCast;
  6568. case Type::STK_Integral: {
  6569. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  6570. if (Context.hasSameType(ET, DestTy))
  6571. return CK_IntegralComplexToReal;
  6572. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  6573. return CK_IntegralCast;
  6574. }
  6575. case Type::STK_Bool:
  6576. return CK_IntegralComplexToBoolean;
  6577. case Type::STK_Floating:
  6578. Src = ImpCastExprToType(Src.get(),
  6579. SrcTy->castAs<ComplexType>()->getElementType(),
  6580. CK_IntegralComplexToReal);
  6581. return CK_IntegralToFloating;
  6582. case Type::STK_CPointer:
  6583. case Type::STK_ObjCObjectPointer:
  6584. case Type::STK_BlockPointer:
  6585. llvm_unreachable("valid complex int->pointer cast?");
  6586. case Type::STK_MemberPointer:
  6587. llvm_unreachable("member pointer type in C");
  6588. case Type::STK_FixedPoint:
  6589. Diag(Src.get()->getExprLoc(),
  6590. diag::err_unimplemented_conversion_with_fixed_point_type)
  6591. << SrcTy;
  6592. return CK_IntegralCast;
  6593. }
  6594. llvm_unreachable("Should have returned before this");
  6595. }
  6596. llvm_unreachable("Unhandled scalar cast");
  6597. }
  6598. static bool breakDownVectorType(QualType type, uint64_t &len,
  6599. QualType &eltType) {
  6600. // Vectors are simple.
  6601. if (const VectorType *vecType = type->getAs<VectorType>()) {
  6602. len = vecType->getNumElements();
  6603. eltType = vecType->getElementType();
  6604. assert(eltType->isScalarType());
  6605. return true;
  6606. }
  6607. // We allow lax conversion to and from non-vector types, but only if
  6608. // they're real types (i.e. non-complex, non-pointer scalar types).
  6609. if (!type->isRealType()) return false;
  6610. len = 1;
  6611. eltType = type;
  6612. return true;
  6613. }
  6614. /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
  6615. /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
  6616. /// allowed?
  6617. ///
  6618. /// This will also return false if the two given types do not make sense from
  6619. /// the perspective of SVE bitcasts.
  6620. bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
  6621. assert(srcTy->isVectorType() || destTy->isVectorType());
  6622. auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
  6623. if (!FirstType->isSizelessBuiltinType())
  6624. return false;
  6625. const auto *VecTy = SecondType->getAs<VectorType>();
  6626. return VecTy &&
  6627. VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
  6628. };
  6629. return ValidScalableConversion(srcTy, destTy) ||
  6630. ValidScalableConversion(destTy, srcTy);
  6631. }
  6632. /// Are the two types matrix types and do they have the same dimensions i.e.
  6633. /// do they have the same number of rows and the same number of columns?
  6634. bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
  6635. if (!destTy->isMatrixType() || !srcTy->isMatrixType())
  6636. return false;
  6637. const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
  6638. const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
  6639. return matSrcType->getNumRows() == matDestType->getNumRows() &&
  6640. matSrcType->getNumColumns() == matDestType->getNumColumns();
  6641. }
  6642. bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
  6643. assert(DestTy->isVectorType() || SrcTy->isVectorType());
  6644. uint64_t SrcLen, DestLen;
  6645. QualType SrcEltTy, DestEltTy;
  6646. if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
  6647. return false;
  6648. if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
  6649. return false;
  6650. // ASTContext::getTypeSize will return the size rounded up to a
  6651. // power of 2, so instead of using that, we need to use the raw
  6652. // element size multiplied by the element count.
  6653. uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
  6654. uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
  6655. return (SrcLen * SrcEltSize == DestLen * DestEltSize);
  6656. }
  6657. /// Are the two types lax-compatible vector types? That is, given
  6658. /// that one of them is a vector, do they have equal storage sizes,
  6659. /// where the storage size is the number of elements times the element
  6660. /// size?
  6661. ///
  6662. /// This will also return false if either of the types is neither a
  6663. /// vector nor a real type.
  6664. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
  6665. assert(destTy->isVectorType() || srcTy->isVectorType());
  6666. // Disallow lax conversions between scalars and ExtVectors (these
  6667. // conversions are allowed for other vector types because common headers
  6668. // depend on them). Most scalar OP ExtVector cases are handled by the
  6669. // splat path anyway, which does what we want (convert, not bitcast).
  6670. // What this rules out for ExtVectors is crazy things like char4*float.
  6671. if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
  6672. if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
  6673. return areVectorTypesSameSize(srcTy, destTy);
  6674. }
  6675. /// Is this a legal conversion between two types, one of which is
  6676. /// known to be a vector type?
  6677. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  6678. assert(destTy->isVectorType() || srcTy->isVectorType());
  6679. switch (Context.getLangOpts().getLaxVectorConversions()) {
  6680. case LangOptions::LaxVectorConversionKind::None:
  6681. return false;
  6682. case LangOptions::LaxVectorConversionKind::Integer:
  6683. if (!srcTy->isIntegralOrEnumerationType()) {
  6684. auto *Vec = srcTy->getAs<VectorType>();
  6685. if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
  6686. return false;
  6687. }
  6688. if (!destTy->isIntegralOrEnumerationType()) {
  6689. auto *Vec = destTy->getAs<VectorType>();
  6690. if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
  6691. return false;
  6692. }
  6693. // OK, integer (vector) -> integer (vector) bitcast.
  6694. break;
  6695. case LangOptions::LaxVectorConversionKind::All:
  6696. break;
  6697. }
  6698. return areLaxCompatibleVectorTypes(srcTy, destTy);
  6699. }
  6700. bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
  6701. CastKind &Kind) {
  6702. if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
  6703. if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
  6704. return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
  6705. << DestTy << SrcTy << R;
  6706. }
  6707. } else if (SrcTy->isMatrixType()) {
  6708. return Diag(R.getBegin(),
  6709. diag::err_invalid_conversion_between_matrix_and_type)
  6710. << SrcTy << DestTy << R;
  6711. } else if (DestTy->isMatrixType()) {
  6712. return Diag(R.getBegin(),
  6713. diag::err_invalid_conversion_between_matrix_and_type)
  6714. << DestTy << SrcTy << R;
  6715. }
  6716. Kind = CK_MatrixCast;
  6717. return false;
  6718. }
  6719. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  6720. CastKind &Kind) {
  6721. assert(VectorTy->isVectorType() && "Not a vector type!");
  6722. if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
  6723. if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
  6724. return Diag(R.getBegin(),
  6725. Ty->isVectorType() ?
  6726. diag::err_invalid_conversion_between_vectors :
  6727. diag::err_invalid_conversion_between_vector_and_integer)
  6728. << VectorTy << Ty << R;
  6729. } else
  6730. return Diag(R.getBegin(),
  6731. diag::err_invalid_conversion_between_vector_and_scalar)
  6732. << VectorTy << Ty << R;
  6733. Kind = CK_BitCast;
  6734. return false;
  6735. }
  6736. ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
  6737. QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
  6738. if (DestElemTy == SplattedExpr->getType())
  6739. return SplattedExpr;
  6740. assert(DestElemTy->isFloatingType() ||
  6741. DestElemTy->isIntegralOrEnumerationType());
  6742. CastKind CK;
  6743. if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
  6744. // OpenCL requires that we convert `true` boolean expressions to -1, but
  6745. // only when splatting vectors.
  6746. if (DestElemTy->isFloatingType()) {
  6747. // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
  6748. // in two steps: boolean to signed integral, then to floating.
  6749. ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
  6750. CK_BooleanToSignedIntegral);
  6751. SplattedExpr = CastExprRes.get();
  6752. CK = CK_IntegralToFloating;
  6753. } else {
  6754. CK = CK_BooleanToSignedIntegral;
  6755. }
  6756. } else {
  6757. ExprResult CastExprRes = SplattedExpr;
  6758. CK = PrepareScalarCast(CastExprRes, DestElemTy);
  6759. if (CastExprRes.isInvalid())
  6760. return ExprError();
  6761. SplattedExpr = CastExprRes.get();
  6762. }
  6763. return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
  6764. }
  6765. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  6766. Expr *CastExpr, CastKind &Kind) {
  6767. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  6768. QualType SrcTy = CastExpr->getType();
  6769. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  6770. // an ExtVectorType.
  6771. // In OpenCL, casts between vectors of different types are not allowed.
  6772. // (See OpenCL 6.2).
  6773. if (SrcTy->isVectorType()) {
  6774. if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
  6775. (getLangOpts().OpenCL &&
  6776. !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
  6777. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  6778. << DestTy << SrcTy << R;
  6779. return ExprError();
  6780. }
  6781. Kind = CK_BitCast;
  6782. return CastExpr;
  6783. }
  6784. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  6785. // conversion will take place first from scalar to elt type, and then
  6786. // splat from elt type to vector.
  6787. if (SrcTy->isPointerType())
  6788. return Diag(R.getBegin(),
  6789. diag::err_invalid_conversion_between_vector_and_scalar)
  6790. << DestTy << SrcTy << R;
  6791. Kind = CK_VectorSplat;
  6792. return prepareVectorSplat(DestTy, CastExpr);
  6793. }
  6794. ExprResult
  6795. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  6796. Declarator &D, ParsedType &Ty,
  6797. SourceLocation RParenLoc, Expr *CastExpr) {
  6798. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  6799. "ActOnCastExpr(): missing type or expr");
  6800. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  6801. if (D.isInvalidType())
  6802. return ExprError();
  6803. if (getLangOpts().CPlusPlus) {
  6804. // Check that there are no default arguments (C++ only).
  6805. CheckExtraCXXDefaultArguments(D);
  6806. } else {
  6807. // Make sure any TypoExprs have been dealt with.
  6808. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  6809. if (!Res.isUsable())
  6810. return ExprError();
  6811. CastExpr = Res.get();
  6812. }
  6813. checkUnusedDeclAttributes(D);
  6814. QualType castType = castTInfo->getType();
  6815. Ty = CreateParsedType(castType, castTInfo);
  6816. bool isVectorLiteral = false;
  6817. // Check for an altivec or OpenCL literal,
  6818. // i.e. all the elements are integer constants.
  6819. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  6820. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  6821. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  6822. && castType->isVectorType() && (PE || PLE)) {
  6823. if (PLE && PLE->getNumExprs() == 0) {
  6824. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  6825. return ExprError();
  6826. }
  6827. if (PE || PLE->getNumExprs() == 1) {
  6828. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  6829. if (!E->isTypeDependent() && !E->getType()->isVectorType())
  6830. isVectorLiteral = true;
  6831. }
  6832. else
  6833. isVectorLiteral = true;
  6834. }
  6835. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  6836. // then handle it as such.
  6837. if (isVectorLiteral)
  6838. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  6839. // If the Expr being casted is a ParenListExpr, handle it specially.
  6840. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  6841. // sequence of BinOp comma operators.
  6842. if (isa<ParenListExpr>(CastExpr)) {
  6843. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  6844. if (Result.isInvalid()) return ExprError();
  6845. CastExpr = Result.get();
  6846. }
  6847. if (getLangOpts().CPlusPlus && !castType->isVoidType())
  6848. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  6849. CheckTollFreeBridgeCast(castType, CastExpr);
  6850. CheckObjCBridgeRelatedCast(castType, CastExpr);
  6851. DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
  6852. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  6853. }
  6854. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  6855. SourceLocation RParenLoc, Expr *E,
  6856. TypeSourceInfo *TInfo) {
  6857. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  6858. "Expected paren or paren list expression");
  6859. Expr **exprs;
  6860. unsigned numExprs;
  6861. Expr *subExpr;
  6862. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  6863. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  6864. LiteralLParenLoc = PE->getLParenLoc();
  6865. LiteralRParenLoc = PE->getRParenLoc();
  6866. exprs = PE->getExprs();
  6867. numExprs = PE->getNumExprs();
  6868. } else { // isa<ParenExpr> by assertion at function entrance
  6869. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  6870. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  6871. subExpr = cast<ParenExpr>(E)->getSubExpr();
  6872. exprs = &subExpr;
  6873. numExprs = 1;
  6874. }
  6875. QualType Ty = TInfo->getType();
  6876. assert(Ty->isVectorType() && "Expected vector type");
  6877. SmallVector<Expr *, 8> initExprs;
  6878. const VectorType *VTy = Ty->castAs<VectorType>();
  6879. unsigned numElems = VTy->getNumElements();
  6880. // '(...)' form of vector initialization in AltiVec: the number of
  6881. // initializers must be one or must match the size of the vector.
  6882. // If a single value is specified in the initializer then it will be
  6883. // replicated to all the components of the vector
  6884. if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
  6885. VTy->getElementType()))
  6886. return ExprError();
  6887. if (ShouldSplatAltivecScalarInCast(VTy)) {
  6888. // The number of initializers must be one or must match the size of the
  6889. // vector. If a single value is specified in the initializer then it will
  6890. // be replicated to all the components of the vector
  6891. if (numExprs == 1) {
  6892. QualType ElemTy = VTy->getElementType();
  6893. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  6894. if (Literal.isInvalid())
  6895. return ExprError();
  6896. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  6897. PrepareScalarCast(Literal, ElemTy));
  6898. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  6899. }
  6900. else if (numExprs < numElems) {
  6901. Diag(E->getExprLoc(),
  6902. diag::err_incorrect_number_of_vector_initializers);
  6903. return ExprError();
  6904. }
  6905. else
  6906. initExprs.append(exprs, exprs + numExprs);
  6907. }
  6908. else {
  6909. // For OpenCL, when the number of initializers is a single value,
  6910. // it will be replicated to all components of the vector.
  6911. if (getLangOpts().OpenCL &&
  6912. VTy->getVectorKind() == VectorType::GenericVector &&
  6913. numExprs == 1) {
  6914. QualType ElemTy = VTy->getElementType();
  6915. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  6916. if (Literal.isInvalid())
  6917. return ExprError();
  6918. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  6919. PrepareScalarCast(Literal, ElemTy));
  6920. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  6921. }
  6922. initExprs.append(exprs, exprs + numExprs);
  6923. }
  6924. // FIXME: This means that pretty-printing the final AST will produce curly
  6925. // braces instead of the original commas.
  6926. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  6927. initExprs, LiteralRParenLoc);
  6928. initE->setType(Ty);
  6929. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  6930. }
  6931. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  6932. /// the ParenListExpr into a sequence of comma binary operators.
  6933. ExprResult
  6934. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  6935. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  6936. if (!E)
  6937. return OrigExpr;
  6938. ExprResult Result(E->getExpr(0));
  6939. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  6940. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  6941. E->getExpr(i));
  6942. if (Result.isInvalid()) return ExprError();
  6943. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  6944. }
  6945. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  6946. SourceLocation R,
  6947. MultiExprArg Val) {
  6948. return ParenListExpr::Create(Context, L, Val, R);
  6949. }
  6950. /// Emit a specialized diagnostic when one expression is a null pointer
  6951. /// constant and the other is not a pointer. Returns true if a diagnostic is
  6952. /// emitted.
  6953. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  6954. SourceLocation QuestionLoc) {
  6955. Expr *NullExpr = LHSExpr;
  6956. Expr *NonPointerExpr = RHSExpr;
  6957. Expr::NullPointerConstantKind NullKind =
  6958. NullExpr->isNullPointerConstant(Context,
  6959. Expr::NPC_ValueDependentIsNotNull);
  6960. if (NullKind == Expr::NPCK_NotNull) {
  6961. NullExpr = RHSExpr;
  6962. NonPointerExpr = LHSExpr;
  6963. NullKind =
  6964. NullExpr->isNullPointerConstant(Context,
  6965. Expr::NPC_ValueDependentIsNotNull);
  6966. }
  6967. if (NullKind == Expr::NPCK_NotNull)
  6968. return false;
  6969. if (NullKind == Expr::NPCK_ZeroExpression)
  6970. return false;
  6971. if (NullKind == Expr::NPCK_ZeroLiteral) {
  6972. // In this case, check to make sure that we got here from a "NULL"
  6973. // string in the source code.
  6974. NullExpr = NullExpr->IgnoreParenImpCasts();
  6975. SourceLocation loc = NullExpr->getExprLoc();
  6976. if (!findMacroSpelling(loc, "NULL"))
  6977. return false;
  6978. }
  6979. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  6980. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  6981. << NonPointerExpr->getType() << DiagType
  6982. << NonPointerExpr->getSourceRange();
  6983. return true;
  6984. }
  6985. /// Return false if the condition expression is valid, true otherwise.
  6986. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  6987. QualType CondTy = Cond->getType();
  6988. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  6989. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  6990. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  6991. << CondTy << Cond->getSourceRange();
  6992. return true;
  6993. }
  6994. // C99 6.5.15p2
  6995. if (CondTy->isScalarType()) return false;
  6996. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  6997. << CondTy << Cond->getSourceRange();
  6998. return true;
  6999. }
  7000. /// Handle when one or both operands are void type.
  7001. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  7002. ExprResult &RHS) {
  7003. Expr *LHSExpr = LHS.get();
  7004. Expr *RHSExpr = RHS.get();
  7005. if (!LHSExpr->getType()->isVoidType())
  7006. S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  7007. << RHSExpr->getSourceRange();
  7008. if (!RHSExpr->getType()->isVoidType())
  7009. S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  7010. << LHSExpr->getSourceRange();
  7011. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  7012. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  7013. return S.Context.VoidTy;
  7014. }
  7015. /// Return false if the NullExpr can be promoted to PointerTy,
  7016. /// true otherwise.
  7017. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  7018. QualType PointerTy) {
  7019. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  7020. !NullExpr.get()->isNullPointerConstant(S.Context,
  7021. Expr::NPC_ValueDependentIsNull))
  7022. return true;
  7023. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  7024. return false;
  7025. }
  7026. /// Checks compatibility between two pointers and return the resulting
  7027. /// type.
  7028. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  7029. ExprResult &RHS,
  7030. SourceLocation Loc) {
  7031. QualType LHSTy = LHS.get()->getType();
  7032. QualType RHSTy = RHS.get()->getType();
  7033. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  7034. // Two identical pointers types are always compatible.
  7035. return LHSTy;
  7036. }
  7037. QualType lhptee, rhptee;
  7038. // Get the pointee types.
  7039. bool IsBlockPointer = false;
  7040. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  7041. lhptee = LHSBTy->getPointeeType();
  7042. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  7043. IsBlockPointer = true;
  7044. } else {
  7045. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  7046. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  7047. }
  7048. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  7049. // differently qualified versions of compatible types, the result type is
  7050. // a pointer to an appropriately qualified version of the composite
  7051. // type.
  7052. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  7053. // clause doesn't make sense for our extensions. E.g. address space 2 should
  7054. // be incompatible with address space 3: they may live on different devices or
  7055. // anything.
  7056. Qualifiers lhQual = lhptee.getQualifiers();
  7057. Qualifiers rhQual = rhptee.getQualifiers();
  7058. LangAS ResultAddrSpace = LangAS::Default;
  7059. LangAS LAddrSpace = lhQual.getAddressSpace();
  7060. LangAS RAddrSpace = rhQual.getAddressSpace();
  7061. // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
  7062. // spaces is disallowed.
  7063. if (lhQual.isAddressSpaceSupersetOf(rhQual))
  7064. ResultAddrSpace = LAddrSpace;
  7065. else if (rhQual.isAddressSpaceSupersetOf(lhQual))
  7066. ResultAddrSpace = RAddrSpace;
  7067. else {
  7068. S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  7069. << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
  7070. << RHS.get()->getSourceRange();
  7071. return QualType();
  7072. }
  7073. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  7074. auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
  7075. lhQual.removeCVRQualifiers();
  7076. rhQual.removeCVRQualifiers();
  7077. // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
  7078. // (C99 6.7.3) for address spaces. We assume that the check should behave in
  7079. // the same manner as it's defined for CVR qualifiers, so for OpenCL two
  7080. // qual types are compatible iff
  7081. // * corresponded types are compatible
  7082. // * CVR qualifiers are equal
  7083. // * address spaces are equal
  7084. // Thus for conditional operator we merge CVR and address space unqualified
  7085. // pointees and if there is a composite type we return a pointer to it with
  7086. // merged qualifiers.
  7087. LHSCastKind =
  7088. LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  7089. RHSCastKind =
  7090. RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  7091. lhQual.removeAddressSpace();
  7092. rhQual.removeAddressSpace();
  7093. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  7094. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  7095. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  7096. if (CompositeTy.isNull()) {
  7097. // In this situation, we assume void* type. No especially good
  7098. // reason, but this is what gcc does, and we do have to pick
  7099. // to get a consistent AST.
  7100. QualType incompatTy;
  7101. incompatTy = S.Context.getPointerType(
  7102. S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
  7103. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
  7104. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
  7105. // FIXME: For OpenCL the warning emission and cast to void* leaves a room
  7106. // for casts between types with incompatible address space qualifiers.
  7107. // For the following code the compiler produces casts between global and
  7108. // local address spaces of the corresponded innermost pointees:
  7109. // local int *global *a;
  7110. // global int *global *b;
  7111. // a = (0 ? a : b); // see C99 6.5.16.1.p1.
  7112. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  7113. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  7114. << RHS.get()->getSourceRange();
  7115. return incompatTy;
  7116. }
  7117. // The pointer types are compatible.
  7118. // In case of OpenCL ResultTy should have the address space qualifier
  7119. // which is a superset of address spaces of both the 2nd and the 3rd
  7120. // operands of the conditional operator.
  7121. QualType ResultTy = [&, ResultAddrSpace]() {
  7122. if (S.getLangOpts().OpenCL) {
  7123. Qualifiers CompositeQuals = CompositeTy.getQualifiers();
  7124. CompositeQuals.setAddressSpace(ResultAddrSpace);
  7125. return S.Context
  7126. .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
  7127. .withCVRQualifiers(MergedCVRQual);
  7128. }
  7129. return CompositeTy.withCVRQualifiers(MergedCVRQual);
  7130. }();
  7131. if (IsBlockPointer)
  7132. ResultTy = S.Context.getBlockPointerType(ResultTy);
  7133. else
  7134. ResultTy = S.Context.getPointerType(ResultTy);
  7135. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
  7136. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
  7137. return ResultTy;
  7138. }
  7139. /// Return the resulting type when the operands are both block pointers.
  7140. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  7141. ExprResult &LHS,
  7142. ExprResult &RHS,
  7143. SourceLocation Loc) {
  7144. QualType LHSTy = LHS.get()->getType();
  7145. QualType RHSTy = RHS.get()->getType();
  7146. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  7147. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  7148. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  7149. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  7150. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  7151. return destType;
  7152. }
  7153. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  7154. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  7155. << RHS.get()->getSourceRange();
  7156. return QualType();
  7157. }
  7158. // We have 2 block pointer types.
  7159. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  7160. }
  7161. /// Return the resulting type when the operands are both pointers.
  7162. static QualType
  7163. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  7164. ExprResult &RHS,
  7165. SourceLocation Loc) {
  7166. // get the pointer types
  7167. QualType LHSTy = LHS.get()->getType();
  7168. QualType RHSTy = RHS.get()->getType();
  7169. // get the "pointed to" types
  7170. QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  7171. QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  7172. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  7173. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  7174. // Figure out necessary qualifiers (C99 6.5.15p6)
  7175. QualType destPointee
  7176. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  7177. QualType destType = S.Context.getPointerType(destPointee);
  7178. // Add qualifiers if necessary.
  7179. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  7180. // Promote to void*.
  7181. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  7182. return destType;
  7183. }
  7184. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  7185. QualType destPointee
  7186. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  7187. QualType destType = S.Context.getPointerType(destPointee);
  7188. // Add qualifiers if necessary.
  7189. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  7190. // Promote to void*.
  7191. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  7192. return destType;
  7193. }
  7194. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  7195. }
  7196. /// Return false if the first expression is not an integer and the second
  7197. /// expression is not a pointer, true otherwise.
  7198. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  7199. Expr* PointerExpr, SourceLocation Loc,
  7200. bool IsIntFirstExpr) {
  7201. if (!PointerExpr->getType()->isPointerType() ||
  7202. !Int.get()->getType()->isIntegerType())
  7203. return false;
  7204. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  7205. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  7206. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  7207. << Expr1->getType() << Expr2->getType()
  7208. << Expr1->getSourceRange() << Expr2->getSourceRange();
  7209. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  7210. CK_IntegralToPointer);
  7211. return true;
  7212. }
  7213. /// Simple conversion between integer and floating point types.
  7214. ///
  7215. /// Used when handling the OpenCL conditional operator where the
  7216. /// condition is a vector while the other operands are scalar.
  7217. ///
  7218. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  7219. /// types are either integer or floating type. Between the two
  7220. /// operands, the type with the higher rank is defined as the "result
  7221. /// type". The other operand needs to be promoted to the same type. No
  7222. /// other type promotion is allowed. We cannot use
  7223. /// UsualArithmeticConversions() for this purpose, since it always
  7224. /// promotes promotable types.
  7225. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  7226. ExprResult &RHS,
  7227. SourceLocation QuestionLoc) {
  7228. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  7229. if (LHS.isInvalid())
  7230. return QualType();
  7231. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  7232. if (RHS.isInvalid())
  7233. return QualType();
  7234. // For conversion purposes, we ignore any qualifiers.
  7235. // For example, "const float" and "float" are equivalent.
  7236. QualType LHSType =
  7237. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  7238. QualType RHSType =
  7239. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  7240. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  7241. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  7242. << LHSType << LHS.get()->getSourceRange();
  7243. return QualType();
  7244. }
  7245. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  7246. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  7247. << RHSType << RHS.get()->getSourceRange();
  7248. return QualType();
  7249. }
  7250. // If both types are identical, no conversion is needed.
  7251. if (LHSType == RHSType)
  7252. return LHSType;
  7253. // Now handle "real" floating types (i.e. float, double, long double).
  7254. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  7255. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  7256. /*IsCompAssign = */ false);
  7257. // Finally, we have two differing integer types.
  7258. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  7259. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  7260. }
  7261. /// Convert scalar operands to a vector that matches the
  7262. /// condition in length.
  7263. ///
  7264. /// Used when handling the OpenCL conditional operator where the
  7265. /// condition is a vector while the other operands are scalar.
  7266. ///
  7267. /// We first compute the "result type" for the scalar operands
  7268. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  7269. /// into a vector of that type where the length matches the condition
  7270. /// vector type. s6.11.6 requires that the element types of the result
  7271. /// and the condition must have the same number of bits.
  7272. static QualType
  7273. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  7274. QualType CondTy, SourceLocation QuestionLoc) {
  7275. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  7276. if (ResTy.isNull()) return QualType();
  7277. const VectorType *CV = CondTy->getAs<VectorType>();
  7278. assert(CV);
  7279. // Determine the vector result type
  7280. unsigned NumElements = CV->getNumElements();
  7281. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  7282. // Ensure that all types have the same number of bits
  7283. if (S.Context.getTypeSize(CV->getElementType())
  7284. != S.Context.getTypeSize(ResTy)) {
  7285. // Since VectorTy is created internally, it does not pretty print
  7286. // with an OpenCL name. Instead, we just print a description.
  7287. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  7288. SmallString<64> Str;
  7289. llvm::raw_svector_ostream OS(Str);
  7290. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  7291. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  7292. << CondTy << OS.str();
  7293. return QualType();
  7294. }
  7295. // Convert operands to the vector result type
  7296. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  7297. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  7298. return VectorTy;
  7299. }
  7300. /// Return false if this is a valid OpenCL condition vector
  7301. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  7302. SourceLocation QuestionLoc) {
  7303. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  7304. // integral type.
  7305. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  7306. assert(CondTy);
  7307. QualType EleTy = CondTy->getElementType();
  7308. if (EleTy->isIntegerType()) return false;
  7309. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  7310. << Cond->getType() << Cond->getSourceRange();
  7311. return true;
  7312. }
  7313. /// Return false if the vector condition type and the vector
  7314. /// result type are compatible.
  7315. ///
  7316. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  7317. /// number of elements, and their element types have the same number
  7318. /// of bits.
  7319. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  7320. SourceLocation QuestionLoc) {
  7321. const VectorType *CV = CondTy->getAs<VectorType>();
  7322. const VectorType *RV = VecResTy->getAs<VectorType>();
  7323. assert(CV && RV);
  7324. if (CV->getNumElements() != RV->getNumElements()) {
  7325. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  7326. << CondTy << VecResTy;
  7327. return true;
  7328. }
  7329. QualType CVE = CV->getElementType();
  7330. QualType RVE = RV->getElementType();
  7331. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  7332. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  7333. << CondTy << VecResTy;
  7334. return true;
  7335. }
  7336. return false;
  7337. }
  7338. /// Return the resulting type for the conditional operator in
  7339. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  7340. /// s6.3.i) when the condition is a vector type.
  7341. static QualType
  7342. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  7343. ExprResult &LHS, ExprResult &RHS,
  7344. SourceLocation QuestionLoc) {
  7345. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  7346. if (Cond.isInvalid())
  7347. return QualType();
  7348. QualType CondTy = Cond.get()->getType();
  7349. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  7350. return QualType();
  7351. // If either operand is a vector then find the vector type of the
  7352. // result as specified in OpenCL v1.1 s6.3.i.
  7353. if (LHS.get()->getType()->isVectorType() ||
  7354. RHS.get()->getType()->isVectorType()) {
  7355. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  7356. /*isCompAssign*/false,
  7357. /*AllowBothBool*/true,
  7358. /*AllowBoolConversions*/false);
  7359. if (VecResTy.isNull()) return QualType();
  7360. // The result type must match the condition type as specified in
  7361. // OpenCL v1.1 s6.11.6.
  7362. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  7363. return QualType();
  7364. return VecResTy;
  7365. }
  7366. // Both operands are scalar.
  7367. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  7368. }
  7369. /// Return true if the Expr is block type
  7370. static bool checkBlockType(Sema &S, const Expr *E) {
  7371. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  7372. QualType Ty = CE->getCallee()->getType();
  7373. if (Ty->isBlockPointerType()) {
  7374. S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
  7375. return true;
  7376. }
  7377. }
  7378. return false;
  7379. }
  7380. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  7381. /// In that case, LHS = cond.
  7382. /// C99 6.5.15
  7383. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  7384. ExprResult &RHS, ExprValueKind &VK,
  7385. ExprObjectKind &OK,
  7386. SourceLocation QuestionLoc) {
  7387. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  7388. if (!LHSResult.isUsable()) return QualType();
  7389. LHS = LHSResult;
  7390. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  7391. if (!RHSResult.isUsable()) return QualType();
  7392. RHS = RHSResult;
  7393. // C++ is sufficiently different to merit its own checker.
  7394. if (getLangOpts().CPlusPlus)
  7395. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  7396. VK = VK_PRValue;
  7397. OK = OK_Ordinary;
  7398. if (Context.isDependenceAllowed() &&
  7399. (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
  7400. RHS.get()->isTypeDependent())) {
  7401. assert(!getLangOpts().CPlusPlus);
  7402. assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
  7403. RHS.get()->containsErrors()) &&
  7404. "should only occur in error-recovery path.");
  7405. return Context.DependentTy;
  7406. }
  7407. // The OpenCL operator with a vector condition is sufficiently
  7408. // different to merit its own checker.
  7409. if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
  7410. Cond.get()->getType()->isExtVectorType())
  7411. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  7412. // First, check the condition.
  7413. Cond = UsualUnaryConversions(Cond.get());
  7414. if (Cond.isInvalid())
  7415. return QualType();
  7416. if (checkCondition(*this, Cond.get(), QuestionLoc))
  7417. return QualType();
  7418. // Now check the two expressions.
  7419. if (LHS.get()->getType()->isVectorType() ||
  7420. RHS.get()->getType()->isVectorType())
  7421. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  7422. /*AllowBothBool*/true,
  7423. /*AllowBoolConversions*/false);
  7424. QualType ResTy =
  7425. UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
  7426. if (LHS.isInvalid() || RHS.isInvalid())
  7427. return QualType();
  7428. QualType LHSTy = LHS.get()->getType();
  7429. QualType RHSTy = RHS.get()->getType();
  7430. // Diagnose attempts to convert between __ibm128, __float128 and long double
  7431. // where such conversions currently can't be handled.
  7432. if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
  7433. Diag(QuestionLoc,
  7434. diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
  7435. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7436. return QualType();
  7437. }
  7438. // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
  7439. // selection operator (?:).
  7440. if (getLangOpts().OpenCL &&
  7441. ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
  7442. return QualType();
  7443. }
  7444. // If both operands have arithmetic type, do the usual arithmetic conversions
  7445. // to find a common type: C99 6.5.15p3,5.
  7446. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  7447. // Disallow invalid arithmetic conversions, such as those between bit-
  7448. // precise integers types of different sizes, or between a bit-precise
  7449. // integer and another type.
  7450. if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
  7451. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  7452. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  7453. << RHS.get()->getSourceRange();
  7454. return QualType();
  7455. }
  7456. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  7457. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  7458. return ResTy;
  7459. }
  7460. // And if they're both bfloat (which isn't arithmetic), that's fine too.
  7461. if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
  7462. return LHSTy;
  7463. }
  7464. // If both operands are the same structure or union type, the result is that
  7465. // type.
  7466. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  7467. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  7468. if (LHSRT->getDecl() == RHSRT->getDecl())
  7469. // "If both the operands have structure or union type, the result has
  7470. // that type." This implies that CV qualifiers are dropped.
  7471. return LHSTy.getUnqualifiedType();
  7472. // FIXME: Type of conditional expression must be complete in C mode.
  7473. }
  7474. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  7475. // The following || allows only one side to be void (a GCC-ism).
  7476. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  7477. return checkConditionalVoidType(*this, LHS, RHS);
  7478. }
  7479. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  7480. // the type of the other operand."
  7481. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  7482. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  7483. // All objective-c pointer type analysis is done here.
  7484. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  7485. QuestionLoc);
  7486. if (LHS.isInvalid() || RHS.isInvalid())
  7487. return QualType();
  7488. if (!compositeType.isNull())
  7489. return compositeType;
  7490. // Handle block pointer types.
  7491. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  7492. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  7493. QuestionLoc);
  7494. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  7495. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  7496. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  7497. QuestionLoc);
  7498. // GCC compatibility: soften pointer/integer mismatch. Note that
  7499. // null pointers have been filtered out by this point.
  7500. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  7501. /*IsIntFirstExpr=*/true))
  7502. return RHSTy;
  7503. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  7504. /*IsIntFirstExpr=*/false))
  7505. return LHSTy;
  7506. // Allow ?: operations in which both operands have the same
  7507. // built-in sizeless type.
  7508. if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
  7509. return LHSTy;
  7510. // Emit a better diagnostic if one of the expressions is a null pointer
  7511. // constant and the other is not a pointer type. In this case, the user most
  7512. // likely forgot to take the address of the other expression.
  7513. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  7514. return QualType();
  7515. // Otherwise, the operands are not compatible.
  7516. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  7517. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  7518. << RHS.get()->getSourceRange();
  7519. return QualType();
  7520. }
  7521. /// FindCompositeObjCPointerType - Helper method to find composite type of
  7522. /// two objective-c pointer types of the two input expressions.
  7523. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  7524. SourceLocation QuestionLoc) {
  7525. QualType LHSTy = LHS.get()->getType();
  7526. QualType RHSTy = RHS.get()->getType();
  7527. // Handle things like Class and struct objc_class*. Here we case the result
  7528. // to the pseudo-builtin, because that will be implicitly cast back to the
  7529. // redefinition type if an attempt is made to access its fields.
  7530. if (LHSTy->isObjCClassType() &&
  7531. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  7532. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  7533. return LHSTy;
  7534. }
  7535. if (RHSTy->isObjCClassType() &&
  7536. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  7537. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  7538. return RHSTy;
  7539. }
  7540. // And the same for struct objc_object* / id
  7541. if (LHSTy->isObjCIdType() &&
  7542. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  7543. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  7544. return LHSTy;
  7545. }
  7546. if (RHSTy->isObjCIdType() &&
  7547. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  7548. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  7549. return RHSTy;
  7550. }
  7551. // And the same for struct objc_selector* / SEL
  7552. if (Context.isObjCSelType(LHSTy) &&
  7553. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  7554. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  7555. return LHSTy;
  7556. }
  7557. if (Context.isObjCSelType(RHSTy) &&
  7558. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  7559. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  7560. return RHSTy;
  7561. }
  7562. // Check constraints for Objective-C object pointers types.
  7563. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  7564. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  7565. // Two identical object pointer types are always compatible.
  7566. return LHSTy;
  7567. }
  7568. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  7569. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  7570. QualType compositeType = LHSTy;
  7571. // If both operands are interfaces and either operand can be
  7572. // assigned to the other, use that type as the composite
  7573. // type. This allows
  7574. // xxx ? (A*) a : (B*) b
  7575. // where B is a subclass of A.
  7576. //
  7577. // Additionally, as for assignment, if either type is 'id'
  7578. // allow silent coercion. Finally, if the types are
  7579. // incompatible then make sure to use 'id' as the composite
  7580. // type so the result is acceptable for sending messages to.
  7581. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  7582. // It could return the composite type.
  7583. if (!(compositeType =
  7584. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  7585. // Nothing more to do.
  7586. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  7587. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  7588. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  7589. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  7590. } else if ((LHSOPT->isObjCQualifiedIdType() ||
  7591. RHSOPT->isObjCQualifiedIdType()) &&
  7592. Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
  7593. true)) {
  7594. // Need to handle "id<xx>" explicitly.
  7595. // GCC allows qualified id and any Objective-C type to devolve to
  7596. // id. Currently localizing to here until clear this should be
  7597. // part of ObjCQualifiedIdTypesAreCompatible.
  7598. compositeType = Context.getObjCIdType();
  7599. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  7600. compositeType = Context.getObjCIdType();
  7601. } else {
  7602. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  7603. << LHSTy << RHSTy
  7604. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7605. QualType incompatTy = Context.getObjCIdType();
  7606. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  7607. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  7608. return incompatTy;
  7609. }
  7610. // The object pointer types are compatible.
  7611. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  7612. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  7613. return compositeType;
  7614. }
  7615. // Check Objective-C object pointer types and 'void *'
  7616. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  7617. if (getLangOpts().ObjCAutoRefCount) {
  7618. // ARC forbids the implicit conversion of object pointers to 'void *',
  7619. // so these types are not compatible.
  7620. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  7621. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7622. LHS = RHS = true;
  7623. return QualType();
  7624. }
  7625. QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  7626. QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
  7627. QualType destPointee
  7628. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  7629. QualType destType = Context.getPointerType(destPointee);
  7630. // Add qualifiers if necessary.
  7631. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  7632. // Promote to void*.
  7633. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  7634. return destType;
  7635. }
  7636. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  7637. if (getLangOpts().ObjCAutoRefCount) {
  7638. // ARC forbids the implicit conversion of object pointers to 'void *',
  7639. // so these types are not compatible.
  7640. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  7641. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7642. LHS = RHS = true;
  7643. return QualType();
  7644. }
  7645. QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
  7646. QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  7647. QualType destPointee
  7648. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  7649. QualType destType = Context.getPointerType(destPointee);
  7650. // Add qualifiers if necessary.
  7651. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  7652. // Promote to void*.
  7653. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  7654. return destType;
  7655. }
  7656. return QualType();
  7657. }
  7658. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  7659. /// ParenRange in parentheses.
  7660. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  7661. const PartialDiagnostic &Note,
  7662. SourceRange ParenRange) {
  7663. SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
  7664. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  7665. EndLoc.isValid()) {
  7666. Self.Diag(Loc, Note)
  7667. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  7668. << FixItHint::CreateInsertion(EndLoc, ")");
  7669. } else {
  7670. // We can't display the parentheses, so just show the bare note.
  7671. Self.Diag(Loc, Note) << ParenRange;
  7672. }
  7673. }
  7674. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  7675. return BinaryOperator::isAdditiveOp(Opc) ||
  7676. BinaryOperator::isMultiplicativeOp(Opc) ||
  7677. BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
  7678. // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
  7679. // not any of the logical operators. Bitwise-xor is commonly used as a
  7680. // logical-xor because there is no logical-xor operator. The logical
  7681. // operators, including uses of xor, have a high false positive rate for
  7682. // precedence warnings.
  7683. }
  7684. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  7685. /// expression, either using a built-in or overloaded operator,
  7686. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  7687. /// expression.
  7688. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  7689. Expr **RHSExprs) {
  7690. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  7691. E = E->IgnoreImpCasts();
  7692. E = E->IgnoreConversionOperatorSingleStep();
  7693. E = E->IgnoreImpCasts();
  7694. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
  7695. E = MTE->getSubExpr();
  7696. E = E->IgnoreImpCasts();
  7697. }
  7698. // Built-in binary operator.
  7699. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  7700. if (IsArithmeticOp(OP->getOpcode())) {
  7701. *Opcode = OP->getOpcode();
  7702. *RHSExprs = OP->getRHS();
  7703. return true;
  7704. }
  7705. }
  7706. // Overloaded operator.
  7707. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  7708. if (Call->getNumArgs() != 2)
  7709. return false;
  7710. // Make sure this is really a binary operator that is safe to pass into
  7711. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  7712. OverloadedOperatorKind OO = Call->getOperator();
  7713. if (OO < OO_Plus || OO > OO_Arrow ||
  7714. OO == OO_PlusPlus || OO == OO_MinusMinus)
  7715. return false;
  7716. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  7717. if (IsArithmeticOp(OpKind)) {
  7718. *Opcode = OpKind;
  7719. *RHSExprs = Call->getArg(1);
  7720. return true;
  7721. }
  7722. }
  7723. return false;
  7724. }
  7725. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  7726. /// or is a logical expression such as (x==y) which has int type, but is
  7727. /// commonly interpreted as boolean.
  7728. static bool ExprLooksBoolean(Expr *E) {
  7729. E = E->IgnoreParenImpCasts();
  7730. if (E->getType()->isBooleanType())
  7731. return true;
  7732. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  7733. return OP->isComparisonOp() || OP->isLogicalOp();
  7734. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  7735. return OP->getOpcode() == UO_LNot;
  7736. if (E->getType()->isPointerType())
  7737. return true;
  7738. // FIXME: What about overloaded operator calls returning "unspecified boolean
  7739. // type"s (commonly pointer-to-members)?
  7740. return false;
  7741. }
  7742. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  7743. /// and binary operator are mixed in a way that suggests the programmer assumed
  7744. /// the conditional operator has higher precedence, for example:
  7745. /// "int x = a + someBinaryCondition ? 1 : 2".
  7746. static void DiagnoseConditionalPrecedence(Sema &Self,
  7747. SourceLocation OpLoc,
  7748. Expr *Condition,
  7749. Expr *LHSExpr,
  7750. Expr *RHSExpr) {
  7751. BinaryOperatorKind CondOpcode;
  7752. Expr *CondRHS;
  7753. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  7754. return;
  7755. if (!ExprLooksBoolean(CondRHS))
  7756. return;
  7757. // The condition is an arithmetic binary expression, with a right-
  7758. // hand side that looks boolean, so warn.
  7759. unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
  7760. ? diag::warn_precedence_bitwise_conditional
  7761. : diag::warn_precedence_conditional;
  7762. Self.Diag(OpLoc, DiagID)
  7763. << Condition->getSourceRange()
  7764. << BinaryOperator::getOpcodeStr(CondOpcode);
  7765. SuggestParentheses(
  7766. Self, OpLoc,
  7767. Self.PDiag(diag::note_precedence_silence)
  7768. << BinaryOperator::getOpcodeStr(CondOpcode),
  7769. SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
  7770. SuggestParentheses(Self, OpLoc,
  7771. Self.PDiag(diag::note_precedence_conditional_first),
  7772. SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
  7773. }
  7774. /// Compute the nullability of a conditional expression.
  7775. static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
  7776. QualType LHSTy, QualType RHSTy,
  7777. ASTContext &Ctx) {
  7778. if (!ResTy->isAnyPointerType())
  7779. return ResTy;
  7780. auto GetNullability = [&Ctx](QualType Ty) {
  7781. Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
  7782. if (Kind) {
  7783. // For our purposes, treat _Nullable_result as _Nullable.
  7784. if (*Kind == NullabilityKind::NullableResult)
  7785. return NullabilityKind::Nullable;
  7786. return *Kind;
  7787. }
  7788. return NullabilityKind::Unspecified;
  7789. };
  7790. auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
  7791. NullabilityKind MergedKind;
  7792. // Compute nullability of a binary conditional expression.
  7793. if (IsBin) {
  7794. if (LHSKind == NullabilityKind::NonNull)
  7795. MergedKind = NullabilityKind::NonNull;
  7796. else
  7797. MergedKind = RHSKind;
  7798. // Compute nullability of a normal conditional expression.
  7799. } else {
  7800. if (LHSKind == NullabilityKind::Nullable ||
  7801. RHSKind == NullabilityKind::Nullable)
  7802. MergedKind = NullabilityKind::Nullable;
  7803. else if (LHSKind == NullabilityKind::NonNull)
  7804. MergedKind = RHSKind;
  7805. else if (RHSKind == NullabilityKind::NonNull)
  7806. MergedKind = LHSKind;
  7807. else
  7808. MergedKind = NullabilityKind::Unspecified;
  7809. }
  7810. // Return if ResTy already has the correct nullability.
  7811. if (GetNullability(ResTy) == MergedKind)
  7812. return ResTy;
  7813. // Strip all nullability from ResTy.
  7814. while (ResTy->getNullability(Ctx))
  7815. ResTy = ResTy.getSingleStepDesugaredType(Ctx);
  7816. // Create a new AttributedType with the new nullability kind.
  7817. auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
  7818. return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
  7819. }
  7820. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  7821. /// in the case of a the GNU conditional expr extension.
  7822. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  7823. SourceLocation ColonLoc,
  7824. Expr *CondExpr, Expr *LHSExpr,
  7825. Expr *RHSExpr) {
  7826. if (!Context.isDependenceAllowed()) {
  7827. // C cannot handle TypoExpr nodes in the condition because it
  7828. // doesn't handle dependent types properly, so make sure any TypoExprs have
  7829. // been dealt with before checking the operands.
  7830. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  7831. ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
  7832. ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
  7833. if (!CondResult.isUsable())
  7834. return ExprError();
  7835. if (LHSExpr) {
  7836. if (!LHSResult.isUsable())
  7837. return ExprError();
  7838. }
  7839. if (!RHSResult.isUsable())
  7840. return ExprError();
  7841. CondExpr = CondResult.get();
  7842. LHSExpr = LHSResult.get();
  7843. RHSExpr = RHSResult.get();
  7844. }
  7845. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  7846. // was the condition.
  7847. OpaqueValueExpr *opaqueValue = nullptr;
  7848. Expr *commonExpr = nullptr;
  7849. if (!LHSExpr) {
  7850. commonExpr = CondExpr;
  7851. // Lower out placeholder types first. This is important so that we don't
  7852. // try to capture a placeholder. This happens in few cases in C++; such
  7853. // as Objective-C++'s dictionary subscripting syntax.
  7854. if (commonExpr->hasPlaceholderType()) {
  7855. ExprResult result = CheckPlaceholderExpr(commonExpr);
  7856. if (!result.isUsable()) return ExprError();
  7857. commonExpr = result.get();
  7858. }
  7859. // We usually want to apply unary conversions *before* saving, except
  7860. // in the special case of a C++ l-value conditional.
  7861. if (!(getLangOpts().CPlusPlus
  7862. && !commonExpr->isTypeDependent()
  7863. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  7864. && commonExpr->isGLValue()
  7865. && commonExpr->isOrdinaryOrBitFieldObject()
  7866. && RHSExpr->isOrdinaryOrBitFieldObject()
  7867. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  7868. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  7869. if (commonRes.isInvalid())
  7870. return ExprError();
  7871. commonExpr = commonRes.get();
  7872. }
  7873. // If the common expression is a class or array prvalue, materialize it
  7874. // so that we can safely refer to it multiple times.
  7875. if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
  7876. commonExpr->getType()->isArrayType())) {
  7877. ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
  7878. if (MatExpr.isInvalid())
  7879. return ExprError();
  7880. commonExpr = MatExpr.get();
  7881. }
  7882. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  7883. commonExpr->getType(),
  7884. commonExpr->getValueKind(),
  7885. commonExpr->getObjectKind(),
  7886. commonExpr);
  7887. LHSExpr = CondExpr = opaqueValue;
  7888. }
  7889. QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
  7890. ExprValueKind VK = VK_PRValue;
  7891. ExprObjectKind OK = OK_Ordinary;
  7892. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  7893. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  7894. VK, OK, QuestionLoc);
  7895. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  7896. RHS.isInvalid())
  7897. return ExprError();
  7898. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  7899. RHS.get());
  7900. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  7901. result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
  7902. Context);
  7903. if (!commonExpr)
  7904. return new (Context)
  7905. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  7906. RHS.get(), result, VK, OK);
  7907. return new (Context) BinaryConditionalOperator(
  7908. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  7909. ColonLoc, result, VK, OK);
  7910. }
  7911. // Check if we have a conversion between incompatible cmse function pointer
  7912. // types, that is, a conversion between a function pointer with the
  7913. // cmse_nonsecure_call attribute and one without.
  7914. static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
  7915. QualType ToType) {
  7916. if (const auto *ToFn =
  7917. dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
  7918. if (const auto *FromFn =
  7919. dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
  7920. FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
  7921. FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
  7922. return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
  7923. }
  7924. }
  7925. return false;
  7926. }
  7927. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  7928. // being closely modeled after the C99 spec:-). The odd characteristic of this
  7929. // routine is it effectively iqnores the qualifiers on the top level pointee.
  7930. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  7931. // FIXME: add a couple examples in this comment.
  7932. static Sema::AssignConvertType
  7933. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  7934. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  7935. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  7936. // get the "pointed to" type (ignoring qualifiers at the top level)
  7937. const Type *lhptee, *rhptee;
  7938. Qualifiers lhq, rhq;
  7939. std::tie(lhptee, lhq) =
  7940. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  7941. std::tie(rhptee, rhq) =
  7942. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  7943. Sema::AssignConvertType ConvTy = Sema::Compatible;
  7944. // C99 6.5.16.1p1: This following citation is common to constraints
  7945. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  7946. // qualifiers of the type *pointed to* by the right;
  7947. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  7948. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  7949. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  7950. // Ignore lifetime for further calculation.
  7951. lhq.removeObjCLifetime();
  7952. rhq.removeObjCLifetime();
  7953. }
  7954. if (!lhq.compatiblyIncludes(rhq)) {
  7955. // Treat address-space mismatches as fatal.
  7956. if (!lhq.isAddressSpaceSupersetOf(rhq))
  7957. return Sema::IncompatiblePointerDiscardsQualifiers;
  7958. // It's okay to add or remove GC or lifetime qualifiers when converting to
  7959. // and from void*.
  7960. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  7961. .compatiblyIncludes(
  7962. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  7963. && (lhptee->isVoidType() || rhptee->isVoidType()))
  7964. ; // keep old
  7965. // Treat lifetime mismatches as fatal.
  7966. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  7967. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  7968. // For GCC/MS compatibility, other qualifier mismatches are treated
  7969. // as still compatible in C.
  7970. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  7971. }
  7972. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  7973. // incomplete type and the other is a pointer to a qualified or unqualified
  7974. // version of void...
  7975. if (lhptee->isVoidType()) {
  7976. if (rhptee->isIncompleteOrObjectType())
  7977. return ConvTy;
  7978. // As an extension, we allow cast to/from void* to function pointer.
  7979. assert(rhptee->isFunctionType());
  7980. return Sema::FunctionVoidPointer;
  7981. }
  7982. if (rhptee->isVoidType()) {
  7983. if (lhptee->isIncompleteOrObjectType())
  7984. return ConvTy;
  7985. // As an extension, we allow cast to/from void* to function pointer.
  7986. assert(lhptee->isFunctionType());
  7987. return Sema::FunctionVoidPointer;
  7988. }
  7989. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  7990. // unqualified versions of compatible types, ...
  7991. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  7992. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  7993. // Check if the pointee types are compatible ignoring the sign.
  7994. // We explicitly check for char so that we catch "char" vs
  7995. // "unsigned char" on systems where "char" is unsigned.
  7996. if (lhptee->isCharType())
  7997. ltrans = S.Context.UnsignedCharTy;
  7998. else if (lhptee->hasSignedIntegerRepresentation())
  7999. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  8000. if (rhptee->isCharType())
  8001. rtrans = S.Context.UnsignedCharTy;
  8002. else if (rhptee->hasSignedIntegerRepresentation())
  8003. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  8004. if (ltrans == rtrans) {
  8005. // Types are compatible ignoring the sign. Qualifier incompatibility
  8006. // takes priority over sign incompatibility because the sign
  8007. // warning can be disabled.
  8008. if (ConvTy != Sema::Compatible)
  8009. return ConvTy;
  8010. return Sema::IncompatiblePointerSign;
  8011. }
  8012. // If we are a multi-level pointer, it's possible that our issue is simply
  8013. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  8014. // the eventual target type is the same and the pointers have the same
  8015. // level of indirection, this must be the issue.
  8016. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  8017. do {
  8018. std::tie(lhptee, lhq) =
  8019. cast<PointerType>(lhptee)->getPointeeType().split().asPair();
  8020. std::tie(rhptee, rhq) =
  8021. cast<PointerType>(rhptee)->getPointeeType().split().asPair();
  8022. // Inconsistent address spaces at this point is invalid, even if the
  8023. // address spaces would be compatible.
  8024. // FIXME: This doesn't catch address space mismatches for pointers of
  8025. // different nesting levels, like:
  8026. // __local int *** a;
  8027. // int ** b = a;
  8028. // It's not clear how to actually determine when such pointers are
  8029. // invalidly incompatible.
  8030. if (lhq.getAddressSpace() != rhq.getAddressSpace())
  8031. return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
  8032. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  8033. if (lhptee == rhptee)
  8034. return Sema::IncompatibleNestedPointerQualifiers;
  8035. }
  8036. // General pointer incompatibility takes priority over qualifiers.
  8037. if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
  8038. return Sema::IncompatibleFunctionPointer;
  8039. return Sema::IncompatiblePointer;
  8040. }
  8041. if (!S.getLangOpts().CPlusPlus &&
  8042. S.IsFunctionConversion(ltrans, rtrans, ltrans))
  8043. return Sema::IncompatibleFunctionPointer;
  8044. if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
  8045. return Sema::IncompatibleFunctionPointer;
  8046. return ConvTy;
  8047. }
  8048. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  8049. /// block pointer types are compatible or whether a block and normal pointer
  8050. /// are compatible. It is more restrict than comparing two function pointer
  8051. // types.
  8052. static Sema::AssignConvertType
  8053. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  8054. QualType RHSType) {
  8055. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  8056. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  8057. QualType lhptee, rhptee;
  8058. // get the "pointed to" type (ignoring qualifiers at the top level)
  8059. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  8060. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  8061. // In C++, the types have to match exactly.
  8062. if (S.getLangOpts().CPlusPlus)
  8063. return Sema::IncompatibleBlockPointer;
  8064. Sema::AssignConvertType ConvTy = Sema::Compatible;
  8065. // For blocks we enforce that qualifiers are identical.
  8066. Qualifiers LQuals = lhptee.getLocalQualifiers();
  8067. Qualifiers RQuals = rhptee.getLocalQualifiers();
  8068. if (S.getLangOpts().OpenCL) {
  8069. LQuals.removeAddressSpace();
  8070. RQuals.removeAddressSpace();
  8071. }
  8072. if (LQuals != RQuals)
  8073. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  8074. // FIXME: OpenCL doesn't define the exact compile time semantics for a block
  8075. // assignment.
  8076. // The current behavior is similar to C++ lambdas. A block might be
  8077. // assigned to a variable iff its return type and parameters are compatible
  8078. // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
  8079. // an assignment. Presumably it should behave in way that a function pointer
  8080. // assignment does in C, so for each parameter and return type:
  8081. // * CVR and address space of LHS should be a superset of CVR and address
  8082. // space of RHS.
  8083. // * unqualified types should be compatible.
  8084. if (S.getLangOpts().OpenCL) {
  8085. if (!S.Context.typesAreBlockPointerCompatible(
  8086. S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
  8087. S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
  8088. return Sema::IncompatibleBlockPointer;
  8089. } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  8090. return Sema::IncompatibleBlockPointer;
  8091. return ConvTy;
  8092. }
  8093. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  8094. /// for assignment compatibility.
  8095. static Sema::AssignConvertType
  8096. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  8097. QualType RHSType) {
  8098. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  8099. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  8100. if (LHSType->isObjCBuiltinType()) {
  8101. // Class is not compatible with ObjC object pointers.
  8102. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  8103. !RHSType->isObjCQualifiedClassType())
  8104. return Sema::IncompatiblePointer;
  8105. return Sema::Compatible;
  8106. }
  8107. if (RHSType->isObjCBuiltinType()) {
  8108. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  8109. !LHSType->isObjCQualifiedClassType())
  8110. return Sema::IncompatiblePointer;
  8111. return Sema::Compatible;
  8112. }
  8113. QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
  8114. QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
  8115. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  8116. // make an exception for id<P>
  8117. !LHSType->isObjCQualifiedIdType())
  8118. return Sema::CompatiblePointerDiscardsQualifiers;
  8119. if (S.Context.typesAreCompatible(LHSType, RHSType))
  8120. return Sema::Compatible;
  8121. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  8122. return Sema::IncompatibleObjCQualifiedId;
  8123. return Sema::IncompatiblePointer;
  8124. }
  8125. Sema::AssignConvertType
  8126. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  8127. QualType LHSType, QualType RHSType) {
  8128. // Fake up an opaque expression. We don't actually care about what
  8129. // cast operations are required, so if CheckAssignmentConstraints
  8130. // adds casts to this they'll be wasted, but fortunately that doesn't
  8131. // usually happen on valid code.
  8132. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
  8133. ExprResult RHSPtr = &RHSExpr;
  8134. CastKind K;
  8135. return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
  8136. }
  8137. /// This helper function returns true if QT is a vector type that has element
  8138. /// type ElementType.
  8139. static bool isVector(QualType QT, QualType ElementType) {
  8140. if (const VectorType *VT = QT->getAs<VectorType>())
  8141. return VT->getElementType().getCanonicalType() == ElementType;
  8142. return false;
  8143. }
  8144. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  8145. /// has code to accommodate several GCC extensions when type checking
  8146. /// pointers. Here are some objectionable examples that GCC considers warnings:
  8147. ///
  8148. /// int a, *pint;
  8149. /// short *pshort;
  8150. /// struct foo *pfoo;
  8151. ///
  8152. /// pint = pshort; // warning: assignment from incompatible pointer type
  8153. /// a = pint; // warning: assignment makes integer from pointer without a cast
  8154. /// pint = a; // warning: assignment makes pointer from integer without a cast
  8155. /// pint = pfoo; // warning: assignment from incompatible pointer type
  8156. ///
  8157. /// As a result, the code for dealing with pointers is more complex than the
  8158. /// C99 spec dictates.
  8159. ///
  8160. /// Sets 'Kind' for any result kind except Incompatible.
  8161. Sema::AssignConvertType
  8162. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  8163. CastKind &Kind, bool ConvertRHS) {
  8164. QualType RHSType = RHS.get()->getType();
  8165. QualType OrigLHSType = LHSType;
  8166. // Get canonical types. We're not formatting these types, just comparing
  8167. // them.
  8168. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  8169. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  8170. // Common case: no conversion required.
  8171. if (LHSType == RHSType) {
  8172. Kind = CK_NoOp;
  8173. return Compatible;
  8174. }
  8175. // If we have an atomic type, try a non-atomic assignment, then just add an
  8176. // atomic qualification step.
  8177. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  8178. Sema::AssignConvertType result =
  8179. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  8180. if (result != Compatible)
  8181. return result;
  8182. if (Kind != CK_NoOp && ConvertRHS)
  8183. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  8184. Kind = CK_NonAtomicToAtomic;
  8185. return Compatible;
  8186. }
  8187. // If the left-hand side is a reference type, then we are in a
  8188. // (rare!) case where we've allowed the use of references in C,
  8189. // e.g., as a parameter type in a built-in function. In this case,
  8190. // just make sure that the type referenced is compatible with the
  8191. // right-hand side type. The caller is responsible for adjusting
  8192. // LHSType so that the resulting expression does not have reference
  8193. // type.
  8194. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  8195. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  8196. Kind = CK_LValueBitCast;
  8197. return Compatible;
  8198. }
  8199. return Incompatible;
  8200. }
  8201. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  8202. // to the same ExtVector type.
  8203. if (LHSType->isExtVectorType()) {
  8204. if (RHSType->isExtVectorType())
  8205. return Incompatible;
  8206. if (RHSType->isArithmeticType()) {
  8207. // CK_VectorSplat does T -> vector T, so first cast to the element type.
  8208. if (ConvertRHS)
  8209. RHS = prepareVectorSplat(LHSType, RHS.get());
  8210. Kind = CK_VectorSplat;
  8211. return Compatible;
  8212. }
  8213. }
  8214. // Conversions to or from vector type.
  8215. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  8216. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  8217. // Allow assignments of an AltiVec vector type to an equivalent GCC
  8218. // vector type and vice versa
  8219. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  8220. Kind = CK_BitCast;
  8221. return Compatible;
  8222. }
  8223. // If we are allowing lax vector conversions, and LHS and RHS are both
  8224. // vectors, the total size only needs to be the same. This is a bitcast;
  8225. // no bits are changed but the result type is different.
  8226. if (isLaxVectorConversion(RHSType, LHSType)) {
  8227. Kind = CK_BitCast;
  8228. return IncompatibleVectors;
  8229. }
  8230. }
  8231. // When the RHS comes from another lax conversion (e.g. binops between
  8232. // scalars and vectors) the result is canonicalized as a vector. When the
  8233. // LHS is also a vector, the lax is allowed by the condition above. Handle
  8234. // the case where LHS is a scalar.
  8235. if (LHSType->isScalarType()) {
  8236. const VectorType *VecType = RHSType->getAs<VectorType>();
  8237. if (VecType && VecType->getNumElements() == 1 &&
  8238. isLaxVectorConversion(RHSType, LHSType)) {
  8239. ExprResult *VecExpr = &RHS;
  8240. *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
  8241. Kind = CK_BitCast;
  8242. return Compatible;
  8243. }
  8244. }
  8245. // Allow assignments between fixed-length and sizeless SVE vectors.
  8246. if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
  8247. (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
  8248. if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
  8249. Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
  8250. Kind = CK_BitCast;
  8251. return Compatible;
  8252. }
  8253. return Incompatible;
  8254. }
  8255. // Diagnose attempts to convert between __ibm128, __float128 and long double
  8256. // where such conversions currently can't be handled.
  8257. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  8258. return Incompatible;
  8259. // Disallow assigning a _Complex to a real type in C++ mode since it simply
  8260. // discards the imaginary part.
  8261. if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
  8262. !LHSType->getAs<ComplexType>())
  8263. return Incompatible;
  8264. // Arithmetic conversions.
  8265. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  8266. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  8267. if (ConvertRHS)
  8268. Kind = PrepareScalarCast(RHS, LHSType);
  8269. return Compatible;
  8270. }
  8271. // Conversions to normal pointers.
  8272. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  8273. // U* -> T*
  8274. if (isa<PointerType>(RHSType)) {
  8275. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  8276. LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  8277. if (AddrSpaceL != AddrSpaceR)
  8278. Kind = CK_AddressSpaceConversion;
  8279. else if (Context.hasCvrSimilarType(RHSType, LHSType))
  8280. Kind = CK_NoOp;
  8281. else
  8282. Kind = CK_BitCast;
  8283. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  8284. }
  8285. // int -> T*
  8286. if (RHSType->isIntegerType()) {
  8287. Kind = CK_IntegralToPointer; // FIXME: null?
  8288. return IntToPointer;
  8289. }
  8290. // C pointers are not compatible with ObjC object pointers,
  8291. // with two exceptions:
  8292. if (isa<ObjCObjectPointerType>(RHSType)) {
  8293. // - conversions to void*
  8294. if (LHSPointer->getPointeeType()->isVoidType()) {
  8295. Kind = CK_BitCast;
  8296. return Compatible;
  8297. }
  8298. // - conversions from 'Class' to the redefinition type
  8299. if (RHSType->isObjCClassType() &&
  8300. Context.hasSameType(LHSType,
  8301. Context.getObjCClassRedefinitionType())) {
  8302. Kind = CK_BitCast;
  8303. return Compatible;
  8304. }
  8305. Kind = CK_BitCast;
  8306. return IncompatiblePointer;
  8307. }
  8308. // U^ -> void*
  8309. if (RHSType->getAs<BlockPointerType>()) {
  8310. if (LHSPointer->getPointeeType()->isVoidType()) {
  8311. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  8312. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  8313. ->getPointeeType()
  8314. .getAddressSpace();
  8315. Kind =
  8316. AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  8317. return Compatible;
  8318. }
  8319. }
  8320. return Incompatible;
  8321. }
  8322. // Conversions to block pointers.
  8323. if (isa<BlockPointerType>(LHSType)) {
  8324. // U^ -> T^
  8325. if (RHSType->isBlockPointerType()) {
  8326. LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
  8327. ->getPointeeType()
  8328. .getAddressSpace();
  8329. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  8330. ->getPointeeType()
  8331. .getAddressSpace();
  8332. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  8333. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  8334. }
  8335. // int or null -> T^
  8336. if (RHSType->isIntegerType()) {
  8337. Kind = CK_IntegralToPointer; // FIXME: null
  8338. return IntToBlockPointer;
  8339. }
  8340. // id -> T^
  8341. if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
  8342. Kind = CK_AnyPointerToBlockPointerCast;
  8343. return Compatible;
  8344. }
  8345. // void* -> T^
  8346. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  8347. if (RHSPT->getPointeeType()->isVoidType()) {
  8348. Kind = CK_AnyPointerToBlockPointerCast;
  8349. return Compatible;
  8350. }
  8351. return Incompatible;
  8352. }
  8353. // Conversions to Objective-C pointers.
  8354. if (isa<ObjCObjectPointerType>(LHSType)) {
  8355. // A* -> B*
  8356. if (RHSType->isObjCObjectPointerType()) {
  8357. Kind = CK_BitCast;
  8358. Sema::AssignConvertType result =
  8359. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  8360. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  8361. result == Compatible &&
  8362. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  8363. result = IncompatibleObjCWeakRef;
  8364. return result;
  8365. }
  8366. // int or null -> A*
  8367. if (RHSType->isIntegerType()) {
  8368. Kind = CK_IntegralToPointer; // FIXME: null
  8369. return IntToPointer;
  8370. }
  8371. // In general, C pointers are not compatible with ObjC object pointers,
  8372. // with two exceptions:
  8373. if (isa<PointerType>(RHSType)) {
  8374. Kind = CK_CPointerToObjCPointerCast;
  8375. // - conversions from 'void*'
  8376. if (RHSType->isVoidPointerType()) {
  8377. return Compatible;
  8378. }
  8379. // - conversions to 'Class' from its redefinition type
  8380. if (LHSType->isObjCClassType() &&
  8381. Context.hasSameType(RHSType,
  8382. Context.getObjCClassRedefinitionType())) {
  8383. return Compatible;
  8384. }
  8385. return IncompatiblePointer;
  8386. }
  8387. // Only under strict condition T^ is compatible with an Objective-C pointer.
  8388. if (RHSType->isBlockPointerType() &&
  8389. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  8390. if (ConvertRHS)
  8391. maybeExtendBlockObject(RHS);
  8392. Kind = CK_BlockPointerToObjCPointerCast;
  8393. return Compatible;
  8394. }
  8395. return Incompatible;
  8396. }
  8397. // Conversions from pointers that are not covered by the above.
  8398. if (isa<PointerType>(RHSType)) {
  8399. // T* -> _Bool
  8400. if (LHSType == Context.BoolTy) {
  8401. Kind = CK_PointerToBoolean;
  8402. return Compatible;
  8403. }
  8404. // T* -> int
  8405. if (LHSType->isIntegerType()) {
  8406. Kind = CK_PointerToIntegral;
  8407. return PointerToInt;
  8408. }
  8409. return Incompatible;
  8410. }
  8411. // Conversions from Objective-C pointers that are not covered by the above.
  8412. if (isa<ObjCObjectPointerType>(RHSType)) {
  8413. // T* -> _Bool
  8414. if (LHSType == Context.BoolTy) {
  8415. Kind = CK_PointerToBoolean;
  8416. return Compatible;
  8417. }
  8418. // T* -> int
  8419. if (LHSType->isIntegerType()) {
  8420. Kind = CK_PointerToIntegral;
  8421. return PointerToInt;
  8422. }
  8423. return Incompatible;
  8424. }
  8425. // struct A -> struct B
  8426. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  8427. if (Context.typesAreCompatible(LHSType, RHSType)) {
  8428. Kind = CK_NoOp;
  8429. return Compatible;
  8430. }
  8431. }
  8432. if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
  8433. Kind = CK_IntToOCLSampler;
  8434. return Compatible;
  8435. }
  8436. return Incompatible;
  8437. }
  8438. /// Constructs a transparent union from an expression that is
  8439. /// used to initialize the transparent union.
  8440. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  8441. ExprResult &EResult, QualType UnionType,
  8442. FieldDecl *Field) {
  8443. // Build an initializer list that designates the appropriate member
  8444. // of the transparent union.
  8445. Expr *E = EResult.get();
  8446. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  8447. E, SourceLocation());
  8448. Initializer->setType(UnionType);
  8449. Initializer->setInitializedFieldInUnion(Field);
  8450. // Build a compound literal constructing a value of the transparent
  8451. // union type from this initializer list.
  8452. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  8453. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  8454. VK_PRValue, Initializer, false);
  8455. }
  8456. Sema::AssignConvertType
  8457. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  8458. ExprResult &RHS) {
  8459. QualType RHSType = RHS.get()->getType();
  8460. // If the ArgType is a Union type, we want to handle a potential
  8461. // transparent_union GCC extension.
  8462. const RecordType *UT = ArgType->getAsUnionType();
  8463. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  8464. return Incompatible;
  8465. // The field to initialize within the transparent union.
  8466. RecordDecl *UD = UT->getDecl();
  8467. FieldDecl *InitField = nullptr;
  8468. // It's compatible if the expression matches any of the fields.
  8469. for (auto *it : UD->fields()) {
  8470. if (it->getType()->isPointerType()) {
  8471. // If the transparent union contains a pointer type, we allow:
  8472. // 1) void pointer
  8473. // 2) null pointer constant
  8474. if (RHSType->isPointerType())
  8475. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  8476. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  8477. InitField = it;
  8478. break;
  8479. }
  8480. if (RHS.get()->isNullPointerConstant(Context,
  8481. Expr::NPC_ValueDependentIsNull)) {
  8482. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  8483. CK_NullToPointer);
  8484. InitField = it;
  8485. break;
  8486. }
  8487. }
  8488. CastKind Kind;
  8489. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  8490. == Compatible) {
  8491. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  8492. InitField = it;
  8493. break;
  8494. }
  8495. }
  8496. if (!InitField)
  8497. return Incompatible;
  8498. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  8499. return Compatible;
  8500. }
  8501. Sema::AssignConvertType
  8502. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
  8503. bool Diagnose,
  8504. bool DiagnoseCFAudited,
  8505. bool ConvertRHS) {
  8506. // We need to be able to tell the caller whether we diagnosed a problem, if
  8507. // they ask us to issue diagnostics.
  8508. assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
  8509. // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
  8510. // we can't avoid *all* modifications at the moment, so we need some somewhere
  8511. // to put the updated value.
  8512. ExprResult LocalRHS = CallerRHS;
  8513. ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
  8514. if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
  8515. if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
  8516. if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
  8517. !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
  8518. Diag(RHS.get()->getExprLoc(),
  8519. diag::warn_noderef_to_dereferenceable_pointer)
  8520. << RHS.get()->getSourceRange();
  8521. }
  8522. }
  8523. }
  8524. if (getLangOpts().CPlusPlus) {
  8525. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  8526. // C++ 5.17p3: If the left operand is not of class type, the
  8527. // expression is implicitly converted (C++ 4) to the
  8528. // cv-unqualified type of the left operand.
  8529. QualType RHSType = RHS.get()->getType();
  8530. if (Diagnose) {
  8531. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  8532. AA_Assigning);
  8533. } else {
  8534. ImplicitConversionSequence ICS =
  8535. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  8536. /*SuppressUserConversions=*/false,
  8537. AllowedExplicit::None,
  8538. /*InOverloadResolution=*/false,
  8539. /*CStyle=*/false,
  8540. /*AllowObjCWritebackConversion=*/false);
  8541. if (ICS.isFailure())
  8542. return Incompatible;
  8543. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  8544. ICS, AA_Assigning);
  8545. }
  8546. if (RHS.isInvalid())
  8547. return Incompatible;
  8548. Sema::AssignConvertType result = Compatible;
  8549. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  8550. !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
  8551. result = IncompatibleObjCWeakRef;
  8552. return result;
  8553. }
  8554. // FIXME: Currently, we fall through and treat C++ classes like C
  8555. // structures.
  8556. // FIXME: We also fall through for atomics; not sure what should
  8557. // happen there, though.
  8558. } else if (RHS.get()->getType() == Context.OverloadTy) {
  8559. // As a set of extensions to C, we support overloading on functions. These
  8560. // functions need to be resolved here.
  8561. DeclAccessPair DAP;
  8562. if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
  8563. RHS.get(), LHSType, /*Complain=*/false, DAP))
  8564. RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
  8565. else
  8566. return Incompatible;
  8567. }
  8568. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  8569. // a null pointer constant.
  8570. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  8571. LHSType->isBlockPointerType()) &&
  8572. RHS.get()->isNullPointerConstant(Context,
  8573. Expr::NPC_ValueDependentIsNull)) {
  8574. if (Diagnose || ConvertRHS) {
  8575. CastKind Kind;
  8576. CXXCastPath Path;
  8577. CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
  8578. /*IgnoreBaseAccess=*/false, Diagnose);
  8579. if (ConvertRHS)
  8580. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
  8581. }
  8582. return Compatible;
  8583. }
  8584. // OpenCL queue_t type assignment.
  8585. if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
  8586. Context, Expr::NPC_ValueDependentIsNull)) {
  8587. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  8588. return Compatible;
  8589. }
  8590. // This check seems unnatural, however it is necessary to ensure the proper
  8591. // conversion of functions/arrays. If the conversion were done for all
  8592. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  8593. // expressions that suppress this implicit conversion (&, sizeof).
  8594. //
  8595. // Suppress this for references: C++ 8.5.3p5.
  8596. if (!LHSType->isReferenceType()) {
  8597. // FIXME: We potentially allocate here even if ConvertRHS is false.
  8598. RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
  8599. if (RHS.isInvalid())
  8600. return Incompatible;
  8601. }
  8602. CastKind Kind;
  8603. Sema::AssignConvertType result =
  8604. CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
  8605. // C99 6.5.16.1p2: The value of the right operand is converted to the
  8606. // type of the assignment expression.
  8607. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  8608. // so that we can use references in built-in functions even in C.
  8609. // The getNonReferenceType() call makes sure that the resulting expression
  8610. // does not have reference type.
  8611. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  8612. QualType Ty = LHSType.getNonLValueExprType(Context);
  8613. Expr *E = RHS.get();
  8614. // Check for various Objective-C errors. If we are not reporting
  8615. // diagnostics and just checking for errors, e.g., during overload
  8616. // resolution, return Incompatible to indicate the failure.
  8617. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  8618. CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  8619. Diagnose, DiagnoseCFAudited) != ACR_okay) {
  8620. if (!Diagnose)
  8621. return Incompatible;
  8622. }
  8623. if (getLangOpts().ObjC &&
  8624. (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
  8625. E->getType(), E, Diagnose) ||
  8626. CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
  8627. if (!Diagnose)
  8628. return Incompatible;
  8629. // Replace the expression with a corrected version and continue so we
  8630. // can find further errors.
  8631. RHS = E;
  8632. return Compatible;
  8633. }
  8634. if (ConvertRHS)
  8635. RHS = ImpCastExprToType(E, Ty, Kind);
  8636. }
  8637. return result;
  8638. }
  8639. namespace {
  8640. /// The original operand to an operator, prior to the application of the usual
  8641. /// arithmetic conversions and converting the arguments of a builtin operator
  8642. /// candidate.
  8643. struct OriginalOperand {
  8644. explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
  8645. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
  8646. Op = MTE->getSubExpr();
  8647. if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
  8648. Op = BTE->getSubExpr();
  8649. if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
  8650. Orig = ICE->getSubExprAsWritten();
  8651. Conversion = ICE->getConversionFunction();
  8652. }
  8653. }
  8654. QualType getType() const { return Orig->getType(); }
  8655. Expr *Orig;
  8656. NamedDecl *Conversion;
  8657. };
  8658. }
  8659. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  8660. ExprResult &RHS) {
  8661. OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
  8662. Diag(Loc, diag::err_typecheck_invalid_operands)
  8663. << OrigLHS.getType() << OrigRHS.getType()
  8664. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8665. // If a user-defined conversion was applied to either of the operands prior
  8666. // to applying the built-in operator rules, tell the user about it.
  8667. if (OrigLHS.Conversion) {
  8668. Diag(OrigLHS.Conversion->getLocation(),
  8669. diag::note_typecheck_invalid_operands_converted)
  8670. << 0 << LHS.get()->getType();
  8671. }
  8672. if (OrigRHS.Conversion) {
  8673. Diag(OrigRHS.Conversion->getLocation(),
  8674. diag::note_typecheck_invalid_operands_converted)
  8675. << 1 << RHS.get()->getType();
  8676. }
  8677. return QualType();
  8678. }
  8679. // Diagnose cases where a scalar was implicitly converted to a vector and
  8680. // diagnose the underlying types. Otherwise, diagnose the error
  8681. // as invalid vector logical operands for non-C++ cases.
  8682. QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
  8683. ExprResult &RHS) {
  8684. QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
  8685. QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
  8686. bool LHSNatVec = LHSType->isVectorType();
  8687. bool RHSNatVec = RHSType->isVectorType();
  8688. if (!(LHSNatVec && RHSNatVec)) {
  8689. Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
  8690. Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
  8691. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  8692. << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
  8693. << Vector->getSourceRange();
  8694. return QualType();
  8695. }
  8696. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  8697. << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
  8698. << RHS.get()->getSourceRange();
  8699. return QualType();
  8700. }
  8701. /// Try to convert a value of non-vector type to a vector type by converting
  8702. /// the type to the element type of the vector and then performing a splat.
  8703. /// If the language is OpenCL, we only use conversions that promote scalar
  8704. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  8705. /// for float->int.
  8706. ///
  8707. /// OpenCL V2.0 6.2.6.p2:
  8708. /// An error shall occur if any scalar operand type has greater rank
  8709. /// than the type of the vector element.
  8710. ///
  8711. /// \param scalar - if non-null, actually perform the conversions
  8712. /// \return true if the operation fails (but without diagnosing the failure)
  8713. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  8714. QualType scalarTy,
  8715. QualType vectorEltTy,
  8716. QualType vectorTy,
  8717. unsigned &DiagID) {
  8718. // The conversion to apply to the scalar before splatting it,
  8719. // if necessary.
  8720. CastKind scalarCast = CK_NoOp;
  8721. if (vectorEltTy->isIntegralType(S.Context)) {
  8722. if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
  8723. (scalarTy->isIntegerType() &&
  8724. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
  8725. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  8726. return true;
  8727. }
  8728. if (!scalarTy->isIntegralType(S.Context))
  8729. return true;
  8730. scalarCast = CK_IntegralCast;
  8731. } else if (vectorEltTy->isRealFloatingType()) {
  8732. if (scalarTy->isRealFloatingType()) {
  8733. if (S.getLangOpts().OpenCL &&
  8734. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
  8735. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  8736. return true;
  8737. }
  8738. scalarCast = CK_FloatingCast;
  8739. }
  8740. else if (scalarTy->isIntegralType(S.Context))
  8741. scalarCast = CK_IntegralToFloating;
  8742. else
  8743. return true;
  8744. } else {
  8745. return true;
  8746. }
  8747. // Adjust scalar if desired.
  8748. if (scalar) {
  8749. if (scalarCast != CK_NoOp)
  8750. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  8751. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  8752. }
  8753. return false;
  8754. }
  8755. /// Convert vector E to a vector with the same number of elements but different
  8756. /// element type.
  8757. static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
  8758. const auto *VecTy = E->getType()->getAs<VectorType>();
  8759. assert(VecTy && "Expression E must be a vector");
  8760. QualType NewVecTy = S.Context.getVectorType(ElementType,
  8761. VecTy->getNumElements(),
  8762. VecTy->getVectorKind());
  8763. // Look through the implicit cast. Return the subexpression if its type is
  8764. // NewVecTy.
  8765. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  8766. if (ICE->getSubExpr()->getType() == NewVecTy)
  8767. return ICE->getSubExpr();
  8768. auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
  8769. return S.ImpCastExprToType(E, NewVecTy, Cast);
  8770. }
  8771. /// Test if a (constant) integer Int can be casted to another integer type
  8772. /// IntTy without losing precision.
  8773. static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
  8774. QualType OtherIntTy) {
  8775. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  8776. // Reject cases where the value of the Int is unknown as that would
  8777. // possibly cause truncation, but accept cases where the scalar can be
  8778. // demoted without loss of precision.
  8779. Expr::EvalResult EVResult;
  8780. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  8781. int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
  8782. bool IntSigned = IntTy->hasSignedIntegerRepresentation();
  8783. bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
  8784. if (CstInt) {
  8785. // If the scalar is constant and is of a higher order and has more active
  8786. // bits that the vector element type, reject it.
  8787. llvm::APSInt Result = EVResult.Val.getInt();
  8788. unsigned NumBits = IntSigned
  8789. ? (Result.isNegative() ? Result.getMinSignedBits()
  8790. : Result.getActiveBits())
  8791. : Result.getActiveBits();
  8792. if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
  8793. return true;
  8794. // If the signedness of the scalar type and the vector element type
  8795. // differs and the number of bits is greater than that of the vector
  8796. // element reject it.
  8797. return (IntSigned != OtherIntSigned &&
  8798. NumBits > S.Context.getIntWidth(OtherIntTy));
  8799. }
  8800. // Reject cases where the value of the scalar is not constant and it's
  8801. // order is greater than that of the vector element type.
  8802. return (Order < 0);
  8803. }
  8804. /// Test if a (constant) integer Int can be casted to floating point type
  8805. /// FloatTy without losing precision.
  8806. static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
  8807. QualType FloatTy) {
  8808. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  8809. // Determine if the integer constant can be expressed as a floating point
  8810. // number of the appropriate type.
  8811. Expr::EvalResult EVResult;
  8812. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  8813. uint64_t Bits = 0;
  8814. if (CstInt) {
  8815. // Reject constants that would be truncated if they were converted to
  8816. // the floating point type. Test by simple to/from conversion.
  8817. // FIXME: Ideally the conversion to an APFloat and from an APFloat
  8818. // could be avoided if there was a convertFromAPInt method
  8819. // which could signal back if implicit truncation occurred.
  8820. llvm::APSInt Result = EVResult.Val.getInt();
  8821. llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
  8822. Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
  8823. llvm::APFloat::rmTowardZero);
  8824. llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
  8825. !IntTy->hasSignedIntegerRepresentation());
  8826. bool Ignored = false;
  8827. Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
  8828. &Ignored);
  8829. if (Result != ConvertBack)
  8830. return true;
  8831. } else {
  8832. // Reject types that cannot be fully encoded into the mantissa of
  8833. // the float.
  8834. Bits = S.Context.getTypeSize(IntTy);
  8835. unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
  8836. S.Context.getFloatTypeSemantics(FloatTy));
  8837. if (Bits > FloatPrec)
  8838. return true;
  8839. }
  8840. return false;
  8841. }
  8842. /// Attempt to convert and splat Scalar into a vector whose types matches
  8843. /// Vector following GCC conversion rules. The rule is that implicit
  8844. /// conversion can occur when Scalar can be casted to match Vector's element
  8845. /// type without causing truncation of Scalar.
  8846. static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
  8847. ExprResult *Vector) {
  8848. QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
  8849. QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
  8850. const VectorType *VT = VectorTy->getAs<VectorType>();
  8851. assert(!isa<ExtVectorType>(VT) &&
  8852. "ExtVectorTypes should not be handled here!");
  8853. QualType VectorEltTy = VT->getElementType();
  8854. // Reject cases where the vector element type or the scalar element type are
  8855. // not integral or floating point types.
  8856. if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
  8857. return true;
  8858. // The conversion to apply to the scalar before splatting it,
  8859. // if necessary.
  8860. CastKind ScalarCast = CK_NoOp;
  8861. // Accept cases where the vector elements are integers and the scalar is
  8862. // an integer.
  8863. // FIXME: Notionally if the scalar was a floating point value with a precise
  8864. // integral representation, we could cast it to an appropriate integer
  8865. // type and then perform the rest of the checks here. GCC will perform
  8866. // this conversion in some cases as determined by the input language.
  8867. // We should accept it on a language independent basis.
  8868. if (VectorEltTy->isIntegralType(S.Context) &&
  8869. ScalarTy->isIntegralType(S.Context) &&
  8870. S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
  8871. if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
  8872. return true;
  8873. ScalarCast = CK_IntegralCast;
  8874. } else if (VectorEltTy->isIntegralType(S.Context) &&
  8875. ScalarTy->isRealFloatingType()) {
  8876. if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
  8877. ScalarCast = CK_FloatingToIntegral;
  8878. else
  8879. return true;
  8880. } else if (VectorEltTy->isRealFloatingType()) {
  8881. if (ScalarTy->isRealFloatingType()) {
  8882. // Reject cases where the scalar type is not a constant and has a higher
  8883. // Order than the vector element type.
  8884. llvm::APFloat Result(0.0);
  8885. // Determine whether this is a constant scalar. In the event that the
  8886. // value is dependent (and thus cannot be evaluated by the constant
  8887. // evaluator), skip the evaluation. This will then diagnose once the
  8888. // expression is instantiated.
  8889. bool CstScalar = Scalar->get()->isValueDependent() ||
  8890. Scalar->get()->EvaluateAsFloat(Result, S.Context);
  8891. int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
  8892. if (!CstScalar && Order < 0)
  8893. return true;
  8894. // If the scalar cannot be safely casted to the vector element type,
  8895. // reject it.
  8896. if (CstScalar) {
  8897. bool Truncated = false;
  8898. Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
  8899. llvm::APFloat::rmNearestTiesToEven, &Truncated);
  8900. if (Truncated)
  8901. return true;
  8902. }
  8903. ScalarCast = CK_FloatingCast;
  8904. } else if (ScalarTy->isIntegralType(S.Context)) {
  8905. if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
  8906. return true;
  8907. ScalarCast = CK_IntegralToFloating;
  8908. } else
  8909. return true;
  8910. } else if (ScalarTy->isEnumeralType())
  8911. return true;
  8912. // Adjust scalar if desired.
  8913. if (Scalar) {
  8914. if (ScalarCast != CK_NoOp)
  8915. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
  8916. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
  8917. }
  8918. return false;
  8919. }
  8920. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  8921. SourceLocation Loc, bool IsCompAssign,
  8922. bool AllowBothBool,
  8923. bool AllowBoolConversions) {
  8924. if (!IsCompAssign) {
  8925. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  8926. if (LHS.isInvalid())
  8927. return QualType();
  8928. }
  8929. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  8930. if (RHS.isInvalid())
  8931. return QualType();
  8932. // For conversion purposes, we ignore any qualifiers.
  8933. // For example, "const float" and "float" are equivalent.
  8934. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  8935. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  8936. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  8937. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  8938. assert(LHSVecType || RHSVecType);
  8939. if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
  8940. (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
  8941. return InvalidOperands(Loc, LHS, RHS);
  8942. // AltiVec-style "vector bool op vector bool" combinations are allowed
  8943. // for some operators but not others.
  8944. if (!AllowBothBool &&
  8945. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  8946. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8947. return InvalidOperands(Loc, LHS, RHS);
  8948. // If the vector types are identical, return.
  8949. if (Context.hasSameType(LHSType, RHSType))
  8950. return LHSType;
  8951. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  8952. if (LHSVecType && RHSVecType &&
  8953. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  8954. if (isa<ExtVectorType>(LHSVecType)) {
  8955. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  8956. return LHSType;
  8957. }
  8958. if (!IsCompAssign)
  8959. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  8960. return RHSType;
  8961. }
  8962. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  8963. // can be mixed, with the result being the non-bool type. The non-bool
  8964. // operand must have integer element type.
  8965. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  8966. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  8967. (Context.getTypeSize(LHSVecType->getElementType()) ==
  8968. Context.getTypeSize(RHSVecType->getElementType()))) {
  8969. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  8970. LHSVecType->getElementType()->isIntegerType() &&
  8971. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  8972. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  8973. return LHSType;
  8974. }
  8975. if (!IsCompAssign &&
  8976. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  8977. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  8978. RHSVecType->getElementType()->isIntegerType()) {
  8979. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  8980. return RHSType;
  8981. }
  8982. }
  8983. // Expressions containing fixed-length and sizeless SVE vectors are invalid
  8984. // since the ambiguity can affect the ABI.
  8985. auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
  8986. const VectorType *VecType = SecondType->getAs<VectorType>();
  8987. return FirstType->isSizelessBuiltinType() && VecType &&
  8988. (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
  8989. VecType->getVectorKind() ==
  8990. VectorType::SveFixedLengthPredicateVector);
  8991. };
  8992. if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
  8993. Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
  8994. return QualType();
  8995. }
  8996. // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
  8997. // since the ambiguity can affect the ABI.
  8998. auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
  8999. const VectorType *FirstVecType = FirstType->getAs<VectorType>();
  9000. const VectorType *SecondVecType = SecondType->getAs<VectorType>();
  9001. if (FirstVecType && SecondVecType)
  9002. return FirstVecType->getVectorKind() == VectorType::GenericVector &&
  9003. (SecondVecType->getVectorKind() ==
  9004. VectorType::SveFixedLengthDataVector ||
  9005. SecondVecType->getVectorKind() ==
  9006. VectorType::SveFixedLengthPredicateVector);
  9007. return FirstType->isSizelessBuiltinType() && SecondVecType &&
  9008. SecondVecType->getVectorKind() == VectorType::GenericVector;
  9009. };
  9010. if (IsSveGnuConversion(LHSType, RHSType) ||
  9011. IsSveGnuConversion(RHSType, LHSType)) {
  9012. Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
  9013. return QualType();
  9014. }
  9015. // If there's a vector type and a scalar, try to convert the scalar to
  9016. // the vector element type and splat.
  9017. unsigned DiagID = diag::err_typecheck_vector_not_convertable;
  9018. if (!RHSVecType) {
  9019. if (isa<ExtVectorType>(LHSVecType)) {
  9020. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  9021. LHSVecType->getElementType(), LHSType,
  9022. DiagID))
  9023. return LHSType;
  9024. } else {
  9025. if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
  9026. return LHSType;
  9027. }
  9028. }
  9029. if (!LHSVecType) {
  9030. if (isa<ExtVectorType>(RHSVecType)) {
  9031. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  9032. LHSType, RHSVecType->getElementType(),
  9033. RHSType, DiagID))
  9034. return RHSType;
  9035. } else {
  9036. if (LHS.get()->isLValue() ||
  9037. !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
  9038. return RHSType;
  9039. }
  9040. }
  9041. // FIXME: The code below also handles conversion between vectors and
  9042. // non-scalars, we should break this down into fine grained specific checks
  9043. // and emit proper diagnostics.
  9044. QualType VecType = LHSVecType ? LHSType : RHSType;
  9045. const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
  9046. QualType OtherType = LHSVecType ? RHSType : LHSType;
  9047. ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
  9048. if (isLaxVectorConversion(OtherType, VecType)) {
  9049. // If we're allowing lax vector conversions, only the total (data) size
  9050. // needs to be the same. For non compound assignment, if one of the types is
  9051. // scalar, the result is always the vector type.
  9052. if (!IsCompAssign) {
  9053. *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
  9054. return VecType;
  9055. // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
  9056. // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
  9057. // type. Note that this is already done by non-compound assignments in
  9058. // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
  9059. // <1 x T> -> T. The result is also a vector type.
  9060. } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
  9061. (OtherType->isScalarType() && VT->getNumElements() == 1)) {
  9062. ExprResult *RHSExpr = &RHS;
  9063. *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
  9064. return VecType;
  9065. }
  9066. }
  9067. // Okay, the expression is invalid.
  9068. // If there's a non-vector, non-real operand, diagnose that.
  9069. if ((!RHSVecType && !RHSType->isRealType()) ||
  9070. (!LHSVecType && !LHSType->isRealType())) {
  9071. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  9072. << LHSType << RHSType
  9073. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9074. return QualType();
  9075. }
  9076. // OpenCL V1.1 6.2.6.p1:
  9077. // If the operands are of more than one vector type, then an error shall
  9078. // occur. Implicit conversions between vector types are not permitted, per
  9079. // section 6.2.1.
  9080. if (getLangOpts().OpenCL &&
  9081. RHSVecType && isa<ExtVectorType>(RHSVecType) &&
  9082. LHSVecType && isa<ExtVectorType>(LHSVecType)) {
  9083. Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
  9084. << RHSType;
  9085. return QualType();
  9086. }
  9087. // If there is a vector type that is not a ExtVector and a scalar, we reach
  9088. // this point if scalar could not be converted to the vector's element type
  9089. // without truncation.
  9090. if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
  9091. (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
  9092. QualType Scalar = LHSVecType ? RHSType : LHSType;
  9093. QualType Vector = LHSVecType ? LHSType : RHSType;
  9094. unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
  9095. Diag(Loc,
  9096. diag::err_typecheck_vector_not_convertable_implict_truncation)
  9097. << ScalarOrVector << Scalar << Vector;
  9098. return QualType();
  9099. }
  9100. // Otherwise, use the generic diagnostic.
  9101. Diag(Loc, DiagID)
  9102. << LHSType << RHSType
  9103. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9104. return QualType();
  9105. }
  9106. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  9107. // expression. These are mainly cases where the null pointer is used as an
  9108. // integer instead of a pointer.
  9109. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  9110. SourceLocation Loc, bool IsCompare) {
  9111. // The canonical way to check for a GNU null is with isNullPointerConstant,
  9112. // but we use a bit of a hack here for speed; this is a relatively
  9113. // hot path, and isNullPointerConstant is slow.
  9114. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  9115. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  9116. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  9117. // Avoid analyzing cases where the result will either be invalid (and
  9118. // diagnosed as such) or entirely valid and not something to warn about.
  9119. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  9120. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  9121. return;
  9122. // Comparison operations would not make sense with a null pointer no matter
  9123. // what the other expression is.
  9124. if (!IsCompare) {
  9125. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  9126. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  9127. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  9128. return;
  9129. }
  9130. // The rest of the operations only make sense with a null pointer
  9131. // if the other expression is a pointer.
  9132. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  9133. NonNullType->canDecayToPointerType())
  9134. return;
  9135. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  9136. << LHSNull /* LHS is NULL */ << NonNullType
  9137. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9138. }
  9139. static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
  9140. SourceLocation Loc) {
  9141. const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
  9142. const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
  9143. if (!LUE || !RUE)
  9144. return;
  9145. if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
  9146. RUE->getKind() != UETT_SizeOf)
  9147. return;
  9148. const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
  9149. QualType LHSTy = LHSArg->getType();
  9150. QualType RHSTy;
  9151. if (RUE->isArgumentType())
  9152. RHSTy = RUE->getArgumentType().getNonReferenceType();
  9153. else
  9154. RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
  9155. if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
  9156. if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
  9157. return;
  9158. S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
  9159. if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
  9160. if (const ValueDecl *LHSArgDecl = DRE->getDecl())
  9161. S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
  9162. << LHSArgDecl;
  9163. }
  9164. } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
  9165. QualType ArrayElemTy = ArrayTy->getElementType();
  9166. if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
  9167. ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
  9168. RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
  9169. S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
  9170. return;
  9171. S.Diag(Loc, diag::warn_division_sizeof_array)
  9172. << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
  9173. if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
  9174. if (const ValueDecl *LHSArgDecl = DRE->getDecl())
  9175. S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
  9176. << LHSArgDecl;
  9177. }
  9178. S.Diag(Loc, diag::note_precedence_silence) << RHS;
  9179. }
  9180. }
  9181. static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
  9182. ExprResult &RHS,
  9183. SourceLocation Loc, bool IsDiv) {
  9184. // Check for division/remainder by zero.
  9185. Expr::EvalResult RHSValue;
  9186. if (!RHS.get()->isValueDependent() &&
  9187. RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
  9188. RHSValue.Val.getInt() == 0)
  9189. S.DiagRuntimeBehavior(Loc, RHS.get(),
  9190. S.PDiag(diag::warn_remainder_division_by_zero)
  9191. << IsDiv << RHS.get()->getSourceRange());
  9192. }
  9193. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  9194. SourceLocation Loc,
  9195. bool IsCompAssign, bool IsDiv) {
  9196. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  9197. QualType LHSTy = LHS.get()->getType();
  9198. QualType RHSTy = RHS.get()->getType();
  9199. if (LHSTy->isVectorType() || RHSTy->isVectorType())
  9200. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9201. /*AllowBothBool*/getLangOpts().AltiVec,
  9202. /*AllowBoolConversions*/false);
  9203. if (!IsDiv &&
  9204. (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
  9205. return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
  9206. // For division, only matrix-by-scalar is supported. Other combinations with
  9207. // matrix types are invalid.
  9208. if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
  9209. return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
  9210. QualType compType = UsualArithmeticConversions(
  9211. LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
  9212. if (LHS.isInvalid() || RHS.isInvalid())
  9213. return QualType();
  9214. if (compType.isNull() || !compType->isArithmeticType())
  9215. return InvalidOperands(Loc, LHS, RHS);
  9216. if (IsDiv) {
  9217. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
  9218. DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
  9219. }
  9220. return compType;
  9221. }
  9222. QualType Sema::CheckRemainderOperands(
  9223. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  9224. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  9225. if (LHS.get()->getType()->isVectorType() ||
  9226. RHS.get()->getType()->isVectorType()) {
  9227. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  9228. RHS.get()->getType()->hasIntegerRepresentation())
  9229. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9230. /*AllowBothBool*/getLangOpts().AltiVec,
  9231. /*AllowBoolConversions*/false);
  9232. return InvalidOperands(Loc, LHS, RHS);
  9233. }
  9234. QualType compType = UsualArithmeticConversions(
  9235. LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
  9236. if (LHS.isInvalid() || RHS.isInvalid())
  9237. return QualType();
  9238. if (compType.isNull() || !compType->isIntegerType())
  9239. return InvalidOperands(Loc, LHS, RHS);
  9240. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
  9241. return compType;
  9242. }
  9243. /// Diagnose invalid arithmetic on two void pointers.
  9244. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  9245. Expr *LHSExpr, Expr *RHSExpr) {
  9246. S.Diag(Loc, S.getLangOpts().CPlusPlus
  9247. ? diag::err_typecheck_pointer_arith_void_type
  9248. : diag::ext_gnu_void_ptr)
  9249. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  9250. << RHSExpr->getSourceRange();
  9251. }
  9252. /// Diagnose invalid arithmetic on a void pointer.
  9253. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  9254. Expr *Pointer) {
  9255. S.Diag(Loc, S.getLangOpts().CPlusPlus
  9256. ? diag::err_typecheck_pointer_arith_void_type
  9257. : diag::ext_gnu_void_ptr)
  9258. << 0 /* one pointer */ << Pointer->getSourceRange();
  9259. }
  9260. /// Diagnose invalid arithmetic on a null pointer.
  9261. ///
  9262. /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
  9263. /// idiom, which we recognize as a GNU extension.
  9264. ///
  9265. static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
  9266. Expr *Pointer, bool IsGNUIdiom) {
  9267. if (IsGNUIdiom)
  9268. S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
  9269. << Pointer->getSourceRange();
  9270. else
  9271. S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
  9272. << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
  9273. }
  9274. /// Diagnose invalid subraction on a null pointer.
  9275. ///
  9276. static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
  9277. Expr *Pointer, bool BothNull) {
  9278. // Null - null is valid in C++ [expr.add]p7
  9279. if (BothNull && S.getLangOpts().CPlusPlus)
  9280. return;
  9281. // Is this s a macro from a system header?
  9282. if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
  9283. return;
  9284. S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
  9285. << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
  9286. }
  9287. /// Diagnose invalid arithmetic on two function pointers.
  9288. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  9289. Expr *LHS, Expr *RHS) {
  9290. assert(LHS->getType()->isAnyPointerType());
  9291. assert(RHS->getType()->isAnyPointerType());
  9292. S.Diag(Loc, S.getLangOpts().CPlusPlus
  9293. ? diag::err_typecheck_pointer_arith_function_type
  9294. : diag::ext_gnu_ptr_func_arith)
  9295. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  9296. // We only show the second type if it differs from the first.
  9297. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  9298. RHS->getType())
  9299. << RHS->getType()->getPointeeType()
  9300. << LHS->getSourceRange() << RHS->getSourceRange();
  9301. }
  9302. /// Diagnose invalid arithmetic on a function pointer.
  9303. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  9304. Expr *Pointer) {
  9305. assert(Pointer->getType()->isAnyPointerType());
  9306. S.Diag(Loc, S.getLangOpts().CPlusPlus
  9307. ? diag::err_typecheck_pointer_arith_function_type
  9308. : diag::ext_gnu_ptr_func_arith)
  9309. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  9310. << 0 /* one pointer, so only one type */
  9311. << Pointer->getSourceRange();
  9312. }
  9313. /// Emit error if Operand is incomplete pointer type
  9314. ///
  9315. /// \returns True if pointer has incomplete type
  9316. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  9317. Expr *Operand) {
  9318. QualType ResType = Operand->getType();
  9319. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  9320. ResType = ResAtomicType->getValueType();
  9321. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  9322. QualType PointeeTy = ResType->getPointeeType();
  9323. return S.RequireCompleteSizedType(
  9324. Loc, PointeeTy,
  9325. diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
  9326. Operand->getSourceRange());
  9327. }
  9328. /// Check the validity of an arithmetic pointer operand.
  9329. ///
  9330. /// If the operand has pointer type, this code will check for pointer types
  9331. /// which are invalid in arithmetic operations. These will be diagnosed
  9332. /// appropriately, including whether or not the use is supported as an
  9333. /// extension.
  9334. ///
  9335. /// \returns True when the operand is valid to use (even if as an extension).
  9336. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  9337. Expr *Operand) {
  9338. QualType ResType = Operand->getType();
  9339. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  9340. ResType = ResAtomicType->getValueType();
  9341. if (!ResType->isAnyPointerType()) return true;
  9342. QualType PointeeTy = ResType->getPointeeType();
  9343. if (PointeeTy->isVoidType()) {
  9344. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  9345. return !S.getLangOpts().CPlusPlus;
  9346. }
  9347. if (PointeeTy->isFunctionType()) {
  9348. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  9349. return !S.getLangOpts().CPlusPlus;
  9350. }
  9351. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  9352. return true;
  9353. }
  9354. /// Check the validity of a binary arithmetic operation w.r.t. pointer
  9355. /// operands.
  9356. ///
  9357. /// This routine will diagnose any invalid arithmetic on pointer operands much
  9358. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  9359. /// for emitting a single diagnostic even for operations where both LHS and RHS
  9360. /// are (potentially problematic) pointers.
  9361. ///
  9362. /// \returns True when the operand is valid to use (even if as an extension).
  9363. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  9364. Expr *LHSExpr, Expr *RHSExpr) {
  9365. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  9366. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  9367. if (!isLHSPointer && !isRHSPointer) return true;
  9368. QualType LHSPointeeTy, RHSPointeeTy;
  9369. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  9370. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  9371. // if both are pointers check if operation is valid wrt address spaces
  9372. if (isLHSPointer && isRHSPointer) {
  9373. if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
  9374. S.Diag(Loc,
  9375. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  9376. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  9377. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  9378. return false;
  9379. }
  9380. }
  9381. // Check for arithmetic on pointers to incomplete types.
  9382. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  9383. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  9384. if (isLHSVoidPtr || isRHSVoidPtr) {
  9385. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  9386. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  9387. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  9388. return !S.getLangOpts().CPlusPlus;
  9389. }
  9390. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  9391. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  9392. if (isLHSFuncPtr || isRHSFuncPtr) {
  9393. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  9394. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  9395. RHSExpr);
  9396. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  9397. return !S.getLangOpts().CPlusPlus;
  9398. }
  9399. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  9400. return false;
  9401. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  9402. return false;
  9403. return true;
  9404. }
  9405. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  9406. /// literal.
  9407. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  9408. Expr *LHSExpr, Expr *RHSExpr) {
  9409. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  9410. Expr* IndexExpr = RHSExpr;
  9411. if (!StrExpr) {
  9412. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  9413. IndexExpr = LHSExpr;
  9414. }
  9415. bool IsStringPlusInt = StrExpr &&
  9416. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  9417. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  9418. return;
  9419. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  9420. Self.Diag(OpLoc, diag::warn_string_plus_int)
  9421. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  9422. // Only print a fixit for "str" + int, not for int + "str".
  9423. if (IndexExpr == RHSExpr) {
  9424. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  9425. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  9426. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  9427. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  9428. << FixItHint::CreateInsertion(EndLoc, "]");
  9429. } else
  9430. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  9431. }
  9432. /// Emit a warning when adding a char literal to a string.
  9433. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  9434. Expr *LHSExpr, Expr *RHSExpr) {
  9435. const Expr *StringRefExpr = LHSExpr;
  9436. const CharacterLiteral *CharExpr =
  9437. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  9438. if (!CharExpr) {
  9439. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  9440. StringRefExpr = RHSExpr;
  9441. }
  9442. if (!CharExpr || !StringRefExpr)
  9443. return;
  9444. const QualType StringType = StringRefExpr->getType();
  9445. // Return if not a PointerType.
  9446. if (!StringType->isAnyPointerType())
  9447. return;
  9448. // Return if not a CharacterType.
  9449. if (!StringType->getPointeeType()->isAnyCharacterType())
  9450. return;
  9451. ASTContext &Ctx = Self.getASTContext();
  9452. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  9453. const QualType CharType = CharExpr->getType();
  9454. if (!CharType->isAnyCharacterType() &&
  9455. CharType->isIntegerType() &&
  9456. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  9457. Self.Diag(OpLoc, diag::warn_string_plus_char)
  9458. << DiagRange << Ctx.CharTy;
  9459. } else {
  9460. Self.Diag(OpLoc, diag::warn_string_plus_char)
  9461. << DiagRange << CharExpr->getType();
  9462. }
  9463. // Only print a fixit for str + char, not for char + str.
  9464. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  9465. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  9466. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  9467. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  9468. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  9469. << FixItHint::CreateInsertion(EndLoc, "]");
  9470. } else {
  9471. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  9472. }
  9473. }
  9474. /// Emit error when two pointers are incompatible.
  9475. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  9476. Expr *LHSExpr, Expr *RHSExpr) {
  9477. assert(LHSExpr->getType()->isAnyPointerType());
  9478. assert(RHSExpr->getType()->isAnyPointerType());
  9479. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  9480. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  9481. << RHSExpr->getSourceRange();
  9482. }
  9483. // C99 6.5.6
  9484. QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
  9485. SourceLocation Loc, BinaryOperatorKind Opc,
  9486. QualType* CompLHSTy) {
  9487. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  9488. if (LHS.get()->getType()->isVectorType() ||
  9489. RHS.get()->getType()->isVectorType()) {
  9490. QualType compType = CheckVectorOperands(
  9491. LHS, RHS, Loc, CompLHSTy,
  9492. /*AllowBothBool*/getLangOpts().AltiVec,
  9493. /*AllowBoolConversions*/getLangOpts().ZVector);
  9494. if (CompLHSTy) *CompLHSTy = compType;
  9495. return compType;
  9496. }
  9497. if (LHS.get()->getType()->isConstantMatrixType() ||
  9498. RHS.get()->getType()->isConstantMatrixType()) {
  9499. QualType compType =
  9500. CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
  9501. if (CompLHSTy)
  9502. *CompLHSTy = compType;
  9503. return compType;
  9504. }
  9505. QualType compType = UsualArithmeticConversions(
  9506. LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
  9507. if (LHS.isInvalid() || RHS.isInvalid())
  9508. return QualType();
  9509. // Diagnose "string literal" '+' int and string '+' "char literal".
  9510. if (Opc == BO_Add) {
  9511. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  9512. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  9513. }
  9514. // handle the common case first (both operands are arithmetic).
  9515. if (!compType.isNull() && compType->isArithmeticType()) {
  9516. if (CompLHSTy) *CompLHSTy = compType;
  9517. return compType;
  9518. }
  9519. // Type-checking. Ultimately the pointer's going to be in PExp;
  9520. // note that we bias towards the LHS being the pointer.
  9521. Expr *PExp = LHS.get(), *IExp = RHS.get();
  9522. bool isObjCPointer;
  9523. if (PExp->getType()->isPointerType()) {
  9524. isObjCPointer = false;
  9525. } else if (PExp->getType()->isObjCObjectPointerType()) {
  9526. isObjCPointer = true;
  9527. } else {
  9528. std::swap(PExp, IExp);
  9529. if (PExp->getType()->isPointerType()) {
  9530. isObjCPointer = false;
  9531. } else if (PExp->getType()->isObjCObjectPointerType()) {
  9532. isObjCPointer = true;
  9533. } else {
  9534. return InvalidOperands(Loc, LHS, RHS);
  9535. }
  9536. }
  9537. assert(PExp->getType()->isAnyPointerType());
  9538. if (!IExp->getType()->isIntegerType())
  9539. return InvalidOperands(Loc, LHS, RHS);
  9540. // Adding to a null pointer results in undefined behavior.
  9541. if (PExp->IgnoreParenCasts()->isNullPointerConstant(
  9542. Context, Expr::NPC_ValueDependentIsNotNull)) {
  9543. // In C++ adding zero to a null pointer is defined.
  9544. Expr::EvalResult KnownVal;
  9545. if (!getLangOpts().CPlusPlus ||
  9546. (!IExp->isValueDependent() &&
  9547. (!IExp->EvaluateAsInt(KnownVal, Context) ||
  9548. KnownVal.Val.getInt() != 0))) {
  9549. // Check the conditions to see if this is the 'p = nullptr + n' idiom.
  9550. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
  9551. Context, BO_Add, PExp, IExp);
  9552. diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
  9553. }
  9554. }
  9555. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  9556. return QualType();
  9557. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  9558. return QualType();
  9559. // Check array bounds for pointer arithemtic
  9560. CheckArrayAccess(PExp, IExp);
  9561. if (CompLHSTy) {
  9562. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  9563. if (LHSTy.isNull()) {
  9564. LHSTy = LHS.get()->getType();
  9565. if (LHSTy->isPromotableIntegerType())
  9566. LHSTy = Context.getPromotedIntegerType(LHSTy);
  9567. }
  9568. *CompLHSTy = LHSTy;
  9569. }
  9570. return PExp->getType();
  9571. }
  9572. // C99 6.5.6
  9573. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  9574. SourceLocation Loc,
  9575. QualType* CompLHSTy) {
  9576. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  9577. if (LHS.get()->getType()->isVectorType() ||
  9578. RHS.get()->getType()->isVectorType()) {
  9579. QualType compType = CheckVectorOperands(
  9580. LHS, RHS, Loc, CompLHSTy,
  9581. /*AllowBothBool*/getLangOpts().AltiVec,
  9582. /*AllowBoolConversions*/getLangOpts().ZVector);
  9583. if (CompLHSTy) *CompLHSTy = compType;
  9584. return compType;
  9585. }
  9586. if (LHS.get()->getType()->isConstantMatrixType() ||
  9587. RHS.get()->getType()->isConstantMatrixType()) {
  9588. QualType compType =
  9589. CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
  9590. if (CompLHSTy)
  9591. *CompLHSTy = compType;
  9592. return compType;
  9593. }
  9594. QualType compType = UsualArithmeticConversions(
  9595. LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
  9596. if (LHS.isInvalid() || RHS.isInvalid())
  9597. return QualType();
  9598. // Enforce type constraints: C99 6.5.6p3.
  9599. // Handle the common case first (both operands are arithmetic).
  9600. if (!compType.isNull() && compType->isArithmeticType()) {
  9601. if (CompLHSTy) *CompLHSTy = compType;
  9602. return compType;
  9603. }
  9604. // Either ptr - int or ptr - ptr.
  9605. if (LHS.get()->getType()->isAnyPointerType()) {
  9606. QualType lpointee = LHS.get()->getType()->getPointeeType();
  9607. // Diagnose bad cases where we step over interface counts.
  9608. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  9609. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  9610. return QualType();
  9611. // The result type of a pointer-int computation is the pointer type.
  9612. if (RHS.get()->getType()->isIntegerType()) {
  9613. // Subtracting from a null pointer should produce a warning.
  9614. // The last argument to the diagnose call says this doesn't match the
  9615. // GNU int-to-pointer idiom.
  9616. if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
  9617. Expr::NPC_ValueDependentIsNotNull)) {
  9618. // In C++ adding zero to a null pointer is defined.
  9619. Expr::EvalResult KnownVal;
  9620. if (!getLangOpts().CPlusPlus ||
  9621. (!RHS.get()->isValueDependent() &&
  9622. (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
  9623. KnownVal.Val.getInt() != 0))) {
  9624. diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
  9625. }
  9626. }
  9627. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  9628. return QualType();
  9629. // Check array bounds for pointer arithemtic
  9630. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  9631. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  9632. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  9633. return LHS.get()->getType();
  9634. }
  9635. // Handle pointer-pointer subtractions.
  9636. if (const PointerType *RHSPTy
  9637. = RHS.get()->getType()->getAs<PointerType>()) {
  9638. QualType rpointee = RHSPTy->getPointeeType();
  9639. if (getLangOpts().CPlusPlus) {
  9640. // Pointee types must be the same: C++ [expr.add]
  9641. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  9642. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  9643. }
  9644. } else {
  9645. // Pointee types must be compatible C99 6.5.6p3
  9646. if (!Context.typesAreCompatible(
  9647. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  9648. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  9649. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  9650. return QualType();
  9651. }
  9652. }
  9653. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  9654. LHS.get(), RHS.get()))
  9655. return QualType();
  9656. bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
  9657. Context, Expr::NPC_ValueDependentIsNotNull);
  9658. bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
  9659. Context, Expr::NPC_ValueDependentIsNotNull);
  9660. // Subtracting nullptr or from nullptr is suspect
  9661. if (LHSIsNullPtr)
  9662. diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
  9663. if (RHSIsNullPtr)
  9664. diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
  9665. // The pointee type may have zero size. As an extension, a structure or
  9666. // union may have zero size or an array may have zero length. In this
  9667. // case subtraction does not make sense.
  9668. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  9669. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  9670. if (ElementSize.isZero()) {
  9671. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  9672. << rpointee.getUnqualifiedType()
  9673. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9674. }
  9675. }
  9676. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  9677. return Context.getPointerDiffType();
  9678. }
  9679. }
  9680. return InvalidOperands(Loc, LHS, RHS);
  9681. }
  9682. static bool isScopedEnumerationType(QualType T) {
  9683. if (const EnumType *ET = T->getAs<EnumType>())
  9684. return ET->getDecl()->isScoped();
  9685. return false;
  9686. }
  9687. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  9688. SourceLocation Loc, BinaryOperatorKind Opc,
  9689. QualType LHSType) {
  9690. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  9691. // so skip remaining warnings as we don't want to modify values within Sema.
  9692. if (S.getLangOpts().OpenCL)
  9693. return;
  9694. // Check right/shifter operand
  9695. Expr::EvalResult RHSResult;
  9696. if (RHS.get()->isValueDependent() ||
  9697. !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
  9698. return;
  9699. llvm::APSInt Right = RHSResult.Val.getInt();
  9700. if (Right.isNegative()) {
  9701. S.DiagRuntimeBehavior(Loc, RHS.get(),
  9702. S.PDiag(diag::warn_shift_negative)
  9703. << RHS.get()->getSourceRange());
  9704. return;
  9705. }
  9706. QualType LHSExprType = LHS.get()->getType();
  9707. uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
  9708. if (LHSExprType->isBitIntType())
  9709. LeftSize = S.Context.getIntWidth(LHSExprType);
  9710. else if (LHSExprType->isFixedPointType()) {
  9711. auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
  9712. LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
  9713. }
  9714. llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
  9715. if (Right.uge(LeftBits)) {
  9716. S.DiagRuntimeBehavior(Loc, RHS.get(),
  9717. S.PDiag(diag::warn_shift_gt_typewidth)
  9718. << RHS.get()->getSourceRange());
  9719. return;
  9720. }
  9721. // FIXME: We probably need to handle fixed point types specially here.
  9722. if (Opc != BO_Shl || LHSExprType->isFixedPointType())
  9723. return;
  9724. // When left shifting an ICE which is signed, we can check for overflow which
  9725. // according to C++ standards prior to C++2a has undefined behavior
  9726. // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
  9727. // more than the maximum value representable in the result type, so never
  9728. // warn for those. (FIXME: Unsigned left-shift overflow in a constant
  9729. // expression is still probably a bug.)
  9730. Expr::EvalResult LHSResult;
  9731. if (LHS.get()->isValueDependent() ||
  9732. LHSType->hasUnsignedIntegerRepresentation() ||
  9733. !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
  9734. return;
  9735. llvm::APSInt Left = LHSResult.Val.getInt();
  9736. // If LHS does not have a signed type and non-negative value
  9737. // then, the behavior is undefined before C++2a. Warn about it.
  9738. if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
  9739. !S.getLangOpts().CPlusPlus20) {
  9740. S.DiagRuntimeBehavior(Loc, LHS.get(),
  9741. S.PDiag(diag::warn_shift_lhs_negative)
  9742. << LHS.get()->getSourceRange());
  9743. return;
  9744. }
  9745. llvm::APInt ResultBits =
  9746. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  9747. if (LeftBits.uge(ResultBits))
  9748. return;
  9749. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  9750. Result = Result.shl(Right);
  9751. // Print the bit representation of the signed integer as an unsigned
  9752. // hexadecimal number.
  9753. SmallString<40> HexResult;
  9754. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  9755. // If we are only missing a sign bit, this is less likely to result in actual
  9756. // bugs -- if the result is cast back to an unsigned type, it will have the
  9757. // expected value. Thus we place this behind a different warning that can be
  9758. // turned off separately if needed.
  9759. if (LeftBits == ResultBits - 1) {
  9760. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  9761. << HexResult << LHSType
  9762. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9763. return;
  9764. }
  9765. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  9766. << HexResult.str() << Result.getMinSignedBits() << LHSType
  9767. << Left.getBitWidth() << LHS.get()->getSourceRange()
  9768. << RHS.get()->getSourceRange();
  9769. }
  9770. /// Return the resulting type when a vector is shifted
  9771. /// by a scalar or vector shift amount.
  9772. static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
  9773. SourceLocation Loc, bool IsCompAssign) {
  9774. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  9775. if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
  9776. !LHS.get()->getType()->isVectorType()) {
  9777. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  9778. << RHS.get()->getType() << LHS.get()->getType()
  9779. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9780. return QualType();
  9781. }
  9782. if (!IsCompAssign) {
  9783. LHS = S.UsualUnaryConversions(LHS.get());
  9784. if (LHS.isInvalid()) return QualType();
  9785. }
  9786. RHS = S.UsualUnaryConversions(RHS.get());
  9787. if (RHS.isInvalid()) return QualType();
  9788. QualType LHSType = LHS.get()->getType();
  9789. // Note that LHS might be a scalar because the routine calls not only in
  9790. // OpenCL case.
  9791. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  9792. QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
  9793. // Note that RHS might not be a vector.
  9794. QualType RHSType = RHS.get()->getType();
  9795. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  9796. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  9797. // The operands need to be integers.
  9798. if (!LHSEleType->isIntegerType()) {
  9799. S.Diag(Loc, diag::err_typecheck_expect_int)
  9800. << LHS.get()->getType() << LHS.get()->getSourceRange();
  9801. return QualType();
  9802. }
  9803. if (!RHSEleType->isIntegerType()) {
  9804. S.Diag(Loc, diag::err_typecheck_expect_int)
  9805. << RHS.get()->getType() << RHS.get()->getSourceRange();
  9806. return QualType();
  9807. }
  9808. if (!LHSVecTy) {
  9809. assert(RHSVecTy);
  9810. if (IsCompAssign)
  9811. return RHSType;
  9812. if (LHSEleType != RHSEleType) {
  9813. LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
  9814. LHSEleType = RHSEleType;
  9815. }
  9816. QualType VecTy =
  9817. S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
  9818. LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
  9819. LHSType = VecTy;
  9820. } else if (RHSVecTy) {
  9821. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  9822. // are applied component-wise. So if RHS is a vector, then ensure
  9823. // that the number of elements is the same as LHS...
  9824. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  9825. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  9826. << LHS.get()->getType() << RHS.get()->getType()
  9827. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9828. return QualType();
  9829. }
  9830. if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
  9831. const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
  9832. const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
  9833. if (LHSBT != RHSBT &&
  9834. S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
  9835. S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
  9836. << LHS.get()->getType() << RHS.get()->getType()
  9837. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9838. }
  9839. }
  9840. } else {
  9841. // ...else expand RHS to match the number of elements in LHS.
  9842. QualType VecTy =
  9843. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  9844. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  9845. }
  9846. return LHSType;
  9847. }
  9848. // C99 6.5.7
  9849. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  9850. SourceLocation Loc, BinaryOperatorKind Opc,
  9851. bool IsCompAssign) {
  9852. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  9853. // Vector shifts promote their scalar inputs to vector type.
  9854. if (LHS.get()->getType()->isVectorType() ||
  9855. RHS.get()->getType()->isVectorType()) {
  9856. if (LangOpts.ZVector) {
  9857. // The shift operators for the z vector extensions work basically
  9858. // like general shifts, except that neither the LHS nor the RHS is
  9859. // allowed to be a "vector bool".
  9860. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  9861. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  9862. return InvalidOperands(Loc, LHS, RHS);
  9863. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  9864. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  9865. return InvalidOperands(Loc, LHS, RHS);
  9866. }
  9867. return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  9868. }
  9869. // Shifts don't perform usual arithmetic conversions, they just do integer
  9870. // promotions on each operand. C99 6.5.7p3
  9871. // For the LHS, do usual unary conversions, but then reset them away
  9872. // if this is a compound assignment.
  9873. ExprResult OldLHS = LHS;
  9874. LHS = UsualUnaryConversions(LHS.get());
  9875. if (LHS.isInvalid())
  9876. return QualType();
  9877. QualType LHSType = LHS.get()->getType();
  9878. if (IsCompAssign) LHS = OldLHS;
  9879. // The RHS is simpler.
  9880. RHS = UsualUnaryConversions(RHS.get());
  9881. if (RHS.isInvalid())
  9882. return QualType();
  9883. QualType RHSType = RHS.get()->getType();
  9884. // C99 6.5.7p2: Each of the operands shall have integer type.
  9885. // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
  9886. if ((!LHSType->isFixedPointOrIntegerType() &&
  9887. !LHSType->hasIntegerRepresentation()) ||
  9888. !RHSType->hasIntegerRepresentation())
  9889. return InvalidOperands(Loc, LHS, RHS);
  9890. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  9891. // hasIntegerRepresentation() above instead of this.
  9892. if (isScopedEnumerationType(LHSType) ||
  9893. isScopedEnumerationType(RHSType)) {
  9894. return InvalidOperands(Loc, LHS, RHS);
  9895. }
  9896. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  9897. // "The type of the result is that of the promoted left operand."
  9898. return LHSType;
  9899. }
  9900. /// Diagnose bad pointer comparisons.
  9901. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  9902. ExprResult &LHS, ExprResult &RHS,
  9903. bool IsError) {
  9904. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  9905. : diag::ext_typecheck_comparison_of_distinct_pointers)
  9906. << LHS.get()->getType() << RHS.get()->getType()
  9907. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9908. }
  9909. /// Returns false if the pointers are converted to a composite type,
  9910. /// true otherwise.
  9911. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  9912. ExprResult &LHS, ExprResult &RHS) {
  9913. // C++ [expr.rel]p2:
  9914. // [...] Pointer conversions (4.10) and qualification
  9915. // conversions (4.4) are performed on pointer operands (or on
  9916. // a pointer operand and a null pointer constant) to bring
  9917. // them to their composite pointer type. [...]
  9918. //
  9919. // C++ [expr.eq]p1 uses the same notion for (in)equality
  9920. // comparisons of pointers.
  9921. QualType LHSType = LHS.get()->getType();
  9922. QualType RHSType = RHS.get()->getType();
  9923. assert(LHSType->isPointerType() || RHSType->isPointerType() ||
  9924. LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
  9925. QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
  9926. if (T.isNull()) {
  9927. if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
  9928. (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
  9929. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  9930. else
  9931. S.InvalidOperands(Loc, LHS, RHS);
  9932. return true;
  9933. }
  9934. return false;
  9935. }
  9936. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  9937. ExprResult &LHS,
  9938. ExprResult &RHS,
  9939. bool IsError) {
  9940. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  9941. : diag::ext_typecheck_comparison_of_fptr_to_void)
  9942. << LHS.get()->getType() << RHS.get()->getType()
  9943. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9944. }
  9945. static bool isObjCObjectLiteral(ExprResult &E) {
  9946. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  9947. case Stmt::ObjCArrayLiteralClass:
  9948. case Stmt::ObjCDictionaryLiteralClass:
  9949. case Stmt::ObjCStringLiteralClass:
  9950. case Stmt::ObjCBoxedExprClass:
  9951. return true;
  9952. default:
  9953. // Note that ObjCBoolLiteral is NOT an object literal!
  9954. return false;
  9955. }
  9956. }
  9957. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  9958. const ObjCObjectPointerType *Type =
  9959. LHS->getType()->getAs<ObjCObjectPointerType>();
  9960. // If this is not actually an Objective-C object, bail out.
  9961. if (!Type)
  9962. return false;
  9963. // Get the LHS object's interface type.
  9964. QualType InterfaceType = Type->getPointeeType();
  9965. // If the RHS isn't an Objective-C object, bail out.
  9966. if (!RHS->getType()->isObjCObjectPointerType())
  9967. return false;
  9968. // Try to find the -isEqual: method.
  9969. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  9970. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  9971. InterfaceType,
  9972. /*IsInstance=*/true);
  9973. if (!Method) {
  9974. if (Type->isObjCIdType()) {
  9975. // For 'id', just check the global pool.
  9976. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  9977. /*receiverId=*/true);
  9978. } else {
  9979. // Check protocols.
  9980. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  9981. /*IsInstance=*/true);
  9982. }
  9983. }
  9984. if (!Method)
  9985. return false;
  9986. QualType T = Method->parameters()[0]->getType();
  9987. if (!T->isObjCObjectPointerType())
  9988. return false;
  9989. QualType R = Method->getReturnType();
  9990. if (!R->isScalarType())
  9991. return false;
  9992. return true;
  9993. }
  9994. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  9995. FromE = FromE->IgnoreParenImpCasts();
  9996. switch (FromE->getStmtClass()) {
  9997. default:
  9998. break;
  9999. case Stmt::ObjCStringLiteralClass:
  10000. // "string literal"
  10001. return LK_String;
  10002. case Stmt::ObjCArrayLiteralClass:
  10003. // "array literal"
  10004. return LK_Array;
  10005. case Stmt::ObjCDictionaryLiteralClass:
  10006. // "dictionary literal"
  10007. return LK_Dictionary;
  10008. case Stmt::BlockExprClass:
  10009. return LK_Block;
  10010. case Stmt::ObjCBoxedExprClass: {
  10011. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  10012. switch (Inner->getStmtClass()) {
  10013. case Stmt::IntegerLiteralClass:
  10014. case Stmt::FloatingLiteralClass:
  10015. case Stmt::CharacterLiteralClass:
  10016. case Stmt::ObjCBoolLiteralExprClass:
  10017. case Stmt::CXXBoolLiteralExprClass:
  10018. // "numeric literal"
  10019. return LK_Numeric;
  10020. case Stmt::ImplicitCastExprClass: {
  10021. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  10022. // Boolean literals can be represented by implicit casts.
  10023. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  10024. return LK_Numeric;
  10025. break;
  10026. }
  10027. default:
  10028. break;
  10029. }
  10030. return LK_Boxed;
  10031. }
  10032. }
  10033. return LK_None;
  10034. }
  10035. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  10036. ExprResult &LHS, ExprResult &RHS,
  10037. BinaryOperator::Opcode Opc){
  10038. Expr *Literal;
  10039. Expr *Other;
  10040. if (isObjCObjectLiteral(LHS)) {
  10041. Literal = LHS.get();
  10042. Other = RHS.get();
  10043. } else {
  10044. Literal = RHS.get();
  10045. Other = LHS.get();
  10046. }
  10047. // Don't warn on comparisons against nil.
  10048. Other = Other->IgnoreParenCasts();
  10049. if (Other->isNullPointerConstant(S.getASTContext(),
  10050. Expr::NPC_ValueDependentIsNotNull))
  10051. return;
  10052. // This should be kept in sync with warn_objc_literal_comparison.
  10053. // LK_String should always be after the other literals, since it has its own
  10054. // warning flag.
  10055. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  10056. assert(LiteralKind != Sema::LK_Block);
  10057. if (LiteralKind == Sema::LK_None) {
  10058. llvm_unreachable("Unknown Objective-C object literal kind");
  10059. }
  10060. if (LiteralKind == Sema::LK_String)
  10061. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  10062. << Literal->getSourceRange();
  10063. else
  10064. S.Diag(Loc, diag::warn_objc_literal_comparison)
  10065. << LiteralKind << Literal->getSourceRange();
  10066. if (BinaryOperator::isEqualityOp(Opc) &&
  10067. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  10068. SourceLocation Start = LHS.get()->getBeginLoc();
  10069. SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
  10070. CharSourceRange OpRange =
  10071. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  10072. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  10073. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  10074. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  10075. << FixItHint::CreateInsertion(End, "]");
  10076. }
  10077. }
  10078. /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
  10079. static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
  10080. ExprResult &RHS, SourceLocation Loc,
  10081. BinaryOperatorKind Opc) {
  10082. // Check that left hand side is !something.
  10083. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  10084. if (!UO || UO->getOpcode() != UO_LNot) return;
  10085. // Only check if the right hand side is non-bool arithmetic type.
  10086. if (RHS.get()->isKnownToHaveBooleanValue()) return;
  10087. // Make sure that the something in !something is not bool.
  10088. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  10089. if (SubExpr->isKnownToHaveBooleanValue()) return;
  10090. // Emit warning.
  10091. bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
  10092. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
  10093. << Loc << IsBitwiseOp;
  10094. // First note suggest !(x < y)
  10095. SourceLocation FirstOpen = SubExpr->getBeginLoc();
  10096. SourceLocation FirstClose = RHS.get()->getEndLoc();
  10097. FirstClose = S.getLocForEndOfToken(FirstClose);
  10098. if (FirstClose.isInvalid())
  10099. FirstOpen = SourceLocation();
  10100. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  10101. << IsBitwiseOp
  10102. << FixItHint::CreateInsertion(FirstOpen, "(")
  10103. << FixItHint::CreateInsertion(FirstClose, ")");
  10104. // Second note suggests (!x) < y
  10105. SourceLocation SecondOpen = LHS.get()->getBeginLoc();
  10106. SourceLocation SecondClose = LHS.get()->getEndLoc();
  10107. SecondClose = S.getLocForEndOfToken(SecondClose);
  10108. if (SecondClose.isInvalid())
  10109. SecondOpen = SourceLocation();
  10110. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  10111. << FixItHint::CreateInsertion(SecondOpen, "(")
  10112. << FixItHint::CreateInsertion(SecondClose, ")");
  10113. }
  10114. // Returns true if E refers to a non-weak array.
  10115. static bool checkForArray(const Expr *E) {
  10116. const ValueDecl *D = nullptr;
  10117. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
  10118. D = DR->getDecl();
  10119. } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
  10120. if (Mem->isImplicitAccess())
  10121. D = Mem->getMemberDecl();
  10122. }
  10123. if (!D)
  10124. return false;
  10125. return D->getType()->isArrayType() && !D->isWeak();
  10126. }
  10127. /// Diagnose some forms of syntactically-obvious tautological comparison.
  10128. static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
  10129. Expr *LHS, Expr *RHS,
  10130. BinaryOperatorKind Opc) {
  10131. Expr *LHSStripped = LHS->IgnoreParenImpCasts();
  10132. Expr *RHSStripped = RHS->IgnoreParenImpCasts();
  10133. QualType LHSType = LHS->getType();
  10134. QualType RHSType = RHS->getType();
  10135. if (LHSType->hasFloatingRepresentation() ||
  10136. (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
  10137. S.inTemplateInstantiation())
  10138. return;
  10139. // Comparisons between two array types are ill-formed for operator<=>, so
  10140. // we shouldn't emit any additional warnings about it.
  10141. if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
  10142. return;
  10143. // For non-floating point types, check for self-comparisons of the form
  10144. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  10145. // often indicate logic errors in the program.
  10146. //
  10147. // NOTE: Don't warn about comparison expressions resulting from macro
  10148. // expansion. Also don't warn about comparisons which are only self
  10149. // comparisons within a template instantiation. The warnings should catch
  10150. // obvious cases in the definition of the template anyways. The idea is to
  10151. // warn when the typed comparison operator will always evaluate to the same
  10152. // result.
  10153. // Used for indexing into %select in warn_comparison_always
  10154. enum {
  10155. AlwaysConstant,
  10156. AlwaysTrue,
  10157. AlwaysFalse,
  10158. AlwaysEqual, // std::strong_ordering::equal from operator<=>
  10159. };
  10160. // C++2a [depr.array.comp]:
  10161. // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
  10162. // operands of array type are deprecated.
  10163. if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
  10164. RHSStripped->getType()->isArrayType()) {
  10165. S.Diag(Loc, diag::warn_depr_array_comparison)
  10166. << LHS->getSourceRange() << RHS->getSourceRange()
  10167. << LHSStripped->getType() << RHSStripped->getType();
  10168. // Carry on to produce the tautological comparison warning, if this
  10169. // expression is potentially-evaluated, we can resolve the array to a
  10170. // non-weak declaration, and so on.
  10171. }
  10172. if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
  10173. if (Expr::isSameComparisonOperand(LHS, RHS)) {
  10174. unsigned Result;
  10175. switch (Opc) {
  10176. case BO_EQ:
  10177. case BO_LE:
  10178. case BO_GE:
  10179. Result = AlwaysTrue;
  10180. break;
  10181. case BO_NE:
  10182. case BO_LT:
  10183. case BO_GT:
  10184. Result = AlwaysFalse;
  10185. break;
  10186. case BO_Cmp:
  10187. Result = AlwaysEqual;
  10188. break;
  10189. default:
  10190. Result = AlwaysConstant;
  10191. break;
  10192. }
  10193. S.DiagRuntimeBehavior(Loc, nullptr,
  10194. S.PDiag(diag::warn_comparison_always)
  10195. << 0 /*self-comparison*/
  10196. << Result);
  10197. } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
  10198. // What is it always going to evaluate to?
  10199. unsigned Result;
  10200. switch (Opc) {
  10201. case BO_EQ: // e.g. array1 == array2
  10202. Result = AlwaysFalse;
  10203. break;
  10204. case BO_NE: // e.g. array1 != array2
  10205. Result = AlwaysTrue;
  10206. break;
  10207. default: // e.g. array1 <= array2
  10208. // The best we can say is 'a constant'
  10209. Result = AlwaysConstant;
  10210. break;
  10211. }
  10212. S.DiagRuntimeBehavior(Loc, nullptr,
  10213. S.PDiag(diag::warn_comparison_always)
  10214. << 1 /*array comparison*/
  10215. << Result);
  10216. }
  10217. }
  10218. if (isa<CastExpr>(LHSStripped))
  10219. LHSStripped = LHSStripped->IgnoreParenCasts();
  10220. if (isa<CastExpr>(RHSStripped))
  10221. RHSStripped = RHSStripped->IgnoreParenCasts();
  10222. // Warn about comparisons against a string constant (unless the other
  10223. // operand is null); the user probably wants string comparison function.
  10224. Expr *LiteralString = nullptr;
  10225. Expr *LiteralStringStripped = nullptr;
  10226. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  10227. !RHSStripped->isNullPointerConstant(S.Context,
  10228. Expr::NPC_ValueDependentIsNull)) {
  10229. LiteralString = LHS;
  10230. LiteralStringStripped = LHSStripped;
  10231. } else if ((isa<StringLiteral>(RHSStripped) ||
  10232. isa<ObjCEncodeExpr>(RHSStripped)) &&
  10233. !LHSStripped->isNullPointerConstant(S.Context,
  10234. Expr::NPC_ValueDependentIsNull)) {
  10235. LiteralString = RHS;
  10236. LiteralStringStripped = RHSStripped;
  10237. }
  10238. if (LiteralString) {
  10239. S.DiagRuntimeBehavior(Loc, nullptr,
  10240. S.PDiag(diag::warn_stringcompare)
  10241. << isa<ObjCEncodeExpr>(LiteralStringStripped)
  10242. << LiteralString->getSourceRange());
  10243. }
  10244. }
  10245. static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
  10246. switch (CK) {
  10247. default: {
  10248. #ifndef NDEBUG
  10249. llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
  10250. << "\n";
  10251. #endif
  10252. llvm_unreachable("unhandled cast kind");
  10253. }
  10254. case CK_UserDefinedConversion:
  10255. return ICK_Identity;
  10256. case CK_LValueToRValue:
  10257. return ICK_Lvalue_To_Rvalue;
  10258. case CK_ArrayToPointerDecay:
  10259. return ICK_Array_To_Pointer;
  10260. case CK_FunctionToPointerDecay:
  10261. return ICK_Function_To_Pointer;
  10262. case CK_IntegralCast:
  10263. return ICK_Integral_Conversion;
  10264. case CK_FloatingCast:
  10265. return ICK_Floating_Conversion;
  10266. case CK_IntegralToFloating:
  10267. case CK_FloatingToIntegral:
  10268. return ICK_Floating_Integral;
  10269. case CK_IntegralComplexCast:
  10270. case CK_FloatingComplexCast:
  10271. case CK_FloatingComplexToIntegralComplex:
  10272. case CK_IntegralComplexToFloatingComplex:
  10273. return ICK_Complex_Conversion;
  10274. case CK_FloatingComplexToReal:
  10275. case CK_FloatingRealToComplex:
  10276. case CK_IntegralComplexToReal:
  10277. case CK_IntegralRealToComplex:
  10278. return ICK_Complex_Real;
  10279. }
  10280. }
  10281. static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
  10282. QualType FromType,
  10283. SourceLocation Loc) {
  10284. // Check for a narrowing implicit conversion.
  10285. StandardConversionSequence SCS;
  10286. SCS.setAsIdentityConversion();
  10287. SCS.setToType(0, FromType);
  10288. SCS.setToType(1, ToType);
  10289. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  10290. SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
  10291. APValue PreNarrowingValue;
  10292. QualType PreNarrowingType;
  10293. switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
  10294. PreNarrowingType,
  10295. /*IgnoreFloatToIntegralConversion*/ true)) {
  10296. case NK_Dependent_Narrowing:
  10297. // Implicit conversion to a narrower type, but the expression is
  10298. // value-dependent so we can't tell whether it's actually narrowing.
  10299. case NK_Not_Narrowing:
  10300. return false;
  10301. case NK_Constant_Narrowing:
  10302. // Implicit conversion to a narrower type, and the value is not a constant
  10303. // expression.
  10304. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  10305. << /*Constant*/ 1
  10306. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
  10307. return true;
  10308. case NK_Variable_Narrowing:
  10309. // Implicit conversion to a narrower type, and the value is not a constant
  10310. // expression.
  10311. case NK_Type_Narrowing:
  10312. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  10313. << /*Constant*/ 0 << FromType << ToType;
  10314. // TODO: It's not a constant expression, but what if the user intended it
  10315. // to be? Can we produce notes to help them figure out why it isn't?
  10316. return true;
  10317. }
  10318. llvm_unreachable("unhandled case in switch");
  10319. }
  10320. static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
  10321. ExprResult &LHS,
  10322. ExprResult &RHS,
  10323. SourceLocation Loc) {
  10324. QualType LHSType = LHS.get()->getType();
  10325. QualType RHSType = RHS.get()->getType();
  10326. // Dig out the original argument type and expression before implicit casts
  10327. // were applied. These are the types/expressions we need to check the
  10328. // [expr.spaceship] requirements against.
  10329. ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
  10330. ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
  10331. QualType LHSStrippedType = LHSStripped.get()->getType();
  10332. QualType RHSStrippedType = RHSStripped.get()->getType();
  10333. // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
  10334. // other is not, the program is ill-formed.
  10335. if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
  10336. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  10337. return QualType();
  10338. }
  10339. // FIXME: Consider combining this with checkEnumArithmeticConversions.
  10340. int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
  10341. RHSStrippedType->isEnumeralType();
  10342. if (NumEnumArgs == 1) {
  10343. bool LHSIsEnum = LHSStrippedType->isEnumeralType();
  10344. QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
  10345. if (OtherTy->hasFloatingRepresentation()) {
  10346. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  10347. return QualType();
  10348. }
  10349. }
  10350. if (NumEnumArgs == 2) {
  10351. // C++2a [expr.spaceship]p5: If both operands have the same enumeration
  10352. // type E, the operator yields the result of converting the operands
  10353. // to the underlying type of E and applying <=> to the converted operands.
  10354. if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
  10355. S.InvalidOperands(Loc, LHS, RHS);
  10356. return QualType();
  10357. }
  10358. QualType IntType =
  10359. LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
  10360. assert(IntType->isArithmeticType());
  10361. // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
  10362. // promote the boolean type, and all other promotable integer types, to
  10363. // avoid this.
  10364. if (IntType->isPromotableIntegerType())
  10365. IntType = S.Context.getPromotedIntegerType(IntType);
  10366. LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
  10367. RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
  10368. LHSType = RHSType = IntType;
  10369. }
  10370. // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
  10371. // usual arithmetic conversions are applied to the operands.
  10372. QualType Type =
  10373. S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
  10374. if (LHS.isInvalid() || RHS.isInvalid())
  10375. return QualType();
  10376. if (Type.isNull())
  10377. return S.InvalidOperands(Loc, LHS, RHS);
  10378. Optional<ComparisonCategoryType> CCT =
  10379. getComparisonCategoryForBuiltinCmp(Type);
  10380. if (!CCT)
  10381. return S.InvalidOperands(Loc, LHS, RHS);
  10382. bool HasNarrowing = checkThreeWayNarrowingConversion(
  10383. S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
  10384. HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
  10385. RHS.get()->getBeginLoc());
  10386. if (HasNarrowing)
  10387. return QualType();
  10388. assert(!Type.isNull() && "composite type for <=> has not been set");
  10389. return S.CheckComparisonCategoryType(
  10390. *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
  10391. }
  10392. static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
  10393. ExprResult &RHS,
  10394. SourceLocation Loc,
  10395. BinaryOperatorKind Opc) {
  10396. if (Opc == BO_Cmp)
  10397. return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
  10398. // C99 6.5.8p3 / C99 6.5.9p4
  10399. QualType Type =
  10400. S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
  10401. if (LHS.isInvalid() || RHS.isInvalid())
  10402. return QualType();
  10403. if (Type.isNull())
  10404. return S.InvalidOperands(Loc, LHS, RHS);
  10405. assert(Type->isArithmeticType() || Type->isEnumeralType());
  10406. if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
  10407. return S.InvalidOperands(Loc, LHS, RHS);
  10408. // Check for comparisons of floating point operands using != and ==.
  10409. if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
  10410. S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
  10411. // The result of comparisons is 'bool' in C++, 'int' in C.
  10412. return S.Context.getLogicalOperationType();
  10413. }
  10414. void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
  10415. if (!NullE.get()->getType()->isAnyPointerType())
  10416. return;
  10417. int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
  10418. if (!E.get()->getType()->isAnyPointerType() &&
  10419. E.get()->isNullPointerConstant(Context,
  10420. Expr::NPC_ValueDependentIsNotNull) ==
  10421. Expr::NPCK_ZeroExpression) {
  10422. if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
  10423. if (CL->getValue() == 0)
  10424. Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
  10425. << NullValue
  10426. << FixItHint::CreateReplacement(E.get()->getExprLoc(),
  10427. NullValue ? "NULL" : "(void *)0");
  10428. } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
  10429. TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
  10430. QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
  10431. if (T == Context.CharTy)
  10432. Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
  10433. << NullValue
  10434. << FixItHint::CreateReplacement(E.get()->getExprLoc(),
  10435. NullValue ? "NULL" : "(void *)0");
  10436. }
  10437. }
  10438. }
  10439. // C99 6.5.8, C++ [expr.rel]
  10440. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  10441. SourceLocation Loc,
  10442. BinaryOperatorKind Opc) {
  10443. bool IsRelational = BinaryOperator::isRelationalOp(Opc);
  10444. bool IsThreeWay = Opc == BO_Cmp;
  10445. bool IsOrdered = IsRelational || IsThreeWay;
  10446. auto IsAnyPointerType = [](ExprResult E) {
  10447. QualType Ty = E.get()->getType();
  10448. return Ty->isPointerType() || Ty->isMemberPointerType();
  10449. };
  10450. // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
  10451. // type, array-to-pointer, ..., conversions are performed on both operands to
  10452. // bring them to their composite type.
  10453. // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
  10454. // any type-related checks.
  10455. if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
  10456. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  10457. if (LHS.isInvalid())
  10458. return QualType();
  10459. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  10460. if (RHS.isInvalid())
  10461. return QualType();
  10462. } else {
  10463. LHS = DefaultLvalueConversion(LHS.get());
  10464. if (LHS.isInvalid())
  10465. return QualType();
  10466. RHS = DefaultLvalueConversion(RHS.get());
  10467. if (RHS.isInvalid())
  10468. return QualType();
  10469. }
  10470. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
  10471. if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
  10472. CheckPtrComparisonWithNullChar(LHS, RHS);
  10473. CheckPtrComparisonWithNullChar(RHS, LHS);
  10474. }
  10475. // Handle vector comparisons separately.
  10476. if (LHS.get()->getType()->isVectorType() ||
  10477. RHS.get()->getType()->isVectorType())
  10478. return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
  10479. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  10480. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  10481. QualType LHSType = LHS.get()->getType();
  10482. QualType RHSType = RHS.get()->getType();
  10483. if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
  10484. (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
  10485. return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
  10486. const Expr::NullPointerConstantKind LHSNullKind =
  10487. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  10488. const Expr::NullPointerConstantKind RHSNullKind =
  10489. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  10490. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  10491. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  10492. auto computeResultTy = [&]() {
  10493. if (Opc != BO_Cmp)
  10494. return Context.getLogicalOperationType();
  10495. assert(getLangOpts().CPlusPlus);
  10496. assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
  10497. QualType CompositeTy = LHS.get()->getType();
  10498. assert(!CompositeTy->isReferenceType());
  10499. Optional<ComparisonCategoryType> CCT =
  10500. getComparisonCategoryForBuiltinCmp(CompositeTy);
  10501. if (!CCT)
  10502. return InvalidOperands(Loc, LHS, RHS);
  10503. if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
  10504. // P0946R0: Comparisons between a null pointer constant and an object
  10505. // pointer result in std::strong_equality, which is ill-formed under
  10506. // P1959R0.
  10507. Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
  10508. << (LHSIsNull ? LHS.get()->getSourceRange()
  10509. : RHS.get()->getSourceRange());
  10510. return QualType();
  10511. }
  10512. return CheckComparisonCategoryType(
  10513. *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
  10514. };
  10515. if (!IsOrdered && LHSIsNull != RHSIsNull) {
  10516. bool IsEquality = Opc == BO_EQ;
  10517. if (RHSIsNull)
  10518. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  10519. RHS.get()->getSourceRange());
  10520. else
  10521. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  10522. LHS.get()->getSourceRange());
  10523. }
  10524. if (IsOrdered && LHSType->isFunctionPointerType() &&
  10525. RHSType->isFunctionPointerType()) {
  10526. // Valid unless a relational comparison of function pointers
  10527. bool IsError = Opc == BO_Cmp;
  10528. auto DiagID =
  10529. IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
  10530. : getLangOpts().CPlusPlus
  10531. ? diag::warn_typecheck_ordered_comparison_of_function_pointers
  10532. : diag::ext_typecheck_ordered_comparison_of_function_pointers;
  10533. Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
  10534. << RHS.get()->getSourceRange();
  10535. if (IsError)
  10536. return QualType();
  10537. }
  10538. if ((LHSType->isIntegerType() && !LHSIsNull) ||
  10539. (RHSType->isIntegerType() && !RHSIsNull)) {
  10540. // Skip normal pointer conversion checks in this case; we have better
  10541. // diagnostics for this below.
  10542. } else if (getLangOpts().CPlusPlus) {
  10543. // Equality comparison of a function pointer to a void pointer is invalid,
  10544. // but we allow it as an extension.
  10545. // FIXME: If we really want to allow this, should it be part of composite
  10546. // pointer type computation so it works in conditionals too?
  10547. if (!IsOrdered &&
  10548. ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
  10549. (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
  10550. // This is a gcc extension compatibility comparison.
  10551. // In a SFINAE context, we treat this as a hard error to maintain
  10552. // conformance with the C++ standard.
  10553. diagnoseFunctionPointerToVoidComparison(
  10554. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  10555. if (isSFINAEContext())
  10556. return QualType();
  10557. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  10558. return computeResultTy();
  10559. }
  10560. // C++ [expr.eq]p2:
  10561. // If at least one operand is a pointer [...] bring them to their
  10562. // composite pointer type.
  10563. // C++ [expr.spaceship]p6
  10564. // If at least one of the operands is of pointer type, [...] bring them
  10565. // to their composite pointer type.
  10566. // C++ [expr.rel]p2:
  10567. // If both operands are pointers, [...] bring them to their composite
  10568. // pointer type.
  10569. // For <=>, the only valid non-pointer types are arrays and functions, and
  10570. // we already decayed those, so this is really the same as the relational
  10571. // comparison rule.
  10572. if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
  10573. (IsOrdered ? 2 : 1) &&
  10574. (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
  10575. RHSType->isObjCObjectPointerType()))) {
  10576. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  10577. return QualType();
  10578. return computeResultTy();
  10579. }
  10580. } else if (LHSType->isPointerType() &&
  10581. RHSType->isPointerType()) { // C99 6.5.8p2
  10582. // All of the following pointer-related warnings are GCC extensions, except
  10583. // when handling null pointer constants.
  10584. QualType LCanPointeeTy =
  10585. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  10586. QualType RCanPointeeTy =
  10587. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  10588. // C99 6.5.9p2 and C99 6.5.8p2
  10589. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  10590. RCanPointeeTy.getUnqualifiedType())) {
  10591. if (IsRelational) {
  10592. // Pointers both need to point to complete or incomplete types
  10593. if ((LCanPointeeTy->isIncompleteType() !=
  10594. RCanPointeeTy->isIncompleteType()) &&
  10595. !getLangOpts().C11) {
  10596. Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
  10597. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
  10598. << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
  10599. << RCanPointeeTy->isIncompleteType();
  10600. }
  10601. }
  10602. } else if (!IsRelational &&
  10603. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  10604. // Valid unless comparison between non-null pointer and function pointer
  10605. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  10606. && !LHSIsNull && !RHSIsNull)
  10607. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  10608. /*isError*/false);
  10609. } else {
  10610. // Invalid
  10611. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  10612. }
  10613. if (LCanPointeeTy != RCanPointeeTy) {
  10614. // Treat NULL constant as a special case in OpenCL.
  10615. if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
  10616. if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
  10617. Diag(Loc,
  10618. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  10619. << LHSType << RHSType << 0 /* comparison */
  10620. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  10621. }
  10622. }
  10623. LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
  10624. LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
  10625. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  10626. : CK_BitCast;
  10627. if (LHSIsNull && !RHSIsNull)
  10628. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  10629. else
  10630. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  10631. }
  10632. return computeResultTy();
  10633. }
  10634. if (getLangOpts().CPlusPlus) {
  10635. // C++ [expr.eq]p4:
  10636. // Two operands of type std::nullptr_t or one operand of type
  10637. // std::nullptr_t and the other a null pointer constant compare equal.
  10638. if (!IsOrdered && LHSIsNull && RHSIsNull) {
  10639. if (LHSType->isNullPtrType()) {
  10640. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  10641. return computeResultTy();
  10642. }
  10643. if (RHSType->isNullPtrType()) {
  10644. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  10645. return computeResultTy();
  10646. }
  10647. }
  10648. // Comparison of Objective-C pointers and block pointers against nullptr_t.
  10649. // These aren't covered by the composite pointer type rules.
  10650. if (!IsOrdered && RHSType->isNullPtrType() &&
  10651. (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
  10652. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  10653. return computeResultTy();
  10654. }
  10655. if (!IsOrdered && LHSType->isNullPtrType() &&
  10656. (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
  10657. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  10658. return computeResultTy();
  10659. }
  10660. if (IsRelational &&
  10661. ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
  10662. (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
  10663. // HACK: Relational comparison of nullptr_t against a pointer type is
  10664. // invalid per DR583, but we allow it within std::less<> and friends,
  10665. // since otherwise common uses of it break.
  10666. // FIXME: Consider removing this hack once LWG fixes std::less<> and
  10667. // friends to have std::nullptr_t overload candidates.
  10668. DeclContext *DC = CurContext;
  10669. if (isa<FunctionDecl>(DC))
  10670. DC = DC->getParent();
  10671. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  10672. if (CTSD->isInStdNamespace() &&
  10673. llvm::StringSwitch<bool>(CTSD->getName())
  10674. .Cases("less", "less_equal", "greater", "greater_equal", true)
  10675. .Default(false)) {
  10676. if (RHSType->isNullPtrType())
  10677. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  10678. else
  10679. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  10680. return computeResultTy();
  10681. }
  10682. }
  10683. }
  10684. // C++ [expr.eq]p2:
  10685. // If at least one operand is a pointer to member, [...] bring them to
  10686. // their composite pointer type.
  10687. if (!IsOrdered &&
  10688. (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
  10689. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  10690. return QualType();
  10691. else
  10692. return computeResultTy();
  10693. }
  10694. }
  10695. // Handle block pointer types.
  10696. if (!IsOrdered && LHSType->isBlockPointerType() &&
  10697. RHSType->isBlockPointerType()) {
  10698. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  10699. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  10700. if (!LHSIsNull && !RHSIsNull &&
  10701. !Context.typesAreCompatible(lpointee, rpointee)) {
  10702. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  10703. << LHSType << RHSType << LHS.get()->getSourceRange()
  10704. << RHS.get()->getSourceRange();
  10705. }
  10706. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  10707. return computeResultTy();
  10708. }
  10709. // Allow block pointers to be compared with null pointer constants.
  10710. if (!IsOrdered
  10711. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  10712. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  10713. if (!LHSIsNull && !RHSIsNull) {
  10714. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  10715. ->getPointeeType()->isVoidType())
  10716. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  10717. ->getPointeeType()->isVoidType())))
  10718. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  10719. << LHSType << RHSType << LHS.get()->getSourceRange()
  10720. << RHS.get()->getSourceRange();
  10721. }
  10722. if (LHSIsNull && !RHSIsNull)
  10723. LHS = ImpCastExprToType(LHS.get(), RHSType,
  10724. RHSType->isPointerType() ? CK_BitCast
  10725. : CK_AnyPointerToBlockPointerCast);
  10726. else
  10727. RHS = ImpCastExprToType(RHS.get(), LHSType,
  10728. LHSType->isPointerType() ? CK_BitCast
  10729. : CK_AnyPointerToBlockPointerCast);
  10730. return computeResultTy();
  10731. }
  10732. if (LHSType->isObjCObjectPointerType() ||
  10733. RHSType->isObjCObjectPointerType()) {
  10734. const PointerType *LPT = LHSType->getAs<PointerType>();
  10735. const PointerType *RPT = RHSType->getAs<PointerType>();
  10736. if (LPT || RPT) {
  10737. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  10738. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  10739. if (!LPtrToVoid && !RPtrToVoid &&
  10740. !Context.typesAreCompatible(LHSType, RHSType)) {
  10741. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  10742. /*isError*/false);
  10743. }
  10744. // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
  10745. // the RHS, but we have test coverage for this behavior.
  10746. // FIXME: Consider using convertPointersToCompositeType in C++.
  10747. if (LHSIsNull && !RHSIsNull) {
  10748. Expr *E = LHS.get();
  10749. if (getLangOpts().ObjCAutoRefCount)
  10750. CheckObjCConversion(SourceRange(), RHSType, E,
  10751. CCK_ImplicitConversion);
  10752. LHS = ImpCastExprToType(E, RHSType,
  10753. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  10754. }
  10755. else {
  10756. Expr *E = RHS.get();
  10757. if (getLangOpts().ObjCAutoRefCount)
  10758. CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
  10759. /*Diagnose=*/true,
  10760. /*DiagnoseCFAudited=*/false, Opc);
  10761. RHS = ImpCastExprToType(E, LHSType,
  10762. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  10763. }
  10764. return computeResultTy();
  10765. }
  10766. if (LHSType->isObjCObjectPointerType() &&
  10767. RHSType->isObjCObjectPointerType()) {
  10768. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  10769. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  10770. /*isError*/false);
  10771. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  10772. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  10773. if (LHSIsNull && !RHSIsNull)
  10774. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  10775. else
  10776. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  10777. return computeResultTy();
  10778. }
  10779. if (!IsOrdered && LHSType->isBlockPointerType() &&
  10780. RHSType->isBlockCompatibleObjCPointerType(Context)) {
  10781. LHS = ImpCastExprToType(LHS.get(), RHSType,
  10782. CK_BlockPointerToObjCPointerCast);
  10783. return computeResultTy();
  10784. } else if (!IsOrdered &&
  10785. LHSType->isBlockCompatibleObjCPointerType(Context) &&
  10786. RHSType->isBlockPointerType()) {
  10787. RHS = ImpCastExprToType(RHS.get(), LHSType,
  10788. CK_BlockPointerToObjCPointerCast);
  10789. return computeResultTy();
  10790. }
  10791. }
  10792. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  10793. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  10794. unsigned DiagID = 0;
  10795. bool isError = false;
  10796. if (LangOpts.DebuggerSupport) {
  10797. // Under a debugger, allow the comparison of pointers to integers,
  10798. // since users tend to want to compare addresses.
  10799. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  10800. (RHSIsNull && RHSType->isIntegerType())) {
  10801. if (IsOrdered) {
  10802. isError = getLangOpts().CPlusPlus;
  10803. DiagID =
  10804. isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
  10805. : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  10806. }
  10807. } else if (getLangOpts().CPlusPlus) {
  10808. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  10809. isError = true;
  10810. } else if (IsOrdered)
  10811. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  10812. else
  10813. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  10814. if (DiagID) {
  10815. Diag(Loc, DiagID)
  10816. << LHSType << RHSType << LHS.get()->getSourceRange()
  10817. << RHS.get()->getSourceRange();
  10818. if (isError)
  10819. return QualType();
  10820. }
  10821. if (LHSType->isIntegerType())
  10822. LHS = ImpCastExprToType(LHS.get(), RHSType,
  10823. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  10824. else
  10825. RHS = ImpCastExprToType(RHS.get(), LHSType,
  10826. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  10827. return computeResultTy();
  10828. }
  10829. // Handle block pointers.
  10830. if (!IsOrdered && RHSIsNull
  10831. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  10832. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  10833. return computeResultTy();
  10834. }
  10835. if (!IsOrdered && LHSIsNull
  10836. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  10837. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  10838. return computeResultTy();
  10839. }
  10840. if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
  10841. if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
  10842. return computeResultTy();
  10843. }
  10844. if (LHSType->isQueueT() && RHSType->isQueueT()) {
  10845. return computeResultTy();
  10846. }
  10847. if (LHSIsNull && RHSType->isQueueT()) {
  10848. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  10849. return computeResultTy();
  10850. }
  10851. if (LHSType->isQueueT() && RHSIsNull) {
  10852. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  10853. return computeResultTy();
  10854. }
  10855. }
  10856. return InvalidOperands(Loc, LHS, RHS);
  10857. }
  10858. // Return a signed ext_vector_type that is of identical size and number of
  10859. // elements. For floating point vectors, return an integer type of identical
  10860. // size and number of elements. In the non ext_vector_type case, search from
  10861. // the largest type to the smallest type to avoid cases where long long == long,
  10862. // where long gets picked over long long.
  10863. QualType Sema::GetSignedVectorType(QualType V) {
  10864. const VectorType *VTy = V->castAs<VectorType>();
  10865. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  10866. if (isa<ExtVectorType>(VTy)) {
  10867. if (TypeSize == Context.getTypeSize(Context.CharTy))
  10868. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  10869. if (TypeSize == Context.getTypeSize(Context.ShortTy))
  10870. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  10871. if (TypeSize == Context.getTypeSize(Context.IntTy))
  10872. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  10873. if (TypeSize == Context.getTypeSize(Context.Int128Ty))
  10874. return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
  10875. if (TypeSize == Context.getTypeSize(Context.LongTy))
  10876. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  10877. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  10878. "Unhandled vector element size in vector compare");
  10879. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  10880. }
  10881. if (TypeSize == Context.getTypeSize(Context.Int128Ty))
  10882. return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
  10883. VectorType::GenericVector);
  10884. if (TypeSize == Context.getTypeSize(Context.LongLongTy))
  10885. return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
  10886. VectorType::GenericVector);
  10887. if (TypeSize == Context.getTypeSize(Context.LongTy))
  10888. return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
  10889. VectorType::GenericVector);
  10890. if (TypeSize == Context.getTypeSize(Context.IntTy))
  10891. return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
  10892. VectorType::GenericVector);
  10893. if (TypeSize == Context.getTypeSize(Context.ShortTy))
  10894. return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
  10895. VectorType::GenericVector);
  10896. assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
  10897. "Unhandled vector element size in vector compare");
  10898. return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
  10899. VectorType::GenericVector);
  10900. }
  10901. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  10902. /// operates on extended vector types. Instead of producing an IntTy result,
  10903. /// like a scalar comparison, a vector comparison produces a vector of integer
  10904. /// types.
  10905. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  10906. SourceLocation Loc,
  10907. BinaryOperatorKind Opc) {
  10908. if (Opc == BO_Cmp) {
  10909. Diag(Loc, diag::err_three_way_vector_comparison);
  10910. return QualType();
  10911. }
  10912. // Check to make sure we're operating on vectors of the same type and width,
  10913. // Allowing one side to be a scalar of element type.
  10914. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  10915. /*AllowBothBool*/true,
  10916. /*AllowBoolConversions*/getLangOpts().ZVector);
  10917. if (vType.isNull())
  10918. return vType;
  10919. QualType LHSType = LHS.get()->getType();
  10920. // Determine the return type of a vector compare. By default clang will return
  10921. // a scalar for all vector compares except vector bool and vector pixel.
  10922. // With the gcc compiler we will always return a vector type and with the xl
  10923. // compiler we will always return a scalar type. This switch allows choosing
  10924. // which behavior is prefered.
  10925. if (getLangOpts().AltiVec) {
  10926. switch (getLangOpts().getAltivecSrcCompat()) {
  10927. case LangOptions::AltivecSrcCompatKind::Mixed:
  10928. // If AltiVec, the comparison results in a numeric type, i.e.
  10929. // bool for C++, int for C
  10930. if (vType->castAs<VectorType>()->getVectorKind() ==
  10931. VectorType::AltiVecVector)
  10932. return Context.getLogicalOperationType();
  10933. else
  10934. Diag(Loc, diag::warn_deprecated_altivec_src_compat);
  10935. break;
  10936. case LangOptions::AltivecSrcCompatKind::GCC:
  10937. // For GCC we always return the vector type.
  10938. break;
  10939. case LangOptions::AltivecSrcCompatKind::XL:
  10940. return Context.getLogicalOperationType();
  10941. break;
  10942. }
  10943. }
  10944. // For non-floating point types, check for self-comparisons of the form
  10945. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  10946. // often indicate logic errors in the program.
  10947. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  10948. // Check for comparisons of floating point operands using != and ==.
  10949. if (BinaryOperator::isEqualityOp(Opc) &&
  10950. LHSType->hasFloatingRepresentation()) {
  10951. assert(RHS.get()->getType()->hasFloatingRepresentation());
  10952. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  10953. }
  10954. // Return a signed type for the vector.
  10955. return GetSignedVectorType(vType);
  10956. }
  10957. static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
  10958. const ExprResult &XorRHS,
  10959. const SourceLocation Loc) {
  10960. // Do not diagnose macros.
  10961. if (Loc.isMacroID())
  10962. return;
  10963. // Do not diagnose if both LHS and RHS are macros.
  10964. if (XorLHS.get()->getExprLoc().isMacroID() &&
  10965. XorRHS.get()->getExprLoc().isMacroID())
  10966. return;
  10967. bool Negative = false;
  10968. bool ExplicitPlus = false;
  10969. const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
  10970. const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
  10971. if (!LHSInt)
  10972. return;
  10973. if (!RHSInt) {
  10974. // Check negative literals.
  10975. if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
  10976. UnaryOperatorKind Opc = UO->getOpcode();
  10977. if (Opc != UO_Minus && Opc != UO_Plus)
  10978. return;
  10979. RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
  10980. if (!RHSInt)
  10981. return;
  10982. Negative = (Opc == UO_Minus);
  10983. ExplicitPlus = !Negative;
  10984. } else {
  10985. return;
  10986. }
  10987. }
  10988. const llvm::APInt &LeftSideValue = LHSInt->getValue();
  10989. llvm::APInt RightSideValue = RHSInt->getValue();
  10990. if (LeftSideValue != 2 && LeftSideValue != 10)
  10991. return;
  10992. if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
  10993. return;
  10994. CharSourceRange ExprRange = CharSourceRange::getCharRange(
  10995. LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
  10996. llvm::StringRef ExprStr =
  10997. Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
  10998. CharSourceRange XorRange =
  10999. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  11000. llvm::StringRef XorStr =
  11001. Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
  11002. // Do not diagnose if xor keyword/macro is used.
  11003. if (XorStr == "xor")
  11004. return;
  11005. std::string LHSStr = std::string(Lexer::getSourceText(
  11006. CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
  11007. S.getSourceManager(), S.getLangOpts()));
  11008. std::string RHSStr = std::string(Lexer::getSourceText(
  11009. CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
  11010. S.getSourceManager(), S.getLangOpts()));
  11011. if (Negative) {
  11012. RightSideValue = -RightSideValue;
  11013. RHSStr = "-" + RHSStr;
  11014. } else if (ExplicitPlus) {
  11015. RHSStr = "+" + RHSStr;
  11016. }
  11017. StringRef LHSStrRef = LHSStr;
  11018. StringRef RHSStrRef = RHSStr;
  11019. // Do not diagnose literals with digit separators, binary, hexadecimal, octal
  11020. // literals.
  11021. if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
  11022. RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
  11023. LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
  11024. RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
  11025. (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
  11026. (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
  11027. LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
  11028. return;
  11029. bool SuggestXor =
  11030. S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
  11031. const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
  11032. int64_t RightSideIntValue = RightSideValue.getSExtValue();
  11033. if (LeftSideValue == 2 && RightSideIntValue >= 0) {
  11034. std::string SuggestedExpr = "1 << " + RHSStr;
  11035. bool Overflow = false;
  11036. llvm::APInt One = (LeftSideValue - 1);
  11037. llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
  11038. if (Overflow) {
  11039. if (RightSideIntValue < 64)
  11040. S.Diag(Loc, diag::warn_xor_used_as_pow_base)
  11041. << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
  11042. << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
  11043. else if (RightSideIntValue == 64)
  11044. S.Diag(Loc, diag::warn_xor_used_as_pow)
  11045. << ExprStr << toString(XorValue, 10, true);
  11046. else
  11047. return;
  11048. } else {
  11049. S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
  11050. << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
  11051. << toString(PowValue, 10, true)
  11052. << FixItHint::CreateReplacement(
  11053. ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
  11054. }
  11055. S.Diag(Loc, diag::note_xor_used_as_pow_silence)
  11056. << ("0x2 ^ " + RHSStr) << SuggestXor;
  11057. } else if (LeftSideValue == 10) {
  11058. std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
  11059. S.Diag(Loc, diag::warn_xor_used_as_pow_base)
  11060. << ExprStr << toString(XorValue, 10, true) << SuggestedValue
  11061. << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
  11062. S.Diag(Loc, diag::note_xor_used_as_pow_silence)
  11063. << ("0xA ^ " + RHSStr) << SuggestXor;
  11064. }
  11065. }
  11066. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  11067. SourceLocation Loc) {
  11068. // Ensure that either both operands are of the same vector type, or
  11069. // one operand is of a vector type and the other is of its element type.
  11070. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  11071. /*AllowBothBool*/true,
  11072. /*AllowBoolConversions*/false);
  11073. if (vType.isNull())
  11074. return InvalidOperands(Loc, LHS, RHS);
  11075. if (getLangOpts().OpenCL &&
  11076. getLangOpts().getOpenCLCompatibleVersion() < 120 &&
  11077. vType->hasFloatingRepresentation())
  11078. return InvalidOperands(Loc, LHS, RHS);
  11079. // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
  11080. // usage of the logical operators && and || with vectors in C. This
  11081. // check could be notionally dropped.
  11082. if (!getLangOpts().CPlusPlus &&
  11083. !(isa<ExtVectorType>(vType->getAs<VectorType>())))
  11084. return InvalidLogicalVectorOperands(Loc, LHS, RHS);
  11085. return GetSignedVectorType(LHS.get()->getType());
  11086. }
  11087. QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
  11088. SourceLocation Loc,
  11089. bool IsCompAssign) {
  11090. if (!IsCompAssign) {
  11091. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  11092. if (LHS.isInvalid())
  11093. return QualType();
  11094. }
  11095. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  11096. if (RHS.isInvalid())
  11097. return QualType();
  11098. // For conversion purposes, we ignore any qualifiers.
  11099. // For example, "const float" and "float" are equivalent.
  11100. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  11101. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  11102. const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
  11103. const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
  11104. assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
  11105. if (Context.hasSameType(LHSType, RHSType))
  11106. return LHSType;
  11107. // Type conversion may change LHS/RHS. Keep copies to the original results, in
  11108. // case we have to return InvalidOperands.
  11109. ExprResult OriginalLHS = LHS;
  11110. ExprResult OriginalRHS = RHS;
  11111. if (LHSMatType && !RHSMatType) {
  11112. RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
  11113. if (!RHS.isInvalid())
  11114. return LHSType;
  11115. return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
  11116. }
  11117. if (!LHSMatType && RHSMatType) {
  11118. LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
  11119. if (!LHS.isInvalid())
  11120. return RHSType;
  11121. return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
  11122. }
  11123. return InvalidOperands(Loc, LHS, RHS);
  11124. }
  11125. QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
  11126. SourceLocation Loc,
  11127. bool IsCompAssign) {
  11128. if (!IsCompAssign) {
  11129. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  11130. if (LHS.isInvalid())
  11131. return QualType();
  11132. }
  11133. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  11134. if (RHS.isInvalid())
  11135. return QualType();
  11136. auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
  11137. auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
  11138. assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
  11139. if (LHSMatType && RHSMatType) {
  11140. if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
  11141. return InvalidOperands(Loc, LHS, RHS);
  11142. if (!Context.hasSameType(LHSMatType->getElementType(),
  11143. RHSMatType->getElementType()))
  11144. return InvalidOperands(Loc, LHS, RHS);
  11145. return Context.getConstantMatrixType(LHSMatType->getElementType(),
  11146. LHSMatType->getNumRows(),
  11147. RHSMatType->getNumColumns());
  11148. }
  11149. return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
  11150. }
  11151. inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
  11152. SourceLocation Loc,
  11153. BinaryOperatorKind Opc) {
  11154. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  11155. bool IsCompAssign =
  11156. Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
  11157. if (LHS.get()->getType()->isVectorType() ||
  11158. RHS.get()->getType()->isVectorType()) {
  11159. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  11160. RHS.get()->getType()->hasIntegerRepresentation())
  11161. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  11162. /*AllowBothBool*/true,
  11163. /*AllowBoolConversions*/getLangOpts().ZVector);
  11164. return InvalidOperands(Loc, LHS, RHS);
  11165. }
  11166. if (Opc == BO_And)
  11167. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  11168. if (LHS.get()->getType()->hasFloatingRepresentation() ||
  11169. RHS.get()->getType()->hasFloatingRepresentation())
  11170. return InvalidOperands(Loc, LHS, RHS);
  11171. ExprResult LHSResult = LHS, RHSResult = RHS;
  11172. QualType compType = UsualArithmeticConversions(
  11173. LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
  11174. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  11175. return QualType();
  11176. LHS = LHSResult.get();
  11177. RHS = RHSResult.get();
  11178. if (Opc == BO_Xor)
  11179. diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
  11180. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  11181. return compType;
  11182. return InvalidOperands(Loc, LHS, RHS);
  11183. }
  11184. // C99 6.5.[13,14]
  11185. inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  11186. SourceLocation Loc,
  11187. BinaryOperatorKind Opc) {
  11188. // Check vector operands differently.
  11189. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  11190. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  11191. bool EnumConstantInBoolContext = false;
  11192. for (const ExprResult &HS : {LHS, RHS}) {
  11193. if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
  11194. const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
  11195. if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
  11196. EnumConstantInBoolContext = true;
  11197. }
  11198. }
  11199. if (EnumConstantInBoolContext)
  11200. Diag(Loc, diag::warn_enum_constant_in_bool_context);
  11201. // Diagnose cases where the user write a logical and/or but probably meant a
  11202. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  11203. // is a constant.
  11204. if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
  11205. !LHS.get()->getType()->isBooleanType() &&
  11206. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  11207. // Don't warn in macros or template instantiations.
  11208. !Loc.isMacroID() && !inTemplateInstantiation()) {
  11209. // If the RHS can be constant folded, and if it constant folds to something
  11210. // that isn't 0 or 1 (which indicate a potential logical operation that
  11211. // happened to fold to true/false) then warn.
  11212. // Parens on the RHS are ignored.
  11213. Expr::EvalResult EVResult;
  11214. if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
  11215. llvm::APSInt Result = EVResult.Val.getInt();
  11216. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  11217. !RHS.get()->getExprLoc().isMacroID()) ||
  11218. (Result != 0 && Result != 1)) {
  11219. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  11220. << RHS.get()->getSourceRange()
  11221. << (Opc == BO_LAnd ? "&&" : "||");
  11222. // Suggest replacing the logical operator with the bitwise version
  11223. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  11224. << (Opc == BO_LAnd ? "&" : "|")
  11225. << FixItHint::CreateReplacement(SourceRange(
  11226. Loc, getLocForEndOfToken(Loc)),
  11227. Opc == BO_LAnd ? "&" : "|");
  11228. if (Opc == BO_LAnd)
  11229. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  11230. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  11231. << FixItHint::CreateRemoval(
  11232. SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
  11233. RHS.get()->getEndLoc()));
  11234. }
  11235. }
  11236. }
  11237. if (!Context.getLangOpts().CPlusPlus) {
  11238. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  11239. // not operate on the built-in scalar and vector float types.
  11240. if (Context.getLangOpts().OpenCL &&
  11241. Context.getLangOpts().OpenCLVersion < 120) {
  11242. if (LHS.get()->getType()->isFloatingType() ||
  11243. RHS.get()->getType()->isFloatingType())
  11244. return InvalidOperands(Loc, LHS, RHS);
  11245. }
  11246. LHS = UsualUnaryConversions(LHS.get());
  11247. if (LHS.isInvalid())
  11248. return QualType();
  11249. RHS = UsualUnaryConversions(RHS.get());
  11250. if (RHS.isInvalid())
  11251. return QualType();
  11252. if (!LHS.get()->getType()->isScalarType() ||
  11253. !RHS.get()->getType()->isScalarType())
  11254. return InvalidOperands(Loc, LHS, RHS);
  11255. return Context.IntTy;
  11256. }
  11257. // The following is safe because we only use this method for
  11258. // non-overloadable operands.
  11259. // C++ [expr.log.and]p1
  11260. // C++ [expr.log.or]p1
  11261. // The operands are both contextually converted to type bool.
  11262. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  11263. if (LHSRes.isInvalid())
  11264. return InvalidOperands(Loc, LHS, RHS);
  11265. LHS = LHSRes;
  11266. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  11267. if (RHSRes.isInvalid())
  11268. return InvalidOperands(Loc, LHS, RHS);
  11269. RHS = RHSRes;
  11270. // C++ [expr.log.and]p2
  11271. // C++ [expr.log.or]p2
  11272. // The result is a bool.
  11273. return Context.BoolTy;
  11274. }
  11275. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  11276. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  11277. if (!ME) return false;
  11278. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  11279. ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
  11280. ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
  11281. if (!Base) return false;
  11282. return Base->getMethodDecl() != nullptr;
  11283. }
  11284. /// Is the given expression (which must be 'const') a reference to a
  11285. /// variable which was originally non-const, but which has become
  11286. /// 'const' due to being captured within a block?
  11287. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  11288. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  11289. assert(E->isLValue() && E->getType().isConstQualified());
  11290. E = E->IgnoreParens();
  11291. // Must be a reference to a declaration from an enclosing scope.
  11292. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  11293. if (!DRE) return NCCK_None;
  11294. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  11295. // The declaration must be a variable which is not declared 'const'.
  11296. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  11297. if (!var) return NCCK_None;
  11298. if (var->getType().isConstQualified()) return NCCK_None;
  11299. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  11300. // Decide whether the first capture was for a block or a lambda.
  11301. DeclContext *DC = S.CurContext, *Prev = nullptr;
  11302. // Decide whether the first capture was for a block or a lambda.
  11303. while (DC) {
  11304. // For init-capture, it is possible that the variable belongs to the
  11305. // template pattern of the current context.
  11306. if (auto *FD = dyn_cast<FunctionDecl>(DC))
  11307. if (var->isInitCapture() &&
  11308. FD->getTemplateInstantiationPattern() == var->getDeclContext())
  11309. break;
  11310. if (DC == var->getDeclContext())
  11311. break;
  11312. Prev = DC;
  11313. DC = DC->getParent();
  11314. }
  11315. // Unless we have an init-capture, we've gone one step too far.
  11316. if (!var->isInitCapture())
  11317. DC = Prev;
  11318. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  11319. }
  11320. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  11321. Ty = Ty.getNonReferenceType();
  11322. if (IsDereference && Ty->isPointerType())
  11323. Ty = Ty->getPointeeType();
  11324. return !Ty.isConstQualified();
  11325. }
  11326. // Update err_typecheck_assign_const and note_typecheck_assign_const
  11327. // when this enum is changed.
  11328. enum {
  11329. ConstFunction,
  11330. ConstVariable,
  11331. ConstMember,
  11332. ConstMethod,
  11333. NestedConstMember,
  11334. ConstUnknown, // Keep as last element
  11335. };
  11336. /// Emit the "read-only variable not assignable" error and print notes to give
  11337. /// more information about why the variable is not assignable, such as pointing
  11338. /// to the declaration of a const variable, showing that a method is const, or
  11339. /// that the function is returning a const reference.
  11340. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  11341. SourceLocation Loc) {
  11342. SourceRange ExprRange = E->getSourceRange();
  11343. // Only emit one error on the first const found. All other consts will emit
  11344. // a note to the error.
  11345. bool DiagnosticEmitted = false;
  11346. // Track if the current expression is the result of a dereference, and if the
  11347. // next checked expression is the result of a dereference.
  11348. bool IsDereference = false;
  11349. bool NextIsDereference = false;
  11350. // Loop to process MemberExpr chains.
  11351. while (true) {
  11352. IsDereference = NextIsDereference;
  11353. E = E->IgnoreImplicit()->IgnoreParenImpCasts();
  11354. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  11355. NextIsDereference = ME->isArrow();
  11356. const ValueDecl *VD = ME->getMemberDecl();
  11357. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  11358. // Mutable fields can be modified even if the class is const.
  11359. if (Field->isMutable()) {
  11360. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  11361. break;
  11362. }
  11363. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  11364. if (!DiagnosticEmitted) {
  11365. S.Diag(Loc, diag::err_typecheck_assign_const)
  11366. << ExprRange << ConstMember << false /*static*/ << Field
  11367. << Field->getType();
  11368. DiagnosticEmitted = true;
  11369. }
  11370. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  11371. << ConstMember << false /*static*/ << Field << Field->getType()
  11372. << Field->getSourceRange();
  11373. }
  11374. E = ME->getBase();
  11375. continue;
  11376. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  11377. if (VDecl->getType().isConstQualified()) {
  11378. if (!DiagnosticEmitted) {
  11379. S.Diag(Loc, diag::err_typecheck_assign_const)
  11380. << ExprRange << ConstMember << true /*static*/ << VDecl
  11381. << VDecl->getType();
  11382. DiagnosticEmitted = true;
  11383. }
  11384. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  11385. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  11386. << VDecl->getSourceRange();
  11387. }
  11388. // Static fields do not inherit constness from parents.
  11389. break;
  11390. }
  11391. break; // End MemberExpr
  11392. } else if (const ArraySubscriptExpr *ASE =
  11393. dyn_cast<ArraySubscriptExpr>(E)) {
  11394. E = ASE->getBase()->IgnoreParenImpCasts();
  11395. continue;
  11396. } else if (const ExtVectorElementExpr *EVE =
  11397. dyn_cast<ExtVectorElementExpr>(E)) {
  11398. E = EVE->getBase()->IgnoreParenImpCasts();
  11399. continue;
  11400. }
  11401. break;
  11402. }
  11403. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  11404. // Function calls
  11405. const FunctionDecl *FD = CE->getDirectCallee();
  11406. if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  11407. if (!DiagnosticEmitted) {
  11408. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  11409. << ConstFunction << FD;
  11410. DiagnosticEmitted = true;
  11411. }
  11412. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  11413. diag::note_typecheck_assign_const)
  11414. << ConstFunction << FD << FD->getReturnType()
  11415. << FD->getReturnTypeSourceRange();
  11416. }
  11417. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  11418. // Point to variable declaration.
  11419. if (const ValueDecl *VD = DRE->getDecl()) {
  11420. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  11421. if (!DiagnosticEmitted) {
  11422. S.Diag(Loc, diag::err_typecheck_assign_const)
  11423. << ExprRange << ConstVariable << VD << VD->getType();
  11424. DiagnosticEmitted = true;
  11425. }
  11426. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  11427. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  11428. }
  11429. }
  11430. } else if (isa<CXXThisExpr>(E)) {
  11431. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  11432. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  11433. if (MD->isConst()) {
  11434. if (!DiagnosticEmitted) {
  11435. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  11436. << ConstMethod << MD;
  11437. DiagnosticEmitted = true;
  11438. }
  11439. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  11440. << ConstMethod << MD << MD->getSourceRange();
  11441. }
  11442. }
  11443. }
  11444. }
  11445. if (DiagnosticEmitted)
  11446. return;
  11447. // Can't determine a more specific message, so display the generic error.
  11448. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  11449. }
  11450. enum OriginalExprKind {
  11451. OEK_Variable,
  11452. OEK_Member,
  11453. OEK_LValue
  11454. };
  11455. static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
  11456. const RecordType *Ty,
  11457. SourceLocation Loc, SourceRange Range,
  11458. OriginalExprKind OEK,
  11459. bool &DiagnosticEmitted) {
  11460. std::vector<const RecordType *> RecordTypeList;
  11461. RecordTypeList.push_back(Ty);
  11462. unsigned NextToCheckIndex = 0;
  11463. // We walk the record hierarchy breadth-first to ensure that we print
  11464. // diagnostics in field nesting order.
  11465. while (RecordTypeList.size() > NextToCheckIndex) {
  11466. bool IsNested = NextToCheckIndex > 0;
  11467. for (const FieldDecl *Field :
  11468. RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
  11469. // First, check every field for constness.
  11470. QualType FieldTy = Field->getType();
  11471. if (FieldTy.isConstQualified()) {
  11472. if (!DiagnosticEmitted) {
  11473. S.Diag(Loc, diag::err_typecheck_assign_const)
  11474. << Range << NestedConstMember << OEK << VD
  11475. << IsNested << Field;
  11476. DiagnosticEmitted = true;
  11477. }
  11478. S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
  11479. << NestedConstMember << IsNested << Field
  11480. << FieldTy << Field->getSourceRange();
  11481. }
  11482. // Then we append it to the list to check next in order.
  11483. FieldTy = FieldTy.getCanonicalType();
  11484. if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
  11485. if (!llvm::is_contained(RecordTypeList, FieldRecTy))
  11486. RecordTypeList.push_back(FieldRecTy);
  11487. }
  11488. }
  11489. ++NextToCheckIndex;
  11490. }
  11491. }
  11492. /// Emit an error for the case where a record we are trying to assign to has a
  11493. /// const-qualified field somewhere in its hierarchy.
  11494. static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
  11495. SourceLocation Loc) {
  11496. QualType Ty = E->getType();
  11497. assert(Ty->isRecordType() && "lvalue was not record?");
  11498. SourceRange Range = E->getSourceRange();
  11499. const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
  11500. bool DiagEmitted = false;
  11501. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  11502. DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
  11503. Range, OEK_Member, DiagEmitted);
  11504. else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  11505. DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
  11506. Range, OEK_Variable, DiagEmitted);
  11507. else
  11508. DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
  11509. Range, OEK_LValue, DiagEmitted);
  11510. if (!DiagEmitted)
  11511. DiagnoseConstAssignment(S, E, Loc);
  11512. }
  11513. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  11514. /// emit an error and return true. If so, return false.
  11515. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  11516. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  11517. S.CheckShadowingDeclModification(E, Loc);
  11518. SourceLocation OrigLoc = Loc;
  11519. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  11520. &Loc);
  11521. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  11522. IsLV = Expr::MLV_InvalidMessageExpression;
  11523. if (IsLV == Expr::MLV_Valid)
  11524. return false;
  11525. unsigned DiagID = 0;
  11526. bool NeedType = false;
  11527. switch (IsLV) { // C99 6.5.16p2
  11528. case Expr::MLV_ConstQualified:
  11529. // Use a specialized diagnostic when we're assigning to an object
  11530. // from an enclosing function or block.
  11531. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  11532. if (NCCK == NCCK_Block)
  11533. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  11534. else
  11535. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  11536. break;
  11537. }
  11538. // In ARC, use some specialized diagnostics for occasions where we
  11539. // infer 'const'. These are always pseudo-strong variables.
  11540. if (S.getLangOpts().ObjCAutoRefCount) {
  11541. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  11542. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  11543. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  11544. // Use the normal diagnostic if it's pseudo-__strong but the
  11545. // user actually wrote 'const'.
  11546. if (var->isARCPseudoStrong() &&
  11547. (!var->getTypeSourceInfo() ||
  11548. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  11549. // There are three pseudo-strong cases:
  11550. // - self
  11551. ObjCMethodDecl *method = S.getCurMethodDecl();
  11552. if (method && var == method->getSelfDecl()) {
  11553. DiagID = method->isClassMethod()
  11554. ? diag::err_typecheck_arc_assign_self_class_method
  11555. : diag::err_typecheck_arc_assign_self;
  11556. // - Objective-C externally_retained attribute.
  11557. } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
  11558. isa<ParmVarDecl>(var)) {
  11559. DiagID = diag::err_typecheck_arc_assign_externally_retained;
  11560. // - fast enumeration variables
  11561. } else {
  11562. DiagID = diag::err_typecheck_arr_assign_enumeration;
  11563. }
  11564. SourceRange Assign;
  11565. if (Loc != OrigLoc)
  11566. Assign = SourceRange(OrigLoc, OrigLoc);
  11567. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  11568. // We need to preserve the AST regardless, so migration tool
  11569. // can do its job.
  11570. return false;
  11571. }
  11572. }
  11573. }
  11574. // If none of the special cases above are triggered, then this is a
  11575. // simple const assignment.
  11576. if (DiagID == 0) {
  11577. DiagnoseConstAssignment(S, E, Loc);
  11578. return true;
  11579. }
  11580. break;
  11581. case Expr::MLV_ConstAddrSpace:
  11582. DiagnoseConstAssignment(S, E, Loc);
  11583. return true;
  11584. case Expr::MLV_ConstQualifiedField:
  11585. DiagnoseRecursiveConstFields(S, E, Loc);
  11586. return true;
  11587. case Expr::MLV_ArrayType:
  11588. case Expr::MLV_ArrayTemporary:
  11589. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  11590. NeedType = true;
  11591. break;
  11592. case Expr::MLV_NotObjectType:
  11593. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  11594. NeedType = true;
  11595. break;
  11596. case Expr::MLV_LValueCast:
  11597. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  11598. break;
  11599. case Expr::MLV_Valid:
  11600. llvm_unreachable("did not take early return for MLV_Valid");
  11601. case Expr::MLV_InvalidExpression:
  11602. case Expr::MLV_MemberFunction:
  11603. case Expr::MLV_ClassTemporary:
  11604. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  11605. break;
  11606. case Expr::MLV_IncompleteType:
  11607. case Expr::MLV_IncompleteVoidType:
  11608. return S.RequireCompleteType(Loc, E->getType(),
  11609. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  11610. case Expr::MLV_DuplicateVectorComponents:
  11611. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  11612. break;
  11613. case Expr::MLV_NoSetterProperty:
  11614. llvm_unreachable("readonly properties should be processed differently");
  11615. case Expr::MLV_InvalidMessageExpression:
  11616. DiagID = diag::err_readonly_message_assignment;
  11617. break;
  11618. case Expr::MLV_SubObjCPropertySetting:
  11619. DiagID = diag::err_no_subobject_property_setting;
  11620. break;
  11621. }
  11622. SourceRange Assign;
  11623. if (Loc != OrigLoc)
  11624. Assign = SourceRange(OrigLoc, OrigLoc);
  11625. if (NeedType)
  11626. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  11627. else
  11628. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  11629. return true;
  11630. }
  11631. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  11632. SourceLocation Loc,
  11633. Sema &Sema) {
  11634. if (Sema.inTemplateInstantiation())
  11635. return;
  11636. if (Sema.isUnevaluatedContext())
  11637. return;
  11638. if (Loc.isInvalid() || Loc.isMacroID())
  11639. return;
  11640. if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
  11641. return;
  11642. // C / C++ fields
  11643. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  11644. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  11645. if (ML && MR) {
  11646. if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
  11647. return;
  11648. const ValueDecl *LHSDecl =
  11649. cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
  11650. const ValueDecl *RHSDecl =
  11651. cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
  11652. if (LHSDecl != RHSDecl)
  11653. return;
  11654. if (LHSDecl->getType().isVolatileQualified())
  11655. return;
  11656. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  11657. if (RefTy->getPointeeType().isVolatileQualified())
  11658. return;
  11659. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  11660. }
  11661. // Objective-C instance variables
  11662. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  11663. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  11664. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  11665. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  11666. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  11667. if (RL && RR && RL->getDecl() == RR->getDecl())
  11668. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  11669. }
  11670. }
  11671. // C99 6.5.16.1
  11672. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  11673. SourceLocation Loc,
  11674. QualType CompoundType) {
  11675. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  11676. // Verify that LHS is a modifiable lvalue, and emit error if not.
  11677. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  11678. return QualType();
  11679. QualType LHSType = LHSExpr->getType();
  11680. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  11681. CompoundType;
  11682. // OpenCL v1.2 s6.1.1.1 p2:
  11683. // The half data type can only be used to declare a pointer to a buffer that
  11684. // contains half values
  11685. if (getLangOpts().OpenCL &&
  11686. !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
  11687. LHSType->isHalfType()) {
  11688. Diag(Loc, diag::err_opencl_half_load_store) << 1
  11689. << LHSType.getUnqualifiedType();
  11690. return QualType();
  11691. }
  11692. AssignConvertType ConvTy;
  11693. if (CompoundType.isNull()) {
  11694. Expr *RHSCheck = RHS.get();
  11695. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  11696. QualType LHSTy(LHSType);
  11697. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  11698. if (RHS.isInvalid())
  11699. return QualType();
  11700. // Special case of NSObject attributes on c-style pointer types.
  11701. if (ConvTy == IncompatiblePointer &&
  11702. ((Context.isObjCNSObjectType(LHSType) &&
  11703. RHSType->isObjCObjectPointerType()) ||
  11704. (Context.isObjCNSObjectType(RHSType) &&
  11705. LHSType->isObjCObjectPointerType())))
  11706. ConvTy = Compatible;
  11707. if (ConvTy == Compatible &&
  11708. LHSType->isObjCObjectType())
  11709. Diag(Loc, diag::err_objc_object_assignment)
  11710. << LHSType;
  11711. // If the RHS is a unary plus or minus, check to see if they = and + are
  11712. // right next to each other. If so, the user may have typo'd "x =+ 4"
  11713. // instead of "x += 4".
  11714. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  11715. RHSCheck = ICE->getSubExpr();
  11716. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  11717. if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
  11718. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  11719. // Only if the two operators are exactly adjacent.
  11720. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  11721. // And there is a space or other character before the subexpr of the
  11722. // unary +/-. We don't want to warn on "x=-1".
  11723. Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
  11724. UO->getSubExpr()->getBeginLoc().isFileID()) {
  11725. Diag(Loc, diag::warn_not_compound_assign)
  11726. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  11727. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  11728. }
  11729. }
  11730. if (ConvTy == Compatible) {
  11731. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  11732. // Warn about retain cycles where a block captures the LHS, but
  11733. // not if the LHS is a simple variable into which the block is
  11734. // being stored...unless that variable can be captured by reference!
  11735. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  11736. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  11737. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  11738. checkRetainCycles(LHSExpr, RHS.get());
  11739. }
  11740. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  11741. LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
  11742. // It is safe to assign a weak reference into a strong variable.
  11743. // Although this code can still have problems:
  11744. // id x = self.weakProp;
  11745. // id y = self.weakProp;
  11746. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  11747. // paths through the function. This should be revisited if
  11748. // -Wrepeated-use-of-weak is made flow-sensitive.
  11749. // For ObjCWeak only, we do not warn if the assign is to a non-weak
  11750. // variable, which will be valid for the current autorelease scope.
  11751. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  11752. RHS.get()->getBeginLoc()))
  11753. getCurFunction()->markSafeWeakUse(RHS.get());
  11754. } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
  11755. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  11756. }
  11757. }
  11758. } else {
  11759. // Compound assignment "x += y"
  11760. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  11761. }
  11762. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  11763. RHS.get(), AA_Assigning))
  11764. return QualType();
  11765. CheckForNullPointerDereference(*this, LHSExpr);
  11766. if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
  11767. if (CompoundType.isNull()) {
  11768. // C++2a [expr.ass]p5:
  11769. // A simple-assignment whose left operand is of a volatile-qualified
  11770. // type is deprecated unless the assignment is either a discarded-value
  11771. // expression or an unevaluated operand
  11772. ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
  11773. } else {
  11774. // C++2a [expr.ass]p6:
  11775. // [Compound-assignment] expressions are deprecated if E1 has
  11776. // volatile-qualified type
  11777. Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
  11778. }
  11779. }
  11780. // C99 6.5.16p3: The type of an assignment expression is the type of the
  11781. // left operand unless the left operand has qualified type, in which case
  11782. // it is the unqualified version of the type of the left operand.
  11783. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  11784. // is converted to the type of the assignment expression (above).
  11785. // C++ 5.17p1: the type of the assignment expression is that of its left
  11786. // operand.
  11787. return (getLangOpts().CPlusPlus
  11788. ? LHSType : LHSType.getUnqualifiedType());
  11789. }
  11790. // Only ignore explicit casts to void.
  11791. static bool IgnoreCommaOperand(const Expr *E) {
  11792. E = E->IgnoreParens();
  11793. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  11794. if (CE->getCastKind() == CK_ToVoid) {
  11795. return true;
  11796. }
  11797. // static_cast<void> on a dependent type will not show up as CK_ToVoid.
  11798. if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
  11799. CE->getSubExpr()->getType()->isDependentType()) {
  11800. return true;
  11801. }
  11802. }
  11803. return false;
  11804. }
  11805. // Look for instances where it is likely the comma operator is confused with
  11806. // another operator. There is an explicit list of acceptable expressions for
  11807. // the left hand side of the comma operator, otherwise emit a warning.
  11808. void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
  11809. // No warnings in macros
  11810. if (Loc.isMacroID())
  11811. return;
  11812. // Don't warn in template instantiations.
  11813. if (inTemplateInstantiation())
  11814. return;
  11815. // Scope isn't fine-grained enough to explicitly list the specific cases, so
  11816. // instead, skip more than needed, then call back into here with the
  11817. // CommaVisitor in SemaStmt.cpp.
  11818. // The listed locations are the initialization and increment portions
  11819. // of a for loop. The additional checks are on the condition of
  11820. // if statements, do/while loops, and for loops.
  11821. // Differences in scope flags for C89 mode requires the extra logic.
  11822. const unsigned ForIncrementFlags =
  11823. getLangOpts().C99 || getLangOpts().CPlusPlus
  11824. ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
  11825. : Scope::ContinueScope | Scope::BreakScope;
  11826. const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
  11827. const unsigned ScopeFlags = getCurScope()->getFlags();
  11828. if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
  11829. (ScopeFlags & ForInitFlags) == ForInitFlags)
  11830. return;
  11831. // If there are multiple comma operators used together, get the RHS of the
  11832. // of the comma operator as the LHS.
  11833. while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
  11834. if (BO->getOpcode() != BO_Comma)
  11835. break;
  11836. LHS = BO->getRHS();
  11837. }
  11838. // Only allow some expressions on LHS to not warn.
  11839. if (IgnoreCommaOperand(LHS))
  11840. return;
  11841. Diag(Loc, diag::warn_comma_operator);
  11842. Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
  11843. << LHS->getSourceRange()
  11844. << FixItHint::CreateInsertion(LHS->getBeginLoc(),
  11845. LangOpts.CPlusPlus ? "static_cast<void>("
  11846. : "(void)(")
  11847. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
  11848. ")");
  11849. }
  11850. // C99 6.5.17
  11851. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  11852. SourceLocation Loc) {
  11853. LHS = S.CheckPlaceholderExpr(LHS.get());
  11854. RHS = S.CheckPlaceholderExpr(RHS.get());
  11855. if (LHS.isInvalid() || RHS.isInvalid())
  11856. return QualType();
  11857. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  11858. // operands, but not unary promotions.
  11859. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  11860. // So we treat the LHS as a ignored value, and in C++ we allow the
  11861. // containing site to determine what should be done with the RHS.
  11862. LHS = S.IgnoredValueConversions(LHS.get());
  11863. if (LHS.isInvalid())
  11864. return QualType();
  11865. S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
  11866. if (!S.getLangOpts().CPlusPlus) {
  11867. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  11868. if (RHS.isInvalid())
  11869. return QualType();
  11870. if (!RHS.get()->getType()->isVoidType())
  11871. S.RequireCompleteType(Loc, RHS.get()->getType(),
  11872. diag::err_incomplete_type);
  11873. }
  11874. if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
  11875. S.DiagnoseCommaOperator(LHS.get(), Loc);
  11876. return RHS.get()->getType();
  11877. }
  11878. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  11879. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  11880. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  11881. ExprValueKind &VK,
  11882. ExprObjectKind &OK,
  11883. SourceLocation OpLoc,
  11884. bool IsInc, bool IsPrefix) {
  11885. if (Op->isTypeDependent())
  11886. return S.Context.DependentTy;
  11887. QualType ResType = Op->getType();
  11888. // Atomic types can be used for increment / decrement where the non-atomic
  11889. // versions can, so ignore the _Atomic() specifier for the purpose of
  11890. // checking.
  11891. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  11892. ResType = ResAtomicType->getValueType();
  11893. assert(!ResType.isNull() && "no type for increment/decrement expression");
  11894. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  11895. // Decrement of bool is not allowed.
  11896. if (!IsInc) {
  11897. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  11898. return QualType();
  11899. }
  11900. // Increment of bool sets it to true, but is deprecated.
  11901. S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
  11902. : diag::warn_increment_bool)
  11903. << Op->getSourceRange();
  11904. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  11905. // Error on enum increments and decrements in C++ mode
  11906. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  11907. return QualType();
  11908. } else if (ResType->isRealType()) {
  11909. // OK!
  11910. } else if (ResType->isPointerType()) {
  11911. // C99 6.5.2.4p2, 6.5.6p2
  11912. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  11913. return QualType();
  11914. } else if (ResType->isObjCObjectPointerType()) {
  11915. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  11916. // Otherwise, we just need a complete type.
  11917. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  11918. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  11919. return QualType();
  11920. } else if (ResType->isAnyComplexType()) {
  11921. // C99 does not support ++/-- on complex types, we allow as an extension.
  11922. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  11923. << ResType << Op->getSourceRange();
  11924. } else if (ResType->isPlaceholderType()) {
  11925. ExprResult PR = S.CheckPlaceholderExpr(Op);
  11926. if (PR.isInvalid()) return QualType();
  11927. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  11928. IsInc, IsPrefix);
  11929. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  11930. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  11931. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  11932. (ResType->castAs<VectorType>()->getVectorKind() !=
  11933. VectorType::AltiVecBool)) {
  11934. // The z vector extensions allow ++ and -- for non-bool vectors.
  11935. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  11936. ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
  11937. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  11938. } else {
  11939. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  11940. << ResType << int(IsInc) << Op->getSourceRange();
  11941. return QualType();
  11942. }
  11943. // At this point, we know we have a real, complex or pointer type.
  11944. // Now make sure the operand is a modifiable lvalue.
  11945. if (CheckForModifiableLvalue(Op, OpLoc, S))
  11946. return QualType();
  11947. if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
  11948. // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
  11949. // An operand with volatile-qualified type is deprecated
  11950. S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
  11951. << IsInc << ResType;
  11952. }
  11953. // In C++, a prefix increment is the same type as the operand. Otherwise
  11954. // (in C or with postfix), the increment is the unqualified type of the
  11955. // operand.
  11956. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  11957. VK = VK_LValue;
  11958. OK = Op->getObjectKind();
  11959. return ResType;
  11960. } else {
  11961. VK = VK_PRValue;
  11962. return ResType.getUnqualifiedType();
  11963. }
  11964. }
  11965. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  11966. /// This routine allows us to typecheck complex/recursive expressions
  11967. /// where the declaration is needed for type checking. We only need to
  11968. /// handle cases when the expression references a function designator
  11969. /// or is an lvalue. Here are some examples:
  11970. /// - &(x) => x
  11971. /// - &*****f => f for f a function designator.
  11972. /// - &s.xx => s
  11973. /// - &s.zz[1].yy -> s, if zz is an array
  11974. /// - *(x + 1) -> x, if x is an array
  11975. /// - &"123"[2] -> 0
  11976. /// - & __real__ x -> x
  11977. ///
  11978. /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
  11979. /// members.
  11980. static ValueDecl *getPrimaryDecl(Expr *E) {
  11981. switch (E->getStmtClass()) {
  11982. case Stmt::DeclRefExprClass:
  11983. return cast<DeclRefExpr>(E)->getDecl();
  11984. case Stmt::MemberExprClass:
  11985. // If this is an arrow operator, the address is an offset from
  11986. // the base's value, so the object the base refers to is
  11987. // irrelevant.
  11988. if (cast<MemberExpr>(E)->isArrow())
  11989. return nullptr;
  11990. // Otherwise, the expression refers to a part of the base
  11991. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  11992. case Stmt::ArraySubscriptExprClass: {
  11993. // FIXME: This code shouldn't be necessary! We should catch the implicit
  11994. // promotion of register arrays earlier.
  11995. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  11996. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  11997. if (ICE->getSubExpr()->getType()->isArrayType())
  11998. return getPrimaryDecl(ICE->getSubExpr());
  11999. }
  12000. return nullptr;
  12001. }
  12002. case Stmt::UnaryOperatorClass: {
  12003. UnaryOperator *UO = cast<UnaryOperator>(E);
  12004. switch(UO->getOpcode()) {
  12005. case UO_Real:
  12006. case UO_Imag:
  12007. case UO_Extension:
  12008. return getPrimaryDecl(UO->getSubExpr());
  12009. default:
  12010. return nullptr;
  12011. }
  12012. }
  12013. case Stmt::ParenExprClass:
  12014. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  12015. case Stmt::ImplicitCastExprClass:
  12016. // If the result of an implicit cast is an l-value, we care about
  12017. // the sub-expression; otherwise, the result here doesn't matter.
  12018. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  12019. case Stmt::CXXUuidofExprClass:
  12020. return cast<CXXUuidofExpr>(E)->getGuidDecl();
  12021. default:
  12022. return nullptr;
  12023. }
  12024. }
  12025. namespace {
  12026. enum {
  12027. AO_Bit_Field = 0,
  12028. AO_Vector_Element = 1,
  12029. AO_Property_Expansion = 2,
  12030. AO_Register_Variable = 3,
  12031. AO_Matrix_Element = 4,
  12032. AO_No_Error = 5
  12033. };
  12034. }
  12035. /// Diagnose invalid operand for address of operations.
  12036. ///
  12037. /// \param Type The type of operand which cannot have its address taken.
  12038. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  12039. Expr *E, unsigned Type) {
  12040. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  12041. }
  12042. /// CheckAddressOfOperand - The operand of & must be either a function
  12043. /// designator or an lvalue designating an object. If it is an lvalue, the
  12044. /// object cannot be declared with storage class register or be a bit field.
  12045. /// Note: The usual conversions are *not* applied to the operand of the &
  12046. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  12047. /// In C++, the operand might be an overloaded function name, in which case
  12048. /// we allow the '&' but retain the overloaded-function type.
  12049. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  12050. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  12051. if (PTy->getKind() == BuiltinType::Overload) {
  12052. Expr *E = OrigOp.get()->IgnoreParens();
  12053. if (!isa<OverloadExpr>(E)) {
  12054. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  12055. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  12056. << OrigOp.get()->getSourceRange();
  12057. return QualType();
  12058. }
  12059. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  12060. if (isa<UnresolvedMemberExpr>(Ovl))
  12061. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  12062. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  12063. << OrigOp.get()->getSourceRange();
  12064. return QualType();
  12065. }
  12066. return Context.OverloadTy;
  12067. }
  12068. if (PTy->getKind() == BuiltinType::UnknownAny)
  12069. return Context.UnknownAnyTy;
  12070. if (PTy->getKind() == BuiltinType::BoundMember) {
  12071. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  12072. << OrigOp.get()->getSourceRange();
  12073. return QualType();
  12074. }
  12075. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  12076. if (OrigOp.isInvalid()) return QualType();
  12077. }
  12078. if (OrigOp.get()->isTypeDependent())
  12079. return Context.DependentTy;
  12080. assert(!OrigOp.get()->hasPlaceholderType());
  12081. // Make sure to ignore parentheses in subsequent checks
  12082. Expr *op = OrigOp.get()->IgnoreParens();
  12083. // In OpenCL captures for blocks called as lambda functions
  12084. // are located in the private address space. Blocks used in
  12085. // enqueue_kernel can be located in a different address space
  12086. // depending on a vendor implementation. Thus preventing
  12087. // taking an address of the capture to avoid invalid AS casts.
  12088. if (LangOpts.OpenCL) {
  12089. auto* VarRef = dyn_cast<DeclRefExpr>(op);
  12090. if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
  12091. Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
  12092. return QualType();
  12093. }
  12094. }
  12095. if (getLangOpts().C99) {
  12096. // Implement C99-only parts of addressof rules.
  12097. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  12098. if (uOp->getOpcode() == UO_Deref)
  12099. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  12100. // (assuming the deref expression is valid).
  12101. return uOp->getSubExpr()->getType();
  12102. }
  12103. // Technically, there should be a check for array subscript
  12104. // expressions here, but the result of one is always an lvalue anyway.
  12105. }
  12106. ValueDecl *dcl = getPrimaryDecl(op);
  12107. if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
  12108. if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  12109. op->getBeginLoc()))
  12110. return QualType();
  12111. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  12112. unsigned AddressOfError = AO_No_Error;
  12113. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  12114. bool sfinae = (bool)isSFINAEContext();
  12115. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  12116. : diag::ext_typecheck_addrof_temporary)
  12117. << op->getType() << op->getSourceRange();
  12118. if (sfinae)
  12119. return QualType();
  12120. // Materialize the temporary as an lvalue so that we can take its address.
  12121. OrigOp = op =
  12122. CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  12123. } else if (isa<ObjCSelectorExpr>(op)) {
  12124. return Context.getPointerType(op->getType());
  12125. } else if (lval == Expr::LV_MemberFunction) {
  12126. // If it's an instance method, make a member pointer.
  12127. // The expression must have exactly the form &A::foo.
  12128. // If the underlying expression isn't a decl ref, give up.
  12129. if (!isa<DeclRefExpr>(op)) {
  12130. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  12131. << OrigOp.get()->getSourceRange();
  12132. return QualType();
  12133. }
  12134. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  12135. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  12136. // The id-expression was parenthesized.
  12137. if (OrigOp.get() != DRE) {
  12138. Diag(OpLoc, diag::err_parens_pointer_member_function)
  12139. << OrigOp.get()->getSourceRange();
  12140. // The method was named without a qualifier.
  12141. } else if (!DRE->getQualifier()) {
  12142. if (MD->getParent()->getName().empty())
  12143. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  12144. << op->getSourceRange();
  12145. else {
  12146. SmallString<32> Str;
  12147. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  12148. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  12149. << op->getSourceRange()
  12150. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  12151. }
  12152. }
  12153. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  12154. if (isa<CXXDestructorDecl>(MD))
  12155. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  12156. QualType MPTy = Context.getMemberPointerType(
  12157. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  12158. // Under the MS ABI, lock down the inheritance model now.
  12159. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  12160. (void)isCompleteType(OpLoc, MPTy);
  12161. return MPTy;
  12162. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  12163. // C99 6.5.3.2p1
  12164. // The operand must be either an l-value or a function designator
  12165. if (!op->getType()->isFunctionType()) {
  12166. // Use a special diagnostic for loads from property references.
  12167. if (isa<PseudoObjectExpr>(op)) {
  12168. AddressOfError = AO_Property_Expansion;
  12169. } else {
  12170. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  12171. << op->getType() << op->getSourceRange();
  12172. return QualType();
  12173. }
  12174. }
  12175. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  12176. // The operand cannot be a bit-field
  12177. AddressOfError = AO_Bit_Field;
  12178. } else if (op->getObjectKind() == OK_VectorComponent) {
  12179. // The operand cannot be an element of a vector
  12180. AddressOfError = AO_Vector_Element;
  12181. } else if (op->getObjectKind() == OK_MatrixComponent) {
  12182. // The operand cannot be an element of a matrix.
  12183. AddressOfError = AO_Matrix_Element;
  12184. } else if (dcl) { // C99 6.5.3.2p1
  12185. // We have an lvalue with a decl. Make sure the decl is not declared
  12186. // with the register storage-class specifier.
  12187. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  12188. // in C++ it is not error to take address of a register
  12189. // variable (c++03 7.1.1P3)
  12190. if (vd->getStorageClass() == SC_Register &&
  12191. !getLangOpts().CPlusPlus) {
  12192. AddressOfError = AO_Register_Variable;
  12193. }
  12194. } else if (isa<MSPropertyDecl>(dcl)) {
  12195. AddressOfError = AO_Property_Expansion;
  12196. } else if (isa<FunctionTemplateDecl>(dcl)) {
  12197. return Context.OverloadTy;
  12198. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  12199. // Okay: we can take the address of a field.
  12200. // Could be a pointer to member, though, if there is an explicit
  12201. // scope qualifier for the class.
  12202. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  12203. DeclContext *Ctx = dcl->getDeclContext();
  12204. if (Ctx && Ctx->isRecord()) {
  12205. if (dcl->getType()->isReferenceType()) {
  12206. Diag(OpLoc,
  12207. diag::err_cannot_form_pointer_to_member_of_reference_type)
  12208. << dcl->getDeclName() << dcl->getType();
  12209. return QualType();
  12210. }
  12211. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  12212. Ctx = Ctx->getParent();
  12213. QualType MPTy = Context.getMemberPointerType(
  12214. op->getType(),
  12215. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  12216. // Under the MS ABI, lock down the inheritance model now.
  12217. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  12218. (void)isCompleteType(OpLoc, MPTy);
  12219. return MPTy;
  12220. }
  12221. }
  12222. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
  12223. !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
  12224. llvm_unreachable("Unknown/unexpected decl type");
  12225. }
  12226. if (AddressOfError != AO_No_Error) {
  12227. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  12228. return QualType();
  12229. }
  12230. if (lval == Expr::LV_IncompleteVoidType) {
  12231. // Taking the address of a void variable is technically illegal, but we
  12232. // allow it in cases which are otherwise valid.
  12233. // Example: "extern void x; void* y = &x;".
  12234. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  12235. }
  12236. // If the operand has type "type", the result has type "pointer to type".
  12237. if (op->getType()->isObjCObjectType())
  12238. return Context.getObjCObjectPointerType(op->getType());
  12239. CheckAddressOfPackedMember(op);
  12240. return Context.getPointerType(op->getType());
  12241. }
  12242. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  12243. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  12244. if (!DRE)
  12245. return;
  12246. const Decl *D = DRE->getDecl();
  12247. if (!D)
  12248. return;
  12249. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  12250. if (!Param)
  12251. return;
  12252. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  12253. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  12254. return;
  12255. if (FunctionScopeInfo *FD = S.getCurFunction())
  12256. if (!FD->ModifiedNonNullParams.count(Param))
  12257. FD->ModifiedNonNullParams.insert(Param);
  12258. }
  12259. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  12260. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  12261. SourceLocation OpLoc) {
  12262. if (Op->isTypeDependent())
  12263. return S.Context.DependentTy;
  12264. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  12265. if (ConvResult.isInvalid())
  12266. return QualType();
  12267. Op = ConvResult.get();
  12268. QualType OpTy = Op->getType();
  12269. QualType Result;
  12270. if (isa<CXXReinterpretCastExpr>(Op)) {
  12271. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  12272. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  12273. Op->getSourceRange());
  12274. }
  12275. if (const PointerType *PT = OpTy->getAs<PointerType>())
  12276. {
  12277. Result = PT->getPointeeType();
  12278. }
  12279. else if (const ObjCObjectPointerType *OPT =
  12280. OpTy->getAs<ObjCObjectPointerType>())
  12281. Result = OPT->getPointeeType();
  12282. else {
  12283. ExprResult PR = S.CheckPlaceholderExpr(Op);
  12284. if (PR.isInvalid()) return QualType();
  12285. if (PR.get() != Op)
  12286. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  12287. }
  12288. if (Result.isNull()) {
  12289. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  12290. << OpTy << Op->getSourceRange();
  12291. return QualType();
  12292. }
  12293. // Note that per both C89 and C99, indirection is always legal, even if Result
  12294. // is an incomplete type or void. It would be possible to warn about
  12295. // dereferencing a void pointer, but it's completely well-defined, and such a
  12296. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  12297. // for pointers to 'void' but is fine for any other pointer type:
  12298. //
  12299. // C++ [expr.unary.op]p1:
  12300. // [...] the expression to which [the unary * operator] is applied shall
  12301. // be a pointer to an object type, or a pointer to a function type
  12302. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  12303. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  12304. << OpTy << Op->getSourceRange();
  12305. // Dereferences are usually l-values...
  12306. VK = VK_LValue;
  12307. // ...except that certain expressions are never l-values in C.
  12308. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  12309. VK = VK_PRValue;
  12310. return Result;
  12311. }
  12312. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  12313. BinaryOperatorKind Opc;
  12314. switch (Kind) {
  12315. default: llvm_unreachable("Unknown binop!");
  12316. case tok::periodstar: Opc = BO_PtrMemD; break;
  12317. case tok::arrowstar: Opc = BO_PtrMemI; break;
  12318. case tok::star: Opc = BO_Mul; break;
  12319. case tok::slash: Opc = BO_Div; break;
  12320. case tok::percent: Opc = BO_Rem; break;
  12321. case tok::plus: Opc = BO_Add; break;
  12322. case tok::minus: Opc = BO_Sub; break;
  12323. case tok::lessless: Opc = BO_Shl; break;
  12324. case tok::greatergreater: Opc = BO_Shr; break;
  12325. case tok::lessequal: Opc = BO_LE; break;
  12326. case tok::less: Opc = BO_LT; break;
  12327. case tok::greaterequal: Opc = BO_GE; break;
  12328. case tok::greater: Opc = BO_GT; break;
  12329. case tok::exclaimequal: Opc = BO_NE; break;
  12330. case tok::equalequal: Opc = BO_EQ; break;
  12331. case tok::spaceship: Opc = BO_Cmp; break;
  12332. case tok::amp: Opc = BO_And; break;
  12333. case tok::caret: Opc = BO_Xor; break;
  12334. case tok::pipe: Opc = BO_Or; break;
  12335. case tok::ampamp: Opc = BO_LAnd; break;
  12336. case tok::pipepipe: Opc = BO_LOr; break;
  12337. case tok::equal: Opc = BO_Assign; break;
  12338. case tok::starequal: Opc = BO_MulAssign; break;
  12339. case tok::slashequal: Opc = BO_DivAssign; break;
  12340. case tok::percentequal: Opc = BO_RemAssign; break;
  12341. case tok::plusequal: Opc = BO_AddAssign; break;
  12342. case tok::minusequal: Opc = BO_SubAssign; break;
  12343. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  12344. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  12345. case tok::ampequal: Opc = BO_AndAssign; break;
  12346. case tok::caretequal: Opc = BO_XorAssign; break;
  12347. case tok::pipeequal: Opc = BO_OrAssign; break;
  12348. case tok::comma: Opc = BO_Comma; break;
  12349. }
  12350. return Opc;
  12351. }
  12352. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  12353. tok::TokenKind Kind) {
  12354. UnaryOperatorKind Opc;
  12355. switch (Kind) {
  12356. default: llvm_unreachable("Unknown unary op!");
  12357. case tok::plusplus: Opc = UO_PreInc; break;
  12358. case tok::minusminus: Opc = UO_PreDec; break;
  12359. case tok::amp: Opc = UO_AddrOf; break;
  12360. case tok::star: Opc = UO_Deref; break;
  12361. case tok::plus: Opc = UO_Plus; break;
  12362. case tok::minus: Opc = UO_Minus; break;
  12363. case tok::tilde: Opc = UO_Not; break;
  12364. case tok::exclaim: Opc = UO_LNot; break;
  12365. case tok::kw___real: Opc = UO_Real; break;
  12366. case tok::kw___imag: Opc = UO_Imag; break;
  12367. case tok::kw___extension__: Opc = UO_Extension; break;
  12368. }
  12369. return Opc;
  12370. }
  12371. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  12372. /// This warning suppressed in the event of macro expansions.
  12373. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  12374. SourceLocation OpLoc, bool IsBuiltin) {
  12375. if (S.inTemplateInstantiation())
  12376. return;
  12377. if (S.isUnevaluatedContext())
  12378. return;
  12379. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  12380. return;
  12381. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  12382. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  12383. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  12384. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  12385. if (!LHSDeclRef || !RHSDeclRef ||
  12386. LHSDeclRef->getLocation().isMacroID() ||
  12387. RHSDeclRef->getLocation().isMacroID())
  12388. return;
  12389. const ValueDecl *LHSDecl =
  12390. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  12391. const ValueDecl *RHSDecl =
  12392. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  12393. if (LHSDecl != RHSDecl)
  12394. return;
  12395. if (LHSDecl->getType().isVolatileQualified())
  12396. return;
  12397. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  12398. if (RefTy->getPointeeType().isVolatileQualified())
  12399. return;
  12400. S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
  12401. : diag::warn_self_assignment_overloaded)
  12402. << LHSDeclRef->getType() << LHSExpr->getSourceRange()
  12403. << RHSExpr->getSourceRange();
  12404. }
  12405. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  12406. /// is usually indicative of introspection within the Objective-C pointer.
  12407. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  12408. SourceLocation OpLoc) {
  12409. if (!S.getLangOpts().ObjC)
  12410. return;
  12411. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  12412. const Expr *LHS = L.get();
  12413. const Expr *RHS = R.get();
  12414. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  12415. ObjCPointerExpr = LHS;
  12416. OtherExpr = RHS;
  12417. }
  12418. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  12419. ObjCPointerExpr = RHS;
  12420. OtherExpr = LHS;
  12421. }
  12422. // This warning is deliberately made very specific to reduce false
  12423. // positives with logic that uses '&' for hashing. This logic mainly
  12424. // looks for code trying to introspect into tagged pointers, which
  12425. // code should generally never do.
  12426. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  12427. unsigned Diag = diag::warn_objc_pointer_masking;
  12428. // Determine if we are introspecting the result of performSelectorXXX.
  12429. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  12430. // Special case messages to -performSelector and friends, which
  12431. // can return non-pointer values boxed in a pointer value.
  12432. // Some clients may wish to silence warnings in this subcase.
  12433. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  12434. Selector S = ME->getSelector();
  12435. StringRef SelArg0 = S.getNameForSlot(0);
  12436. if (SelArg0.startswith("performSelector"))
  12437. Diag = diag::warn_objc_pointer_masking_performSelector;
  12438. }
  12439. S.Diag(OpLoc, Diag)
  12440. << ObjCPointerExpr->getSourceRange();
  12441. }
  12442. }
  12443. static NamedDecl *getDeclFromExpr(Expr *E) {
  12444. if (!E)
  12445. return nullptr;
  12446. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  12447. return DRE->getDecl();
  12448. if (auto *ME = dyn_cast<MemberExpr>(E))
  12449. return ME->getMemberDecl();
  12450. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  12451. return IRE->getDecl();
  12452. return nullptr;
  12453. }
  12454. // This helper function promotes a binary operator's operands (which are of a
  12455. // half vector type) to a vector of floats and then truncates the result to
  12456. // a vector of either half or short.
  12457. static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
  12458. BinaryOperatorKind Opc, QualType ResultTy,
  12459. ExprValueKind VK, ExprObjectKind OK,
  12460. bool IsCompAssign, SourceLocation OpLoc,
  12461. FPOptionsOverride FPFeatures) {
  12462. auto &Context = S.getASTContext();
  12463. assert((isVector(ResultTy, Context.HalfTy) ||
  12464. isVector(ResultTy, Context.ShortTy)) &&
  12465. "Result must be a vector of half or short");
  12466. assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
  12467. isVector(RHS.get()->getType(), Context.HalfTy) &&
  12468. "both operands expected to be a half vector");
  12469. RHS = convertVector(RHS.get(), Context.FloatTy, S);
  12470. QualType BinOpResTy = RHS.get()->getType();
  12471. // If Opc is a comparison, ResultType is a vector of shorts. In that case,
  12472. // change BinOpResTy to a vector of ints.
  12473. if (isVector(ResultTy, Context.ShortTy))
  12474. BinOpResTy = S.GetSignedVectorType(BinOpResTy);
  12475. if (IsCompAssign)
  12476. return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
  12477. ResultTy, VK, OK, OpLoc, FPFeatures,
  12478. BinOpResTy, BinOpResTy);
  12479. LHS = convertVector(LHS.get(), Context.FloatTy, S);
  12480. auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
  12481. BinOpResTy, VK, OK, OpLoc, FPFeatures);
  12482. return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
  12483. }
  12484. static std::pair<ExprResult, ExprResult>
  12485. CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
  12486. Expr *RHSExpr) {
  12487. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  12488. if (!S.Context.isDependenceAllowed()) {
  12489. // C cannot handle TypoExpr nodes on either side of a binop because it
  12490. // doesn't handle dependent types properly, so make sure any TypoExprs have
  12491. // been dealt with before checking the operands.
  12492. LHS = S.CorrectDelayedTyposInExpr(LHS);
  12493. RHS = S.CorrectDelayedTyposInExpr(
  12494. RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
  12495. [Opc, LHS](Expr *E) {
  12496. if (Opc != BO_Assign)
  12497. return ExprResult(E);
  12498. // Avoid correcting the RHS to the same Expr as the LHS.
  12499. Decl *D = getDeclFromExpr(E);
  12500. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  12501. });
  12502. }
  12503. return std::make_pair(LHS, RHS);
  12504. }
  12505. /// Returns true if conversion between vectors of halfs and vectors of floats
  12506. /// is needed.
  12507. static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
  12508. Expr *E0, Expr *E1 = nullptr) {
  12509. if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
  12510. Ctx.getTargetInfo().useFP16ConversionIntrinsics())
  12511. return false;
  12512. auto HasVectorOfHalfType = [&Ctx](Expr *E) {
  12513. QualType Ty = E->IgnoreImplicit()->getType();
  12514. // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
  12515. // to vectors of floats. Although the element type of the vectors is __fp16,
  12516. // the vectors shouldn't be treated as storage-only types. See the
  12517. // discussion here: https://reviews.llvm.org/rG825235c140e7
  12518. if (const VectorType *VT = Ty->getAs<VectorType>()) {
  12519. if (VT->getVectorKind() == VectorType::NeonVector)
  12520. return false;
  12521. return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
  12522. }
  12523. return false;
  12524. };
  12525. return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
  12526. }
  12527. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  12528. /// operator @p Opc at location @c TokLoc. This routine only supports
  12529. /// built-in operations; ActOnBinOp handles overloaded operators.
  12530. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  12531. BinaryOperatorKind Opc,
  12532. Expr *LHSExpr, Expr *RHSExpr) {
  12533. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  12534. // The syntax only allows initializer lists on the RHS of assignment,
  12535. // so we don't need to worry about accepting invalid code for
  12536. // non-assignment operators.
  12537. // C++11 5.17p9:
  12538. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  12539. // of x = {} is x = T().
  12540. InitializationKind Kind = InitializationKind::CreateDirectList(
  12541. RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  12542. InitializedEntity Entity =
  12543. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  12544. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  12545. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  12546. if (Init.isInvalid())
  12547. return Init;
  12548. RHSExpr = Init.get();
  12549. }
  12550. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  12551. QualType ResultTy; // Result type of the binary operator.
  12552. // The following two variables are used for compound assignment operators
  12553. QualType CompLHSTy; // Type of LHS after promotions for computation
  12554. QualType CompResultTy; // Type of computation result
  12555. ExprValueKind VK = VK_PRValue;
  12556. ExprObjectKind OK = OK_Ordinary;
  12557. bool ConvertHalfVec = false;
  12558. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  12559. if (!LHS.isUsable() || !RHS.isUsable())
  12560. return ExprError();
  12561. if (getLangOpts().OpenCL) {
  12562. QualType LHSTy = LHSExpr->getType();
  12563. QualType RHSTy = RHSExpr->getType();
  12564. // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
  12565. // the ATOMIC_VAR_INIT macro.
  12566. if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
  12567. SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  12568. if (BO_Assign == Opc)
  12569. Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
  12570. else
  12571. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  12572. return ExprError();
  12573. }
  12574. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  12575. // only with a builtin functions and therefore should be disallowed here.
  12576. if (LHSTy->isImageType() || RHSTy->isImageType() ||
  12577. LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
  12578. LHSTy->isPipeType() || RHSTy->isPipeType() ||
  12579. LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
  12580. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  12581. return ExprError();
  12582. }
  12583. }
  12584. checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
  12585. checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
  12586. switch (Opc) {
  12587. case BO_Assign:
  12588. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  12589. if (getLangOpts().CPlusPlus &&
  12590. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  12591. VK = LHS.get()->getValueKind();
  12592. OK = LHS.get()->getObjectKind();
  12593. }
  12594. if (!ResultTy.isNull()) {
  12595. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  12596. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  12597. // Avoid copying a block to the heap if the block is assigned to a local
  12598. // auto variable that is declared in the same scope as the block. This
  12599. // optimization is unsafe if the local variable is declared in an outer
  12600. // scope. For example:
  12601. //
  12602. // BlockTy b;
  12603. // {
  12604. // b = ^{...};
  12605. // }
  12606. // // It is unsafe to invoke the block here if it wasn't copied to the
  12607. // // heap.
  12608. // b();
  12609. if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
  12610. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
  12611. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  12612. if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
  12613. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  12614. if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
  12615. checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
  12616. NTCUC_Assignment, NTCUK_Copy);
  12617. }
  12618. RecordModifiableNonNullParam(*this, LHS.get());
  12619. break;
  12620. case BO_PtrMemD:
  12621. case BO_PtrMemI:
  12622. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  12623. Opc == BO_PtrMemI);
  12624. break;
  12625. case BO_Mul:
  12626. case BO_Div:
  12627. ConvertHalfVec = true;
  12628. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  12629. Opc == BO_Div);
  12630. break;
  12631. case BO_Rem:
  12632. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  12633. break;
  12634. case BO_Add:
  12635. ConvertHalfVec = true;
  12636. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  12637. break;
  12638. case BO_Sub:
  12639. ConvertHalfVec = true;
  12640. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  12641. break;
  12642. case BO_Shl:
  12643. case BO_Shr:
  12644. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  12645. break;
  12646. case BO_LE:
  12647. case BO_LT:
  12648. case BO_GE:
  12649. case BO_GT:
  12650. ConvertHalfVec = true;
  12651. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  12652. break;
  12653. case BO_EQ:
  12654. case BO_NE:
  12655. ConvertHalfVec = true;
  12656. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  12657. break;
  12658. case BO_Cmp:
  12659. ConvertHalfVec = true;
  12660. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  12661. assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
  12662. break;
  12663. case BO_And:
  12664. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  12665. LLVM_FALLTHROUGH;
  12666. case BO_Xor:
  12667. case BO_Or:
  12668. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  12669. break;
  12670. case BO_LAnd:
  12671. case BO_LOr:
  12672. ConvertHalfVec = true;
  12673. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  12674. break;
  12675. case BO_MulAssign:
  12676. case BO_DivAssign:
  12677. ConvertHalfVec = true;
  12678. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  12679. Opc == BO_DivAssign);
  12680. CompLHSTy = CompResultTy;
  12681. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  12682. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  12683. break;
  12684. case BO_RemAssign:
  12685. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  12686. CompLHSTy = CompResultTy;
  12687. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  12688. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  12689. break;
  12690. case BO_AddAssign:
  12691. ConvertHalfVec = true;
  12692. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  12693. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  12694. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  12695. break;
  12696. case BO_SubAssign:
  12697. ConvertHalfVec = true;
  12698. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  12699. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  12700. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  12701. break;
  12702. case BO_ShlAssign:
  12703. case BO_ShrAssign:
  12704. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  12705. CompLHSTy = CompResultTy;
  12706. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  12707. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  12708. break;
  12709. case BO_AndAssign:
  12710. case BO_OrAssign: // fallthrough
  12711. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  12712. LLVM_FALLTHROUGH;
  12713. case BO_XorAssign:
  12714. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  12715. CompLHSTy = CompResultTy;
  12716. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  12717. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  12718. break;
  12719. case BO_Comma:
  12720. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  12721. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  12722. VK = RHS.get()->getValueKind();
  12723. OK = RHS.get()->getObjectKind();
  12724. }
  12725. break;
  12726. }
  12727. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  12728. return ExprError();
  12729. // Some of the binary operations require promoting operands of half vector to
  12730. // float vectors and truncating the result back to half vector. For now, we do
  12731. // this only when HalfArgsAndReturn is set (that is, when the target is arm or
  12732. // arm64).
  12733. assert(
  12734. (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
  12735. isVector(LHS.get()->getType(), Context.HalfTy)) &&
  12736. "both sides are half vectors or neither sides are");
  12737. ConvertHalfVec =
  12738. needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
  12739. // Check for array bounds violations for both sides of the BinaryOperator
  12740. CheckArrayAccess(LHS.get());
  12741. CheckArrayAccess(RHS.get());
  12742. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  12743. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  12744. &Context.Idents.get("object_setClass"),
  12745. SourceLocation(), LookupOrdinaryName);
  12746. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  12747. SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
  12748. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
  12749. << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
  12750. "object_setClass(")
  12751. << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
  12752. ",")
  12753. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  12754. }
  12755. else
  12756. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  12757. }
  12758. else if (const ObjCIvarRefExpr *OIRE =
  12759. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  12760. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  12761. // Opc is not a compound assignment if CompResultTy is null.
  12762. if (CompResultTy.isNull()) {
  12763. if (ConvertHalfVec)
  12764. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
  12765. OpLoc, CurFPFeatureOverrides());
  12766. return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
  12767. VK, OK, OpLoc, CurFPFeatureOverrides());
  12768. }
  12769. // Handle compound assignments.
  12770. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  12771. OK_ObjCProperty) {
  12772. VK = VK_LValue;
  12773. OK = LHS.get()->getObjectKind();
  12774. }
  12775. // The LHS is not converted to the result type for fixed-point compound
  12776. // assignment as the common type is computed on demand. Reset the CompLHSTy
  12777. // to the LHS type we would have gotten after unary conversions.
  12778. if (CompResultTy->isFixedPointType())
  12779. CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
  12780. if (ConvertHalfVec)
  12781. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
  12782. OpLoc, CurFPFeatureOverrides());
  12783. return CompoundAssignOperator::Create(
  12784. Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
  12785. CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
  12786. }
  12787. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  12788. /// operators are mixed in a way that suggests that the programmer forgot that
  12789. /// comparison operators have higher precedence. The most typical example of
  12790. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  12791. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  12792. SourceLocation OpLoc, Expr *LHSExpr,
  12793. Expr *RHSExpr) {
  12794. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  12795. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  12796. // Check that one of the sides is a comparison operator and the other isn't.
  12797. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  12798. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  12799. if (isLeftComp == isRightComp)
  12800. return;
  12801. // Bitwise operations are sometimes used as eager logical ops.
  12802. // Don't diagnose this.
  12803. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  12804. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  12805. if (isLeftBitwise || isRightBitwise)
  12806. return;
  12807. SourceRange DiagRange = isLeftComp
  12808. ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
  12809. : SourceRange(OpLoc, RHSExpr->getEndLoc());
  12810. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  12811. SourceRange ParensRange =
  12812. isLeftComp
  12813. ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
  12814. : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
  12815. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  12816. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  12817. SuggestParentheses(Self, OpLoc,
  12818. Self.PDiag(diag::note_precedence_silence) << OpStr,
  12819. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  12820. SuggestParentheses(Self, OpLoc,
  12821. Self.PDiag(diag::note_precedence_bitwise_first)
  12822. << BinaryOperator::getOpcodeStr(Opc),
  12823. ParensRange);
  12824. }
  12825. /// It accepts a '&&' expr that is inside a '||' one.
  12826. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  12827. /// in parentheses.
  12828. static void
  12829. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  12830. BinaryOperator *Bop) {
  12831. assert(Bop->getOpcode() == BO_LAnd);
  12832. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  12833. << Bop->getSourceRange() << OpLoc;
  12834. SuggestParentheses(Self, Bop->getOperatorLoc(),
  12835. Self.PDiag(diag::note_precedence_silence)
  12836. << Bop->getOpcodeStr(),
  12837. Bop->getSourceRange());
  12838. }
  12839. /// Returns true if the given expression can be evaluated as a constant
  12840. /// 'true'.
  12841. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  12842. bool Res;
  12843. return !E->isValueDependent() &&
  12844. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  12845. }
  12846. /// Returns true if the given expression can be evaluated as a constant
  12847. /// 'false'.
  12848. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  12849. bool Res;
  12850. return !E->isValueDependent() &&
  12851. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  12852. }
  12853. /// Look for '&&' in the left hand of a '||' expr.
  12854. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  12855. Expr *LHSExpr, Expr *RHSExpr) {
  12856. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  12857. if (Bop->getOpcode() == BO_LAnd) {
  12858. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  12859. if (EvaluatesAsFalse(S, RHSExpr))
  12860. return;
  12861. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  12862. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  12863. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  12864. } else if (Bop->getOpcode() == BO_LOr) {
  12865. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  12866. // If it's "a || b && 1 || c" we didn't warn earlier for
  12867. // "a || b && 1", but warn now.
  12868. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  12869. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  12870. }
  12871. }
  12872. }
  12873. }
  12874. /// Look for '&&' in the right hand of a '||' expr.
  12875. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  12876. Expr *LHSExpr, Expr *RHSExpr) {
  12877. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  12878. if (Bop->getOpcode() == BO_LAnd) {
  12879. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  12880. if (EvaluatesAsFalse(S, LHSExpr))
  12881. return;
  12882. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  12883. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  12884. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  12885. }
  12886. }
  12887. }
  12888. /// Look for bitwise op in the left or right hand of a bitwise op with
  12889. /// lower precedence and emit a diagnostic together with a fixit hint that wraps
  12890. /// the '&' expression in parentheses.
  12891. static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
  12892. SourceLocation OpLoc, Expr *SubExpr) {
  12893. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  12894. if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
  12895. S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
  12896. << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
  12897. << Bop->getSourceRange() << OpLoc;
  12898. SuggestParentheses(S, Bop->getOperatorLoc(),
  12899. S.PDiag(diag::note_precedence_silence)
  12900. << Bop->getOpcodeStr(),
  12901. Bop->getSourceRange());
  12902. }
  12903. }
  12904. }
  12905. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  12906. Expr *SubExpr, StringRef Shift) {
  12907. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  12908. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  12909. StringRef Op = Bop->getOpcodeStr();
  12910. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  12911. << Bop->getSourceRange() << OpLoc << Shift << Op;
  12912. SuggestParentheses(S, Bop->getOperatorLoc(),
  12913. S.PDiag(diag::note_precedence_silence) << Op,
  12914. Bop->getSourceRange());
  12915. }
  12916. }
  12917. }
  12918. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  12919. Expr *LHSExpr, Expr *RHSExpr) {
  12920. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  12921. if (!OCE)
  12922. return;
  12923. FunctionDecl *FD = OCE->getDirectCallee();
  12924. if (!FD || !FD->isOverloadedOperator())
  12925. return;
  12926. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  12927. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  12928. return;
  12929. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  12930. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  12931. << (Kind == OO_LessLess);
  12932. SuggestParentheses(S, OCE->getOperatorLoc(),
  12933. S.PDiag(diag::note_precedence_silence)
  12934. << (Kind == OO_LessLess ? "<<" : ">>"),
  12935. OCE->getSourceRange());
  12936. SuggestParentheses(
  12937. S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
  12938. SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
  12939. }
  12940. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  12941. /// precedence.
  12942. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  12943. SourceLocation OpLoc, Expr *LHSExpr,
  12944. Expr *RHSExpr){
  12945. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  12946. if (BinaryOperator::isBitwiseOp(Opc))
  12947. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  12948. // Diagnose "arg1 & arg2 | arg3"
  12949. if ((Opc == BO_Or || Opc == BO_Xor) &&
  12950. !OpLoc.isMacroID()/* Don't warn in macros. */) {
  12951. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
  12952. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
  12953. }
  12954. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  12955. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  12956. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  12957. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  12958. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  12959. }
  12960. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  12961. || Opc == BO_Shr) {
  12962. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  12963. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  12964. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  12965. }
  12966. // Warn on overloaded shift operators and comparisons, such as:
  12967. // cout << 5 == 4;
  12968. if (BinaryOperator::isComparisonOp(Opc))
  12969. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  12970. }
  12971. // Binary Operators. 'Tok' is the token for the operator.
  12972. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  12973. tok::TokenKind Kind,
  12974. Expr *LHSExpr, Expr *RHSExpr) {
  12975. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  12976. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  12977. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  12978. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  12979. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  12980. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  12981. }
  12982. void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
  12983. UnresolvedSetImpl &Functions) {
  12984. OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
  12985. if (OverOp != OO_None && OverOp != OO_Equal)
  12986. LookupOverloadedOperatorName(OverOp, S, Functions);
  12987. // In C++20 onwards, we may have a second operator to look up.
  12988. if (getLangOpts().CPlusPlus20) {
  12989. if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
  12990. LookupOverloadedOperatorName(ExtraOp, S, Functions);
  12991. }
  12992. }
  12993. /// Build an overloaded binary operator expression in the given scope.
  12994. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  12995. BinaryOperatorKind Opc,
  12996. Expr *LHS, Expr *RHS) {
  12997. switch (Opc) {
  12998. case BO_Assign:
  12999. case BO_DivAssign:
  13000. case BO_RemAssign:
  13001. case BO_SubAssign:
  13002. case BO_AndAssign:
  13003. case BO_OrAssign:
  13004. case BO_XorAssign:
  13005. DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
  13006. CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
  13007. break;
  13008. default:
  13009. break;
  13010. }
  13011. // Find all of the overloaded operators visible from this point.
  13012. UnresolvedSet<16> Functions;
  13013. S.LookupBinOp(Sc, OpLoc, Opc, Functions);
  13014. // Build the (potentially-overloaded, potentially-dependent)
  13015. // binary operation.
  13016. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  13017. }
  13018. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  13019. BinaryOperatorKind Opc,
  13020. Expr *LHSExpr, Expr *RHSExpr) {
  13021. ExprResult LHS, RHS;
  13022. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  13023. if (!LHS.isUsable() || !RHS.isUsable())
  13024. return ExprError();
  13025. LHSExpr = LHS.get();
  13026. RHSExpr = RHS.get();
  13027. // We want to end up calling one of checkPseudoObjectAssignment
  13028. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  13029. // both expressions are overloadable or either is type-dependent),
  13030. // or CreateBuiltinBinOp (in any other case). We also want to get
  13031. // any placeholder types out of the way.
  13032. // Handle pseudo-objects in the LHS.
  13033. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  13034. // Assignments with a pseudo-object l-value need special analysis.
  13035. if (pty->getKind() == BuiltinType::PseudoObject &&
  13036. BinaryOperator::isAssignmentOp(Opc))
  13037. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  13038. // Don't resolve overloads if the other type is overloadable.
  13039. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
  13040. // We can't actually test that if we still have a placeholder,
  13041. // though. Fortunately, none of the exceptions we see in that
  13042. // code below are valid when the LHS is an overload set. Note
  13043. // that an overload set can be dependently-typed, but it never
  13044. // instantiates to having an overloadable type.
  13045. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  13046. if (resolvedRHS.isInvalid()) return ExprError();
  13047. RHSExpr = resolvedRHS.get();
  13048. if (RHSExpr->isTypeDependent() ||
  13049. RHSExpr->getType()->isOverloadableType())
  13050. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  13051. }
  13052. // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
  13053. // template, diagnose the missing 'template' keyword instead of diagnosing
  13054. // an invalid use of a bound member function.
  13055. //
  13056. // Note that "A::x < b" might be valid if 'b' has an overloadable type due
  13057. // to C++1z [over.over]/1.4, but we already checked for that case above.
  13058. if (Opc == BO_LT && inTemplateInstantiation() &&
  13059. (pty->getKind() == BuiltinType::BoundMember ||
  13060. pty->getKind() == BuiltinType::Overload)) {
  13061. auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
  13062. if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
  13063. std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
  13064. return isa<FunctionTemplateDecl>(ND);
  13065. })) {
  13066. Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
  13067. : OE->getNameLoc(),
  13068. diag::err_template_kw_missing)
  13069. << OE->getName().getAsString() << "";
  13070. return ExprError();
  13071. }
  13072. }
  13073. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  13074. if (LHS.isInvalid()) return ExprError();
  13075. LHSExpr = LHS.get();
  13076. }
  13077. // Handle pseudo-objects in the RHS.
  13078. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  13079. // An overload in the RHS can potentially be resolved by the type
  13080. // being assigned to.
  13081. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  13082. if (getLangOpts().CPlusPlus &&
  13083. (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
  13084. LHSExpr->getType()->isOverloadableType()))
  13085. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  13086. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  13087. }
  13088. // Don't resolve overloads if the other type is overloadable.
  13089. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
  13090. LHSExpr->getType()->isOverloadableType())
  13091. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  13092. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  13093. if (!resolvedRHS.isUsable()) return ExprError();
  13094. RHSExpr = resolvedRHS.get();
  13095. }
  13096. if (getLangOpts().CPlusPlus) {
  13097. // If either expression is type-dependent, always build an
  13098. // overloaded op.
  13099. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  13100. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  13101. // Otherwise, build an overloaded op if either expression has an
  13102. // overloadable type.
  13103. if (LHSExpr->getType()->isOverloadableType() ||
  13104. RHSExpr->getType()->isOverloadableType())
  13105. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  13106. }
  13107. if (getLangOpts().RecoveryAST &&
  13108. (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
  13109. assert(!getLangOpts().CPlusPlus);
  13110. assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
  13111. "Should only occur in error-recovery path.");
  13112. if (BinaryOperator::isCompoundAssignmentOp(Opc))
  13113. // C [6.15.16] p3:
  13114. // An assignment expression has the value of the left operand after the
  13115. // assignment, but is not an lvalue.
  13116. return CompoundAssignOperator::Create(
  13117. Context, LHSExpr, RHSExpr, Opc,
  13118. LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
  13119. OpLoc, CurFPFeatureOverrides());
  13120. QualType ResultType;
  13121. switch (Opc) {
  13122. case BO_Assign:
  13123. ResultType = LHSExpr->getType().getUnqualifiedType();
  13124. break;
  13125. case BO_LT:
  13126. case BO_GT:
  13127. case BO_LE:
  13128. case BO_GE:
  13129. case BO_EQ:
  13130. case BO_NE:
  13131. case BO_LAnd:
  13132. case BO_LOr:
  13133. // These operators have a fixed result type regardless of operands.
  13134. ResultType = Context.IntTy;
  13135. break;
  13136. case BO_Comma:
  13137. ResultType = RHSExpr->getType();
  13138. break;
  13139. default:
  13140. ResultType = Context.DependentTy;
  13141. break;
  13142. }
  13143. return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
  13144. VK_PRValue, OK_Ordinary, OpLoc,
  13145. CurFPFeatureOverrides());
  13146. }
  13147. // Build a built-in binary operation.
  13148. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  13149. }
  13150. static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
  13151. if (T.isNull() || T->isDependentType())
  13152. return false;
  13153. if (!T->isPromotableIntegerType())
  13154. return true;
  13155. return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
  13156. }
  13157. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  13158. UnaryOperatorKind Opc,
  13159. Expr *InputExpr) {
  13160. ExprResult Input = InputExpr;
  13161. ExprValueKind VK = VK_PRValue;
  13162. ExprObjectKind OK = OK_Ordinary;
  13163. QualType resultType;
  13164. bool CanOverflow = false;
  13165. bool ConvertHalfVec = false;
  13166. if (getLangOpts().OpenCL) {
  13167. QualType Ty = InputExpr->getType();
  13168. // The only legal unary operation for atomics is '&'.
  13169. if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
  13170. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  13171. // only with a builtin functions and therefore should be disallowed here.
  13172. (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
  13173. || Ty->isBlockPointerType())) {
  13174. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  13175. << InputExpr->getType()
  13176. << Input.get()->getSourceRange());
  13177. }
  13178. }
  13179. switch (Opc) {
  13180. case UO_PreInc:
  13181. case UO_PreDec:
  13182. case UO_PostInc:
  13183. case UO_PostDec:
  13184. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  13185. OpLoc,
  13186. Opc == UO_PreInc ||
  13187. Opc == UO_PostInc,
  13188. Opc == UO_PreInc ||
  13189. Opc == UO_PreDec);
  13190. CanOverflow = isOverflowingIntegerType(Context, resultType);
  13191. break;
  13192. case UO_AddrOf:
  13193. resultType = CheckAddressOfOperand(Input, OpLoc);
  13194. CheckAddressOfNoDeref(InputExpr);
  13195. RecordModifiableNonNullParam(*this, InputExpr);
  13196. break;
  13197. case UO_Deref: {
  13198. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  13199. if (Input.isInvalid()) return ExprError();
  13200. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  13201. break;
  13202. }
  13203. case UO_Plus:
  13204. case UO_Minus:
  13205. CanOverflow = Opc == UO_Minus &&
  13206. isOverflowingIntegerType(Context, Input.get()->getType());
  13207. Input = UsualUnaryConversions(Input.get());
  13208. if (Input.isInvalid()) return ExprError();
  13209. // Unary plus and minus require promoting an operand of half vector to a
  13210. // float vector and truncating the result back to a half vector. For now, we
  13211. // do this only when HalfArgsAndReturns is set (that is, when the target is
  13212. // arm or arm64).
  13213. ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
  13214. // If the operand is a half vector, promote it to a float vector.
  13215. if (ConvertHalfVec)
  13216. Input = convertVector(Input.get(), Context.FloatTy, *this);
  13217. resultType = Input.get()->getType();
  13218. if (resultType->isDependentType())
  13219. break;
  13220. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  13221. break;
  13222. else if (resultType->isVectorType() &&
  13223. // The z vector extensions don't allow + or - with bool vectors.
  13224. (!Context.getLangOpts().ZVector ||
  13225. resultType->castAs<VectorType>()->getVectorKind() !=
  13226. VectorType::AltiVecBool))
  13227. break;
  13228. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  13229. Opc == UO_Plus &&
  13230. resultType->isPointerType())
  13231. break;
  13232. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  13233. << resultType << Input.get()->getSourceRange());
  13234. case UO_Not: // bitwise complement
  13235. Input = UsualUnaryConversions(Input.get());
  13236. if (Input.isInvalid())
  13237. return ExprError();
  13238. resultType = Input.get()->getType();
  13239. if (resultType->isDependentType())
  13240. break;
  13241. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  13242. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  13243. // C99 does not support '~' for complex conjugation.
  13244. Diag(OpLoc, diag::ext_integer_complement_complex)
  13245. << resultType << Input.get()->getSourceRange();
  13246. else if (resultType->hasIntegerRepresentation())
  13247. break;
  13248. else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
  13249. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  13250. // on vector float types.
  13251. QualType T = resultType->castAs<ExtVectorType>()->getElementType();
  13252. if (!T->isIntegerType())
  13253. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  13254. << resultType << Input.get()->getSourceRange());
  13255. } else {
  13256. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  13257. << resultType << Input.get()->getSourceRange());
  13258. }
  13259. break;
  13260. case UO_LNot: // logical negation
  13261. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  13262. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  13263. if (Input.isInvalid()) return ExprError();
  13264. resultType = Input.get()->getType();
  13265. // Though we still have to promote half FP to float...
  13266. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  13267. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  13268. resultType = Context.FloatTy;
  13269. }
  13270. if (resultType->isDependentType())
  13271. break;
  13272. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  13273. // C99 6.5.3.3p1: ok, fallthrough;
  13274. if (Context.getLangOpts().CPlusPlus) {
  13275. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  13276. // operand contextually converted to bool.
  13277. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  13278. ScalarTypeToBooleanCastKind(resultType));
  13279. } else if (Context.getLangOpts().OpenCL &&
  13280. Context.getLangOpts().OpenCLVersion < 120) {
  13281. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  13282. // operate on scalar float types.
  13283. if (!resultType->isIntegerType() && !resultType->isPointerType())
  13284. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  13285. << resultType << Input.get()->getSourceRange());
  13286. }
  13287. } else if (resultType->isExtVectorType()) {
  13288. if (Context.getLangOpts().OpenCL &&
  13289. Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
  13290. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  13291. // operate on vector float types.
  13292. QualType T = resultType->castAs<ExtVectorType>()->getElementType();
  13293. if (!T->isIntegerType())
  13294. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  13295. << resultType << Input.get()->getSourceRange());
  13296. }
  13297. // Vector logical not returns the signed variant of the operand type.
  13298. resultType = GetSignedVectorType(resultType);
  13299. break;
  13300. } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
  13301. const VectorType *VTy = resultType->castAs<VectorType>();
  13302. if (VTy->getVectorKind() != VectorType::GenericVector)
  13303. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  13304. << resultType << Input.get()->getSourceRange());
  13305. // Vector logical not returns the signed variant of the operand type.
  13306. resultType = GetSignedVectorType(resultType);
  13307. break;
  13308. } else {
  13309. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  13310. << resultType << Input.get()->getSourceRange());
  13311. }
  13312. // LNot always has type int. C99 6.5.3.3p5.
  13313. // In C++, it's bool. C++ 5.3.1p8
  13314. resultType = Context.getLogicalOperationType();
  13315. break;
  13316. case UO_Real:
  13317. case UO_Imag:
  13318. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  13319. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  13320. // complex l-values to ordinary l-values and all other values to r-values.
  13321. if (Input.isInvalid()) return ExprError();
  13322. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  13323. if (Input.get()->isGLValue() &&
  13324. Input.get()->getObjectKind() == OK_Ordinary)
  13325. VK = Input.get()->getValueKind();
  13326. } else if (!getLangOpts().CPlusPlus) {
  13327. // In C, a volatile scalar is read by __imag. In C++, it is not.
  13328. Input = DefaultLvalueConversion(Input.get());
  13329. }
  13330. break;
  13331. case UO_Extension:
  13332. resultType = Input.get()->getType();
  13333. VK = Input.get()->getValueKind();
  13334. OK = Input.get()->getObjectKind();
  13335. break;
  13336. case UO_Coawait:
  13337. // It's unnecessary to represent the pass-through operator co_await in the
  13338. // AST; just return the input expression instead.
  13339. assert(!Input.get()->getType()->isDependentType() &&
  13340. "the co_await expression must be non-dependant before "
  13341. "building operator co_await");
  13342. return Input;
  13343. }
  13344. if (resultType.isNull() || Input.isInvalid())
  13345. return ExprError();
  13346. // Check for array bounds violations in the operand of the UnaryOperator,
  13347. // except for the '*' and '&' operators that have to be handled specially
  13348. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  13349. // that are explicitly defined as valid by the standard).
  13350. if (Opc != UO_AddrOf && Opc != UO_Deref)
  13351. CheckArrayAccess(Input.get());
  13352. auto *UO =
  13353. UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
  13354. OpLoc, CanOverflow, CurFPFeatureOverrides());
  13355. if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
  13356. !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
  13357. !isUnevaluatedContext())
  13358. ExprEvalContexts.back().PossibleDerefs.insert(UO);
  13359. // Convert the result back to a half vector.
  13360. if (ConvertHalfVec)
  13361. return convertVector(UO, Context.HalfTy, *this);
  13362. return UO;
  13363. }
  13364. /// Determine whether the given expression is a qualified member
  13365. /// access expression, of a form that could be turned into a pointer to member
  13366. /// with the address-of operator.
  13367. bool Sema::isQualifiedMemberAccess(Expr *E) {
  13368. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  13369. if (!DRE->getQualifier())
  13370. return false;
  13371. ValueDecl *VD = DRE->getDecl();
  13372. if (!VD->isCXXClassMember())
  13373. return false;
  13374. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  13375. return true;
  13376. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  13377. return Method->isInstance();
  13378. return false;
  13379. }
  13380. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  13381. if (!ULE->getQualifier())
  13382. return false;
  13383. for (NamedDecl *D : ULE->decls()) {
  13384. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  13385. if (Method->isInstance())
  13386. return true;
  13387. } else {
  13388. // Overload set does not contain methods.
  13389. break;
  13390. }
  13391. }
  13392. return false;
  13393. }
  13394. return false;
  13395. }
  13396. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  13397. UnaryOperatorKind Opc, Expr *Input) {
  13398. // First things first: handle placeholders so that the
  13399. // overloaded-operator check considers the right type.
  13400. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  13401. // Increment and decrement of pseudo-object references.
  13402. if (pty->getKind() == BuiltinType::PseudoObject &&
  13403. UnaryOperator::isIncrementDecrementOp(Opc))
  13404. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  13405. // extension is always a builtin operator.
  13406. if (Opc == UO_Extension)
  13407. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  13408. // & gets special logic for several kinds of placeholder.
  13409. // The builtin code knows what to do.
  13410. if (Opc == UO_AddrOf &&
  13411. (pty->getKind() == BuiltinType::Overload ||
  13412. pty->getKind() == BuiltinType::UnknownAny ||
  13413. pty->getKind() == BuiltinType::BoundMember))
  13414. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  13415. // Anything else needs to be handled now.
  13416. ExprResult Result = CheckPlaceholderExpr(Input);
  13417. if (Result.isInvalid()) return ExprError();
  13418. Input = Result.get();
  13419. }
  13420. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  13421. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  13422. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  13423. // Find all of the overloaded operators visible from this point.
  13424. UnresolvedSet<16> Functions;
  13425. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  13426. if (S && OverOp != OO_None)
  13427. LookupOverloadedOperatorName(OverOp, S, Functions);
  13428. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  13429. }
  13430. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  13431. }
  13432. // Unary Operators. 'Tok' is the token for the operator.
  13433. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  13434. tok::TokenKind Op, Expr *Input) {
  13435. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  13436. }
  13437. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  13438. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  13439. LabelDecl *TheDecl) {
  13440. TheDecl->markUsed(Context);
  13441. // Create the AST node. The address of a label always has type 'void*'.
  13442. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  13443. Context.getPointerType(Context.VoidTy));
  13444. }
  13445. void Sema::ActOnStartStmtExpr() {
  13446. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  13447. }
  13448. void Sema::ActOnStmtExprError() {
  13449. // Note that function is also called by TreeTransform when leaving a
  13450. // StmtExpr scope without rebuilding anything.
  13451. DiscardCleanupsInEvaluationContext();
  13452. PopExpressionEvaluationContext();
  13453. }
  13454. ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
  13455. SourceLocation RPLoc) {
  13456. return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
  13457. }
  13458. ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  13459. SourceLocation RPLoc, unsigned TemplateDepth) {
  13460. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  13461. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  13462. if (hasAnyUnrecoverableErrorsInThisFunction())
  13463. DiscardCleanupsInEvaluationContext();
  13464. assert(!Cleanup.exprNeedsCleanups() &&
  13465. "cleanups within StmtExpr not correctly bound!");
  13466. PopExpressionEvaluationContext();
  13467. // FIXME: there are a variety of strange constraints to enforce here, for
  13468. // example, it is not possible to goto into a stmt expression apparently.
  13469. // More semantic analysis is needed.
  13470. // If there are sub-stmts in the compound stmt, take the type of the last one
  13471. // as the type of the stmtexpr.
  13472. QualType Ty = Context.VoidTy;
  13473. bool StmtExprMayBindToTemp = false;
  13474. if (!Compound->body_empty()) {
  13475. // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
  13476. if (const auto *LastStmt =
  13477. dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
  13478. if (const Expr *Value = LastStmt->getExprStmt()) {
  13479. StmtExprMayBindToTemp = true;
  13480. Ty = Value->getType();
  13481. }
  13482. }
  13483. }
  13484. // FIXME: Check that expression type is complete/non-abstract; statement
  13485. // expressions are not lvalues.
  13486. Expr *ResStmtExpr =
  13487. new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
  13488. if (StmtExprMayBindToTemp)
  13489. return MaybeBindToTemporary(ResStmtExpr);
  13490. return ResStmtExpr;
  13491. }
  13492. ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
  13493. if (ER.isInvalid())
  13494. return ExprError();
  13495. // Do function/array conversion on the last expression, but not
  13496. // lvalue-to-rvalue. However, initialize an unqualified type.
  13497. ER = DefaultFunctionArrayConversion(ER.get());
  13498. if (ER.isInvalid())
  13499. return ExprError();
  13500. Expr *E = ER.get();
  13501. if (E->isTypeDependent())
  13502. return E;
  13503. // In ARC, if the final expression ends in a consume, splice
  13504. // the consume out and bind it later. In the alternate case
  13505. // (when dealing with a retainable type), the result
  13506. // initialization will create a produce. In both cases the
  13507. // result will be +1, and we'll need to balance that out with
  13508. // a bind.
  13509. auto *Cast = dyn_cast<ImplicitCastExpr>(E);
  13510. if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
  13511. return Cast->getSubExpr();
  13512. // FIXME: Provide a better location for the initialization.
  13513. return PerformCopyInitialization(
  13514. InitializedEntity::InitializeStmtExprResult(
  13515. E->getBeginLoc(), E->getType().getUnqualifiedType()),
  13516. SourceLocation(), E);
  13517. }
  13518. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  13519. TypeSourceInfo *TInfo,
  13520. ArrayRef<OffsetOfComponent> Components,
  13521. SourceLocation RParenLoc) {
  13522. QualType ArgTy = TInfo->getType();
  13523. bool Dependent = ArgTy->isDependentType();
  13524. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  13525. // We must have at least one component that refers to the type, and the first
  13526. // one is known to be a field designator. Verify that the ArgTy represents
  13527. // a struct/union/class.
  13528. if (!Dependent && !ArgTy->isRecordType())
  13529. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  13530. << ArgTy << TypeRange);
  13531. // Type must be complete per C99 7.17p3 because a declaring a variable
  13532. // with an incomplete type would be ill-formed.
  13533. if (!Dependent
  13534. && RequireCompleteType(BuiltinLoc, ArgTy,
  13535. diag::err_offsetof_incomplete_type, TypeRange))
  13536. return ExprError();
  13537. bool DidWarnAboutNonPOD = false;
  13538. QualType CurrentType = ArgTy;
  13539. SmallVector<OffsetOfNode, 4> Comps;
  13540. SmallVector<Expr*, 4> Exprs;
  13541. for (const OffsetOfComponent &OC : Components) {
  13542. if (OC.isBrackets) {
  13543. // Offset of an array sub-field. TODO: Should we allow vector elements?
  13544. if (!CurrentType->isDependentType()) {
  13545. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  13546. if(!AT)
  13547. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  13548. << CurrentType);
  13549. CurrentType = AT->getElementType();
  13550. } else
  13551. CurrentType = Context.DependentTy;
  13552. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  13553. if (IdxRval.isInvalid())
  13554. return ExprError();
  13555. Expr *Idx = IdxRval.get();
  13556. // The expression must be an integral expression.
  13557. // FIXME: An integral constant expression?
  13558. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  13559. !Idx->getType()->isIntegerType())
  13560. return ExprError(
  13561. Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
  13562. << Idx->getSourceRange());
  13563. // Record this array index.
  13564. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  13565. Exprs.push_back(Idx);
  13566. continue;
  13567. }
  13568. // Offset of a field.
  13569. if (CurrentType->isDependentType()) {
  13570. // We have the offset of a field, but we can't look into the dependent
  13571. // type. Just record the identifier of the field.
  13572. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  13573. CurrentType = Context.DependentTy;
  13574. continue;
  13575. }
  13576. // We need to have a complete type to look into.
  13577. if (RequireCompleteType(OC.LocStart, CurrentType,
  13578. diag::err_offsetof_incomplete_type))
  13579. return ExprError();
  13580. // Look for the designated field.
  13581. const RecordType *RC = CurrentType->getAs<RecordType>();
  13582. if (!RC)
  13583. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  13584. << CurrentType);
  13585. RecordDecl *RD = RC->getDecl();
  13586. // C++ [lib.support.types]p5:
  13587. // The macro offsetof accepts a restricted set of type arguments in this
  13588. // International Standard. type shall be a POD structure or a POD union
  13589. // (clause 9).
  13590. // C++11 [support.types]p4:
  13591. // If type is not a standard-layout class (Clause 9), the results are
  13592. // undefined.
  13593. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  13594. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  13595. unsigned DiagID =
  13596. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  13597. : diag::ext_offsetof_non_pod_type;
  13598. if (!IsSafe && !DidWarnAboutNonPOD &&
  13599. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  13600. PDiag(DiagID)
  13601. << SourceRange(Components[0].LocStart, OC.LocEnd)
  13602. << CurrentType))
  13603. DidWarnAboutNonPOD = true;
  13604. }
  13605. // Look for the field.
  13606. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  13607. LookupQualifiedName(R, RD);
  13608. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  13609. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  13610. if (!MemberDecl) {
  13611. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  13612. MemberDecl = IndirectMemberDecl->getAnonField();
  13613. }
  13614. if (!MemberDecl)
  13615. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  13616. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  13617. OC.LocEnd));
  13618. // C99 7.17p3:
  13619. // (If the specified member is a bit-field, the behavior is undefined.)
  13620. //
  13621. // We diagnose this as an error.
  13622. if (MemberDecl->isBitField()) {
  13623. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  13624. << MemberDecl->getDeclName()
  13625. << SourceRange(BuiltinLoc, RParenLoc);
  13626. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  13627. return ExprError();
  13628. }
  13629. RecordDecl *Parent = MemberDecl->getParent();
  13630. if (IndirectMemberDecl)
  13631. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  13632. // If the member was found in a base class, introduce OffsetOfNodes for
  13633. // the base class indirections.
  13634. CXXBasePaths Paths;
  13635. if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
  13636. Paths)) {
  13637. if (Paths.getDetectedVirtual()) {
  13638. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  13639. << MemberDecl->getDeclName()
  13640. << SourceRange(BuiltinLoc, RParenLoc);
  13641. return ExprError();
  13642. }
  13643. CXXBasePath &Path = Paths.front();
  13644. for (const CXXBasePathElement &B : Path)
  13645. Comps.push_back(OffsetOfNode(B.Base));
  13646. }
  13647. if (IndirectMemberDecl) {
  13648. for (auto *FI : IndirectMemberDecl->chain()) {
  13649. assert(isa<FieldDecl>(FI));
  13650. Comps.push_back(OffsetOfNode(OC.LocStart,
  13651. cast<FieldDecl>(FI), OC.LocEnd));
  13652. }
  13653. } else
  13654. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  13655. CurrentType = MemberDecl->getType().getNonReferenceType();
  13656. }
  13657. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  13658. Comps, Exprs, RParenLoc);
  13659. }
  13660. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  13661. SourceLocation BuiltinLoc,
  13662. SourceLocation TypeLoc,
  13663. ParsedType ParsedArgTy,
  13664. ArrayRef<OffsetOfComponent> Components,
  13665. SourceLocation RParenLoc) {
  13666. TypeSourceInfo *ArgTInfo;
  13667. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  13668. if (ArgTy.isNull())
  13669. return ExprError();
  13670. if (!ArgTInfo)
  13671. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  13672. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
  13673. }
  13674. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  13675. Expr *CondExpr,
  13676. Expr *LHSExpr, Expr *RHSExpr,
  13677. SourceLocation RPLoc) {
  13678. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  13679. ExprValueKind VK = VK_PRValue;
  13680. ExprObjectKind OK = OK_Ordinary;
  13681. QualType resType;
  13682. bool CondIsTrue = false;
  13683. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  13684. resType = Context.DependentTy;
  13685. } else {
  13686. // The conditional expression is required to be a constant expression.
  13687. llvm::APSInt condEval(32);
  13688. ExprResult CondICE = VerifyIntegerConstantExpression(
  13689. CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
  13690. if (CondICE.isInvalid())
  13691. return ExprError();
  13692. CondExpr = CondICE.get();
  13693. CondIsTrue = condEval.getZExtValue();
  13694. // If the condition is > zero, then the AST type is the same as the LHSExpr.
  13695. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  13696. resType = ActiveExpr->getType();
  13697. VK = ActiveExpr->getValueKind();
  13698. OK = ActiveExpr->getObjectKind();
  13699. }
  13700. return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
  13701. resType, VK, OK, RPLoc, CondIsTrue);
  13702. }
  13703. //===----------------------------------------------------------------------===//
  13704. // Clang Extensions.
  13705. //===----------------------------------------------------------------------===//
  13706. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  13707. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  13708. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  13709. if (LangOpts.CPlusPlus) {
  13710. MangleNumberingContext *MCtx;
  13711. Decl *ManglingContextDecl;
  13712. std::tie(MCtx, ManglingContextDecl) =
  13713. getCurrentMangleNumberContext(Block->getDeclContext());
  13714. if (MCtx) {
  13715. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  13716. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  13717. }
  13718. }
  13719. PushBlockScope(CurScope, Block);
  13720. CurContext->addDecl(Block);
  13721. if (CurScope)
  13722. PushDeclContext(CurScope, Block);
  13723. else
  13724. CurContext = Block;
  13725. getCurBlock()->HasImplicitReturnType = true;
  13726. // Enter a new evaluation context to insulate the block from any
  13727. // cleanups from the enclosing full-expression.
  13728. PushExpressionEvaluationContext(
  13729. ExpressionEvaluationContext::PotentiallyEvaluated);
  13730. }
  13731. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  13732. Scope *CurScope) {
  13733. assert(ParamInfo.getIdentifier() == nullptr &&
  13734. "block-id should have no identifier!");
  13735. assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
  13736. BlockScopeInfo *CurBlock = getCurBlock();
  13737. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  13738. QualType T = Sig->getType();
  13739. // FIXME: We should allow unexpanded parameter packs here, but that would,
  13740. // in turn, make the block expression contain unexpanded parameter packs.
  13741. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  13742. // Drop the parameters.
  13743. FunctionProtoType::ExtProtoInfo EPI;
  13744. EPI.HasTrailingReturn = false;
  13745. EPI.TypeQuals.addConst();
  13746. T = Context.getFunctionType(Context.DependentTy, None, EPI);
  13747. Sig = Context.getTrivialTypeSourceInfo(T);
  13748. }
  13749. // GetTypeForDeclarator always produces a function type for a block
  13750. // literal signature. Furthermore, it is always a FunctionProtoType
  13751. // unless the function was written with a typedef.
  13752. assert(T->isFunctionType() &&
  13753. "GetTypeForDeclarator made a non-function block signature");
  13754. // Look for an explicit signature in that function type.
  13755. FunctionProtoTypeLoc ExplicitSignature;
  13756. if ((ExplicitSignature = Sig->getTypeLoc()
  13757. .getAsAdjusted<FunctionProtoTypeLoc>())) {
  13758. // Check whether that explicit signature was synthesized by
  13759. // GetTypeForDeclarator. If so, don't save that as part of the
  13760. // written signature.
  13761. if (ExplicitSignature.getLocalRangeBegin() ==
  13762. ExplicitSignature.getLocalRangeEnd()) {
  13763. // This would be much cheaper if we stored TypeLocs instead of
  13764. // TypeSourceInfos.
  13765. TypeLoc Result = ExplicitSignature.getReturnLoc();
  13766. unsigned Size = Result.getFullDataSize();
  13767. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  13768. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  13769. ExplicitSignature = FunctionProtoTypeLoc();
  13770. }
  13771. }
  13772. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  13773. CurBlock->FunctionType = T;
  13774. const auto *Fn = T->castAs<FunctionType>();
  13775. QualType RetTy = Fn->getReturnType();
  13776. bool isVariadic =
  13777. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  13778. CurBlock->TheDecl->setIsVariadic(isVariadic);
  13779. // Context.DependentTy is used as a placeholder for a missing block
  13780. // return type. TODO: what should we do with declarators like:
  13781. // ^ * { ... }
  13782. // If the answer is "apply template argument deduction"....
  13783. if (RetTy != Context.DependentTy) {
  13784. CurBlock->ReturnType = RetTy;
  13785. CurBlock->TheDecl->setBlockMissingReturnType(false);
  13786. CurBlock->HasImplicitReturnType = false;
  13787. }
  13788. // Push block parameters from the declarator if we had them.
  13789. SmallVector<ParmVarDecl*, 8> Params;
  13790. if (ExplicitSignature) {
  13791. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  13792. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  13793. if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
  13794. !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
  13795. // Diagnose this as an extension in C17 and earlier.
  13796. if (!getLangOpts().C2x)
  13797. Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
  13798. }
  13799. Params.push_back(Param);
  13800. }
  13801. // Fake up parameter variables if we have a typedef, like
  13802. // ^ fntype { ... }
  13803. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  13804. for (const auto &I : Fn->param_types()) {
  13805. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  13806. CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
  13807. Params.push_back(Param);
  13808. }
  13809. }
  13810. // Set the parameters on the block decl.
  13811. if (!Params.empty()) {
  13812. CurBlock->TheDecl->setParams(Params);
  13813. CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
  13814. /*CheckParameterNames=*/false);
  13815. }
  13816. // Finally we can process decl attributes.
  13817. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  13818. // Put the parameter variables in scope.
  13819. for (auto AI : CurBlock->TheDecl->parameters()) {
  13820. AI->setOwningFunction(CurBlock->TheDecl);
  13821. // If this has an identifier, add it to the scope stack.
  13822. if (AI->getIdentifier()) {
  13823. CheckShadow(CurBlock->TheScope, AI);
  13824. PushOnScopeChains(AI, CurBlock->TheScope);
  13825. }
  13826. }
  13827. }
  13828. /// ActOnBlockError - If there is an error parsing a block, this callback
  13829. /// is invoked to pop the information about the block from the action impl.
  13830. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  13831. // Leave the expression-evaluation context.
  13832. DiscardCleanupsInEvaluationContext();
  13833. PopExpressionEvaluationContext();
  13834. // Pop off CurBlock, handle nested blocks.
  13835. PopDeclContext();
  13836. PopFunctionScopeInfo();
  13837. }
  13838. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  13839. /// literal was successfully completed. ^(int x){...}
  13840. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  13841. Stmt *Body, Scope *CurScope) {
  13842. // If blocks are disabled, emit an error.
  13843. if (!LangOpts.Blocks)
  13844. Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
  13845. // Leave the expression-evaluation context.
  13846. if (hasAnyUnrecoverableErrorsInThisFunction())
  13847. DiscardCleanupsInEvaluationContext();
  13848. assert(!Cleanup.exprNeedsCleanups() &&
  13849. "cleanups within block not correctly bound!");
  13850. PopExpressionEvaluationContext();
  13851. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  13852. BlockDecl *BD = BSI->TheDecl;
  13853. if (BSI->HasImplicitReturnType)
  13854. deduceClosureReturnType(*BSI);
  13855. QualType RetTy = Context.VoidTy;
  13856. if (!BSI->ReturnType.isNull())
  13857. RetTy = BSI->ReturnType;
  13858. bool NoReturn = BD->hasAttr<NoReturnAttr>();
  13859. QualType BlockTy;
  13860. // If the user wrote a function type in some form, try to use that.
  13861. if (!BSI->FunctionType.isNull()) {
  13862. const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
  13863. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  13864. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  13865. // Turn protoless block types into nullary block types.
  13866. if (isa<FunctionNoProtoType>(FTy)) {
  13867. FunctionProtoType::ExtProtoInfo EPI;
  13868. EPI.ExtInfo = Ext;
  13869. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  13870. // Otherwise, if we don't need to change anything about the function type,
  13871. // preserve its sugar structure.
  13872. } else if (FTy->getReturnType() == RetTy &&
  13873. (!NoReturn || FTy->getNoReturnAttr())) {
  13874. BlockTy = BSI->FunctionType;
  13875. // Otherwise, make the minimal modifications to the function type.
  13876. } else {
  13877. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  13878. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  13879. EPI.TypeQuals = Qualifiers();
  13880. EPI.ExtInfo = Ext;
  13881. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  13882. }
  13883. // If we don't have a function type, just build one from nothing.
  13884. } else {
  13885. FunctionProtoType::ExtProtoInfo EPI;
  13886. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  13887. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  13888. }
  13889. DiagnoseUnusedParameters(BD->parameters());
  13890. BlockTy = Context.getBlockPointerType(BlockTy);
  13891. // If needed, diagnose invalid gotos and switches in the block.
  13892. if (getCurFunction()->NeedsScopeChecking() &&
  13893. !PP.isCodeCompletionEnabled())
  13894. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  13895. BD->setBody(cast<CompoundStmt>(Body));
  13896. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  13897. DiagnoseUnguardedAvailabilityViolations(BD);
  13898. // Try to apply the named return value optimization. We have to check again
  13899. // if we can do this, though, because blocks keep return statements around
  13900. // to deduce an implicit return type.
  13901. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  13902. !BD->isDependentContext())
  13903. computeNRVO(Body, BSI);
  13904. if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
  13905. RetTy.hasNonTrivialToPrimitiveCopyCUnion())
  13906. checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
  13907. NTCUK_Destruct|NTCUK_Copy);
  13908. PopDeclContext();
  13909. // Set the captured variables on the block.
  13910. SmallVector<BlockDecl::Capture, 4> Captures;
  13911. for (Capture &Cap : BSI->Captures) {
  13912. if (Cap.isInvalid() || Cap.isThisCapture())
  13913. continue;
  13914. VarDecl *Var = Cap.getVariable();
  13915. Expr *CopyExpr = nullptr;
  13916. if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
  13917. if (const RecordType *Record =
  13918. Cap.getCaptureType()->getAs<RecordType>()) {
  13919. // The capture logic needs the destructor, so make sure we mark it.
  13920. // Usually this is unnecessary because most local variables have
  13921. // their destructors marked at declaration time, but parameters are
  13922. // an exception because it's technically only the call site that
  13923. // actually requires the destructor.
  13924. if (isa<ParmVarDecl>(Var))
  13925. FinalizeVarWithDestructor(Var, Record);
  13926. // Enter a separate potentially-evaluated context while building block
  13927. // initializers to isolate their cleanups from those of the block
  13928. // itself.
  13929. // FIXME: Is this appropriate even when the block itself occurs in an
  13930. // unevaluated operand?
  13931. EnterExpressionEvaluationContext EvalContext(
  13932. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  13933. SourceLocation Loc = Cap.getLocation();
  13934. ExprResult Result = BuildDeclarationNameExpr(
  13935. CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
  13936. // According to the blocks spec, the capture of a variable from
  13937. // the stack requires a const copy constructor. This is not true
  13938. // of the copy/move done to move a __block variable to the heap.
  13939. if (!Result.isInvalid() &&
  13940. !Result.get()->getType().isConstQualified()) {
  13941. Result = ImpCastExprToType(Result.get(),
  13942. Result.get()->getType().withConst(),
  13943. CK_NoOp, VK_LValue);
  13944. }
  13945. if (!Result.isInvalid()) {
  13946. Result = PerformCopyInitialization(
  13947. InitializedEntity::InitializeBlock(Var->getLocation(),
  13948. Cap.getCaptureType()),
  13949. Loc, Result.get());
  13950. }
  13951. // Build a full-expression copy expression if initialization
  13952. // succeeded and used a non-trivial constructor. Recover from
  13953. // errors by pretending that the copy isn't necessary.
  13954. if (!Result.isInvalid() &&
  13955. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  13956. ->isTrivial()) {
  13957. Result = MaybeCreateExprWithCleanups(Result);
  13958. CopyExpr = Result.get();
  13959. }
  13960. }
  13961. }
  13962. BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
  13963. CopyExpr);
  13964. Captures.push_back(NewCap);
  13965. }
  13966. BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
  13967. // Pop the block scope now but keep it alive to the end of this function.
  13968. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  13969. PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
  13970. BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
  13971. // If the block isn't obviously global, i.e. it captures anything at
  13972. // all, then we need to do a few things in the surrounding context:
  13973. if (Result->getBlockDecl()->hasCaptures()) {
  13974. // First, this expression has a new cleanup object.
  13975. ExprCleanupObjects.push_back(Result->getBlockDecl());
  13976. Cleanup.setExprNeedsCleanups(true);
  13977. // It also gets a branch-protected scope if any of the captured
  13978. // variables needs destruction.
  13979. for (const auto &CI : Result->getBlockDecl()->captures()) {
  13980. const VarDecl *var = CI.getVariable();
  13981. if (var->getType().isDestructedType() != QualType::DK_none) {
  13982. setFunctionHasBranchProtectedScope();
  13983. break;
  13984. }
  13985. }
  13986. }
  13987. if (getCurFunction())
  13988. getCurFunction()->addBlock(BD);
  13989. return Result;
  13990. }
  13991. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
  13992. SourceLocation RPLoc) {
  13993. TypeSourceInfo *TInfo;
  13994. GetTypeFromParser(Ty, &TInfo);
  13995. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  13996. }
  13997. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  13998. Expr *E, TypeSourceInfo *TInfo,
  13999. SourceLocation RPLoc) {
  14000. Expr *OrigExpr = E;
  14001. bool IsMS = false;
  14002. // CUDA device code does not support varargs.
  14003. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  14004. if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
  14005. CUDAFunctionTarget T = IdentifyCUDATarget(F);
  14006. if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
  14007. return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
  14008. }
  14009. }
  14010. // NVPTX does not support va_arg expression.
  14011. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  14012. Context.getTargetInfo().getTriple().isNVPTX())
  14013. targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
  14014. // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
  14015. // as Microsoft ABI on an actual Microsoft platform, where
  14016. // __builtin_ms_va_list and __builtin_va_list are the same.)
  14017. if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
  14018. Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
  14019. QualType MSVaListType = Context.getBuiltinMSVaListType();
  14020. if (Context.hasSameType(MSVaListType, E->getType())) {
  14021. if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
  14022. return ExprError();
  14023. IsMS = true;
  14024. }
  14025. }
  14026. // Get the va_list type
  14027. QualType VaListType = Context.getBuiltinVaListType();
  14028. if (!IsMS) {
  14029. if (VaListType->isArrayType()) {
  14030. // Deal with implicit array decay; for example, on x86-64,
  14031. // va_list is an array, but it's supposed to decay to
  14032. // a pointer for va_arg.
  14033. VaListType = Context.getArrayDecayedType(VaListType);
  14034. // Make sure the input expression also decays appropriately.
  14035. ExprResult Result = UsualUnaryConversions(E);
  14036. if (Result.isInvalid())
  14037. return ExprError();
  14038. E = Result.get();
  14039. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  14040. // If va_list is a record type and we are compiling in C++ mode,
  14041. // check the argument using reference binding.
  14042. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  14043. Context, Context.getLValueReferenceType(VaListType), false);
  14044. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  14045. if (Init.isInvalid())
  14046. return ExprError();
  14047. E = Init.getAs<Expr>();
  14048. } else {
  14049. // Otherwise, the va_list argument must be an l-value because
  14050. // it is modified by va_arg.
  14051. if (!E->isTypeDependent() &&
  14052. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  14053. return ExprError();
  14054. }
  14055. }
  14056. if (!IsMS && !E->isTypeDependent() &&
  14057. !Context.hasSameType(VaListType, E->getType()))
  14058. return ExprError(
  14059. Diag(E->getBeginLoc(),
  14060. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  14061. << OrigExpr->getType() << E->getSourceRange());
  14062. if (!TInfo->getType()->isDependentType()) {
  14063. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  14064. diag::err_second_parameter_to_va_arg_incomplete,
  14065. TInfo->getTypeLoc()))
  14066. return ExprError();
  14067. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  14068. TInfo->getType(),
  14069. diag::err_second_parameter_to_va_arg_abstract,
  14070. TInfo->getTypeLoc()))
  14071. return ExprError();
  14072. if (!TInfo->getType().isPODType(Context)) {
  14073. Diag(TInfo->getTypeLoc().getBeginLoc(),
  14074. TInfo->getType()->isObjCLifetimeType()
  14075. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  14076. : diag::warn_second_parameter_to_va_arg_not_pod)
  14077. << TInfo->getType()
  14078. << TInfo->getTypeLoc().getSourceRange();
  14079. }
  14080. // Check for va_arg where arguments of the given type will be promoted
  14081. // (i.e. this va_arg is guaranteed to have undefined behavior).
  14082. QualType PromoteType;
  14083. if (TInfo->getType()->isPromotableIntegerType()) {
  14084. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  14085. // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
  14086. // and C2x 7.16.1.1p2 says, in part:
  14087. // If type is not compatible with the type of the actual next argument
  14088. // (as promoted according to the default argument promotions), the
  14089. // behavior is undefined, except for the following cases:
  14090. // - both types are pointers to qualified or unqualified versions of
  14091. // compatible types;
  14092. // - one type is a signed integer type, the other type is the
  14093. // corresponding unsigned integer type, and the value is
  14094. // representable in both types;
  14095. // - one type is pointer to qualified or unqualified void and the
  14096. // other is a pointer to a qualified or unqualified character type.
  14097. // Given that type compatibility is the primary requirement (ignoring
  14098. // qualifications), you would think we could call typesAreCompatible()
  14099. // directly to test this. However, in C++, that checks for *same type*,
  14100. // which causes false positives when passing an enumeration type to
  14101. // va_arg. Instead, get the underlying type of the enumeration and pass
  14102. // that.
  14103. QualType UnderlyingType = TInfo->getType();
  14104. if (const auto *ET = UnderlyingType->getAs<EnumType>())
  14105. UnderlyingType = ET->getDecl()->getIntegerType();
  14106. if (Context.typesAreCompatible(PromoteType, UnderlyingType,
  14107. /*CompareUnqualified*/ true))
  14108. PromoteType = QualType();
  14109. // If the types are still not compatible, we need to test whether the
  14110. // promoted type and the underlying type are the same except for
  14111. // signedness. Ask the AST for the correctly corresponding type and see
  14112. // if that's compatible.
  14113. if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
  14114. PromoteType->isUnsignedIntegerType() !=
  14115. UnderlyingType->isUnsignedIntegerType()) {
  14116. UnderlyingType =
  14117. UnderlyingType->isUnsignedIntegerType()
  14118. ? Context.getCorrespondingSignedType(UnderlyingType)
  14119. : Context.getCorrespondingUnsignedType(UnderlyingType);
  14120. if (Context.typesAreCompatible(PromoteType, UnderlyingType,
  14121. /*CompareUnqualified*/ true))
  14122. PromoteType = QualType();
  14123. }
  14124. }
  14125. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  14126. PromoteType = Context.DoubleTy;
  14127. if (!PromoteType.isNull())
  14128. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  14129. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  14130. << TInfo->getType()
  14131. << PromoteType
  14132. << TInfo->getTypeLoc().getSourceRange());
  14133. }
  14134. QualType T = TInfo->getType().getNonLValueExprType(Context);
  14135. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
  14136. }
  14137. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  14138. // The type of __null will be int or long, depending on the size of
  14139. // pointers on the target.
  14140. QualType Ty;
  14141. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  14142. if (pw == Context.getTargetInfo().getIntWidth())
  14143. Ty = Context.IntTy;
  14144. else if (pw == Context.getTargetInfo().getLongWidth())
  14145. Ty = Context.LongTy;
  14146. else if (pw == Context.getTargetInfo().getLongLongWidth())
  14147. Ty = Context.LongLongTy;
  14148. else {
  14149. llvm_unreachable("I don't know size of pointer!");
  14150. }
  14151. return new (Context) GNUNullExpr(Ty, TokenLoc);
  14152. }
  14153. ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
  14154. SourceLocation BuiltinLoc,
  14155. SourceLocation RPLoc) {
  14156. return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
  14157. }
  14158. ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
  14159. SourceLocation BuiltinLoc,
  14160. SourceLocation RPLoc,
  14161. DeclContext *ParentContext) {
  14162. return new (Context)
  14163. SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
  14164. }
  14165. bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
  14166. bool Diagnose) {
  14167. if (!getLangOpts().ObjC)
  14168. return false;
  14169. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  14170. if (!PT)
  14171. return false;
  14172. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  14173. // Ignore any parens, implicit casts (should only be
  14174. // array-to-pointer decays), and not-so-opaque values. The last is
  14175. // important for making this trigger for property assignments.
  14176. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  14177. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  14178. if (OV->getSourceExpr())
  14179. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  14180. if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
  14181. if (!PT->isObjCIdType() &&
  14182. !(ID && ID->getIdentifier()->isStr("NSString")))
  14183. return false;
  14184. if (!SL->isAscii())
  14185. return false;
  14186. if (Diagnose) {
  14187. Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
  14188. << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
  14189. Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
  14190. }
  14191. return true;
  14192. }
  14193. if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
  14194. isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
  14195. isa<CXXBoolLiteralExpr>(SrcExpr)) &&
  14196. !SrcExpr->isNullPointerConstant(
  14197. getASTContext(), Expr::NPC_NeverValueDependent)) {
  14198. if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
  14199. return false;
  14200. if (Diagnose) {
  14201. Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
  14202. << /*number*/1
  14203. << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
  14204. Expr *NumLit =
  14205. BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
  14206. if (NumLit)
  14207. Exp = NumLit;
  14208. }
  14209. return true;
  14210. }
  14211. return false;
  14212. }
  14213. static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
  14214. const Expr *SrcExpr) {
  14215. if (!DstType->isFunctionPointerType() ||
  14216. !SrcExpr->getType()->isFunctionType())
  14217. return false;
  14218. auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
  14219. if (!DRE)
  14220. return false;
  14221. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  14222. if (!FD)
  14223. return false;
  14224. return !S.checkAddressOfFunctionIsAvailable(FD,
  14225. /*Complain=*/true,
  14226. SrcExpr->getBeginLoc());
  14227. }
  14228. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  14229. SourceLocation Loc,
  14230. QualType DstType, QualType SrcType,
  14231. Expr *SrcExpr, AssignmentAction Action,
  14232. bool *Complained) {
  14233. if (Complained)
  14234. *Complained = false;
  14235. // Decode the result (notice that AST's are still created for extensions).
  14236. bool CheckInferredResultType = false;
  14237. bool isInvalid = false;
  14238. unsigned DiagKind = 0;
  14239. ConversionFixItGenerator ConvHints;
  14240. bool MayHaveConvFixit = false;
  14241. bool MayHaveFunctionDiff = false;
  14242. const ObjCInterfaceDecl *IFace = nullptr;
  14243. const ObjCProtocolDecl *PDecl = nullptr;
  14244. switch (ConvTy) {
  14245. case Compatible:
  14246. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  14247. return false;
  14248. case PointerToInt:
  14249. if (getLangOpts().CPlusPlus) {
  14250. DiagKind = diag::err_typecheck_convert_pointer_int;
  14251. isInvalid = true;
  14252. } else {
  14253. DiagKind = diag::ext_typecheck_convert_pointer_int;
  14254. }
  14255. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  14256. MayHaveConvFixit = true;
  14257. break;
  14258. case IntToPointer:
  14259. if (getLangOpts().CPlusPlus) {
  14260. DiagKind = diag::err_typecheck_convert_int_pointer;
  14261. isInvalid = true;
  14262. } else {
  14263. DiagKind = diag::ext_typecheck_convert_int_pointer;
  14264. }
  14265. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  14266. MayHaveConvFixit = true;
  14267. break;
  14268. case IncompatibleFunctionPointer:
  14269. if (getLangOpts().CPlusPlus) {
  14270. DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
  14271. isInvalid = true;
  14272. } else {
  14273. DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
  14274. }
  14275. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  14276. MayHaveConvFixit = true;
  14277. break;
  14278. case IncompatiblePointer:
  14279. if (Action == AA_Passing_CFAudited) {
  14280. DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
  14281. } else if (getLangOpts().CPlusPlus) {
  14282. DiagKind = diag::err_typecheck_convert_incompatible_pointer;
  14283. isInvalid = true;
  14284. } else {
  14285. DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
  14286. }
  14287. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  14288. SrcType->isObjCObjectPointerType();
  14289. if (!CheckInferredResultType) {
  14290. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  14291. } else if (CheckInferredResultType) {
  14292. SrcType = SrcType.getUnqualifiedType();
  14293. DstType = DstType.getUnqualifiedType();
  14294. }
  14295. MayHaveConvFixit = true;
  14296. break;
  14297. case IncompatiblePointerSign:
  14298. if (getLangOpts().CPlusPlus) {
  14299. DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
  14300. isInvalid = true;
  14301. } else {
  14302. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  14303. }
  14304. break;
  14305. case FunctionVoidPointer:
  14306. if (getLangOpts().CPlusPlus) {
  14307. DiagKind = diag::err_typecheck_convert_pointer_void_func;
  14308. isInvalid = true;
  14309. } else {
  14310. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  14311. }
  14312. break;
  14313. case IncompatiblePointerDiscardsQualifiers: {
  14314. // Perform array-to-pointer decay if necessary.
  14315. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  14316. isInvalid = true;
  14317. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  14318. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  14319. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  14320. DiagKind = diag::err_typecheck_incompatible_address_space;
  14321. break;
  14322. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  14323. DiagKind = diag::err_typecheck_incompatible_ownership;
  14324. break;
  14325. }
  14326. llvm_unreachable("unknown error case for discarding qualifiers!");
  14327. // fallthrough
  14328. }
  14329. case CompatiblePointerDiscardsQualifiers:
  14330. // If the qualifiers lost were because we were applying the
  14331. // (deprecated) C++ conversion from a string literal to a char*
  14332. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  14333. // Ideally, this check would be performed in
  14334. // checkPointerTypesForAssignment. However, that would require a
  14335. // bit of refactoring (so that the second argument is an
  14336. // expression, rather than a type), which should be done as part
  14337. // of a larger effort to fix checkPointerTypesForAssignment for
  14338. // C++ semantics.
  14339. if (getLangOpts().CPlusPlus &&
  14340. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  14341. return false;
  14342. if (getLangOpts().CPlusPlus) {
  14343. DiagKind = diag::err_typecheck_convert_discards_qualifiers;
  14344. isInvalid = true;
  14345. } else {
  14346. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  14347. }
  14348. break;
  14349. case IncompatibleNestedPointerQualifiers:
  14350. if (getLangOpts().CPlusPlus) {
  14351. isInvalid = true;
  14352. DiagKind = diag::err_nested_pointer_qualifier_mismatch;
  14353. } else {
  14354. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  14355. }
  14356. break;
  14357. case IncompatibleNestedPointerAddressSpaceMismatch:
  14358. DiagKind = diag::err_typecheck_incompatible_nested_address_space;
  14359. isInvalid = true;
  14360. break;
  14361. case IntToBlockPointer:
  14362. DiagKind = diag::err_int_to_block_pointer;
  14363. isInvalid = true;
  14364. break;
  14365. case IncompatibleBlockPointer:
  14366. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  14367. isInvalid = true;
  14368. break;
  14369. case IncompatibleObjCQualifiedId: {
  14370. if (SrcType->isObjCQualifiedIdType()) {
  14371. const ObjCObjectPointerType *srcOPT =
  14372. SrcType->castAs<ObjCObjectPointerType>();
  14373. for (auto *srcProto : srcOPT->quals()) {
  14374. PDecl = srcProto;
  14375. break;
  14376. }
  14377. if (const ObjCInterfaceType *IFaceT =
  14378. DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
  14379. IFace = IFaceT->getDecl();
  14380. }
  14381. else if (DstType->isObjCQualifiedIdType()) {
  14382. const ObjCObjectPointerType *dstOPT =
  14383. DstType->castAs<ObjCObjectPointerType>();
  14384. for (auto *dstProto : dstOPT->quals()) {
  14385. PDecl = dstProto;
  14386. break;
  14387. }
  14388. if (const ObjCInterfaceType *IFaceT =
  14389. SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
  14390. IFace = IFaceT->getDecl();
  14391. }
  14392. if (getLangOpts().CPlusPlus) {
  14393. DiagKind = diag::err_incompatible_qualified_id;
  14394. isInvalid = true;
  14395. } else {
  14396. DiagKind = diag::warn_incompatible_qualified_id;
  14397. }
  14398. break;
  14399. }
  14400. case IncompatibleVectors:
  14401. if (getLangOpts().CPlusPlus) {
  14402. DiagKind = diag::err_incompatible_vectors;
  14403. isInvalid = true;
  14404. } else {
  14405. DiagKind = diag::warn_incompatible_vectors;
  14406. }
  14407. break;
  14408. case IncompatibleObjCWeakRef:
  14409. DiagKind = diag::err_arc_weak_unavailable_assign;
  14410. isInvalid = true;
  14411. break;
  14412. case Incompatible:
  14413. if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
  14414. if (Complained)
  14415. *Complained = true;
  14416. return true;
  14417. }
  14418. DiagKind = diag::err_typecheck_convert_incompatible;
  14419. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  14420. MayHaveConvFixit = true;
  14421. isInvalid = true;
  14422. MayHaveFunctionDiff = true;
  14423. break;
  14424. }
  14425. QualType FirstType, SecondType;
  14426. switch (Action) {
  14427. case AA_Assigning:
  14428. case AA_Initializing:
  14429. // The destination type comes first.
  14430. FirstType = DstType;
  14431. SecondType = SrcType;
  14432. break;
  14433. case AA_Returning:
  14434. case AA_Passing:
  14435. case AA_Passing_CFAudited:
  14436. case AA_Converting:
  14437. case AA_Sending:
  14438. case AA_Casting:
  14439. // The source type comes first.
  14440. FirstType = SrcType;
  14441. SecondType = DstType;
  14442. break;
  14443. }
  14444. PartialDiagnostic FDiag = PDiag(DiagKind);
  14445. if (Action == AA_Passing_CFAudited)
  14446. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  14447. else
  14448. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  14449. if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
  14450. DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
  14451. auto isPlainChar = [](const clang::Type *Type) {
  14452. return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
  14453. Type->isSpecificBuiltinType(BuiltinType::Char_U);
  14454. };
  14455. FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
  14456. isPlainChar(SecondType->getPointeeOrArrayElementType()));
  14457. }
  14458. // If we can fix the conversion, suggest the FixIts.
  14459. if (!ConvHints.isNull()) {
  14460. for (FixItHint &H : ConvHints.Hints)
  14461. FDiag << H;
  14462. }
  14463. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  14464. if (MayHaveFunctionDiff)
  14465. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  14466. Diag(Loc, FDiag);
  14467. if ((DiagKind == diag::warn_incompatible_qualified_id ||
  14468. DiagKind == diag::err_incompatible_qualified_id) &&
  14469. PDecl && IFace && !IFace->hasDefinition())
  14470. Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
  14471. << IFace << PDecl;
  14472. if (SecondType == Context.OverloadTy)
  14473. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  14474. FirstType, /*TakingAddress=*/true);
  14475. if (CheckInferredResultType)
  14476. EmitRelatedResultTypeNote(SrcExpr);
  14477. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  14478. EmitRelatedResultTypeNoteForReturn(DstType);
  14479. if (Complained)
  14480. *Complained = true;
  14481. return isInvalid;
  14482. }
  14483. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  14484. llvm::APSInt *Result,
  14485. AllowFoldKind CanFold) {
  14486. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  14487. public:
  14488. SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
  14489. QualType T) override {
  14490. return S.Diag(Loc, diag::err_ice_not_integral)
  14491. << T << S.LangOpts.CPlusPlus;
  14492. }
  14493. SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
  14494. return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
  14495. }
  14496. } Diagnoser;
  14497. return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
  14498. }
  14499. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  14500. llvm::APSInt *Result,
  14501. unsigned DiagID,
  14502. AllowFoldKind CanFold) {
  14503. class IDDiagnoser : public VerifyICEDiagnoser {
  14504. unsigned DiagID;
  14505. public:
  14506. IDDiagnoser(unsigned DiagID)
  14507. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  14508. SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
  14509. return S.Diag(Loc, DiagID);
  14510. }
  14511. } Diagnoser(DiagID);
  14512. return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
  14513. }
  14514. Sema::SemaDiagnosticBuilder
  14515. Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
  14516. QualType T) {
  14517. return diagnoseNotICE(S, Loc);
  14518. }
  14519. Sema::SemaDiagnosticBuilder
  14520. Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
  14521. return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
  14522. }
  14523. ExprResult
  14524. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  14525. VerifyICEDiagnoser &Diagnoser,
  14526. AllowFoldKind CanFold) {
  14527. SourceLocation DiagLoc = E->getBeginLoc();
  14528. if (getLangOpts().CPlusPlus11) {
  14529. // C++11 [expr.const]p5:
  14530. // If an expression of literal class type is used in a context where an
  14531. // integral constant expression is required, then that class type shall
  14532. // have a single non-explicit conversion function to an integral or
  14533. // unscoped enumeration type
  14534. ExprResult Converted;
  14535. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  14536. VerifyICEDiagnoser &BaseDiagnoser;
  14537. public:
  14538. CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
  14539. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
  14540. BaseDiagnoser.Suppress, true),
  14541. BaseDiagnoser(BaseDiagnoser) {}
  14542. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  14543. QualType T) override {
  14544. return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
  14545. }
  14546. SemaDiagnosticBuilder diagnoseIncomplete(
  14547. Sema &S, SourceLocation Loc, QualType T) override {
  14548. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  14549. }
  14550. SemaDiagnosticBuilder diagnoseExplicitConv(
  14551. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  14552. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  14553. }
  14554. SemaDiagnosticBuilder noteExplicitConv(
  14555. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  14556. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  14557. << ConvTy->isEnumeralType() << ConvTy;
  14558. }
  14559. SemaDiagnosticBuilder diagnoseAmbiguous(
  14560. Sema &S, SourceLocation Loc, QualType T) override {
  14561. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  14562. }
  14563. SemaDiagnosticBuilder noteAmbiguous(
  14564. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  14565. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  14566. << ConvTy->isEnumeralType() << ConvTy;
  14567. }
  14568. SemaDiagnosticBuilder diagnoseConversion(
  14569. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  14570. llvm_unreachable("conversion functions are permitted");
  14571. }
  14572. } ConvertDiagnoser(Diagnoser);
  14573. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  14574. ConvertDiagnoser);
  14575. if (Converted.isInvalid())
  14576. return Converted;
  14577. E = Converted.get();
  14578. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  14579. return ExprError();
  14580. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  14581. // An ICE must be of integral or unscoped enumeration type.
  14582. if (!Diagnoser.Suppress)
  14583. Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
  14584. << E->getSourceRange();
  14585. return ExprError();
  14586. }
  14587. ExprResult RValueExpr = DefaultLvalueConversion(E);
  14588. if (RValueExpr.isInvalid())
  14589. return ExprError();
  14590. E = RValueExpr.get();
  14591. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  14592. // in the non-ICE case.
  14593. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  14594. if (Result)
  14595. *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
  14596. if (!isa<ConstantExpr>(E))
  14597. E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
  14598. : ConstantExpr::Create(Context, E);
  14599. return E;
  14600. }
  14601. Expr::EvalResult EvalResult;
  14602. SmallVector<PartialDiagnosticAt, 8> Notes;
  14603. EvalResult.Diag = &Notes;
  14604. // Try to evaluate the expression, and produce diagnostics explaining why it's
  14605. // not a constant expression as a side-effect.
  14606. bool Folded =
  14607. E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
  14608. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  14609. if (!isa<ConstantExpr>(E))
  14610. E = ConstantExpr::Create(Context, E, EvalResult.Val);
  14611. // In C++11, we can rely on diagnostics being produced for any expression
  14612. // which is not a constant expression. If no diagnostics were produced, then
  14613. // this is a constant expression.
  14614. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  14615. if (Result)
  14616. *Result = EvalResult.Val.getInt();
  14617. return E;
  14618. }
  14619. // If our only note is the usual "invalid subexpression" note, just point
  14620. // the caret at its location rather than producing an essentially
  14621. // redundant note.
  14622. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  14623. diag::note_invalid_subexpr_in_const_expr) {
  14624. DiagLoc = Notes[0].first;
  14625. Notes.clear();
  14626. }
  14627. if (!Folded || !CanFold) {
  14628. if (!Diagnoser.Suppress) {
  14629. Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
  14630. for (const PartialDiagnosticAt &Note : Notes)
  14631. Diag(Note.first, Note.second);
  14632. }
  14633. return ExprError();
  14634. }
  14635. Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
  14636. for (const PartialDiagnosticAt &Note : Notes)
  14637. Diag(Note.first, Note.second);
  14638. if (Result)
  14639. *Result = EvalResult.Val.getInt();
  14640. return E;
  14641. }
  14642. namespace {
  14643. // Handle the case where we conclude a expression which we speculatively
  14644. // considered to be unevaluated is actually evaluated.
  14645. class TransformToPE : public TreeTransform<TransformToPE> {
  14646. typedef TreeTransform<TransformToPE> BaseTransform;
  14647. public:
  14648. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  14649. // Make sure we redo semantic analysis
  14650. bool AlwaysRebuild() { return true; }
  14651. bool ReplacingOriginal() { return true; }
  14652. // We need to special-case DeclRefExprs referring to FieldDecls which
  14653. // are not part of a member pointer formation; normal TreeTransforming
  14654. // doesn't catch this case because of the way we represent them in the AST.
  14655. // FIXME: This is a bit ugly; is it really the best way to handle this
  14656. // case?
  14657. //
  14658. // Error on DeclRefExprs referring to FieldDecls.
  14659. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  14660. if (isa<FieldDecl>(E->getDecl()) &&
  14661. !SemaRef.isUnevaluatedContext())
  14662. return SemaRef.Diag(E->getLocation(),
  14663. diag::err_invalid_non_static_member_use)
  14664. << E->getDecl() << E->getSourceRange();
  14665. return BaseTransform::TransformDeclRefExpr(E);
  14666. }
  14667. // Exception: filter out member pointer formation
  14668. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  14669. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  14670. return E;
  14671. return BaseTransform::TransformUnaryOperator(E);
  14672. }
  14673. // The body of a lambda-expression is in a separate expression evaluation
  14674. // context so never needs to be transformed.
  14675. // FIXME: Ideally we wouldn't transform the closure type either, and would
  14676. // just recreate the capture expressions and lambda expression.
  14677. StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
  14678. return SkipLambdaBody(E, Body);
  14679. }
  14680. };
  14681. }
  14682. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  14683. assert(isUnevaluatedContext() &&
  14684. "Should only transform unevaluated expressions");
  14685. ExprEvalContexts.back().Context =
  14686. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  14687. if (isUnevaluatedContext())
  14688. return E;
  14689. return TransformToPE(*this).TransformExpr(E);
  14690. }
  14691. TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
  14692. assert(isUnevaluatedContext() &&
  14693. "Should only transform unevaluated expressions");
  14694. ExprEvalContexts.back().Context =
  14695. ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
  14696. if (isUnevaluatedContext())
  14697. return TInfo;
  14698. return TransformToPE(*this).TransformType(TInfo);
  14699. }
  14700. void
  14701. Sema::PushExpressionEvaluationContext(
  14702. ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
  14703. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  14704. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
  14705. LambdaContextDecl, ExprContext);
  14706. // Discarded statements and immediate contexts nested in other
  14707. // discarded statements or immediate context are themselves
  14708. // a discarded statement or an immediate context, respectively.
  14709. ExprEvalContexts.back().InDiscardedStatement =
  14710. ExprEvalContexts[ExprEvalContexts.size() - 2]
  14711. .isDiscardedStatementContext();
  14712. ExprEvalContexts.back().InImmediateFunctionContext =
  14713. ExprEvalContexts[ExprEvalContexts.size() - 2]
  14714. .isImmediateFunctionContext();
  14715. Cleanup.reset();
  14716. if (!MaybeODRUseExprs.empty())
  14717. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  14718. }
  14719. void
  14720. Sema::PushExpressionEvaluationContext(
  14721. ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
  14722. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  14723. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  14724. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
  14725. }
  14726. namespace {
  14727. const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
  14728. PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
  14729. if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
  14730. if (E->getOpcode() == UO_Deref)
  14731. return CheckPossibleDeref(S, E->getSubExpr());
  14732. } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
  14733. return CheckPossibleDeref(S, E->getBase());
  14734. } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
  14735. return CheckPossibleDeref(S, E->getBase());
  14736. } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
  14737. QualType Inner;
  14738. QualType Ty = E->getType();
  14739. if (const auto *Ptr = Ty->getAs<PointerType>())
  14740. Inner = Ptr->getPointeeType();
  14741. else if (const auto *Arr = S.Context.getAsArrayType(Ty))
  14742. Inner = Arr->getElementType();
  14743. else
  14744. return nullptr;
  14745. if (Inner->hasAttr(attr::NoDeref))
  14746. return E;
  14747. }
  14748. return nullptr;
  14749. }
  14750. } // namespace
  14751. void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
  14752. for (const Expr *E : Rec.PossibleDerefs) {
  14753. const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
  14754. if (DeclRef) {
  14755. const ValueDecl *Decl = DeclRef->getDecl();
  14756. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
  14757. << Decl->getName() << E->getSourceRange();
  14758. Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
  14759. } else {
  14760. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
  14761. << E->getSourceRange();
  14762. }
  14763. }
  14764. Rec.PossibleDerefs.clear();
  14765. }
  14766. /// Check whether E, which is either a discarded-value expression or an
  14767. /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
  14768. /// and if so, remove it from the list of volatile-qualified assignments that
  14769. /// we are going to warn are deprecated.
  14770. void Sema::CheckUnusedVolatileAssignment(Expr *E) {
  14771. if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
  14772. return;
  14773. // Note: ignoring parens here is not justified by the standard rules, but
  14774. // ignoring parentheses seems like a more reasonable approach, and this only
  14775. // drives a deprecation warning so doesn't affect conformance.
  14776. if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
  14777. if (BO->getOpcode() == BO_Assign) {
  14778. auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
  14779. llvm::erase_value(LHSs, BO->getLHS());
  14780. }
  14781. }
  14782. }
  14783. ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
  14784. if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
  14785. !Decl->isConsteval() || isConstantEvaluated() ||
  14786. RebuildingImmediateInvocation || isImmediateFunctionContext())
  14787. return E;
  14788. /// Opportunistically remove the callee from ReferencesToConsteval if we can.
  14789. /// It's OK if this fails; we'll also remove this in
  14790. /// HandleImmediateInvocations, but catching it here allows us to avoid
  14791. /// walking the AST looking for it in simple cases.
  14792. if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
  14793. if (auto *DeclRef =
  14794. dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
  14795. ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
  14796. E = MaybeCreateExprWithCleanups(E);
  14797. ConstantExpr *Res = ConstantExpr::Create(
  14798. getASTContext(), E.get(),
  14799. ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
  14800. getASTContext()),
  14801. /*IsImmediateInvocation*/ true);
  14802. ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
  14803. return Res;
  14804. }
  14805. static void EvaluateAndDiagnoseImmediateInvocation(
  14806. Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
  14807. llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
  14808. Expr::EvalResult Eval;
  14809. Eval.Diag = &Notes;
  14810. ConstantExpr *CE = Candidate.getPointer();
  14811. bool Result = CE->EvaluateAsConstantExpr(
  14812. Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
  14813. if (!Result || !Notes.empty()) {
  14814. Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
  14815. if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
  14816. InnerExpr = FunctionalCast->getSubExpr();
  14817. FunctionDecl *FD = nullptr;
  14818. if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
  14819. FD = cast<FunctionDecl>(Call->getCalleeDecl());
  14820. else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
  14821. FD = Call->getConstructor();
  14822. else
  14823. llvm_unreachable("unhandled decl kind");
  14824. assert(FD->isConsteval());
  14825. SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
  14826. for (auto &Note : Notes)
  14827. SemaRef.Diag(Note.first, Note.second);
  14828. return;
  14829. }
  14830. CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
  14831. }
  14832. static void RemoveNestedImmediateInvocation(
  14833. Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
  14834. SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
  14835. struct ComplexRemove : TreeTransform<ComplexRemove> {
  14836. using Base = TreeTransform<ComplexRemove>;
  14837. llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
  14838. SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
  14839. SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
  14840. CurrentII;
  14841. ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
  14842. SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
  14843. SmallVector<Sema::ImmediateInvocationCandidate,
  14844. 4>::reverse_iterator Current)
  14845. : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
  14846. void RemoveImmediateInvocation(ConstantExpr* E) {
  14847. auto It = std::find_if(CurrentII, IISet.rend(),
  14848. [E](Sema::ImmediateInvocationCandidate Elem) {
  14849. return Elem.getPointer() == E;
  14850. });
  14851. assert(It != IISet.rend() &&
  14852. "ConstantExpr marked IsImmediateInvocation should "
  14853. "be present");
  14854. It->setInt(1); // Mark as deleted
  14855. }
  14856. ExprResult TransformConstantExpr(ConstantExpr *E) {
  14857. if (!E->isImmediateInvocation())
  14858. return Base::TransformConstantExpr(E);
  14859. RemoveImmediateInvocation(E);
  14860. return Base::TransformExpr(E->getSubExpr());
  14861. }
  14862. /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
  14863. /// we need to remove its DeclRefExpr from the DRSet.
  14864. ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  14865. DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
  14866. return Base::TransformCXXOperatorCallExpr(E);
  14867. }
  14868. /// Base::TransformInitializer skip ConstantExpr so we need to visit them
  14869. /// here.
  14870. ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
  14871. if (!Init)
  14872. return Init;
  14873. /// ConstantExpr are the first layer of implicit node to be removed so if
  14874. /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
  14875. if (auto *CE = dyn_cast<ConstantExpr>(Init))
  14876. if (CE->isImmediateInvocation())
  14877. RemoveImmediateInvocation(CE);
  14878. return Base::TransformInitializer(Init, NotCopyInit);
  14879. }
  14880. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  14881. DRSet.erase(E);
  14882. return E;
  14883. }
  14884. bool AlwaysRebuild() { return false; }
  14885. bool ReplacingOriginal() { return true; }
  14886. bool AllowSkippingCXXConstructExpr() {
  14887. bool Res = AllowSkippingFirstCXXConstructExpr;
  14888. AllowSkippingFirstCXXConstructExpr = true;
  14889. return Res;
  14890. }
  14891. bool AllowSkippingFirstCXXConstructExpr = true;
  14892. } Transformer(SemaRef, Rec.ReferenceToConsteval,
  14893. Rec.ImmediateInvocationCandidates, It);
  14894. /// CXXConstructExpr with a single argument are getting skipped by
  14895. /// TreeTransform in some situtation because they could be implicit. This
  14896. /// can only occur for the top-level CXXConstructExpr because it is used
  14897. /// nowhere in the expression being transformed therefore will not be rebuilt.
  14898. /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
  14899. /// skipping the first CXXConstructExpr.
  14900. if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
  14901. Transformer.AllowSkippingFirstCXXConstructExpr = false;
  14902. ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
  14903. assert(Res.isUsable());
  14904. Res = SemaRef.MaybeCreateExprWithCleanups(Res);
  14905. It->getPointer()->setSubExpr(Res.get());
  14906. }
  14907. static void
  14908. HandleImmediateInvocations(Sema &SemaRef,
  14909. Sema::ExpressionEvaluationContextRecord &Rec) {
  14910. if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
  14911. Rec.ReferenceToConsteval.size() == 0) ||
  14912. SemaRef.RebuildingImmediateInvocation)
  14913. return;
  14914. /// When we have more then 1 ImmediateInvocationCandidates we need to check
  14915. /// for nested ImmediateInvocationCandidates. when we have only 1 we only
  14916. /// need to remove ReferenceToConsteval in the immediate invocation.
  14917. if (Rec.ImmediateInvocationCandidates.size() > 1) {
  14918. /// Prevent sema calls during the tree transform from adding pointers that
  14919. /// are already in the sets.
  14920. llvm::SaveAndRestore<bool> DisableIITracking(
  14921. SemaRef.RebuildingImmediateInvocation, true);
  14922. /// Prevent diagnostic during tree transfrom as they are duplicates
  14923. Sema::TentativeAnalysisScope DisableDiag(SemaRef);
  14924. for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
  14925. It != Rec.ImmediateInvocationCandidates.rend(); It++)
  14926. if (!It->getInt())
  14927. RemoveNestedImmediateInvocation(SemaRef, Rec, It);
  14928. } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
  14929. Rec.ReferenceToConsteval.size()) {
  14930. struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
  14931. llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
  14932. SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
  14933. bool VisitDeclRefExpr(DeclRefExpr *E) {
  14934. DRSet.erase(E);
  14935. return DRSet.size();
  14936. }
  14937. } Visitor(Rec.ReferenceToConsteval);
  14938. Visitor.TraverseStmt(
  14939. Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
  14940. }
  14941. for (auto CE : Rec.ImmediateInvocationCandidates)
  14942. if (!CE.getInt())
  14943. EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
  14944. for (auto DR : Rec.ReferenceToConsteval) {
  14945. auto *FD = cast<FunctionDecl>(DR->getDecl());
  14946. SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
  14947. << FD;
  14948. SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
  14949. }
  14950. }
  14951. void Sema::PopExpressionEvaluationContext() {
  14952. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  14953. unsigned NumTypos = Rec.NumTypos;
  14954. if (!Rec.Lambdas.empty()) {
  14955. using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
  14956. if (!getLangOpts().CPlusPlus20 &&
  14957. (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
  14958. Rec.isUnevaluated() ||
  14959. (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
  14960. unsigned D;
  14961. if (Rec.isUnevaluated()) {
  14962. // C++11 [expr.prim.lambda]p2:
  14963. // A lambda-expression shall not appear in an unevaluated operand
  14964. // (Clause 5).
  14965. D = diag::err_lambda_unevaluated_operand;
  14966. } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
  14967. // C++1y [expr.const]p2:
  14968. // A conditional-expression e is a core constant expression unless the
  14969. // evaluation of e, following the rules of the abstract machine, would
  14970. // evaluate [...] a lambda-expression.
  14971. D = diag::err_lambda_in_constant_expression;
  14972. } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
  14973. // C++17 [expr.prim.lamda]p2:
  14974. // A lambda-expression shall not appear [...] in a template-argument.
  14975. D = diag::err_lambda_in_invalid_context;
  14976. } else
  14977. llvm_unreachable("Couldn't infer lambda error message.");
  14978. for (const auto *L : Rec.Lambdas)
  14979. Diag(L->getBeginLoc(), D);
  14980. }
  14981. }
  14982. WarnOnPendingNoDerefs(Rec);
  14983. HandleImmediateInvocations(*this, Rec);
  14984. // Warn on any volatile-qualified simple-assignments that are not discarded-
  14985. // value expressions nor unevaluated operands (those cases get removed from
  14986. // this list by CheckUnusedVolatileAssignment).
  14987. for (auto *BO : Rec.VolatileAssignmentLHSs)
  14988. Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
  14989. << BO->getType();
  14990. // When are coming out of an unevaluated context, clear out any
  14991. // temporaries that we may have created as part of the evaluation of
  14992. // the expression in that context: they aren't relevant because they
  14993. // will never be constructed.
  14994. if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
  14995. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  14996. ExprCleanupObjects.end());
  14997. Cleanup = Rec.ParentCleanup;
  14998. CleanupVarDeclMarking();
  14999. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  15000. // Otherwise, merge the contexts together.
  15001. } else {
  15002. Cleanup.mergeFrom(Rec.ParentCleanup);
  15003. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  15004. Rec.SavedMaybeODRUseExprs.end());
  15005. }
  15006. // Pop the current expression evaluation context off the stack.
  15007. ExprEvalContexts.pop_back();
  15008. // The global expression evaluation context record is never popped.
  15009. ExprEvalContexts.back().NumTypos += NumTypos;
  15010. }
  15011. void Sema::DiscardCleanupsInEvaluationContext() {
  15012. ExprCleanupObjects.erase(
  15013. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  15014. ExprCleanupObjects.end());
  15015. Cleanup.reset();
  15016. MaybeODRUseExprs.clear();
  15017. }
  15018. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  15019. ExprResult Result = CheckPlaceholderExpr(E);
  15020. if (Result.isInvalid())
  15021. return ExprError();
  15022. E = Result.get();
  15023. if (!E->getType()->isVariablyModifiedType())
  15024. return E;
  15025. return TransformToPotentiallyEvaluated(E);
  15026. }
  15027. /// Are we in a context that is potentially constant evaluated per C++20
  15028. /// [expr.const]p12?
  15029. static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
  15030. /// C++2a [expr.const]p12:
  15031. // An expression or conversion is potentially constant evaluated if it is
  15032. switch (SemaRef.ExprEvalContexts.back().Context) {
  15033. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  15034. case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
  15035. // -- a manifestly constant-evaluated expression,
  15036. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  15037. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  15038. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  15039. // -- a potentially-evaluated expression,
  15040. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  15041. // -- an immediate subexpression of a braced-init-list,
  15042. // -- [FIXME] an expression of the form & cast-expression that occurs
  15043. // within a templated entity
  15044. // -- a subexpression of one of the above that is not a subexpression of
  15045. // a nested unevaluated operand.
  15046. return true;
  15047. case Sema::ExpressionEvaluationContext::Unevaluated:
  15048. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  15049. // Expressions in this context are never evaluated.
  15050. return false;
  15051. }
  15052. llvm_unreachable("Invalid context");
  15053. }
  15054. /// Return true if this function has a calling convention that requires mangling
  15055. /// in the size of the parameter pack.
  15056. static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
  15057. // These manglings don't do anything on non-Windows or non-x86 platforms, so
  15058. // we don't need parameter type sizes.
  15059. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  15060. if (!TT.isOSWindows() || !TT.isX86())
  15061. return false;
  15062. // If this is C++ and this isn't an extern "C" function, parameters do not
  15063. // need to be complete. In this case, C++ mangling will apply, which doesn't
  15064. // use the size of the parameters.
  15065. if (S.getLangOpts().CPlusPlus && !FD->isExternC())
  15066. return false;
  15067. // Stdcall, fastcall, and vectorcall need this special treatment.
  15068. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  15069. switch (CC) {
  15070. case CC_X86StdCall:
  15071. case CC_X86FastCall:
  15072. case CC_X86VectorCall:
  15073. return true;
  15074. default:
  15075. break;
  15076. }
  15077. return false;
  15078. }
  15079. /// Require that all of the parameter types of function be complete. Normally,
  15080. /// parameter types are only required to be complete when a function is called
  15081. /// or defined, but to mangle functions with certain calling conventions, the
  15082. /// mangler needs to know the size of the parameter list. In this situation,
  15083. /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
  15084. /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
  15085. /// result in a linker error. Clang doesn't implement this behavior, and instead
  15086. /// attempts to error at compile time.
  15087. static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
  15088. SourceLocation Loc) {
  15089. class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
  15090. FunctionDecl *FD;
  15091. ParmVarDecl *Param;
  15092. public:
  15093. ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
  15094. : FD(FD), Param(Param) {}
  15095. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  15096. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  15097. StringRef CCName;
  15098. switch (CC) {
  15099. case CC_X86StdCall:
  15100. CCName = "stdcall";
  15101. break;
  15102. case CC_X86FastCall:
  15103. CCName = "fastcall";
  15104. break;
  15105. case CC_X86VectorCall:
  15106. CCName = "vectorcall";
  15107. break;
  15108. default:
  15109. llvm_unreachable("CC does not need mangling");
  15110. }
  15111. S.Diag(Loc, diag::err_cconv_incomplete_param_type)
  15112. << Param->getDeclName() << FD->getDeclName() << CCName;
  15113. }
  15114. };
  15115. for (ParmVarDecl *Param : FD->parameters()) {
  15116. ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
  15117. S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
  15118. }
  15119. }
  15120. namespace {
  15121. enum class OdrUseContext {
  15122. /// Declarations in this context are not odr-used.
  15123. None,
  15124. /// Declarations in this context are formally odr-used, but this is a
  15125. /// dependent context.
  15126. Dependent,
  15127. /// Declarations in this context are odr-used but not actually used (yet).
  15128. FormallyOdrUsed,
  15129. /// Declarations in this context are used.
  15130. Used
  15131. };
  15132. }
  15133. /// Are we within a context in which references to resolved functions or to
  15134. /// variables result in odr-use?
  15135. static OdrUseContext isOdrUseContext(Sema &SemaRef) {
  15136. OdrUseContext Result;
  15137. switch (SemaRef.ExprEvalContexts.back().Context) {
  15138. case Sema::ExpressionEvaluationContext::Unevaluated:
  15139. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  15140. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  15141. return OdrUseContext::None;
  15142. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  15143. case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
  15144. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  15145. Result = OdrUseContext::Used;
  15146. break;
  15147. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  15148. Result = OdrUseContext::FormallyOdrUsed;
  15149. break;
  15150. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  15151. // A default argument formally results in odr-use, but doesn't actually
  15152. // result in a use in any real sense until it itself is used.
  15153. Result = OdrUseContext::FormallyOdrUsed;
  15154. break;
  15155. }
  15156. if (SemaRef.CurContext->isDependentContext())
  15157. return OdrUseContext::Dependent;
  15158. return Result;
  15159. }
  15160. static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
  15161. if (!Func->isConstexpr())
  15162. return false;
  15163. if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
  15164. return true;
  15165. auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
  15166. return CCD && CCD->getInheritedConstructor();
  15167. }
  15168. /// Mark a function referenced, and check whether it is odr-used
  15169. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  15170. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  15171. bool MightBeOdrUse) {
  15172. assert(Func && "No function?");
  15173. Func->setReferenced();
  15174. // Recursive functions aren't really used until they're used from some other
  15175. // context.
  15176. bool IsRecursiveCall = CurContext == Func;
  15177. // C++11 [basic.def.odr]p3:
  15178. // A function whose name appears as a potentially-evaluated expression is
  15179. // odr-used if it is the unique lookup result or the selected member of a
  15180. // set of overloaded functions [...].
  15181. //
  15182. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  15183. // can just check that here.
  15184. OdrUseContext OdrUse =
  15185. MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
  15186. if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
  15187. OdrUse = OdrUseContext::FormallyOdrUsed;
  15188. // Trivial default constructors and destructors are never actually used.
  15189. // FIXME: What about other special members?
  15190. if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
  15191. OdrUse == OdrUseContext::Used) {
  15192. if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
  15193. if (Constructor->isDefaultConstructor())
  15194. OdrUse = OdrUseContext::FormallyOdrUsed;
  15195. if (isa<CXXDestructorDecl>(Func))
  15196. OdrUse = OdrUseContext::FormallyOdrUsed;
  15197. }
  15198. // C++20 [expr.const]p12:
  15199. // A function [...] is needed for constant evaluation if it is [...] a
  15200. // constexpr function that is named by an expression that is potentially
  15201. // constant evaluated
  15202. bool NeededForConstantEvaluation =
  15203. isPotentiallyConstantEvaluatedContext(*this) &&
  15204. isImplicitlyDefinableConstexprFunction(Func);
  15205. // Determine whether we require a function definition to exist, per
  15206. // C++11 [temp.inst]p3:
  15207. // Unless a function template specialization has been explicitly
  15208. // instantiated or explicitly specialized, the function template
  15209. // specialization is implicitly instantiated when the specialization is
  15210. // referenced in a context that requires a function definition to exist.
  15211. // C++20 [temp.inst]p7:
  15212. // The existence of a definition of a [...] function is considered to
  15213. // affect the semantics of the program if the [...] function is needed for
  15214. // constant evaluation by an expression
  15215. // C++20 [basic.def.odr]p10:
  15216. // Every program shall contain exactly one definition of every non-inline
  15217. // function or variable that is odr-used in that program outside of a
  15218. // discarded statement
  15219. // C++20 [special]p1:
  15220. // The implementation will implicitly define [defaulted special members]
  15221. // if they are odr-used or needed for constant evaluation.
  15222. //
  15223. // Note that we skip the implicit instantiation of templates that are only
  15224. // used in unused default arguments or by recursive calls to themselves.
  15225. // This is formally non-conforming, but seems reasonable in practice.
  15226. bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
  15227. NeededForConstantEvaluation);
  15228. // C++14 [temp.expl.spec]p6:
  15229. // If a template [...] is explicitly specialized then that specialization
  15230. // shall be declared before the first use of that specialization that would
  15231. // cause an implicit instantiation to take place, in every translation unit
  15232. // in which such a use occurs
  15233. if (NeedDefinition &&
  15234. (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
  15235. Func->getMemberSpecializationInfo()))
  15236. checkSpecializationVisibility(Loc, Func);
  15237. if (getLangOpts().CUDA)
  15238. CheckCUDACall(Loc, Func);
  15239. if (getLangOpts().SYCLIsDevice)
  15240. checkSYCLDeviceFunction(Loc, Func);
  15241. // If we need a definition, try to create one.
  15242. if (NeedDefinition && !Func->getBody()) {
  15243. runWithSufficientStackSpace(Loc, [&] {
  15244. if (CXXConstructorDecl *Constructor =
  15245. dyn_cast<CXXConstructorDecl>(Func)) {
  15246. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  15247. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  15248. if (Constructor->isDefaultConstructor()) {
  15249. if (Constructor->isTrivial() &&
  15250. !Constructor->hasAttr<DLLExportAttr>())
  15251. return;
  15252. DefineImplicitDefaultConstructor(Loc, Constructor);
  15253. } else if (Constructor->isCopyConstructor()) {
  15254. DefineImplicitCopyConstructor(Loc, Constructor);
  15255. } else if (Constructor->isMoveConstructor()) {
  15256. DefineImplicitMoveConstructor(Loc, Constructor);
  15257. }
  15258. } else if (Constructor->getInheritedConstructor()) {
  15259. DefineInheritingConstructor(Loc, Constructor);
  15260. }
  15261. } else if (CXXDestructorDecl *Destructor =
  15262. dyn_cast<CXXDestructorDecl>(Func)) {
  15263. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  15264. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  15265. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  15266. return;
  15267. DefineImplicitDestructor(Loc, Destructor);
  15268. }
  15269. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  15270. MarkVTableUsed(Loc, Destructor->getParent());
  15271. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  15272. if (MethodDecl->isOverloadedOperator() &&
  15273. MethodDecl->getOverloadedOperator() == OO_Equal) {
  15274. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  15275. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  15276. if (MethodDecl->isCopyAssignmentOperator())
  15277. DefineImplicitCopyAssignment(Loc, MethodDecl);
  15278. else if (MethodDecl->isMoveAssignmentOperator())
  15279. DefineImplicitMoveAssignment(Loc, MethodDecl);
  15280. }
  15281. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  15282. MethodDecl->getParent()->isLambda()) {
  15283. CXXConversionDecl *Conversion =
  15284. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  15285. if (Conversion->isLambdaToBlockPointerConversion())
  15286. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  15287. else
  15288. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  15289. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  15290. MarkVTableUsed(Loc, MethodDecl->getParent());
  15291. }
  15292. if (Func->isDefaulted() && !Func->isDeleted()) {
  15293. DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
  15294. if (DCK != DefaultedComparisonKind::None)
  15295. DefineDefaultedComparison(Loc, Func, DCK);
  15296. }
  15297. // Implicit instantiation of function templates and member functions of
  15298. // class templates.
  15299. if (Func->isImplicitlyInstantiable()) {
  15300. TemplateSpecializationKind TSK =
  15301. Func->getTemplateSpecializationKindForInstantiation();
  15302. SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
  15303. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  15304. if (FirstInstantiation) {
  15305. PointOfInstantiation = Loc;
  15306. if (auto *MSI = Func->getMemberSpecializationInfo())
  15307. MSI->setPointOfInstantiation(Loc);
  15308. // FIXME: Notify listener.
  15309. else
  15310. Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  15311. } else if (TSK != TSK_ImplicitInstantiation) {
  15312. // Use the point of use as the point of instantiation, instead of the
  15313. // point of explicit instantiation (which we track as the actual point
  15314. // of instantiation). This gives better backtraces in diagnostics.
  15315. PointOfInstantiation = Loc;
  15316. }
  15317. if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
  15318. Func->isConstexpr()) {
  15319. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  15320. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  15321. CodeSynthesisContexts.size())
  15322. PendingLocalImplicitInstantiations.push_back(
  15323. std::make_pair(Func, PointOfInstantiation));
  15324. else if (Func->isConstexpr())
  15325. // Do not defer instantiations of constexpr functions, to avoid the
  15326. // expression evaluator needing to call back into Sema if it sees a
  15327. // call to such a function.
  15328. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  15329. else {
  15330. Func->setInstantiationIsPending(true);
  15331. PendingInstantiations.push_back(
  15332. std::make_pair(Func, PointOfInstantiation));
  15333. // Notify the consumer that a function was implicitly instantiated.
  15334. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  15335. }
  15336. }
  15337. } else {
  15338. // Walk redefinitions, as some of them may be instantiable.
  15339. for (auto i : Func->redecls()) {
  15340. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  15341. MarkFunctionReferenced(Loc, i, MightBeOdrUse);
  15342. }
  15343. }
  15344. });
  15345. }
  15346. // C++14 [except.spec]p17:
  15347. // An exception-specification is considered to be needed when:
  15348. // - the function is odr-used or, if it appears in an unevaluated operand,
  15349. // would be odr-used if the expression were potentially-evaluated;
  15350. //
  15351. // Note, we do this even if MightBeOdrUse is false. That indicates that the
  15352. // function is a pure virtual function we're calling, and in that case the
  15353. // function was selected by overload resolution and we need to resolve its
  15354. // exception specification for a different reason.
  15355. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  15356. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  15357. ResolveExceptionSpec(Loc, FPT);
  15358. // If this is the first "real" use, act on that.
  15359. if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
  15360. // Keep track of used but undefined functions.
  15361. if (!Func->isDefined()) {
  15362. if (mightHaveNonExternalLinkage(Func))
  15363. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  15364. else if (Func->getMostRecentDecl()->isInlined() &&
  15365. !LangOpts.GNUInline &&
  15366. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  15367. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  15368. else if (isExternalWithNoLinkageType(Func))
  15369. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  15370. }
  15371. // Some x86 Windows calling conventions mangle the size of the parameter
  15372. // pack into the name. Computing the size of the parameters requires the
  15373. // parameter types to be complete. Check that now.
  15374. if (funcHasParameterSizeMangling(*this, Func))
  15375. CheckCompleteParameterTypesForMangler(*this, Func, Loc);
  15376. // In the MS C++ ABI, the compiler emits destructor variants where they are
  15377. // used. If the destructor is used here but defined elsewhere, mark the
  15378. // virtual base destructors referenced. If those virtual base destructors
  15379. // are inline, this will ensure they are defined when emitting the complete
  15380. // destructor variant. This checking may be redundant if the destructor is
  15381. // provided later in this TU.
  15382. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  15383. if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
  15384. CXXRecordDecl *Parent = Dtor->getParent();
  15385. if (Parent->getNumVBases() > 0 && !Dtor->getBody())
  15386. CheckCompleteDestructorVariant(Loc, Dtor);
  15387. }
  15388. }
  15389. Func->markUsed(Context);
  15390. }
  15391. }
  15392. /// Directly mark a variable odr-used. Given a choice, prefer to use
  15393. /// MarkVariableReferenced since it does additional checks and then
  15394. /// calls MarkVarDeclODRUsed.
  15395. /// If the variable must be captured:
  15396. /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
  15397. /// - else capture it in the DeclContext that maps to the
  15398. /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
  15399. static void
  15400. MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
  15401. const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
  15402. // Keep track of used but undefined variables.
  15403. // FIXME: We shouldn't suppress this warning for static data members.
  15404. if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
  15405. (!Var->isExternallyVisible() || Var->isInline() ||
  15406. SemaRef.isExternalWithNoLinkageType(Var)) &&
  15407. !(Var->isStaticDataMember() && Var->hasInit())) {
  15408. SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
  15409. if (old.isInvalid())
  15410. old = Loc;
  15411. }
  15412. QualType CaptureType, DeclRefType;
  15413. if (SemaRef.LangOpts.OpenMP)
  15414. SemaRef.tryCaptureOpenMPLambdas(Var);
  15415. SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
  15416. /*EllipsisLoc*/ SourceLocation(),
  15417. /*BuildAndDiagnose*/ true,
  15418. CaptureType, DeclRefType,
  15419. FunctionScopeIndexToStopAt);
  15420. if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) {
  15421. auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
  15422. auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
  15423. auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
  15424. if (VarTarget == Sema::CVT_Host &&
  15425. (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
  15426. UserTarget == Sema::CFT_Global)) {
  15427. // Diagnose ODR-use of host global variables in device functions.
  15428. // Reference of device global variables in host functions is allowed
  15429. // through shadow variables therefore it is not diagnosed.
  15430. if (SemaRef.LangOpts.CUDAIsDevice) {
  15431. SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
  15432. << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
  15433. SemaRef.targetDiag(Var->getLocation(),
  15434. Var->getType().isConstQualified()
  15435. ? diag::note_cuda_const_var_unpromoted
  15436. : diag::note_cuda_host_var);
  15437. }
  15438. } else if (VarTarget == Sema::CVT_Device &&
  15439. (UserTarget == Sema::CFT_Host ||
  15440. UserTarget == Sema::CFT_HostDevice) &&
  15441. !Var->hasExternalStorage()) {
  15442. // Record a CUDA/HIP device side variable if it is ODR-used
  15443. // by host code. This is done conservatively, when the variable is
  15444. // referenced in any of the following contexts:
  15445. // - a non-function context
  15446. // - a host function
  15447. // - a host device function
  15448. // This makes the ODR-use of the device side variable by host code to
  15449. // be visible in the device compilation for the compiler to be able to
  15450. // emit template variables instantiated by host code only and to
  15451. // externalize the static device side variable ODR-used by host code.
  15452. SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
  15453. }
  15454. }
  15455. Var->markUsed(SemaRef.Context);
  15456. }
  15457. void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
  15458. SourceLocation Loc,
  15459. unsigned CapturingScopeIndex) {
  15460. MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
  15461. }
  15462. static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  15463. ValueDecl *var) {
  15464. DeclContext *VarDC = var->getDeclContext();
  15465. // If the parameter still belongs to the translation unit, then
  15466. // we're actually just using one parameter in the declaration of
  15467. // the next.
  15468. if (isa<ParmVarDecl>(var) &&
  15469. isa<TranslationUnitDecl>(VarDC))
  15470. return;
  15471. // For C code, don't diagnose about capture if we're not actually in code
  15472. // right now; it's impossible to write a non-constant expression outside of
  15473. // function context, so we'll get other (more useful) diagnostics later.
  15474. //
  15475. // For C++, things get a bit more nasty... it would be nice to suppress this
  15476. // diagnostic for certain cases like using a local variable in an array bound
  15477. // for a member of a local class, but the correct predicate is not obvious.
  15478. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  15479. return;
  15480. unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
  15481. unsigned ContextKind = 3; // unknown
  15482. if (isa<CXXMethodDecl>(VarDC) &&
  15483. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  15484. ContextKind = 2;
  15485. } else if (isa<FunctionDecl>(VarDC)) {
  15486. ContextKind = 0;
  15487. } else if (isa<BlockDecl>(VarDC)) {
  15488. ContextKind = 1;
  15489. }
  15490. S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
  15491. << var << ValueKind << ContextKind << VarDC;
  15492. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  15493. << var;
  15494. // FIXME: Add additional diagnostic info about class etc. which prevents
  15495. // capture.
  15496. }
  15497. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  15498. bool &SubCapturesAreNested,
  15499. QualType &CaptureType,
  15500. QualType &DeclRefType) {
  15501. // Check whether we've already captured it.
  15502. if (CSI->CaptureMap.count(Var)) {
  15503. // If we found a capture, any subcaptures are nested.
  15504. SubCapturesAreNested = true;
  15505. // Retrieve the capture type for this variable.
  15506. CaptureType = CSI->getCapture(Var).getCaptureType();
  15507. // Compute the type of an expression that refers to this variable.
  15508. DeclRefType = CaptureType.getNonReferenceType();
  15509. // Similarly to mutable captures in lambda, all the OpenMP captures by copy
  15510. // are mutable in the sense that user can change their value - they are
  15511. // private instances of the captured declarations.
  15512. const Capture &Cap = CSI->getCapture(Var);
  15513. if (Cap.isCopyCapture() &&
  15514. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
  15515. !(isa<CapturedRegionScopeInfo>(CSI) &&
  15516. cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
  15517. DeclRefType.addConst();
  15518. return true;
  15519. }
  15520. return false;
  15521. }
  15522. // Only block literals, captured statements, and lambda expressions can
  15523. // capture; other scopes don't work.
  15524. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  15525. SourceLocation Loc,
  15526. const bool Diagnose, Sema &S) {
  15527. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  15528. return getLambdaAwareParentOfDeclContext(DC);
  15529. else if (Var->hasLocalStorage()) {
  15530. if (Diagnose)
  15531. diagnoseUncapturableValueReference(S, Loc, Var);
  15532. }
  15533. return nullptr;
  15534. }
  15535. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  15536. // certain types of variables (unnamed, variably modified types etc.)
  15537. // so check for eligibility.
  15538. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  15539. SourceLocation Loc,
  15540. const bool Diagnose, Sema &S) {
  15541. bool IsBlock = isa<BlockScopeInfo>(CSI);
  15542. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  15543. // Lambdas are not allowed to capture unnamed variables
  15544. // (e.g. anonymous unions).
  15545. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  15546. // assuming that's the intent.
  15547. if (IsLambda && !Var->getDeclName()) {
  15548. if (Diagnose) {
  15549. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  15550. S.Diag(Var->getLocation(), diag::note_declared_at);
  15551. }
  15552. return false;
  15553. }
  15554. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  15555. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  15556. if (Diagnose) {
  15557. S.Diag(Loc, diag::err_ref_vm_type);
  15558. S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  15559. }
  15560. return false;
  15561. }
  15562. // Prohibit structs with flexible array members too.
  15563. // We cannot capture what is in the tail end of the struct.
  15564. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  15565. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  15566. if (Diagnose) {
  15567. if (IsBlock)
  15568. S.Diag(Loc, diag::err_ref_flexarray_type);
  15569. else
  15570. S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
  15571. S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  15572. }
  15573. return false;
  15574. }
  15575. }
  15576. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  15577. // Lambdas and captured statements are not allowed to capture __block
  15578. // variables; they don't support the expected semantics.
  15579. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  15580. if (Diagnose) {
  15581. S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
  15582. S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  15583. }
  15584. return false;
  15585. }
  15586. // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
  15587. if (S.getLangOpts().OpenCL && IsBlock &&
  15588. Var->getType()->isBlockPointerType()) {
  15589. if (Diagnose)
  15590. S.Diag(Loc, diag::err_opencl_block_ref_block);
  15591. return false;
  15592. }
  15593. return true;
  15594. }
  15595. // Returns true if the capture by block was successful.
  15596. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  15597. SourceLocation Loc,
  15598. const bool BuildAndDiagnose,
  15599. QualType &CaptureType,
  15600. QualType &DeclRefType,
  15601. const bool Nested,
  15602. Sema &S, bool Invalid) {
  15603. bool ByRef = false;
  15604. // Blocks are not allowed to capture arrays, excepting OpenCL.
  15605. // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
  15606. // (decayed to pointers).
  15607. if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
  15608. if (BuildAndDiagnose) {
  15609. S.Diag(Loc, diag::err_ref_array_type);
  15610. S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  15611. Invalid = true;
  15612. } else {
  15613. return false;
  15614. }
  15615. }
  15616. // Forbid the block-capture of autoreleasing variables.
  15617. if (!Invalid &&
  15618. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  15619. if (BuildAndDiagnose) {
  15620. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  15621. << /*block*/ 0;
  15622. S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  15623. Invalid = true;
  15624. } else {
  15625. return false;
  15626. }
  15627. }
  15628. // Warn about implicitly autoreleasing indirect parameters captured by blocks.
  15629. if (const auto *PT = CaptureType->getAs<PointerType>()) {
  15630. QualType PointeeTy = PT->getPointeeType();
  15631. if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
  15632. PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
  15633. !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
  15634. if (BuildAndDiagnose) {
  15635. SourceLocation VarLoc = Var->getLocation();
  15636. S.Diag(Loc, diag::warn_block_capture_autoreleasing);
  15637. S.Diag(VarLoc, diag::note_declare_parameter_strong);
  15638. }
  15639. }
  15640. }
  15641. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  15642. if (HasBlocksAttr || CaptureType->isReferenceType() ||
  15643. (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
  15644. // Block capture by reference does not change the capture or
  15645. // declaration reference types.
  15646. ByRef = true;
  15647. } else {
  15648. // Block capture by copy introduces 'const'.
  15649. CaptureType = CaptureType.getNonReferenceType().withConst();
  15650. DeclRefType = CaptureType;
  15651. }
  15652. // Actually capture the variable.
  15653. if (BuildAndDiagnose)
  15654. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
  15655. CaptureType, Invalid);
  15656. return !Invalid;
  15657. }
  15658. /// Capture the given variable in the captured region.
  15659. static bool captureInCapturedRegion(
  15660. CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
  15661. const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
  15662. const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
  15663. bool IsTopScope, Sema &S, bool Invalid) {
  15664. // By default, capture variables by reference.
  15665. bool ByRef = true;
  15666. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  15667. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  15668. } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
  15669. // Using an LValue reference type is consistent with Lambdas (see below).
  15670. if (S.isOpenMPCapturedDecl(Var)) {
  15671. bool HasConst = DeclRefType.isConstQualified();
  15672. DeclRefType = DeclRefType.getUnqualifiedType();
  15673. // Don't lose diagnostics about assignments to const.
  15674. if (HasConst)
  15675. DeclRefType.addConst();
  15676. }
  15677. // Do not capture firstprivates in tasks.
  15678. if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
  15679. OMPC_unknown)
  15680. return true;
  15681. ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
  15682. RSI->OpenMPCaptureLevel);
  15683. }
  15684. if (ByRef)
  15685. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  15686. else
  15687. CaptureType = DeclRefType;
  15688. // Actually capture the variable.
  15689. if (BuildAndDiagnose)
  15690. RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
  15691. Loc, SourceLocation(), CaptureType, Invalid);
  15692. return !Invalid;
  15693. }
  15694. /// Capture the given variable in the lambda.
  15695. static bool captureInLambda(LambdaScopeInfo *LSI,
  15696. VarDecl *Var,
  15697. SourceLocation Loc,
  15698. const bool BuildAndDiagnose,
  15699. QualType &CaptureType,
  15700. QualType &DeclRefType,
  15701. const bool RefersToCapturedVariable,
  15702. const Sema::TryCaptureKind Kind,
  15703. SourceLocation EllipsisLoc,
  15704. const bool IsTopScope,
  15705. Sema &S, bool Invalid) {
  15706. // Determine whether we are capturing by reference or by value.
  15707. bool ByRef = false;
  15708. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  15709. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  15710. } else {
  15711. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  15712. }
  15713. // Compute the type of the field that will capture this variable.
  15714. if (ByRef) {
  15715. // C++11 [expr.prim.lambda]p15:
  15716. // An entity is captured by reference if it is implicitly or
  15717. // explicitly captured but not captured by copy. It is
  15718. // unspecified whether additional unnamed non-static data
  15719. // members are declared in the closure type for entities
  15720. // captured by reference.
  15721. //
  15722. // FIXME: It is not clear whether we want to build an lvalue reference
  15723. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  15724. // to do the former, while EDG does the latter. Core issue 1249 will
  15725. // clarify, but for now we follow GCC because it's a more permissive and
  15726. // easily defensible position.
  15727. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  15728. } else {
  15729. // C++11 [expr.prim.lambda]p14:
  15730. // For each entity captured by copy, an unnamed non-static
  15731. // data member is declared in the closure type. The
  15732. // declaration order of these members is unspecified. The type
  15733. // of such a data member is the type of the corresponding
  15734. // captured entity if the entity is not a reference to an
  15735. // object, or the referenced type otherwise. [Note: If the
  15736. // captured entity is a reference to a function, the
  15737. // corresponding data member is also a reference to a
  15738. // function. - end note ]
  15739. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  15740. if (!RefType->getPointeeType()->isFunctionType())
  15741. CaptureType = RefType->getPointeeType();
  15742. }
  15743. // Forbid the lambda copy-capture of autoreleasing variables.
  15744. if (!Invalid &&
  15745. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  15746. if (BuildAndDiagnose) {
  15747. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  15748. S.Diag(Var->getLocation(), diag::note_previous_decl)
  15749. << Var->getDeclName();
  15750. Invalid = true;
  15751. } else {
  15752. return false;
  15753. }
  15754. }
  15755. // Make sure that by-copy captures are of a complete and non-abstract type.
  15756. if (!Invalid && BuildAndDiagnose) {
  15757. if (!CaptureType->isDependentType() &&
  15758. S.RequireCompleteSizedType(
  15759. Loc, CaptureType,
  15760. diag::err_capture_of_incomplete_or_sizeless_type,
  15761. Var->getDeclName()))
  15762. Invalid = true;
  15763. else if (S.RequireNonAbstractType(Loc, CaptureType,
  15764. diag::err_capture_of_abstract_type))
  15765. Invalid = true;
  15766. }
  15767. }
  15768. // Compute the type of a reference to this captured variable.
  15769. if (ByRef)
  15770. DeclRefType = CaptureType.getNonReferenceType();
  15771. else {
  15772. // C++ [expr.prim.lambda]p5:
  15773. // The closure type for a lambda-expression has a public inline
  15774. // function call operator [...]. This function call operator is
  15775. // declared const (9.3.1) if and only if the lambda-expression's
  15776. // parameter-declaration-clause is not followed by mutable.
  15777. DeclRefType = CaptureType.getNonReferenceType();
  15778. if (!LSI->Mutable && !CaptureType->isReferenceType())
  15779. DeclRefType.addConst();
  15780. }
  15781. // Add the capture.
  15782. if (BuildAndDiagnose)
  15783. LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
  15784. Loc, EllipsisLoc, CaptureType, Invalid);
  15785. return !Invalid;
  15786. }
  15787. static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
  15788. // Offer a Copy fix even if the type is dependent.
  15789. if (Var->getType()->isDependentType())
  15790. return true;
  15791. QualType T = Var->getType().getNonReferenceType();
  15792. if (T.isTriviallyCopyableType(Context))
  15793. return true;
  15794. if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
  15795. if (!(RD = RD->getDefinition()))
  15796. return false;
  15797. if (RD->hasSimpleCopyConstructor())
  15798. return true;
  15799. if (RD->hasUserDeclaredCopyConstructor())
  15800. for (CXXConstructorDecl *Ctor : RD->ctors())
  15801. if (Ctor->isCopyConstructor())
  15802. return !Ctor->isDeleted();
  15803. }
  15804. return false;
  15805. }
  15806. /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
  15807. /// default capture. Fixes may be omitted if they aren't allowed by the
  15808. /// standard, for example we can't emit a default copy capture fix-it if we
  15809. /// already explicitly copy capture capture another variable.
  15810. static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
  15811. VarDecl *Var) {
  15812. assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
  15813. // Don't offer Capture by copy of default capture by copy fixes if Var is
  15814. // known not to be copy constructible.
  15815. bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
  15816. SmallString<32> FixBuffer;
  15817. StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
  15818. if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
  15819. SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
  15820. if (ShouldOfferCopyFix) {
  15821. // Offer fixes to insert an explicit capture for the variable.
  15822. // [] -> [VarName]
  15823. // [OtherCapture] -> [OtherCapture, VarName]
  15824. FixBuffer.assign({Separator, Var->getName()});
  15825. Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
  15826. << Var << /*value*/ 0
  15827. << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
  15828. }
  15829. // As above but capture by reference.
  15830. FixBuffer.assign({Separator, "&", Var->getName()});
  15831. Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
  15832. << Var << /*reference*/ 1
  15833. << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
  15834. }
  15835. // Only try to offer default capture if there are no captures excluding this
  15836. // and init captures.
  15837. // [this]: OK.
  15838. // [X = Y]: OK.
  15839. // [&A, &B]: Don't offer.
  15840. // [A, B]: Don't offer.
  15841. if (llvm::any_of(LSI->Captures, [](Capture &C) {
  15842. return !C.isThisCapture() && !C.isInitCapture();
  15843. }))
  15844. return;
  15845. // The default capture specifiers, '=' or '&', must appear first in the
  15846. // capture body.
  15847. SourceLocation DefaultInsertLoc =
  15848. LSI->IntroducerRange.getBegin().getLocWithOffset(1);
  15849. if (ShouldOfferCopyFix) {
  15850. bool CanDefaultCopyCapture = true;
  15851. // [=, *this] OK since c++17
  15852. // [=, this] OK since c++20
  15853. if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
  15854. CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
  15855. ? LSI->getCXXThisCapture().isCopyCapture()
  15856. : false;
  15857. // We can't use default capture by copy if any captures already specified
  15858. // capture by copy.
  15859. if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
  15860. return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
  15861. })) {
  15862. FixBuffer.assign({"=", Separator});
  15863. Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
  15864. << /*value*/ 0
  15865. << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
  15866. }
  15867. }
  15868. // We can't use default capture by reference if any captures already specified
  15869. // capture by reference.
  15870. if (llvm::none_of(LSI->Captures, [](Capture &C) {
  15871. return !C.isInitCapture() && C.isReferenceCapture() &&
  15872. !C.isThisCapture();
  15873. })) {
  15874. FixBuffer.assign({"&", Separator});
  15875. Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
  15876. << /*reference*/ 1
  15877. << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
  15878. }
  15879. }
  15880. bool Sema::tryCaptureVariable(
  15881. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  15882. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  15883. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  15884. // An init-capture is notionally from the context surrounding its
  15885. // declaration, but its parent DC is the lambda class.
  15886. DeclContext *VarDC = Var->getDeclContext();
  15887. if (Var->isInitCapture())
  15888. VarDC = VarDC->getParent();
  15889. DeclContext *DC = CurContext;
  15890. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  15891. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  15892. // We need to sync up the Declaration Context with the
  15893. // FunctionScopeIndexToStopAt
  15894. if (FunctionScopeIndexToStopAt) {
  15895. unsigned FSIndex = FunctionScopes.size() - 1;
  15896. while (FSIndex != MaxFunctionScopesIndex) {
  15897. DC = getLambdaAwareParentOfDeclContext(DC);
  15898. --FSIndex;
  15899. }
  15900. }
  15901. // If the variable is declared in the current context, there is no need to
  15902. // capture it.
  15903. if (VarDC == DC) return true;
  15904. // Capture global variables if it is required to use private copy of this
  15905. // variable.
  15906. bool IsGlobal = !Var->hasLocalStorage();
  15907. if (IsGlobal &&
  15908. !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
  15909. MaxFunctionScopesIndex)))
  15910. return true;
  15911. Var = Var->getCanonicalDecl();
  15912. // Walk up the stack to determine whether we can capture the variable,
  15913. // performing the "simple" checks that don't depend on type. We stop when
  15914. // we've either hit the declared scope of the variable or find an existing
  15915. // capture of that variable. We start from the innermost capturing-entity
  15916. // (the DC) and ensure that all intervening capturing-entities
  15917. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  15918. // declcontext can either capture the variable or have already captured
  15919. // the variable.
  15920. CaptureType = Var->getType();
  15921. DeclRefType = CaptureType.getNonReferenceType();
  15922. bool Nested = false;
  15923. bool Explicit = (Kind != TryCapture_Implicit);
  15924. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  15925. do {
  15926. // Only block literals, captured statements, and lambda expressions can
  15927. // capture; other scopes don't work.
  15928. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  15929. ExprLoc,
  15930. BuildAndDiagnose,
  15931. *this);
  15932. // We need to check for the parent *first* because, if we *have*
  15933. // private-captured a global variable, we need to recursively capture it in
  15934. // intermediate blocks, lambdas, etc.
  15935. if (!ParentDC) {
  15936. if (IsGlobal) {
  15937. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  15938. break;
  15939. }
  15940. return true;
  15941. }
  15942. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  15943. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  15944. // Check whether we've already captured it.
  15945. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  15946. DeclRefType)) {
  15947. CSI->getCapture(Var).markUsed(BuildAndDiagnose);
  15948. break;
  15949. }
  15950. // If we are instantiating a generic lambda call operator body,
  15951. // we do not want to capture new variables. What was captured
  15952. // during either a lambdas transformation or initial parsing
  15953. // should be used.
  15954. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  15955. if (BuildAndDiagnose) {
  15956. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  15957. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  15958. Diag(ExprLoc, diag::err_lambda_impcap) << Var;
  15959. Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  15960. Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
  15961. buildLambdaCaptureFixit(*this, LSI, Var);
  15962. } else
  15963. diagnoseUncapturableValueReference(*this, ExprLoc, Var);
  15964. }
  15965. return true;
  15966. }
  15967. // Try to capture variable-length arrays types.
  15968. if (Var->getType()->isVariablyModifiedType()) {
  15969. // We're going to walk down into the type and look for VLA
  15970. // expressions.
  15971. QualType QTy = Var->getType();
  15972. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  15973. QTy = PVD->getOriginalType();
  15974. captureVariablyModifiedType(Context, QTy, CSI);
  15975. }
  15976. if (getLangOpts().OpenMP) {
  15977. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  15978. // OpenMP private variables should not be captured in outer scope, so
  15979. // just break here. Similarly, global variables that are captured in a
  15980. // target region should not be captured outside the scope of the region.
  15981. if (RSI->CapRegionKind == CR_OpenMP) {
  15982. OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
  15983. Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
  15984. // If the variable is private (i.e. not captured) and has variably
  15985. // modified type, we still need to capture the type for correct
  15986. // codegen in all regions, associated with the construct. Currently,
  15987. // it is captured in the innermost captured region only.
  15988. if (IsOpenMPPrivateDecl != OMPC_unknown &&
  15989. Var->getType()->isVariablyModifiedType()) {
  15990. QualType QTy = Var->getType();
  15991. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  15992. QTy = PVD->getOriginalType();
  15993. for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
  15994. I < E; ++I) {
  15995. auto *OuterRSI = cast<CapturedRegionScopeInfo>(
  15996. FunctionScopes[FunctionScopesIndex - I]);
  15997. assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
  15998. "Wrong number of captured regions associated with the "
  15999. "OpenMP construct.");
  16000. captureVariablyModifiedType(Context, QTy, OuterRSI);
  16001. }
  16002. }
  16003. bool IsTargetCap =
  16004. IsOpenMPPrivateDecl != OMPC_private &&
  16005. isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
  16006. RSI->OpenMPCaptureLevel);
  16007. // Do not capture global if it is not privatized in outer regions.
  16008. bool IsGlobalCap =
  16009. IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
  16010. RSI->OpenMPCaptureLevel);
  16011. // When we detect target captures we are looking from inside the
  16012. // target region, therefore we need to propagate the capture from the
  16013. // enclosing region. Therefore, the capture is not initially nested.
  16014. if (IsTargetCap)
  16015. adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
  16016. if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
  16017. (IsGlobal && !IsGlobalCap)) {
  16018. Nested = !IsTargetCap;
  16019. bool HasConst = DeclRefType.isConstQualified();
  16020. DeclRefType = DeclRefType.getUnqualifiedType();
  16021. // Don't lose diagnostics about assignments to const.
  16022. if (HasConst)
  16023. DeclRefType.addConst();
  16024. CaptureType = Context.getLValueReferenceType(DeclRefType);
  16025. break;
  16026. }
  16027. }
  16028. }
  16029. }
  16030. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  16031. // No capture-default, and this is not an explicit capture
  16032. // so cannot capture this variable.
  16033. if (BuildAndDiagnose) {
  16034. Diag(ExprLoc, diag::err_lambda_impcap) << Var;
  16035. Diag(Var->getLocation(), diag::note_previous_decl) << Var;
  16036. auto *LSI = cast<LambdaScopeInfo>(CSI);
  16037. if (LSI->Lambda) {
  16038. Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
  16039. buildLambdaCaptureFixit(*this, LSI, Var);
  16040. }
  16041. // FIXME: If we error out because an outer lambda can not implicitly
  16042. // capture a variable that an inner lambda explicitly captures, we
  16043. // should have the inner lambda do the explicit capture - because
  16044. // it makes for cleaner diagnostics later. This would purely be done
  16045. // so that the diagnostic does not misleadingly claim that a variable
  16046. // can not be captured by a lambda implicitly even though it is captured
  16047. // explicitly. Suggestion:
  16048. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  16049. // at the function head
  16050. // - cache the StartingDeclContext - this must be a lambda
  16051. // - captureInLambda in the innermost lambda the variable.
  16052. }
  16053. return true;
  16054. }
  16055. FunctionScopesIndex--;
  16056. DC = ParentDC;
  16057. Explicit = false;
  16058. } while (!VarDC->Equals(DC));
  16059. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  16060. // computing the type of the capture at each step, checking type-specific
  16061. // requirements, and adding captures if requested.
  16062. // If the variable had already been captured previously, we start capturing
  16063. // at the lambda nested within that one.
  16064. bool Invalid = false;
  16065. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  16066. ++I) {
  16067. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  16068. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  16069. // certain types of variables (unnamed, variably modified types etc.)
  16070. // so check for eligibility.
  16071. if (!Invalid)
  16072. Invalid =
  16073. !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
  16074. // After encountering an error, if we're actually supposed to capture, keep
  16075. // capturing in nested contexts to suppress any follow-on diagnostics.
  16076. if (Invalid && !BuildAndDiagnose)
  16077. return true;
  16078. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  16079. Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  16080. DeclRefType, Nested, *this, Invalid);
  16081. Nested = true;
  16082. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  16083. Invalid = !captureInCapturedRegion(
  16084. RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
  16085. Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
  16086. Nested = true;
  16087. } else {
  16088. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  16089. Invalid =
  16090. !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  16091. DeclRefType, Nested, Kind, EllipsisLoc,
  16092. /*IsTopScope*/ I == N - 1, *this, Invalid);
  16093. Nested = true;
  16094. }
  16095. if (Invalid && !BuildAndDiagnose)
  16096. return true;
  16097. }
  16098. return Invalid;
  16099. }
  16100. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  16101. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  16102. QualType CaptureType;
  16103. QualType DeclRefType;
  16104. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  16105. /*BuildAndDiagnose=*/true, CaptureType,
  16106. DeclRefType, nullptr);
  16107. }
  16108. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  16109. QualType CaptureType;
  16110. QualType DeclRefType;
  16111. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  16112. /*BuildAndDiagnose=*/false, CaptureType,
  16113. DeclRefType, nullptr);
  16114. }
  16115. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  16116. QualType CaptureType;
  16117. QualType DeclRefType;
  16118. // Determine whether we can capture this variable.
  16119. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  16120. /*BuildAndDiagnose=*/false, CaptureType,
  16121. DeclRefType, nullptr))
  16122. return QualType();
  16123. return DeclRefType;
  16124. }
  16125. namespace {
  16126. // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
  16127. // The produced TemplateArgumentListInfo* points to data stored within this
  16128. // object, so should only be used in contexts where the pointer will not be
  16129. // used after the CopiedTemplateArgs object is destroyed.
  16130. class CopiedTemplateArgs {
  16131. bool HasArgs;
  16132. TemplateArgumentListInfo TemplateArgStorage;
  16133. public:
  16134. template<typename RefExpr>
  16135. CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
  16136. if (HasArgs)
  16137. E->copyTemplateArgumentsInto(TemplateArgStorage);
  16138. }
  16139. operator TemplateArgumentListInfo*()
  16140. #ifdef __has_cpp_attribute
  16141. #if __has_cpp_attribute(clang::lifetimebound)
  16142. [[clang::lifetimebound]]
  16143. #endif
  16144. #endif
  16145. {
  16146. return HasArgs ? &TemplateArgStorage : nullptr;
  16147. }
  16148. };
  16149. }
  16150. /// Walk the set of potential results of an expression and mark them all as
  16151. /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
  16152. ///
  16153. /// \return A new expression if we found any potential results, ExprEmpty() if
  16154. /// not, and ExprError() if we diagnosed an error.
  16155. static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
  16156. NonOdrUseReason NOUR) {
  16157. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  16158. // an object that satisfies the requirements for appearing in a
  16159. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  16160. // is immediately applied." This function handles the lvalue-to-rvalue
  16161. // conversion part.
  16162. //
  16163. // If we encounter a node that claims to be an odr-use but shouldn't be, we
  16164. // transform it into the relevant kind of non-odr-use node and rebuild the
  16165. // tree of nodes leading to it.
  16166. //
  16167. // This is a mini-TreeTransform that only transforms a restricted subset of
  16168. // nodes (and only certain operands of them).
  16169. // Rebuild a subexpression.
  16170. auto Rebuild = [&](Expr *Sub) {
  16171. return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
  16172. };
  16173. // Check whether a potential result satisfies the requirements of NOUR.
  16174. auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
  16175. // Any entity other than a VarDecl is always odr-used whenever it's named
  16176. // in a potentially-evaluated expression.
  16177. auto *VD = dyn_cast<VarDecl>(D);
  16178. if (!VD)
  16179. return true;
  16180. // C++2a [basic.def.odr]p4:
  16181. // A variable x whose name appears as a potentially-evalauted expression
  16182. // e is odr-used by e unless
  16183. // -- x is a reference that is usable in constant expressions, or
  16184. // -- x is a variable of non-reference type that is usable in constant
  16185. // expressions and has no mutable subobjects, and e is an element of
  16186. // the set of potential results of an expression of
  16187. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  16188. // conversion is applied, or
  16189. // -- x is a variable of non-reference type, and e is an element of the
  16190. // set of potential results of a discarded-value expression to which
  16191. // the lvalue-to-rvalue conversion is not applied
  16192. //
  16193. // We check the first bullet and the "potentially-evaluated" condition in
  16194. // BuildDeclRefExpr. We check the type requirements in the second bullet
  16195. // in CheckLValueToRValueConversionOperand below.
  16196. switch (NOUR) {
  16197. case NOUR_None:
  16198. case NOUR_Unevaluated:
  16199. llvm_unreachable("unexpected non-odr-use-reason");
  16200. case NOUR_Constant:
  16201. // Constant references were handled when they were built.
  16202. if (VD->getType()->isReferenceType())
  16203. return true;
  16204. if (auto *RD = VD->getType()->getAsCXXRecordDecl())
  16205. if (RD->hasMutableFields())
  16206. return true;
  16207. if (!VD->isUsableInConstantExpressions(S.Context))
  16208. return true;
  16209. break;
  16210. case NOUR_Discarded:
  16211. if (VD->getType()->isReferenceType())
  16212. return true;
  16213. break;
  16214. }
  16215. return false;
  16216. };
  16217. // Mark that this expression does not constitute an odr-use.
  16218. auto MarkNotOdrUsed = [&] {
  16219. S.MaybeODRUseExprs.remove(E);
  16220. if (LambdaScopeInfo *LSI = S.getCurLambda())
  16221. LSI->markVariableExprAsNonODRUsed(E);
  16222. };
  16223. // C++2a [basic.def.odr]p2:
  16224. // The set of potential results of an expression e is defined as follows:
  16225. switch (E->getStmtClass()) {
  16226. // -- If e is an id-expression, ...
  16227. case Expr::DeclRefExprClass: {
  16228. auto *DRE = cast<DeclRefExpr>(E);
  16229. if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
  16230. break;
  16231. // Rebuild as a non-odr-use DeclRefExpr.
  16232. MarkNotOdrUsed();
  16233. return DeclRefExpr::Create(
  16234. S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
  16235. DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
  16236. DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
  16237. DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
  16238. }
  16239. case Expr::FunctionParmPackExprClass: {
  16240. auto *FPPE = cast<FunctionParmPackExpr>(E);
  16241. // If any of the declarations in the pack is odr-used, then the expression
  16242. // as a whole constitutes an odr-use.
  16243. for (VarDecl *D : *FPPE)
  16244. if (IsPotentialResultOdrUsed(D))
  16245. return ExprEmpty();
  16246. // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
  16247. // nothing cares about whether we marked this as an odr-use, but it might
  16248. // be useful for non-compiler tools.
  16249. MarkNotOdrUsed();
  16250. break;
  16251. }
  16252. // -- If e is a subscripting operation with an array operand...
  16253. case Expr::ArraySubscriptExprClass: {
  16254. auto *ASE = cast<ArraySubscriptExpr>(E);
  16255. Expr *OldBase = ASE->getBase()->IgnoreImplicit();
  16256. if (!OldBase->getType()->isArrayType())
  16257. break;
  16258. ExprResult Base = Rebuild(OldBase);
  16259. if (!Base.isUsable())
  16260. return Base;
  16261. Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
  16262. Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
  16263. SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
  16264. return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
  16265. ASE->getRBracketLoc());
  16266. }
  16267. case Expr::MemberExprClass: {
  16268. auto *ME = cast<MemberExpr>(E);
  16269. // -- If e is a class member access expression [...] naming a non-static
  16270. // data member...
  16271. if (isa<FieldDecl>(ME->getMemberDecl())) {
  16272. ExprResult Base = Rebuild(ME->getBase());
  16273. if (!Base.isUsable())
  16274. return Base;
  16275. return MemberExpr::Create(
  16276. S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
  16277. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
  16278. ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
  16279. CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
  16280. ME->getObjectKind(), ME->isNonOdrUse());
  16281. }
  16282. if (ME->getMemberDecl()->isCXXInstanceMember())
  16283. break;
  16284. // -- If e is a class member access expression naming a static data member,
  16285. // ...
  16286. if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
  16287. break;
  16288. // Rebuild as a non-odr-use MemberExpr.
  16289. MarkNotOdrUsed();
  16290. return MemberExpr::Create(
  16291. S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
  16292. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
  16293. ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
  16294. ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
  16295. }
  16296. case Expr::BinaryOperatorClass: {
  16297. auto *BO = cast<BinaryOperator>(E);
  16298. Expr *LHS = BO->getLHS();
  16299. Expr *RHS = BO->getRHS();
  16300. // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
  16301. if (BO->getOpcode() == BO_PtrMemD) {
  16302. ExprResult Sub = Rebuild(LHS);
  16303. if (!Sub.isUsable())
  16304. return Sub;
  16305. LHS = Sub.get();
  16306. // -- If e is a comma expression, ...
  16307. } else if (BO->getOpcode() == BO_Comma) {
  16308. ExprResult Sub = Rebuild(RHS);
  16309. if (!Sub.isUsable())
  16310. return Sub;
  16311. RHS = Sub.get();
  16312. } else {
  16313. break;
  16314. }
  16315. return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
  16316. LHS, RHS);
  16317. }
  16318. // -- If e has the form (e1)...
  16319. case Expr::ParenExprClass: {
  16320. auto *PE = cast<ParenExpr>(E);
  16321. ExprResult Sub = Rebuild(PE->getSubExpr());
  16322. if (!Sub.isUsable())
  16323. return Sub;
  16324. return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
  16325. }
  16326. // -- If e is a glvalue conditional expression, ...
  16327. // We don't apply this to a binary conditional operator. FIXME: Should we?
  16328. case Expr::ConditionalOperatorClass: {
  16329. auto *CO = cast<ConditionalOperator>(E);
  16330. ExprResult LHS = Rebuild(CO->getLHS());
  16331. if (LHS.isInvalid())
  16332. return ExprError();
  16333. ExprResult RHS = Rebuild(CO->getRHS());
  16334. if (RHS.isInvalid())
  16335. return ExprError();
  16336. if (!LHS.isUsable() && !RHS.isUsable())
  16337. return ExprEmpty();
  16338. if (!LHS.isUsable())
  16339. LHS = CO->getLHS();
  16340. if (!RHS.isUsable())
  16341. RHS = CO->getRHS();
  16342. return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
  16343. CO->getCond(), LHS.get(), RHS.get());
  16344. }
  16345. // [Clang extension]
  16346. // -- If e has the form __extension__ e1...
  16347. case Expr::UnaryOperatorClass: {
  16348. auto *UO = cast<UnaryOperator>(E);
  16349. if (UO->getOpcode() != UO_Extension)
  16350. break;
  16351. ExprResult Sub = Rebuild(UO->getSubExpr());
  16352. if (!Sub.isUsable())
  16353. return Sub;
  16354. return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
  16355. Sub.get());
  16356. }
  16357. // [Clang extension]
  16358. // -- If e has the form _Generic(...), the set of potential results is the
  16359. // union of the sets of potential results of the associated expressions.
  16360. case Expr::GenericSelectionExprClass: {
  16361. auto *GSE = cast<GenericSelectionExpr>(E);
  16362. SmallVector<Expr *, 4> AssocExprs;
  16363. bool AnyChanged = false;
  16364. for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
  16365. ExprResult AssocExpr = Rebuild(OrigAssocExpr);
  16366. if (AssocExpr.isInvalid())
  16367. return ExprError();
  16368. if (AssocExpr.isUsable()) {
  16369. AssocExprs.push_back(AssocExpr.get());
  16370. AnyChanged = true;
  16371. } else {
  16372. AssocExprs.push_back(OrigAssocExpr);
  16373. }
  16374. }
  16375. return AnyChanged ? S.CreateGenericSelectionExpr(
  16376. GSE->getGenericLoc(), GSE->getDefaultLoc(),
  16377. GSE->getRParenLoc(), GSE->getControllingExpr(),
  16378. GSE->getAssocTypeSourceInfos(), AssocExprs)
  16379. : ExprEmpty();
  16380. }
  16381. // [Clang extension]
  16382. // -- If e has the form __builtin_choose_expr(...), the set of potential
  16383. // results is the union of the sets of potential results of the
  16384. // second and third subexpressions.
  16385. case Expr::ChooseExprClass: {
  16386. auto *CE = cast<ChooseExpr>(E);
  16387. ExprResult LHS = Rebuild(CE->getLHS());
  16388. if (LHS.isInvalid())
  16389. return ExprError();
  16390. ExprResult RHS = Rebuild(CE->getLHS());
  16391. if (RHS.isInvalid())
  16392. return ExprError();
  16393. if (!LHS.get() && !RHS.get())
  16394. return ExprEmpty();
  16395. if (!LHS.isUsable())
  16396. LHS = CE->getLHS();
  16397. if (!RHS.isUsable())
  16398. RHS = CE->getRHS();
  16399. return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
  16400. RHS.get(), CE->getRParenLoc());
  16401. }
  16402. // Step through non-syntactic nodes.
  16403. case Expr::ConstantExprClass: {
  16404. auto *CE = cast<ConstantExpr>(E);
  16405. ExprResult Sub = Rebuild(CE->getSubExpr());
  16406. if (!Sub.isUsable())
  16407. return Sub;
  16408. return ConstantExpr::Create(S.Context, Sub.get());
  16409. }
  16410. // We could mostly rely on the recursive rebuilding to rebuild implicit
  16411. // casts, but not at the top level, so rebuild them here.
  16412. case Expr::ImplicitCastExprClass: {
  16413. auto *ICE = cast<ImplicitCastExpr>(E);
  16414. // Only step through the narrow set of cast kinds we expect to encounter.
  16415. // Anything else suggests we've left the region in which potential results
  16416. // can be found.
  16417. switch (ICE->getCastKind()) {
  16418. case CK_NoOp:
  16419. case CK_DerivedToBase:
  16420. case CK_UncheckedDerivedToBase: {
  16421. ExprResult Sub = Rebuild(ICE->getSubExpr());
  16422. if (!Sub.isUsable())
  16423. return Sub;
  16424. CXXCastPath Path(ICE->path());
  16425. return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
  16426. ICE->getValueKind(), &Path);
  16427. }
  16428. default:
  16429. break;
  16430. }
  16431. break;
  16432. }
  16433. default:
  16434. break;
  16435. }
  16436. // Can't traverse through this node. Nothing to do.
  16437. return ExprEmpty();
  16438. }
  16439. ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
  16440. // Check whether the operand is or contains an object of non-trivial C union
  16441. // type.
  16442. if (E->getType().isVolatileQualified() &&
  16443. (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
  16444. E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
  16445. checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
  16446. Sema::NTCUC_LValueToRValueVolatile,
  16447. NTCUK_Destruct|NTCUK_Copy);
  16448. // C++2a [basic.def.odr]p4:
  16449. // [...] an expression of non-volatile-qualified non-class type to which
  16450. // the lvalue-to-rvalue conversion is applied [...]
  16451. if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
  16452. return E;
  16453. ExprResult Result =
  16454. rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
  16455. if (Result.isInvalid())
  16456. return ExprError();
  16457. return Result.get() ? Result : E;
  16458. }
  16459. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  16460. Res = CorrectDelayedTyposInExpr(Res);
  16461. if (!Res.isUsable())
  16462. return Res;
  16463. // If a constant-expression is a reference to a variable where we delay
  16464. // deciding whether it is an odr-use, just assume we will apply the
  16465. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  16466. // (a non-type template argument), we have special handling anyway.
  16467. return CheckLValueToRValueConversionOperand(Res.get());
  16468. }
  16469. void Sema::CleanupVarDeclMarking() {
  16470. // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
  16471. // call.
  16472. MaybeODRUseExprSet LocalMaybeODRUseExprs;
  16473. std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
  16474. for (Expr *E : LocalMaybeODRUseExprs) {
  16475. if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  16476. MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
  16477. DRE->getLocation(), *this);
  16478. } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
  16479. MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
  16480. *this);
  16481. } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
  16482. for (VarDecl *VD : *FP)
  16483. MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
  16484. } else {
  16485. llvm_unreachable("Unexpected expression");
  16486. }
  16487. }
  16488. assert(MaybeODRUseExprs.empty() &&
  16489. "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
  16490. }
  16491. static void DoMarkVarDeclReferenced(
  16492. Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
  16493. llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
  16494. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
  16495. isa<FunctionParmPackExpr>(E)) &&
  16496. "Invalid Expr argument to DoMarkVarDeclReferenced");
  16497. Var->setReferenced();
  16498. if (Var->isInvalidDecl())
  16499. return;
  16500. auto *MSI = Var->getMemberSpecializationInfo();
  16501. TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
  16502. : Var->getTemplateSpecializationKind();
  16503. OdrUseContext OdrUse = isOdrUseContext(SemaRef);
  16504. bool UsableInConstantExpr =
  16505. Var->mightBeUsableInConstantExpressions(SemaRef.Context);
  16506. if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
  16507. RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
  16508. }
  16509. // C++20 [expr.const]p12:
  16510. // A variable [...] is needed for constant evaluation if it is [...] a
  16511. // variable whose name appears as a potentially constant evaluated
  16512. // expression that is either a contexpr variable or is of non-volatile
  16513. // const-qualified integral type or of reference type
  16514. bool NeededForConstantEvaluation =
  16515. isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
  16516. bool NeedDefinition =
  16517. OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
  16518. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  16519. "Can't instantiate a partial template specialization.");
  16520. // If this might be a member specialization of a static data member, check
  16521. // the specialization is visible. We already did the checks for variable
  16522. // template specializations when we created them.
  16523. if (NeedDefinition && TSK != TSK_Undeclared &&
  16524. !isa<VarTemplateSpecializationDecl>(Var))
  16525. SemaRef.checkSpecializationVisibility(Loc, Var);
  16526. // Perform implicit instantiation of static data members, static data member
  16527. // templates of class templates, and variable template specializations. Delay
  16528. // instantiations of variable templates, except for those that could be used
  16529. // in a constant expression.
  16530. if (NeedDefinition && isTemplateInstantiation(TSK)) {
  16531. // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
  16532. // instantiation declaration if a variable is usable in a constant
  16533. // expression (among other cases).
  16534. bool TryInstantiating =
  16535. TSK == TSK_ImplicitInstantiation ||
  16536. (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
  16537. if (TryInstantiating) {
  16538. SourceLocation PointOfInstantiation =
  16539. MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
  16540. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  16541. if (FirstInstantiation) {
  16542. PointOfInstantiation = Loc;
  16543. if (MSI)
  16544. MSI->setPointOfInstantiation(PointOfInstantiation);
  16545. // FIXME: Notify listener.
  16546. else
  16547. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  16548. }
  16549. if (UsableInConstantExpr) {
  16550. // Do not defer instantiations of variables that could be used in a
  16551. // constant expression.
  16552. SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
  16553. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  16554. });
  16555. // Re-set the member to trigger a recomputation of the dependence bits
  16556. // for the expression.
  16557. if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
  16558. DRE->setDecl(DRE->getDecl());
  16559. else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
  16560. ME->setMemberDecl(ME->getMemberDecl());
  16561. } else if (FirstInstantiation ||
  16562. isa<VarTemplateSpecializationDecl>(Var)) {
  16563. // FIXME: For a specialization of a variable template, we don't
  16564. // distinguish between "declaration and type implicitly instantiated"
  16565. // and "implicit instantiation of definition requested", so we have
  16566. // no direct way to avoid enqueueing the pending instantiation
  16567. // multiple times.
  16568. SemaRef.PendingInstantiations
  16569. .push_back(std::make_pair(Var, PointOfInstantiation));
  16570. }
  16571. }
  16572. }
  16573. // C++2a [basic.def.odr]p4:
  16574. // A variable x whose name appears as a potentially-evaluated expression e
  16575. // is odr-used by e unless
  16576. // -- x is a reference that is usable in constant expressions
  16577. // -- x is a variable of non-reference type that is usable in constant
  16578. // expressions and has no mutable subobjects [FIXME], and e is an
  16579. // element of the set of potential results of an expression of
  16580. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  16581. // conversion is applied
  16582. // -- x is a variable of non-reference type, and e is an element of the set
  16583. // of potential results of a discarded-value expression to which the
  16584. // lvalue-to-rvalue conversion is not applied [FIXME]
  16585. //
  16586. // We check the first part of the second bullet here, and
  16587. // Sema::CheckLValueToRValueConversionOperand deals with the second part.
  16588. // FIXME: To get the third bullet right, we need to delay this even for
  16589. // variables that are not usable in constant expressions.
  16590. // If we already know this isn't an odr-use, there's nothing more to do.
  16591. if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
  16592. if (DRE->isNonOdrUse())
  16593. return;
  16594. if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
  16595. if (ME->isNonOdrUse())
  16596. return;
  16597. switch (OdrUse) {
  16598. case OdrUseContext::None:
  16599. assert((!E || isa<FunctionParmPackExpr>(E)) &&
  16600. "missing non-odr-use marking for unevaluated decl ref");
  16601. break;
  16602. case OdrUseContext::FormallyOdrUsed:
  16603. // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
  16604. // behavior.
  16605. break;
  16606. case OdrUseContext::Used:
  16607. // If we might later find that this expression isn't actually an odr-use,
  16608. // delay the marking.
  16609. if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
  16610. SemaRef.MaybeODRUseExprs.insert(E);
  16611. else
  16612. MarkVarDeclODRUsed(Var, Loc, SemaRef);
  16613. break;
  16614. case OdrUseContext::Dependent:
  16615. // If this is a dependent context, we don't need to mark variables as
  16616. // odr-used, but we may still need to track them for lambda capture.
  16617. // FIXME: Do we also need to do this inside dependent typeid expressions
  16618. // (which are modeled as unevaluated at this point)?
  16619. const bool RefersToEnclosingScope =
  16620. (SemaRef.CurContext != Var->getDeclContext() &&
  16621. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  16622. if (RefersToEnclosingScope) {
  16623. LambdaScopeInfo *const LSI =
  16624. SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
  16625. if (LSI && (!LSI->CallOperator ||
  16626. !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
  16627. // If a variable could potentially be odr-used, defer marking it so
  16628. // until we finish analyzing the full expression for any
  16629. // lvalue-to-rvalue
  16630. // or discarded value conversions that would obviate odr-use.
  16631. // Add it to the list of potential captures that will be analyzed
  16632. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  16633. // unless the variable is a reference that was initialized by a constant
  16634. // expression (this will never need to be captured or odr-used).
  16635. //
  16636. // FIXME: We can simplify this a lot after implementing P0588R1.
  16637. assert(E && "Capture variable should be used in an expression.");
  16638. if (!Var->getType()->isReferenceType() ||
  16639. !Var->isUsableInConstantExpressions(SemaRef.Context))
  16640. LSI->addPotentialCapture(E->IgnoreParens());
  16641. }
  16642. }
  16643. break;
  16644. }
  16645. }
  16646. /// Mark a variable referenced, and check whether it is odr-used
  16647. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  16648. /// used directly for normal expressions referring to VarDecl.
  16649. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  16650. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
  16651. }
  16652. static void
  16653. MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
  16654. bool MightBeOdrUse,
  16655. llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
  16656. if (SemaRef.isInOpenMPDeclareTargetContext())
  16657. SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
  16658. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  16659. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
  16660. return;
  16661. }
  16662. SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
  16663. // If this is a call to a method via a cast, also mark the method in the
  16664. // derived class used in case codegen can devirtualize the call.
  16665. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  16666. if (!ME)
  16667. return;
  16668. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  16669. if (!MD)
  16670. return;
  16671. // Only attempt to devirtualize if this is truly a virtual call.
  16672. bool IsVirtualCall = MD->isVirtual() &&
  16673. ME->performsVirtualDispatch(SemaRef.getLangOpts());
  16674. if (!IsVirtualCall)
  16675. return;
  16676. // If it's possible to devirtualize the call, mark the called function
  16677. // referenced.
  16678. CXXMethodDecl *DM = MD->getDevirtualizedMethod(
  16679. ME->getBase(), SemaRef.getLangOpts().AppleKext);
  16680. if (DM)
  16681. SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
  16682. }
  16683. /// Perform reference-marking and odr-use handling for a DeclRefExpr.
  16684. ///
  16685. /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
  16686. /// handled with care if the DeclRefExpr is not newly-created.
  16687. void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
  16688. // TODO: update this with DR# once a defect report is filed.
  16689. // C++11 defect. The address of a pure member should not be an ODR use, even
  16690. // if it's a qualified reference.
  16691. bool OdrUse = true;
  16692. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  16693. if (Method->isVirtual() &&
  16694. !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
  16695. OdrUse = false;
  16696. if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
  16697. if (!isUnevaluatedContext() && !isConstantEvaluated() &&
  16698. FD->isConsteval() && !RebuildingImmediateInvocation)
  16699. ExprEvalContexts.back().ReferenceToConsteval.insert(E);
  16700. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
  16701. RefsMinusAssignments);
  16702. }
  16703. /// Perform reference-marking and odr-use handling for a MemberExpr.
  16704. void Sema::MarkMemberReferenced(MemberExpr *E) {
  16705. // C++11 [basic.def.odr]p2:
  16706. // A non-overloaded function whose name appears as a potentially-evaluated
  16707. // expression or a member of a set of candidate functions, if selected by
  16708. // overload resolution when referred to from a potentially-evaluated
  16709. // expression, is odr-used, unless it is a pure virtual function and its
  16710. // name is not explicitly qualified.
  16711. bool MightBeOdrUse = true;
  16712. if (E->performsVirtualDispatch(getLangOpts())) {
  16713. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  16714. if (Method->isPure())
  16715. MightBeOdrUse = false;
  16716. }
  16717. SourceLocation Loc =
  16718. E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
  16719. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
  16720. RefsMinusAssignments);
  16721. }
  16722. /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
  16723. void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
  16724. for (VarDecl *VD : *E)
  16725. MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
  16726. RefsMinusAssignments);
  16727. }
  16728. /// Perform marking for a reference to an arbitrary declaration. It
  16729. /// marks the declaration referenced, and performs odr-use checking for
  16730. /// functions and variables. This method should not be used when building a
  16731. /// normal expression which refers to a variable.
  16732. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
  16733. bool MightBeOdrUse) {
  16734. if (MightBeOdrUse) {
  16735. if (auto *VD = dyn_cast<VarDecl>(D)) {
  16736. MarkVariableReferenced(Loc, VD);
  16737. return;
  16738. }
  16739. }
  16740. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  16741. MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
  16742. return;
  16743. }
  16744. D->setReferenced();
  16745. }
  16746. namespace {
  16747. // Mark all of the declarations used by a type as referenced.
  16748. // FIXME: Not fully implemented yet! We need to have a better understanding
  16749. // of when we're entering a context we should not recurse into.
  16750. // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
  16751. // TreeTransforms rebuilding the type in a new context. Rather than
  16752. // duplicating the TreeTransform logic, we should consider reusing it here.
  16753. // Currently that causes problems when rebuilding LambdaExprs.
  16754. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  16755. Sema &S;
  16756. SourceLocation Loc;
  16757. public:
  16758. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  16759. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  16760. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  16761. };
  16762. }
  16763. bool MarkReferencedDecls::TraverseTemplateArgument(
  16764. const TemplateArgument &Arg) {
  16765. {
  16766. // A non-type template argument is a constant-evaluated context.
  16767. EnterExpressionEvaluationContext Evaluated(
  16768. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  16769. if (Arg.getKind() == TemplateArgument::Declaration) {
  16770. if (Decl *D = Arg.getAsDecl())
  16771. S.MarkAnyDeclReferenced(Loc, D, true);
  16772. } else if (Arg.getKind() == TemplateArgument::Expression) {
  16773. S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
  16774. }
  16775. }
  16776. return Inherited::TraverseTemplateArgument(Arg);
  16777. }
  16778. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  16779. MarkReferencedDecls Marker(*this, Loc);
  16780. Marker.TraverseType(T);
  16781. }
  16782. namespace {
  16783. /// Helper class that marks all of the declarations referenced by
  16784. /// potentially-evaluated subexpressions as "referenced".
  16785. class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
  16786. public:
  16787. typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
  16788. bool SkipLocalVariables;
  16789. ArrayRef<const Expr *> StopAt;
  16790. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
  16791. ArrayRef<const Expr *> StopAt)
  16792. : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
  16793. void visitUsedDecl(SourceLocation Loc, Decl *D) {
  16794. S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
  16795. }
  16796. void Visit(Expr *E) {
  16797. if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end())
  16798. return;
  16799. Inherited::Visit(E);
  16800. }
  16801. void VisitDeclRefExpr(DeclRefExpr *E) {
  16802. // If we were asked not to visit local variables, don't.
  16803. if (SkipLocalVariables) {
  16804. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  16805. if (VD->hasLocalStorage())
  16806. return;
  16807. }
  16808. // FIXME: This can trigger the instantiation of the initializer of a
  16809. // variable, which can cause the expression to become value-dependent
  16810. // or error-dependent. Do we need to propagate the new dependence bits?
  16811. S.MarkDeclRefReferenced(E);
  16812. }
  16813. void VisitMemberExpr(MemberExpr *E) {
  16814. S.MarkMemberReferenced(E);
  16815. Visit(E->getBase());
  16816. }
  16817. };
  16818. } // namespace
  16819. /// Mark any declarations that appear within this expression or any
  16820. /// potentially-evaluated subexpressions as "referenced".
  16821. ///
  16822. /// \param SkipLocalVariables If true, don't mark local variables as
  16823. /// 'referenced'.
  16824. /// \param StopAt Subexpressions that we shouldn't recurse into.
  16825. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  16826. bool SkipLocalVariables,
  16827. ArrayRef<const Expr*> StopAt) {
  16828. EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
  16829. }
  16830. /// Emit a diagnostic when statements are reachable.
  16831. /// FIXME: check for reachability even in expressions for which we don't build a
  16832. /// CFG (eg, in the initializer of a global or in a constant expression).
  16833. /// For example,
  16834. /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
  16835. bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
  16836. const PartialDiagnostic &PD) {
  16837. if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
  16838. if (!FunctionScopes.empty())
  16839. FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
  16840. sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
  16841. return true;
  16842. }
  16843. // The initializer of a constexpr variable or of the first declaration of a
  16844. // static data member is not syntactically a constant evaluated constant,
  16845. // but nonetheless is always required to be a constant expression, so we
  16846. // can skip diagnosing.
  16847. // FIXME: Using the mangling context here is a hack.
  16848. if (auto *VD = dyn_cast_or_null<VarDecl>(
  16849. ExprEvalContexts.back().ManglingContextDecl)) {
  16850. if (VD->isConstexpr() ||
  16851. (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
  16852. return false;
  16853. // FIXME: For any other kind of variable, we should build a CFG for its
  16854. // initializer and check whether the context in question is reachable.
  16855. }
  16856. Diag(Loc, PD);
  16857. return true;
  16858. }
  16859. /// Emit a diagnostic that describes an effect on the run-time behavior
  16860. /// of the program being compiled.
  16861. ///
  16862. /// This routine emits the given diagnostic when the code currently being
  16863. /// type-checked is "potentially evaluated", meaning that there is a
  16864. /// possibility that the code will actually be executable. Code in sizeof()
  16865. /// expressions, code used only during overload resolution, etc., are not
  16866. /// potentially evaluated. This routine will suppress such diagnostics or,
  16867. /// in the absolutely nutty case of potentially potentially evaluated
  16868. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  16869. /// later.
  16870. ///
  16871. /// This routine should be used for all diagnostics that describe the run-time
  16872. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  16873. /// Failure to do so will likely result in spurious diagnostics or failures
  16874. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  16875. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
  16876. const PartialDiagnostic &PD) {
  16877. if (ExprEvalContexts.back().isDiscardedStatementContext())
  16878. return false;
  16879. switch (ExprEvalContexts.back().Context) {
  16880. case ExpressionEvaluationContext::Unevaluated:
  16881. case ExpressionEvaluationContext::UnevaluatedList:
  16882. case ExpressionEvaluationContext::UnevaluatedAbstract:
  16883. case ExpressionEvaluationContext::DiscardedStatement:
  16884. // The argument will never be evaluated, so don't complain.
  16885. break;
  16886. case ExpressionEvaluationContext::ConstantEvaluated:
  16887. case ExpressionEvaluationContext::ImmediateFunctionContext:
  16888. // Relevant diagnostics should be produced by constant evaluation.
  16889. break;
  16890. case ExpressionEvaluationContext::PotentiallyEvaluated:
  16891. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  16892. return DiagIfReachable(Loc, Stmts, PD);
  16893. }
  16894. return false;
  16895. }
  16896. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  16897. const PartialDiagnostic &PD) {
  16898. return DiagRuntimeBehavior(
  16899. Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
  16900. }
  16901. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  16902. CallExpr *CE, FunctionDecl *FD) {
  16903. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  16904. return false;
  16905. // If we're inside a decltype's expression, don't check for a valid return
  16906. // type or construct temporaries until we know whether this is the last call.
  16907. if (ExprEvalContexts.back().ExprContext ==
  16908. ExpressionEvaluationContextRecord::EK_Decltype) {
  16909. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  16910. return false;
  16911. }
  16912. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  16913. FunctionDecl *FD;
  16914. CallExpr *CE;
  16915. public:
  16916. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  16917. : FD(FD), CE(CE) { }
  16918. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  16919. if (!FD) {
  16920. S.Diag(Loc, diag::err_call_incomplete_return)
  16921. << T << CE->getSourceRange();
  16922. return;
  16923. }
  16924. S.Diag(Loc, diag::err_call_function_incomplete_return)
  16925. << CE->getSourceRange() << FD << T;
  16926. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  16927. << FD->getDeclName();
  16928. }
  16929. } Diagnoser(FD, CE);
  16930. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  16931. return true;
  16932. return false;
  16933. }
  16934. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  16935. // will prevent this condition from triggering, which is what we want.
  16936. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  16937. SourceLocation Loc;
  16938. unsigned diagnostic = diag::warn_condition_is_assignment;
  16939. bool IsOrAssign = false;
  16940. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  16941. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  16942. return;
  16943. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  16944. // Greylist some idioms by putting them into a warning subcategory.
  16945. if (ObjCMessageExpr *ME
  16946. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  16947. Selector Sel = ME->getSelector();
  16948. // self = [<foo> init...]
  16949. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  16950. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  16951. // <foo> = [<bar> nextObject]
  16952. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  16953. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  16954. }
  16955. Loc = Op->getOperatorLoc();
  16956. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  16957. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  16958. return;
  16959. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  16960. Loc = Op->getOperatorLoc();
  16961. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  16962. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  16963. else {
  16964. // Not an assignment.
  16965. return;
  16966. }
  16967. Diag(Loc, diagnostic) << E->getSourceRange();
  16968. SourceLocation Open = E->getBeginLoc();
  16969. SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
  16970. Diag(Loc, diag::note_condition_assign_silence)
  16971. << FixItHint::CreateInsertion(Open, "(")
  16972. << FixItHint::CreateInsertion(Close, ")");
  16973. if (IsOrAssign)
  16974. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  16975. << FixItHint::CreateReplacement(Loc, "!=");
  16976. else
  16977. Diag(Loc, diag::note_condition_assign_to_comparison)
  16978. << FixItHint::CreateReplacement(Loc, "==");
  16979. }
  16980. /// Redundant parentheses over an equality comparison can indicate
  16981. /// that the user intended an assignment used as condition.
  16982. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  16983. // Don't warn if the parens came from a macro.
  16984. SourceLocation parenLoc = ParenE->getBeginLoc();
  16985. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  16986. return;
  16987. // Don't warn for dependent expressions.
  16988. if (ParenE->isTypeDependent())
  16989. return;
  16990. Expr *E = ParenE->IgnoreParens();
  16991. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  16992. if (opE->getOpcode() == BO_EQ &&
  16993. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  16994. == Expr::MLV_Valid) {
  16995. SourceLocation Loc = opE->getOperatorLoc();
  16996. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  16997. SourceRange ParenERange = ParenE->getSourceRange();
  16998. Diag(Loc, diag::note_equality_comparison_silence)
  16999. << FixItHint::CreateRemoval(ParenERange.getBegin())
  17000. << FixItHint::CreateRemoval(ParenERange.getEnd());
  17001. Diag(Loc, diag::note_equality_comparison_to_assign)
  17002. << FixItHint::CreateReplacement(Loc, "=");
  17003. }
  17004. }
  17005. ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
  17006. bool IsConstexpr) {
  17007. DiagnoseAssignmentAsCondition(E);
  17008. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  17009. DiagnoseEqualityWithExtraParens(parenE);
  17010. ExprResult result = CheckPlaceholderExpr(E);
  17011. if (result.isInvalid()) return ExprError();
  17012. E = result.get();
  17013. if (!E->isTypeDependent()) {
  17014. if (getLangOpts().CPlusPlus)
  17015. return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
  17016. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  17017. if (ERes.isInvalid())
  17018. return ExprError();
  17019. E = ERes.get();
  17020. QualType T = E->getType();
  17021. if (!T->isScalarType()) { // C99 6.8.4.1p1
  17022. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  17023. << T << E->getSourceRange();
  17024. return ExprError();
  17025. }
  17026. CheckBoolLikeConversion(E, Loc);
  17027. }
  17028. return E;
  17029. }
  17030. Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
  17031. Expr *SubExpr, ConditionKind CK,
  17032. bool MissingOK) {
  17033. // MissingOK indicates whether having no condition expression is valid
  17034. // (for loop) or invalid (e.g. while loop).
  17035. if (!SubExpr)
  17036. return MissingOK ? ConditionResult() : ConditionError();
  17037. ExprResult Cond;
  17038. switch (CK) {
  17039. case ConditionKind::Boolean:
  17040. Cond = CheckBooleanCondition(Loc, SubExpr);
  17041. break;
  17042. case ConditionKind::ConstexprIf:
  17043. Cond = CheckBooleanCondition(Loc, SubExpr, true);
  17044. break;
  17045. case ConditionKind::Switch:
  17046. Cond = CheckSwitchCondition(Loc, SubExpr);
  17047. break;
  17048. }
  17049. if (Cond.isInvalid()) {
  17050. Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
  17051. {SubExpr}, PreferredConditionType(CK));
  17052. if (!Cond.get())
  17053. return ConditionError();
  17054. }
  17055. // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
  17056. FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
  17057. if (!FullExpr.get())
  17058. return ConditionError();
  17059. return ConditionResult(*this, nullptr, FullExpr,
  17060. CK == ConditionKind::ConstexprIf);
  17061. }
  17062. namespace {
  17063. /// A visitor for rebuilding a call to an __unknown_any expression
  17064. /// to have an appropriate type.
  17065. struct RebuildUnknownAnyFunction
  17066. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  17067. Sema &S;
  17068. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  17069. ExprResult VisitStmt(Stmt *S) {
  17070. llvm_unreachable("unexpected statement!");
  17071. }
  17072. ExprResult VisitExpr(Expr *E) {
  17073. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  17074. << E->getSourceRange();
  17075. return ExprError();
  17076. }
  17077. /// Rebuild an expression which simply semantically wraps another
  17078. /// expression which it shares the type and value kind of.
  17079. template <class T> ExprResult rebuildSugarExpr(T *E) {
  17080. ExprResult SubResult = Visit(E->getSubExpr());
  17081. if (SubResult.isInvalid()) return ExprError();
  17082. Expr *SubExpr = SubResult.get();
  17083. E->setSubExpr(SubExpr);
  17084. E->setType(SubExpr->getType());
  17085. E->setValueKind(SubExpr->getValueKind());
  17086. assert(E->getObjectKind() == OK_Ordinary);
  17087. return E;
  17088. }
  17089. ExprResult VisitParenExpr(ParenExpr *E) {
  17090. return rebuildSugarExpr(E);
  17091. }
  17092. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  17093. return rebuildSugarExpr(E);
  17094. }
  17095. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  17096. ExprResult SubResult = Visit(E->getSubExpr());
  17097. if (SubResult.isInvalid()) return ExprError();
  17098. Expr *SubExpr = SubResult.get();
  17099. E->setSubExpr(SubExpr);
  17100. E->setType(S.Context.getPointerType(SubExpr->getType()));
  17101. assert(E->isPRValue());
  17102. assert(E->getObjectKind() == OK_Ordinary);
  17103. return E;
  17104. }
  17105. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  17106. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  17107. E->setType(VD->getType());
  17108. assert(E->isPRValue());
  17109. if (S.getLangOpts().CPlusPlus &&
  17110. !(isa<CXXMethodDecl>(VD) &&
  17111. cast<CXXMethodDecl>(VD)->isInstance()))
  17112. E->setValueKind(VK_LValue);
  17113. return E;
  17114. }
  17115. ExprResult VisitMemberExpr(MemberExpr *E) {
  17116. return resolveDecl(E, E->getMemberDecl());
  17117. }
  17118. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  17119. return resolveDecl(E, E->getDecl());
  17120. }
  17121. };
  17122. }
  17123. /// Given a function expression of unknown-any type, try to rebuild it
  17124. /// to have a function type.
  17125. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  17126. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  17127. if (Result.isInvalid()) return ExprError();
  17128. return S.DefaultFunctionArrayConversion(Result.get());
  17129. }
  17130. namespace {
  17131. /// A visitor for rebuilding an expression of type __unknown_anytype
  17132. /// into one which resolves the type directly on the referring
  17133. /// expression. Strict preservation of the original source
  17134. /// structure is not a goal.
  17135. struct RebuildUnknownAnyExpr
  17136. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  17137. Sema &S;
  17138. /// The current destination type.
  17139. QualType DestType;
  17140. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  17141. : S(S), DestType(CastType) {}
  17142. ExprResult VisitStmt(Stmt *S) {
  17143. llvm_unreachable("unexpected statement!");
  17144. }
  17145. ExprResult VisitExpr(Expr *E) {
  17146. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  17147. << E->getSourceRange();
  17148. return ExprError();
  17149. }
  17150. ExprResult VisitCallExpr(CallExpr *E);
  17151. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  17152. /// Rebuild an expression which simply semantically wraps another
  17153. /// expression which it shares the type and value kind of.
  17154. template <class T> ExprResult rebuildSugarExpr(T *E) {
  17155. ExprResult SubResult = Visit(E->getSubExpr());
  17156. if (SubResult.isInvalid()) return ExprError();
  17157. Expr *SubExpr = SubResult.get();
  17158. E->setSubExpr(SubExpr);
  17159. E->setType(SubExpr->getType());
  17160. E->setValueKind(SubExpr->getValueKind());
  17161. assert(E->getObjectKind() == OK_Ordinary);
  17162. return E;
  17163. }
  17164. ExprResult VisitParenExpr(ParenExpr *E) {
  17165. return rebuildSugarExpr(E);
  17166. }
  17167. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  17168. return rebuildSugarExpr(E);
  17169. }
  17170. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  17171. const PointerType *Ptr = DestType->getAs<PointerType>();
  17172. if (!Ptr) {
  17173. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  17174. << E->getSourceRange();
  17175. return ExprError();
  17176. }
  17177. if (isa<CallExpr>(E->getSubExpr())) {
  17178. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
  17179. << E->getSourceRange();
  17180. return ExprError();
  17181. }
  17182. assert(E->isPRValue());
  17183. assert(E->getObjectKind() == OK_Ordinary);
  17184. E->setType(DestType);
  17185. // Build the sub-expression as if it were an object of the pointee type.
  17186. DestType = Ptr->getPointeeType();
  17187. ExprResult SubResult = Visit(E->getSubExpr());
  17188. if (SubResult.isInvalid()) return ExprError();
  17189. E->setSubExpr(SubResult.get());
  17190. return E;
  17191. }
  17192. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  17193. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  17194. ExprResult VisitMemberExpr(MemberExpr *E) {
  17195. return resolveDecl(E, E->getMemberDecl());
  17196. }
  17197. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  17198. return resolveDecl(E, E->getDecl());
  17199. }
  17200. };
  17201. }
  17202. /// Rebuilds a call expression which yielded __unknown_anytype.
  17203. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  17204. Expr *CalleeExpr = E->getCallee();
  17205. enum FnKind {
  17206. FK_MemberFunction,
  17207. FK_FunctionPointer,
  17208. FK_BlockPointer
  17209. };
  17210. FnKind Kind;
  17211. QualType CalleeType = CalleeExpr->getType();
  17212. if (CalleeType == S.Context.BoundMemberTy) {
  17213. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  17214. Kind = FK_MemberFunction;
  17215. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  17216. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  17217. CalleeType = Ptr->getPointeeType();
  17218. Kind = FK_FunctionPointer;
  17219. } else {
  17220. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  17221. Kind = FK_BlockPointer;
  17222. }
  17223. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  17224. // Verify that this is a legal result type of a function.
  17225. if (DestType->isArrayType() || DestType->isFunctionType()) {
  17226. unsigned diagID = diag::err_func_returning_array_function;
  17227. if (Kind == FK_BlockPointer)
  17228. diagID = diag::err_block_returning_array_function;
  17229. S.Diag(E->getExprLoc(), diagID)
  17230. << DestType->isFunctionType() << DestType;
  17231. return ExprError();
  17232. }
  17233. // Otherwise, go ahead and set DestType as the call's result.
  17234. E->setType(DestType.getNonLValueExprType(S.Context));
  17235. E->setValueKind(Expr::getValueKindForType(DestType));
  17236. assert(E->getObjectKind() == OK_Ordinary);
  17237. // Rebuild the function type, replacing the result type with DestType.
  17238. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  17239. if (Proto) {
  17240. // __unknown_anytype(...) is a special case used by the debugger when
  17241. // it has no idea what a function's signature is.
  17242. //
  17243. // We want to build this call essentially under the K&R
  17244. // unprototyped rules, but making a FunctionNoProtoType in C++
  17245. // would foul up all sorts of assumptions. However, we cannot
  17246. // simply pass all arguments as variadic arguments, nor can we
  17247. // portably just call the function under a non-variadic type; see
  17248. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  17249. // However, it turns out that in practice it is generally safe to
  17250. // call a function declared as "A foo(B,C,D);" under the prototype
  17251. // "A foo(B,C,D,...);". The only known exception is with the
  17252. // Windows ABI, where any variadic function is implicitly cdecl
  17253. // regardless of its normal CC. Therefore we change the parameter
  17254. // types to match the types of the arguments.
  17255. //
  17256. // This is a hack, but it is far superior to moving the
  17257. // corresponding target-specific code from IR-gen to Sema/AST.
  17258. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  17259. SmallVector<QualType, 8> ArgTypes;
  17260. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  17261. ArgTypes.reserve(E->getNumArgs());
  17262. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  17263. ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
  17264. }
  17265. ParamTypes = ArgTypes;
  17266. }
  17267. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  17268. Proto->getExtProtoInfo());
  17269. } else {
  17270. DestType = S.Context.getFunctionNoProtoType(DestType,
  17271. FnType->getExtInfo());
  17272. }
  17273. // Rebuild the appropriate pointer-to-function type.
  17274. switch (Kind) {
  17275. case FK_MemberFunction:
  17276. // Nothing to do.
  17277. break;
  17278. case FK_FunctionPointer:
  17279. DestType = S.Context.getPointerType(DestType);
  17280. break;
  17281. case FK_BlockPointer:
  17282. DestType = S.Context.getBlockPointerType(DestType);
  17283. break;
  17284. }
  17285. // Finally, we can recurse.
  17286. ExprResult CalleeResult = Visit(CalleeExpr);
  17287. if (!CalleeResult.isUsable()) return ExprError();
  17288. E->setCallee(CalleeResult.get());
  17289. // Bind a temporary if necessary.
  17290. return S.MaybeBindToTemporary(E);
  17291. }
  17292. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  17293. // Verify that this is a legal result type of a call.
  17294. if (DestType->isArrayType() || DestType->isFunctionType()) {
  17295. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  17296. << DestType->isFunctionType() << DestType;
  17297. return ExprError();
  17298. }
  17299. // Rewrite the method result type if available.
  17300. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  17301. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  17302. Method->setReturnType(DestType);
  17303. }
  17304. // Change the type of the message.
  17305. E->setType(DestType.getNonReferenceType());
  17306. E->setValueKind(Expr::getValueKindForType(DestType));
  17307. return S.MaybeBindToTemporary(E);
  17308. }
  17309. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  17310. // The only case we should ever see here is a function-to-pointer decay.
  17311. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  17312. assert(E->isPRValue());
  17313. assert(E->getObjectKind() == OK_Ordinary);
  17314. E->setType(DestType);
  17315. // Rebuild the sub-expression as the pointee (function) type.
  17316. DestType = DestType->castAs<PointerType>()->getPointeeType();
  17317. ExprResult Result = Visit(E->getSubExpr());
  17318. if (!Result.isUsable()) return ExprError();
  17319. E->setSubExpr(Result.get());
  17320. return E;
  17321. } else if (E->getCastKind() == CK_LValueToRValue) {
  17322. assert(E->isPRValue());
  17323. assert(E->getObjectKind() == OK_Ordinary);
  17324. assert(isa<BlockPointerType>(E->getType()));
  17325. E->setType(DestType);
  17326. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  17327. DestType = S.Context.getLValueReferenceType(DestType);
  17328. ExprResult Result = Visit(E->getSubExpr());
  17329. if (!Result.isUsable()) return ExprError();
  17330. E->setSubExpr(Result.get());
  17331. return E;
  17332. } else {
  17333. llvm_unreachable("Unhandled cast type!");
  17334. }
  17335. }
  17336. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  17337. ExprValueKind ValueKind = VK_LValue;
  17338. QualType Type = DestType;
  17339. // We know how to make this work for certain kinds of decls:
  17340. // - functions
  17341. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  17342. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  17343. DestType = Ptr->getPointeeType();
  17344. ExprResult Result = resolveDecl(E, VD);
  17345. if (Result.isInvalid()) return ExprError();
  17346. return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
  17347. VK_PRValue);
  17348. }
  17349. if (!Type->isFunctionType()) {
  17350. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  17351. << VD << E->getSourceRange();
  17352. return ExprError();
  17353. }
  17354. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  17355. // We must match the FunctionDecl's type to the hack introduced in
  17356. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  17357. // type. See the lengthy commentary in that routine.
  17358. QualType FDT = FD->getType();
  17359. const FunctionType *FnType = FDT->castAs<FunctionType>();
  17360. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  17361. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  17362. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  17363. SourceLocation Loc = FD->getLocation();
  17364. FunctionDecl *NewFD = FunctionDecl::Create(
  17365. S.Context, FD->getDeclContext(), Loc, Loc,
  17366. FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
  17367. SC_None, S.getCurFPFeatures().isFPConstrained(),
  17368. false /*isInlineSpecified*/, FD->hasPrototype(),
  17369. /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
  17370. if (FD->getQualifier())
  17371. NewFD->setQualifierInfo(FD->getQualifierLoc());
  17372. SmallVector<ParmVarDecl*, 16> Params;
  17373. for (const auto &AI : FT->param_types()) {
  17374. ParmVarDecl *Param =
  17375. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  17376. Param->setScopeInfo(0, Params.size());
  17377. Params.push_back(Param);
  17378. }
  17379. NewFD->setParams(Params);
  17380. DRE->setDecl(NewFD);
  17381. VD = DRE->getDecl();
  17382. }
  17383. }
  17384. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  17385. if (MD->isInstance()) {
  17386. ValueKind = VK_PRValue;
  17387. Type = S.Context.BoundMemberTy;
  17388. }
  17389. // Function references aren't l-values in C.
  17390. if (!S.getLangOpts().CPlusPlus)
  17391. ValueKind = VK_PRValue;
  17392. // - variables
  17393. } else if (isa<VarDecl>(VD)) {
  17394. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  17395. Type = RefTy->getPointeeType();
  17396. } else if (Type->isFunctionType()) {
  17397. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  17398. << VD << E->getSourceRange();
  17399. return ExprError();
  17400. }
  17401. // - nothing else
  17402. } else {
  17403. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  17404. << VD << E->getSourceRange();
  17405. return ExprError();
  17406. }
  17407. // Modifying the declaration like this is friendly to IR-gen but
  17408. // also really dangerous.
  17409. VD->setType(DestType);
  17410. E->setType(Type);
  17411. E->setValueKind(ValueKind);
  17412. return E;
  17413. }
  17414. /// Check a cast of an unknown-any type. We intentionally only
  17415. /// trigger this for C-style casts.
  17416. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  17417. Expr *CastExpr, CastKind &CastKind,
  17418. ExprValueKind &VK, CXXCastPath &Path) {
  17419. // The type we're casting to must be either void or complete.
  17420. if (!CastType->isVoidType() &&
  17421. RequireCompleteType(TypeRange.getBegin(), CastType,
  17422. diag::err_typecheck_cast_to_incomplete))
  17423. return ExprError();
  17424. // Rewrite the casted expression from scratch.
  17425. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  17426. if (!result.isUsable()) return ExprError();
  17427. CastExpr = result.get();
  17428. VK = CastExpr->getValueKind();
  17429. CastKind = CK_NoOp;
  17430. return CastExpr;
  17431. }
  17432. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  17433. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  17434. }
  17435. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  17436. Expr *arg, QualType &paramType) {
  17437. // If the syntactic form of the argument is not an explicit cast of
  17438. // any sort, just do default argument promotion.
  17439. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  17440. if (!castArg) {
  17441. ExprResult result = DefaultArgumentPromotion(arg);
  17442. if (result.isInvalid()) return ExprError();
  17443. paramType = result.get()->getType();
  17444. return result;
  17445. }
  17446. // Otherwise, use the type that was written in the explicit cast.
  17447. assert(!arg->hasPlaceholderType());
  17448. paramType = castArg->getTypeAsWritten();
  17449. // Copy-initialize a parameter of that type.
  17450. InitializedEntity entity =
  17451. InitializedEntity::InitializeParameter(Context, paramType,
  17452. /*consumed*/ false);
  17453. return PerformCopyInitialization(entity, callLoc, arg);
  17454. }
  17455. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  17456. Expr *orig = E;
  17457. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  17458. while (true) {
  17459. E = E->IgnoreParenImpCasts();
  17460. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  17461. E = call->getCallee();
  17462. diagID = diag::err_uncasted_call_of_unknown_any;
  17463. } else {
  17464. break;
  17465. }
  17466. }
  17467. SourceLocation loc;
  17468. NamedDecl *d;
  17469. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  17470. loc = ref->getLocation();
  17471. d = ref->getDecl();
  17472. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  17473. loc = mem->getMemberLoc();
  17474. d = mem->getMemberDecl();
  17475. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  17476. diagID = diag::err_uncasted_call_of_unknown_any;
  17477. loc = msg->getSelectorStartLoc();
  17478. d = msg->getMethodDecl();
  17479. if (!d) {
  17480. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  17481. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  17482. << orig->getSourceRange();
  17483. return ExprError();
  17484. }
  17485. } else {
  17486. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  17487. << E->getSourceRange();
  17488. return ExprError();
  17489. }
  17490. S.Diag(loc, diagID) << d << orig->getSourceRange();
  17491. // Never recoverable.
  17492. return ExprError();
  17493. }
  17494. /// Check for operands with placeholder types and complain if found.
  17495. /// Returns ExprError() if there was an error and no recovery was possible.
  17496. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  17497. if (!Context.isDependenceAllowed()) {
  17498. // C cannot handle TypoExpr nodes on either side of a binop because it
  17499. // doesn't handle dependent types properly, so make sure any TypoExprs have
  17500. // been dealt with before checking the operands.
  17501. ExprResult Result = CorrectDelayedTyposInExpr(E);
  17502. if (!Result.isUsable()) return ExprError();
  17503. E = Result.get();
  17504. }
  17505. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  17506. if (!placeholderType) return E;
  17507. switch (placeholderType->getKind()) {
  17508. // Overloaded expressions.
  17509. case BuiltinType::Overload: {
  17510. // Try to resolve a single function template specialization.
  17511. // This is obligatory.
  17512. ExprResult Result = E;
  17513. if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
  17514. return Result;
  17515. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  17516. // leaves Result unchanged on failure.
  17517. Result = E;
  17518. if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
  17519. return Result;
  17520. // If that failed, try to recover with a call.
  17521. tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
  17522. /*complain*/ true);
  17523. return Result;
  17524. }
  17525. // Bound member functions.
  17526. case BuiltinType::BoundMember: {
  17527. ExprResult result = E;
  17528. const Expr *BME = E->IgnoreParens();
  17529. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  17530. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  17531. if (isa<CXXPseudoDestructorExpr>(BME)) {
  17532. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  17533. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  17534. if (ME->getMemberNameInfo().getName().getNameKind() ==
  17535. DeclarationName::CXXDestructorName)
  17536. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  17537. }
  17538. tryToRecoverWithCall(result, PD,
  17539. /*complain*/ true);
  17540. return result;
  17541. }
  17542. // ARC unbridged casts.
  17543. case BuiltinType::ARCUnbridgedCast: {
  17544. Expr *realCast = stripARCUnbridgedCast(E);
  17545. diagnoseARCUnbridgedCast(realCast);
  17546. return realCast;
  17547. }
  17548. // Expressions of unknown type.
  17549. case BuiltinType::UnknownAny:
  17550. return diagnoseUnknownAnyExpr(*this, E);
  17551. // Pseudo-objects.
  17552. case BuiltinType::PseudoObject:
  17553. return checkPseudoObjectRValue(E);
  17554. case BuiltinType::BuiltinFn: {
  17555. // Accept __noop without parens by implicitly converting it to a call expr.
  17556. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  17557. if (DRE) {
  17558. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  17559. if (FD->getBuiltinID() == Builtin::BI__noop) {
  17560. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  17561. CK_BuiltinFnToFnPtr)
  17562. .get();
  17563. return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
  17564. VK_PRValue, SourceLocation(),
  17565. FPOptionsOverride());
  17566. }
  17567. }
  17568. Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
  17569. return ExprError();
  17570. }
  17571. case BuiltinType::IncompleteMatrixIdx:
  17572. Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
  17573. ->getRowIdx()
  17574. ->getBeginLoc(),
  17575. diag::err_matrix_incomplete_index);
  17576. return ExprError();
  17577. // Expressions of unknown type.
  17578. case BuiltinType::OMPArraySection:
  17579. Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
  17580. return ExprError();
  17581. // Expressions of unknown type.
  17582. case BuiltinType::OMPArrayShaping:
  17583. return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
  17584. case BuiltinType::OMPIterator:
  17585. return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
  17586. // Everything else should be impossible.
  17587. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  17588. case BuiltinType::Id:
  17589. #include "clang/Basic/OpenCLImageTypes.def"
  17590. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  17591. case BuiltinType::Id:
  17592. #include "clang/Basic/OpenCLExtensionTypes.def"
  17593. #define SVE_TYPE(Name, Id, SingletonId) \
  17594. case BuiltinType::Id:
  17595. #include "clang/Basic/AArch64SVEACLETypes.def"
  17596. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  17597. case BuiltinType::Id:
  17598. #include "clang/Basic/PPCTypes.def"
  17599. #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
  17600. #include "clang/Basic/RISCVVTypes.def"
  17601. #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
  17602. #define PLACEHOLDER_TYPE(Id, SingletonId)
  17603. #include "clang/AST/BuiltinTypes.def"
  17604. break;
  17605. }
  17606. llvm_unreachable("invalid placeholder type!");
  17607. }
  17608. bool Sema::CheckCaseExpression(Expr *E) {
  17609. if (E->isTypeDependent())
  17610. return true;
  17611. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  17612. return E->getType()->isIntegralOrEnumerationType();
  17613. return false;
  17614. }
  17615. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  17616. ExprResult
  17617. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  17618. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  17619. "Unknown Objective-C Boolean value!");
  17620. QualType BoolT = Context.ObjCBuiltinBoolTy;
  17621. if (!Context.getBOOLDecl()) {
  17622. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  17623. Sema::LookupOrdinaryName);
  17624. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  17625. NamedDecl *ND = Result.getFoundDecl();
  17626. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  17627. Context.setBOOLDecl(TD);
  17628. }
  17629. }
  17630. if (Context.getBOOLDecl())
  17631. BoolT = Context.getBOOLType();
  17632. return new (Context)
  17633. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  17634. }
  17635. ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
  17636. llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
  17637. SourceLocation RParen) {
  17638. auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
  17639. auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
  17640. return Spec.getPlatform() == Platform;
  17641. });
  17642. // Transcribe the "ios" availability check to "maccatalyst" when compiling
  17643. // for "maccatalyst" if "maccatalyst" is not specified.
  17644. if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
  17645. Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
  17646. return Spec.getPlatform() == "ios";
  17647. });
  17648. }
  17649. if (Spec == AvailSpecs.end())
  17650. return None;
  17651. return Spec->getVersion();
  17652. };
  17653. VersionTuple Version;
  17654. if (auto MaybeVersion =
  17655. FindSpecVersion(Context.getTargetInfo().getPlatformName()))
  17656. Version = *MaybeVersion;
  17657. // The use of `@available` in the enclosing context should be analyzed to
  17658. // warn when it's used inappropriately (i.e. not if(@available)).
  17659. if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
  17660. Context->HasPotentialAvailabilityViolations = true;
  17661. return new (Context)
  17662. ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
  17663. }
  17664. ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
  17665. ArrayRef<Expr *> SubExprs, QualType T) {
  17666. if (!Context.getLangOpts().RecoveryAST)
  17667. return ExprError();
  17668. if (isSFINAEContext())
  17669. return ExprError();
  17670. if (T.isNull() || T->isUndeducedType() ||
  17671. !Context.getLangOpts().RecoveryASTType)
  17672. // We don't know the concrete type, fallback to dependent type.
  17673. T = Context.DependentTy;
  17674. return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
  17675. }