SemaExpr.cpp 644 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637
  1. //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for expressions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "TreeTransform.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/RecursiveASTVisitor.h"
  27. #include "clang/AST/TypeLoc.h"
  28. #include "clang/Basic/FixedPoint.h"
  29. #include "clang/Basic/PartialDiagnostic.h"
  30. #include "clang/Basic/SourceManager.h"
  31. #include "clang/Basic/TargetInfo.h"
  32. #include "clang/Lex/LiteralSupport.h"
  33. #include "clang/Lex/Preprocessor.h"
  34. #include "clang/Sema/AnalysisBasedWarnings.h"
  35. #include "clang/Sema/DeclSpec.h"
  36. #include "clang/Sema/DelayedDiagnostic.h"
  37. #include "clang/Sema/Designator.h"
  38. #include "clang/Sema/Initialization.h"
  39. #include "clang/Sema/Lookup.h"
  40. #include "clang/Sema/Overload.h"
  41. #include "clang/Sema/ParsedTemplate.h"
  42. #include "clang/Sema/Scope.h"
  43. #include "clang/Sema/ScopeInfo.h"
  44. #include "clang/Sema/SemaFixItUtils.h"
  45. #include "clang/Sema/SemaInternal.h"
  46. #include "clang/Sema/Template.h"
  47. #include "llvm/Support/ConvertUTF.h"
  48. using namespace clang;
  49. using namespace sema;
  50. /// Determine whether the use of this declaration is valid, without
  51. /// emitting diagnostics.
  52. bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
  53. // See if this is an auto-typed variable whose initializer we are parsing.
  54. if (ParsingInitForAutoVars.count(D))
  55. return false;
  56. // See if this is a deleted function.
  57. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  58. if (FD->isDeleted())
  59. return false;
  60. // If the function has a deduced return type, and we can't deduce it,
  61. // then we can't use it either.
  62. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  63. DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
  64. return false;
  65. }
  66. // See if this function is unavailable.
  67. if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
  68. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  69. return false;
  70. return true;
  71. }
  72. static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  73. // Warn if this is used but marked unused.
  74. if (const auto *A = D->getAttr<UnusedAttr>()) {
  75. // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
  76. // should diagnose them.
  77. if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
  78. A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
  79. const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
  80. if (DC && !DC->hasAttr<UnusedAttr>())
  81. S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
  82. }
  83. }
  84. }
  85. /// Emit a note explaining that this function is deleted.
  86. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  87. assert(Decl->isDeleted());
  88. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
  89. if (Method && Method->isDeleted() && Method->isDefaulted()) {
  90. // If the method was explicitly defaulted, point at that declaration.
  91. if (!Method->isImplicit())
  92. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  93. // Try to diagnose why this special member function was implicitly
  94. // deleted. This might fail, if that reason no longer applies.
  95. CXXSpecialMember CSM = getSpecialMember(Method);
  96. if (CSM != CXXInvalid)
  97. ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
  98. return;
  99. }
  100. auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
  101. if (Ctor && Ctor->isInheritingConstructor())
  102. return NoteDeletedInheritingConstructor(Ctor);
  103. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  104. << Decl << true;
  105. }
  106. /// Determine whether a FunctionDecl was ever declared with an
  107. /// explicit storage class.
  108. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  109. for (auto I : D->redecls()) {
  110. if (I->getStorageClass() != SC_None)
  111. return true;
  112. }
  113. return false;
  114. }
  115. /// Check whether we're in an extern inline function and referring to a
  116. /// variable or function with internal linkage (C11 6.7.4p3).
  117. ///
  118. /// This is only a warning because we used to silently accept this code, but
  119. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  120. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  121. /// and so while there may still be user mistakes, most of the time we can't
  122. /// prove that there are errors.
  123. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  124. const NamedDecl *D,
  125. SourceLocation Loc) {
  126. // This is disabled under C++; there are too many ways for this to fire in
  127. // contexts where the warning is a false positive, or where it is technically
  128. // correct but benign.
  129. if (S.getLangOpts().CPlusPlus)
  130. return;
  131. // Check if this is an inlined function or method.
  132. FunctionDecl *Current = S.getCurFunctionDecl();
  133. if (!Current)
  134. return;
  135. if (!Current->isInlined())
  136. return;
  137. if (!Current->isExternallyVisible())
  138. return;
  139. // Check if the decl has internal linkage.
  140. if (D->getFormalLinkage() != InternalLinkage)
  141. return;
  142. // Downgrade from ExtWarn to Extension if
  143. // (1) the supposedly external inline function is in the main file,
  144. // and probably won't be included anywhere else.
  145. // (2) the thing we're referencing is a pure function.
  146. // (3) the thing we're referencing is another inline function.
  147. // This last can give us false negatives, but it's better than warning on
  148. // wrappers for simple C library functions.
  149. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  150. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  151. if (!DowngradeWarning && UsedFn)
  152. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  153. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  154. : diag::ext_internal_in_extern_inline)
  155. << /*IsVar=*/!UsedFn << D;
  156. S.MaybeSuggestAddingStaticToDecl(Current);
  157. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  158. << D;
  159. }
  160. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  161. const FunctionDecl *First = Cur->getFirstDecl();
  162. // Suggest "static" on the function, if possible.
  163. if (!hasAnyExplicitStorageClass(First)) {
  164. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  165. Diag(DeclBegin, diag::note_convert_inline_to_static)
  166. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  167. }
  168. }
  169. /// Determine whether the use of this declaration is valid, and
  170. /// emit any corresponding diagnostics.
  171. ///
  172. /// This routine diagnoses various problems with referencing
  173. /// declarations that can occur when using a declaration. For example,
  174. /// it might warn if a deprecated or unavailable declaration is being
  175. /// used, or produce an error (and return true) if a C++0x deleted
  176. /// function is being used.
  177. ///
  178. /// \returns true if there was an error (this declaration cannot be
  179. /// referenced), false otherwise.
  180. ///
  181. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
  182. const ObjCInterfaceDecl *UnknownObjCClass,
  183. bool ObjCPropertyAccess,
  184. bool AvoidPartialAvailabilityChecks,
  185. ObjCInterfaceDecl *ClassReceiver) {
  186. SourceLocation Loc = Locs.front();
  187. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  188. // If there were any diagnostics suppressed by template argument deduction,
  189. // emit them now.
  190. auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  191. if (Pos != SuppressedDiagnostics.end()) {
  192. for (const PartialDiagnosticAt &Suppressed : Pos->second)
  193. Diag(Suppressed.first, Suppressed.second);
  194. // Clear out the list of suppressed diagnostics, so that we don't emit
  195. // them again for this specialization. However, we don't obsolete this
  196. // entry from the table, because we want to avoid ever emitting these
  197. // diagnostics again.
  198. Pos->second.clear();
  199. }
  200. // C++ [basic.start.main]p3:
  201. // The function 'main' shall not be used within a program.
  202. if (cast<FunctionDecl>(D)->isMain())
  203. Diag(Loc, diag::ext_main_used);
  204. }
  205. // See if this is an auto-typed variable whose initializer we are parsing.
  206. if (ParsingInitForAutoVars.count(D)) {
  207. if (isa<BindingDecl>(D)) {
  208. Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
  209. << D->getDeclName();
  210. } else {
  211. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  212. << D->getDeclName() << cast<VarDecl>(D)->getType();
  213. }
  214. return true;
  215. }
  216. // See if this is a deleted function.
  217. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  218. if (FD->isDeleted()) {
  219. auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
  220. if (Ctor && Ctor->isInheritingConstructor())
  221. Diag(Loc, diag::err_deleted_inherited_ctor_use)
  222. << Ctor->getParent()
  223. << Ctor->getInheritedConstructor().getConstructor()->getParent();
  224. else
  225. Diag(Loc, diag::err_deleted_function_use);
  226. NoteDeletedFunction(FD);
  227. return true;
  228. }
  229. // If the function has a deduced return type, and we can't deduce it,
  230. // then we can't use it either.
  231. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  232. DeduceReturnType(FD, Loc))
  233. return true;
  234. if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
  235. return true;
  236. }
  237. if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  238. // Lambdas are only default-constructible or assignable in C++2a onwards.
  239. if (MD->getParent()->isLambda() &&
  240. ((isa<CXXConstructorDecl>(MD) &&
  241. cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
  242. MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
  243. Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
  244. << !isa<CXXConstructorDecl>(MD);
  245. }
  246. }
  247. auto getReferencedObjCProp = [](const NamedDecl *D) ->
  248. const ObjCPropertyDecl * {
  249. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  250. return MD->findPropertyDecl();
  251. return nullptr;
  252. };
  253. if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
  254. if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
  255. return true;
  256. } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
  257. return true;
  258. }
  259. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  260. // Only the variables omp_in and omp_out are allowed in the combiner.
  261. // Only the variables omp_priv and omp_orig are allowed in the
  262. // initializer-clause.
  263. auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
  264. if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
  265. isa<VarDecl>(D)) {
  266. Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
  267. << getCurFunction()->HasOMPDeclareReductionCombiner;
  268. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  269. return true;
  270. }
  271. DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
  272. AvoidPartialAvailabilityChecks, ClassReceiver);
  273. DiagnoseUnusedOfDecl(*this, D, Loc);
  274. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  275. return false;
  276. }
  277. /// Retrieve the message suffix that should be added to a
  278. /// diagnostic complaining about the given function being deleted or
  279. /// unavailable.
  280. std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
  281. std::string Message;
  282. if (FD->getAvailability(&Message))
  283. return ": " + Message;
  284. return std::string();
  285. }
  286. /// DiagnoseSentinelCalls - This routine checks whether a call or
  287. /// message-send is to a declaration with the sentinel attribute, and
  288. /// if so, it checks that the requirements of the sentinel are
  289. /// satisfied.
  290. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  291. ArrayRef<Expr *> Args) {
  292. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  293. if (!attr)
  294. return;
  295. // The number of formal parameters of the declaration.
  296. unsigned numFormalParams;
  297. // The kind of declaration. This is also an index into a %select in
  298. // the diagnostic.
  299. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  300. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  301. numFormalParams = MD->param_size();
  302. calleeType = CT_Method;
  303. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  304. numFormalParams = FD->param_size();
  305. calleeType = CT_Function;
  306. } else if (isa<VarDecl>(D)) {
  307. QualType type = cast<ValueDecl>(D)->getType();
  308. const FunctionType *fn = nullptr;
  309. if (const PointerType *ptr = type->getAs<PointerType>()) {
  310. fn = ptr->getPointeeType()->getAs<FunctionType>();
  311. if (!fn) return;
  312. calleeType = CT_Function;
  313. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  314. fn = ptr->getPointeeType()->castAs<FunctionType>();
  315. calleeType = CT_Block;
  316. } else {
  317. return;
  318. }
  319. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  320. numFormalParams = proto->getNumParams();
  321. } else {
  322. numFormalParams = 0;
  323. }
  324. } else {
  325. return;
  326. }
  327. // "nullPos" is the number of formal parameters at the end which
  328. // effectively count as part of the variadic arguments. This is
  329. // useful if you would prefer to not have *any* formal parameters,
  330. // but the language forces you to have at least one.
  331. unsigned nullPos = attr->getNullPos();
  332. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  333. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  334. // The number of arguments which should follow the sentinel.
  335. unsigned numArgsAfterSentinel = attr->getSentinel();
  336. // If there aren't enough arguments for all the formal parameters,
  337. // the sentinel, and the args after the sentinel, complain.
  338. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  339. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  340. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  341. return;
  342. }
  343. // Otherwise, find the sentinel expression.
  344. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  345. if (!sentinelExpr) return;
  346. if (sentinelExpr->isValueDependent()) return;
  347. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  348. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  349. // or 'NULL' if those are actually defined in the context. Only use
  350. // 'nil' for ObjC methods, where it's much more likely that the
  351. // variadic arguments form a list of object pointers.
  352. SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
  353. std::string NullValue;
  354. if (calleeType == CT_Method && PP.isMacroDefined("nil"))
  355. NullValue = "nil";
  356. else if (getLangOpts().CPlusPlus11)
  357. NullValue = "nullptr";
  358. else if (PP.isMacroDefined("NULL"))
  359. NullValue = "NULL";
  360. else
  361. NullValue = "(void*) 0";
  362. if (MissingNilLoc.isInvalid())
  363. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  364. else
  365. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  366. << int(calleeType)
  367. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  368. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  369. }
  370. SourceRange Sema::getExprRange(Expr *E) const {
  371. return E ? E->getSourceRange() : SourceRange();
  372. }
  373. //===----------------------------------------------------------------------===//
  374. // Standard Promotions and Conversions
  375. //===----------------------------------------------------------------------===//
  376. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  377. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
  378. // Handle any placeholder expressions which made it here.
  379. if (E->getType()->isPlaceholderType()) {
  380. ExprResult result = CheckPlaceholderExpr(E);
  381. if (result.isInvalid()) return ExprError();
  382. E = result.get();
  383. }
  384. QualType Ty = E->getType();
  385. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  386. if (Ty->isFunctionType()) {
  387. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
  388. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
  389. if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
  390. return ExprError();
  391. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  392. CK_FunctionToPointerDecay).get();
  393. } else if (Ty->isArrayType()) {
  394. // In C90 mode, arrays only promote to pointers if the array expression is
  395. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  396. // type 'array of type' is converted to an expression that has type 'pointer
  397. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  398. // that has type 'array of type' ...". The relevant change is "an lvalue"
  399. // (C90) to "an expression" (C99).
  400. //
  401. // C++ 4.2p1:
  402. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  403. // T" can be converted to an rvalue of type "pointer to T".
  404. //
  405. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
  406. E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  407. CK_ArrayToPointerDecay).get();
  408. }
  409. return E;
  410. }
  411. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  412. // Check to see if we are dereferencing a null pointer. If so,
  413. // and if not volatile-qualified, this is undefined behavior that the
  414. // optimizer will delete, so warn about it. People sometimes try to use this
  415. // to get a deterministic trap and are surprised by clang's behavior. This
  416. // only handles the pattern "*null", which is a very syntactic check.
  417. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  418. if (UO->getOpcode() == UO_Deref &&
  419. UO->getSubExpr()->IgnoreParenCasts()->
  420. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  421. !UO->getType().isVolatileQualified()) {
  422. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  423. S.PDiag(diag::warn_indirection_through_null)
  424. << UO->getSubExpr()->getSourceRange());
  425. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  426. S.PDiag(diag::note_indirection_through_null));
  427. }
  428. }
  429. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  430. SourceLocation AssignLoc,
  431. const Expr* RHS) {
  432. const ObjCIvarDecl *IV = OIRE->getDecl();
  433. if (!IV)
  434. return;
  435. DeclarationName MemberName = IV->getDeclName();
  436. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  437. if (!Member || !Member->isStr("isa"))
  438. return;
  439. const Expr *Base = OIRE->getBase();
  440. QualType BaseType = Base->getType();
  441. if (OIRE->isArrow())
  442. BaseType = BaseType->getPointeeType();
  443. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  444. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  445. ObjCInterfaceDecl *ClassDeclared = nullptr;
  446. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  447. if (!ClassDeclared->getSuperClass()
  448. && (*ClassDeclared->ivar_begin()) == IV) {
  449. if (RHS) {
  450. NamedDecl *ObjectSetClass =
  451. S.LookupSingleName(S.TUScope,
  452. &S.Context.Idents.get("object_setClass"),
  453. SourceLocation(), S.LookupOrdinaryName);
  454. if (ObjectSetClass) {
  455. SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
  456. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
  457. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  458. "object_setClass(")
  459. << FixItHint::CreateReplacement(
  460. SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
  461. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  462. }
  463. else
  464. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  465. } else {
  466. NamedDecl *ObjectGetClass =
  467. S.LookupSingleName(S.TUScope,
  468. &S.Context.Idents.get("object_getClass"),
  469. SourceLocation(), S.LookupOrdinaryName);
  470. if (ObjectGetClass)
  471. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
  472. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  473. "object_getClass(")
  474. << FixItHint::CreateReplacement(
  475. SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
  476. else
  477. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  478. }
  479. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  480. }
  481. }
  482. }
  483. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  484. // Handle any placeholder expressions which made it here.
  485. if (E->getType()->isPlaceholderType()) {
  486. ExprResult result = CheckPlaceholderExpr(E);
  487. if (result.isInvalid()) return ExprError();
  488. E = result.get();
  489. }
  490. // C++ [conv.lval]p1:
  491. // A glvalue of a non-function, non-array type T can be
  492. // converted to a prvalue.
  493. if (!E->isGLValue()) return E;
  494. QualType T = E->getType();
  495. assert(!T.isNull() && "r-value conversion on typeless expression?");
  496. // We don't want to throw lvalue-to-rvalue casts on top of
  497. // expressions of certain types in C++.
  498. if (getLangOpts().CPlusPlus &&
  499. (E->getType() == Context.OverloadTy ||
  500. T->isDependentType() ||
  501. T->isRecordType()))
  502. return E;
  503. // The C standard is actually really unclear on this point, and
  504. // DR106 tells us what the result should be but not why. It's
  505. // generally best to say that void types just doesn't undergo
  506. // lvalue-to-rvalue at all. Note that expressions of unqualified
  507. // 'void' type are never l-values, but qualified void can be.
  508. if (T->isVoidType())
  509. return E;
  510. // OpenCL usually rejects direct accesses to values of 'half' type.
  511. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  512. T->isHalfType()) {
  513. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  514. << 0 << T;
  515. return ExprError();
  516. }
  517. CheckForNullPointerDereference(*this, E);
  518. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  519. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  520. &Context.Idents.get("object_getClass"),
  521. SourceLocation(), LookupOrdinaryName);
  522. if (ObjectGetClass)
  523. Diag(E->getExprLoc(), diag::warn_objc_isa_use)
  524. << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
  525. << FixItHint::CreateReplacement(
  526. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  527. else
  528. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  529. }
  530. else if (const ObjCIvarRefExpr *OIRE =
  531. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  532. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  533. // C++ [conv.lval]p1:
  534. // [...] If T is a non-class type, the type of the prvalue is the
  535. // cv-unqualified version of T. Otherwise, the type of the
  536. // rvalue is T.
  537. //
  538. // C99 6.3.2.1p2:
  539. // If the lvalue has qualified type, the value has the unqualified
  540. // version of the type of the lvalue; otherwise, the value has the
  541. // type of the lvalue.
  542. if (T.hasQualifiers())
  543. T = T.getUnqualifiedType();
  544. // Under the MS ABI, lock down the inheritance model now.
  545. if (T->isMemberPointerType() &&
  546. Context.getTargetInfo().getCXXABI().isMicrosoft())
  547. (void)isCompleteType(E->getExprLoc(), T);
  548. UpdateMarkingForLValueToRValue(E);
  549. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  550. // balance that.
  551. if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  552. Cleanup.setExprNeedsCleanups(true);
  553. ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
  554. nullptr, VK_RValue);
  555. // C11 6.3.2.1p2:
  556. // ... if the lvalue has atomic type, the value has the non-atomic version
  557. // of the type of the lvalue ...
  558. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  559. T = Atomic->getValueType().getUnqualifiedType();
  560. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  561. nullptr, VK_RValue);
  562. }
  563. return Res;
  564. }
  565. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
  566. ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
  567. if (Res.isInvalid())
  568. return ExprError();
  569. Res = DefaultLvalueConversion(Res.get());
  570. if (Res.isInvalid())
  571. return ExprError();
  572. return Res;
  573. }
  574. /// CallExprUnaryConversions - a special case of an unary conversion
  575. /// performed on a function designator of a call expression.
  576. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  577. QualType Ty = E->getType();
  578. ExprResult Res = E;
  579. // Only do implicit cast for a function type, but not for a pointer
  580. // to function type.
  581. if (Ty->isFunctionType()) {
  582. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  583. CK_FunctionToPointerDecay).get();
  584. if (Res.isInvalid())
  585. return ExprError();
  586. }
  587. Res = DefaultLvalueConversion(Res.get());
  588. if (Res.isInvalid())
  589. return ExprError();
  590. return Res.get();
  591. }
  592. /// UsualUnaryConversions - Performs various conversions that are common to most
  593. /// operators (C99 6.3). The conversions of array and function types are
  594. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  595. /// apply if the array is an argument to the sizeof or address (&) operators.
  596. /// In these instances, this routine should *not* be called.
  597. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  598. // First, convert to an r-value.
  599. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  600. if (Res.isInvalid())
  601. return ExprError();
  602. E = Res.get();
  603. QualType Ty = E->getType();
  604. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  605. // Half FP have to be promoted to float unless it is natively supported
  606. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  607. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  608. // Try to perform integral promotions if the object has a theoretically
  609. // promotable type.
  610. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  611. // C99 6.3.1.1p2:
  612. //
  613. // The following may be used in an expression wherever an int or
  614. // unsigned int may be used:
  615. // - an object or expression with an integer type whose integer
  616. // conversion rank is less than or equal to the rank of int
  617. // and unsigned int.
  618. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  619. //
  620. // If an int can represent all values of the original type, the
  621. // value is converted to an int; otherwise, it is converted to an
  622. // unsigned int. These are called the integer promotions. All
  623. // other types are unchanged by the integer promotions.
  624. QualType PTy = Context.isPromotableBitField(E);
  625. if (!PTy.isNull()) {
  626. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  627. return E;
  628. }
  629. if (Ty->isPromotableIntegerType()) {
  630. QualType PT = Context.getPromotedIntegerType(Ty);
  631. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  632. return E;
  633. }
  634. }
  635. return E;
  636. }
  637. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  638. /// do not have a prototype. Arguments that have type float or __fp16
  639. /// are promoted to double. All other argument types are converted by
  640. /// UsualUnaryConversions().
  641. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  642. QualType Ty = E->getType();
  643. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  644. ExprResult Res = UsualUnaryConversions(E);
  645. if (Res.isInvalid())
  646. return ExprError();
  647. E = Res.get();
  648. // If this is a 'float' or '__fp16' (CVR qualified or typedef)
  649. // promote to double.
  650. // Note that default argument promotion applies only to float (and
  651. // half/fp16); it does not apply to _Float16.
  652. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  653. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  654. BTy->getKind() == BuiltinType::Float)) {
  655. if (getLangOpts().OpenCL &&
  656. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  657. if (BTy->getKind() == BuiltinType::Half) {
  658. E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
  659. }
  660. } else {
  661. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  662. }
  663. }
  664. // C++ performs lvalue-to-rvalue conversion as a default argument
  665. // promotion, even on class types, but note:
  666. // C++11 [conv.lval]p2:
  667. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  668. // operand or a subexpression thereof the value contained in the
  669. // referenced object is not accessed. Otherwise, if the glvalue
  670. // has a class type, the conversion copy-initializes a temporary
  671. // of type T from the glvalue and the result of the conversion
  672. // is a prvalue for the temporary.
  673. // FIXME: add some way to gate this entire thing for correctness in
  674. // potentially potentially evaluated contexts.
  675. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  676. ExprResult Temp = PerformCopyInitialization(
  677. InitializedEntity::InitializeTemporary(E->getType()),
  678. E->getExprLoc(), E);
  679. if (Temp.isInvalid())
  680. return ExprError();
  681. E = Temp.get();
  682. }
  683. return E;
  684. }
  685. /// Determine the degree of POD-ness for an expression.
  686. /// Incomplete types are considered POD, since this check can be performed
  687. /// when we're in an unevaluated context.
  688. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  689. if (Ty->isIncompleteType()) {
  690. // C++11 [expr.call]p7:
  691. // After these conversions, if the argument does not have arithmetic,
  692. // enumeration, pointer, pointer to member, or class type, the program
  693. // is ill-formed.
  694. //
  695. // Since we've already performed array-to-pointer and function-to-pointer
  696. // decay, the only such type in C++ is cv void. This also handles
  697. // initializer lists as variadic arguments.
  698. if (Ty->isVoidType())
  699. return VAK_Invalid;
  700. if (Ty->isObjCObjectType())
  701. return VAK_Invalid;
  702. return VAK_Valid;
  703. }
  704. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  705. return VAK_Invalid;
  706. if (Ty.isCXX98PODType(Context))
  707. return VAK_Valid;
  708. // C++11 [expr.call]p7:
  709. // Passing a potentially-evaluated argument of class type (Clause 9)
  710. // having a non-trivial copy constructor, a non-trivial move constructor,
  711. // or a non-trivial destructor, with no corresponding parameter,
  712. // is conditionally-supported with implementation-defined semantics.
  713. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  714. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  715. if (!Record->hasNonTrivialCopyConstructor() &&
  716. !Record->hasNonTrivialMoveConstructor() &&
  717. !Record->hasNonTrivialDestructor())
  718. return VAK_ValidInCXX11;
  719. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  720. return VAK_Valid;
  721. if (Ty->isObjCObjectType())
  722. return VAK_Invalid;
  723. if (getLangOpts().MSVCCompat)
  724. return VAK_MSVCUndefined;
  725. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  726. // permitted to reject them. We should consider doing so.
  727. return VAK_Undefined;
  728. }
  729. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  730. // Don't allow one to pass an Objective-C interface to a vararg.
  731. const QualType &Ty = E->getType();
  732. VarArgKind VAK = isValidVarArgType(Ty);
  733. // Complain about passing non-POD types through varargs.
  734. switch (VAK) {
  735. case VAK_ValidInCXX11:
  736. DiagRuntimeBehavior(
  737. E->getBeginLoc(), nullptr,
  738. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
  739. LLVM_FALLTHROUGH;
  740. case VAK_Valid:
  741. if (Ty->isRecordType()) {
  742. // This is unlikely to be what the user intended. If the class has a
  743. // 'c_str' member function, the user probably meant to call that.
  744. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  745. PDiag(diag::warn_pass_class_arg_to_vararg)
  746. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  747. }
  748. break;
  749. case VAK_Undefined:
  750. case VAK_MSVCUndefined:
  751. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  752. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  753. << getLangOpts().CPlusPlus11 << Ty << CT);
  754. break;
  755. case VAK_Invalid:
  756. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  757. Diag(E->getBeginLoc(),
  758. diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
  759. << Ty << CT;
  760. else if (Ty->isObjCObjectType())
  761. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  762. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  763. << Ty << CT);
  764. else
  765. Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
  766. << isa<InitListExpr>(E) << Ty << CT;
  767. break;
  768. }
  769. }
  770. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  771. /// will create a trap if the resulting type is not a POD type.
  772. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  773. FunctionDecl *FDecl) {
  774. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  775. // Strip the unbridged-cast placeholder expression off, if applicable.
  776. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  777. (CT == VariadicMethod ||
  778. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  779. E = stripARCUnbridgedCast(E);
  780. // Otherwise, do normal placeholder checking.
  781. } else {
  782. ExprResult ExprRes = CheckPlaceholderExpr(E);
  783. if (ExprRes.isInvalid())
  784. return ExprError();
  785. E = ExprRes.get();
  786. }
  787. }
  788. ExprResult ExprRes = DefaultArgumentPromotion(E);
  789. if (ExprRes.isInvalid())
  790. return ExprError();
  791. E = ExprRes.get();
  792. // Diagnostics regarding non-POD argument types are
  793. // emitted along with format string checking in Sema::CheckFunctionCall().
  794. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  795. // Turn this into a trap.
  796. CXXScopeSpec SS;
  797. SourceLocation TemplateKWLoc;
  798. UnqualifiedId Name;
  799. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  800. E->getBeginLoc());
  801. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
  802. Name, true, false);
  803. if (TrapFn.isInvalid())
  804. return ExprError();
  805. ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
  806. None, E->getEndLoc());
  807. if (Call.isInvalid())
  808. return ExprError();
  809. ExprResult Comma =
  810. ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
  811. if (Comma.isInvalid())
  812. return ExprError();
  813. return Comma.get();
  814. }
  815. if (!getLangOpts().CPlusPlus &&
  816. RequireCompleteType(E->getExprLoc(), E->getType(),
  817. diag::err_call_incomplete_argument))
  818. return ExprError();
  819. return E;
  820. }
  821. /// Converts an integer to complex float type. Helper function of
  822. /// UsualArithmeticConversions()
  823. ///
  824. /// \return false if the integer expression is an integer type and is
  825. /// successfully converted to the complex type.
  826. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  827. ExprResult &ComplexExpr,
  828. QualType IntTy,
  829. QualType ComplexTy,
  830. bool SkipCast) {
  831. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  832. if (SkipCast) return false;
  833. if (IntTy->isIntegerType()) {
  834. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  835. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  836. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  837. CK_FloatingRealToComplex);
  838. } else {
  839. assert(IntTy->isComplexIntegerType());
  840. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  841. CK_IntegralComplexToFloatingComplex);
  842. }
  843. return false;
  844. }
  845. /// Handle arithmetic conversion with complex types. Helper function of
  846. /// UsualArithmeticConversions()
  847. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  848. ExprResult &RHS, QualType LHSType,
  849. QualType RHSType,
  850. bool IsCompAssign) {
  851. // if we have an integer operand, the result is the complex type.
  852. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  853. /*skipCast*/false))
  854. return LHSType;
  855. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  856. /*skipCast*/IsCompAssign))
  857. return RHSType;
  858. // This handles complex/complex, complex/float, or float/complex.
  859. // When both operands are complex, the shorter operand is converted to the
  860. // type of the longer, and that is the type of the result. This corresponds
  861. // to what is done when combining two real floating-point operands.
  862. // The fun begins when size promotion occur across type domains.
  863. // From H&S 6.3.4: When one operand is complex and the other is a real
  864. // floating-point type, the less precise type is converted, within it's
  865. // real or complex domain, to the precision of the other type. For example,
  866. // when combining a "long double" with a "double _Complex", the
  867. // "double _Complex" is promoted to "long double _Complex".
  868. // Compute the rank of the two types, regardless of whether they are complex.
  869. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  870. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  871. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  872. QualType LHSElementType =
  873. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  874. QualType RHSElementType =
  875. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  876. QualType ResultType = S.Context.getComplexType(LHSElementType);
  877. if (Order < 0) {
  878. // Promote the precision of the LHS if not an assignment.
  879. ResultType = S.Context.getComplexType(RHSElementType);
  880. if (!IsCompAssign) {
  881. if (LHSComplexType)
  882. LHS =
  883. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  884. else
  885. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  886. }
  887. } else if (Order > 0) {
  888. // Promote the precision of the RHS.
  889. if (RHSComplexType)
  890. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  891. else
  892. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  893. }
  894. return ResultType;
  895. }
  896. /// Handle arithmetic conversion from integer to float. Helper function
  897. /// of UsualArithmeticConversions()
  898. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  899. ExprResult &IntExpr,
  900. QualType FloatTy, QualType IntTy,
  901. bool ConvertFloat, bool ConvertInt) {
  902. if (IntTy->isIntegerType()) {
  903. if (ConvertInt)
  904. // Convert intExpr to the lhs floating point type.
  905. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  906. CK_IntegralToFloating);
  907. return FloatTy;
  908. }
  909. // Convert both sides to the appropriate complex float.
  910. assert(IntTy->isComplexIntegerType());
  911. QualType result = S.Context.getComplexType(FloatTy);
  912. // _Complex int -> _Complex float
  913. if (ConvertInt)
  914. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  915. CK_IntegralComplexToFloatingComplex);
  916. // float -> _Complex float
  917. if (ConvertFloat)
  918. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  919. CK_FloatingRealToComplex);
  920. return result;
  921. }
  922. /// Handle arithmethic conversion with floating point types. Helper
  923. /// function of UsualArithmeticConversions()
  924. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  925. ExprResult &RHS, QualType LHSType,
  926. QualType RHSType, bool IsCompAssign) {
  927. bool LHSFloat = LHSType->isRealFloatingType();
  928. bool RHSFloat = RHSType->isRealFloatingType();
  929. // If we have two real floating types, convert the smaller operand
  930. // to the bigger result.
  931. if (LHSFloat && RHSFloat) {
  932. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  933. if (order > 0) {
  934. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  935. return LHSType;
  936. }
  937. assert(order < 0 && "illegal float comparison");
  938. if (!IsCompAssign)
  939. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  940. return RHSType;
  941. }
  942. if (LHSFloat) {
  943. // Half FP has to be promoted to float unless it is natively supported
  944. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  945. LHSType = S.Context.FloatTy;
  946. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  947. /*convertFloat=*/!IsCompAssign,
  948. /*convertInt=*/ true);
  949. }
  950. assert(RHSFloat);
  951. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  952. /*convertInt=*/ true,
  953. /*convertFloat=*/!IsCompAssign);
  954. }
  955. /// Diagnose attempts to convert between __float128 and long double if
  956. /// there is no support for such conversion. Helper function of
  957. /// UsualArithmeticConversions().
  958. static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
  959. QualType RHSType) {
  960. /* No issue converting if at least one of the types is not a floating point
  961. type or the two types have the same rank.
  962. */
  963. if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
  964. S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
  965. return false;
  966. assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
  967. "The remaining types must be floating point types.");
  968. auto *LHSComplex = LHSType->getAs<ComplexType>();
  969. auto *RHSComplex = RHSType->getAs<ComplexType>();
  970. QualType LHSElemType = LHSComplex ?
  971. LHSComplex->getElementType() : LHSType;
  972. QualType RHSElemType = RHSComplex ?
  973. RHSComplex->getElementType() : RHSType;
  974. // No issue if the two types have the same representation
  975. if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
  976. &S.Context.getFloatTypeSemantics(RHSElemType))
  977. return false;
  978. bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
  979. RHSElemType == S.Context.LongDoubleTy);
  980. Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
  981. RHSElemType == S.Context.Float128Ty);
  982. // We've handled the situation where __float128 and long double have the same
  983. // representation. We allow all conversions for all possible long double types
  984. // except PPC's double double.
  985. return Float128AndLongDouble &&
  986. (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
  987. &llvm::APFloat::PPCDoubleDouble());
  988. }
  989. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  990. namespace {
  991. /// These helper callbacks are placed in an anonymous namespace to
  992. /// permit their use as function template parameters.
  993. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  994. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  995. }
  996. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  997. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  998. CK_IntegralComplexCast);
  999. }
  1000. }
  1001. /// Handle integer arithmetic conversions. Helper function of
  1002. /// UsualArithmeticConversions()
  1003. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  1004. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  1005. ExprResult &RHS, QualType LHSType,
  1006. QualType RHSType, bool IsCompAssign) {
  1007. // The rules for this case are in C99 6.3.1.8
  1008. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  1009. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  1010. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  1011. if (LHSSigned == RHSSigned) {
  1012. // Same signedness; use the higher-ranked type
  1013. if (order >= 0) {
  1014. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1015. return LHSType;
  1016. } else if (!IsCompAssign)
  1017. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1018. return RHSType;
  1019. } else if (order != (LHSSigned ? 1 : -1)) {
  1020. // The unsigned type has greater than or equal rank to the
  1021. // signed type, so use the unsigned type
  1022. if (RHSSigned) {
  1023. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1024. return LHSType;
  1025. } else if (!IsCompAssign)
  1026. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1027. return RHSType;
  1028. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1029. // The two types are different widths; if we are here, that
  1030. // means the signed type is larger than the unsigned type, so
  1031. // use the signed type.
  1032. if (LHSSigned) {
  1033. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1034. return LHSType;
  1035. } else if (!IsCompAssign)
  1036. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1037. return RHSType;
  1038. } else {
  1039. // The signed type is higher-ranked than the unsigned type,
  1040. // but isn't actually any bigger (like unsigned int and long
  1041. // on most 32-bit systems). Use the unsigned type corresponding
  1042. // to the signed type.
  1043. QualType result =
  1044. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1045. RHS = (*doRHSCast)(S, RHS.get(), result);
  1046. if (!IsCompAssign)
  1047. LHS = (*doLHSCast)(S, LHS.get(), result);
  1048. return result;
  1049. }
  1050. }
  1051. /// Handle conversions with GCC complex int extension. Helper function
  1052. /// of UsualArithmeticConversions()
  1053. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1054. ExprResult &RHS, QualType LHSType,
  1055. QualType RHSType,
  1056. bool IsCompAssign) {
  1057. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1058. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1059. if (LHSComplexInt && RHSComplexInt) {
  1060. QualType LHSEltType = LHSComplexInt->getElementType();
  1061. QualType RHSEltType = RHSComplexInt->getElementType();
  1062. QualType ScalarType =
  1063. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1064. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1065. return S.Context.getComplexType(ScalarType);
  1066. }
  1067. if (LHSComplexInt) {
  1068. QualType LHSEltType = LHSComplexInt->getElementType();
  1069. QualType ScalarType =
  1070. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1071. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1072. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1073. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1074. CK_IntegralRealToComplex);
  1075. return ComplexType;
  1076. }
  1077. assert(RHSComplexInt);
  1078. QualType RHSEltType = RHSComplexInt->getElementType();
  1079. QualType ScalarType =
  1080. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1081. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1082. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1083. if (!IsCompAssign)
  1084. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1085. CK_IntegralRealToComplex);
  1086. return ComplexType;
  1087. }
  1088. /// UsualArithmeticConversions - Performs various conversions that are common to
  1089. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1090. /// routine returns the first non-arithmetic type found. The client is
  1091. /// responsible for emitting appropriate error diagnostics.
  1092. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1093. bool IsCompAssign) {
  1094. if (!IsCompAssign) {
  1095. LHS = UsualUnaryConversions(LHS.get());
  1096. if (LHS.isInvalid())
  1097. return QualType();
  1098. }
  1099. RHS = UsualUnaryConversions(RHS.get());
  1100. if (RHS.isInvalid())
  1101. return QualType();
  1102. // For conversion purposes, we ignore any qualifiers.
  1103. // For example, "const float" and "float" are equivalent.
  1104. QualType LHSType =
  1105. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1106. QualType RHSType =
  1107. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1108. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1109. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1110. LHSType = AtomicLHS->getValueType();
  1111. // If both types are identical, no conversion is needed.
  1112. if (LHSType == RHSType)
  1113. return LHSType;
  1114. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1115. // The caller can deal with this (e.g. pointer + int).
  1116. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1117. return QualType();
  1118. // Apply unary and bitfield promotions to the LHS's type.
  1119. QualType LHSUnpromotedType = LHSType;
  1120. if (LHSType->isPromotableIntegerType())
  1121. LHSType = Context.getPromotedIntegerType(LHSType);
  1122. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1123. if (!LHSBitfieldPromoteTy.isNull())
  1124. LHSType = LHSBitfieldPromoteTy;
  1125. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  1126. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1127. // If both types are identical, no conversion is needed.
  1128. if (LHSType == RHSType)
  1129. return LHSType;
  1130. // At this point, we have two different arithmetic types.
  1131. // Diagnose attempts to convert between __float128 and long double where
  1132. // such conversions currently can't be handled.
  1133. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  1134. return QualType();
  1135. // Handle complex types first (C99 6.3.1.8p1).
  1136. if (LHSType->isComplexType() || RHSType->isComplexType())
  1137. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1138. IsCompAssign);
  1139. // Now handle "real" floating types (i.e. float, double, long double).
  1140. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1141. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1142. IsCompAssign);
  1143. // Handle GCC complex int extension.
  1144. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1145. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1146. IsCompAssign);
  1147. // Finally, we have two differing integer types.
  1148. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1149. (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
  1150. }
  1151. //===----------------------------------------------------------------------===//
  1152. // Semantic Analysis for various Expression Types
  1153. //===----------------------------------------------------------------------===//
  1154. ExprResult
  1155. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1156. SourceLocation DefaultLoc,
  1157. SourceLocation RParenLoc,
  1158. Expr *ControllingExpr,
  1159. ArrayRef<ParsedType> ArgTypes,
  1160. ArrayRef<Expr *> ArgExprs) {
  1161. unsigned NumAssocs = ArgTypes.size();
  1162. assert(NumAssocs == ArgExprs.size());
  1163. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1164. for (unsigned i = 0; i < NumAssocs; ++i) {
  1165. if (ArgTypes[i])
  1166. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1167. else
  1168. Types[i] = nullptr;
  1169. }
  1170. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1171. ControllingExpr,
  1172. llvm::makeArrayRef(Types, NumAssocs),
  1173. ArgExprs);
  1174. delete [] Types;
  1175. return ER;
  1176. }
  1177. ExprResult
  1178. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1179. SourceLocation DefaultLoc,
  1180. SourceLocation RParenLoc,
  1181. Expr *ControllingExpr,
  1182. ArrayRef<TypeSourceInfo *> Types,
  1183. ArrayRef<Expr *> Exprs) {
  1184. unsigned NumAssocs = Types.size();
  1185. assert(NumAssocs == Exprs.size());
  1186. // Decay and strip qualifiers for the controlling expression type, and handle
  1187. // placeholder type replacement. See committee discussion from WG14 DR423.
  1188. {
  1189. EnterExpressionEvaluationContext Unevaluated(
  1190. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  1191. ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
  1192. if (R.isInvalid())
  1193. return ExprError();
  1194. ControllingExpr = R.get();
  1195. }
  1196. // The controlling expression is an unevaluated operand, so side effects are
  1197. // likely unintended.
  1198. if (!inTemplateInstantiation() &&
  1199. ControllingExpr->HasSideEffects(Context, false))
  1200. Diag(ControllingExpr->getExprLoc(),
  1201. diag::warn_side_effects_unevaluated_context);
  1202. bool TypeErrorFound = false,
  1203. IsResultDependent = ControllingExpr->isTypeDependent(),
  1204. ContainsUnexpandedParameterPack
  1205. = ControllingExpr->containsUnexpandedParameterPack();
  1206. for (unsigned i = 0; i < NumAssocs; ++i) {
  1207. if (Exprs[i]->containsUnexpandedParameterPack())
  1208. ContainsUnexpandedParameterPack = true;
  1209. if (Types[i]) {
  1210. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1211. ContainsUnexpandedParameterPack = true;
  1212. if (Types[i]->getType()->isDependentType()) {
  1213. IsResultDependent = true;
  1214. } else {
  1215. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1216. // complete object type other than a variably modified type."
  1217. unsigned D = 0;
  1218. if (Types[i]->getType()->isIncompleteType())
  1219. D = diag::err_assoc_type_incomplete;
  1220. else if (!Types[i]->getType()->isObjectType())
  1221. D = diag::err_assoc_type_nonobject;
  1222. else if (Types[i]->getType()->isVariablyModifiedType())
  1223. D = diag::err_assoc_type_variably_modified;
  1224. if (D != 0) {
  1225. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1226. << Types[i]->getTypeLoc().getSourceRange()
  1227. << Types[i]->getType();
  1228. TypeErrorFound = true;
  1229. }
  1230. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1231. // selection shall specify compatible types."
  1232. for (unsigned j = i+1; j < NumAssocs; ++j)
  1233. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1234. Context.typesAreCompatible(Types[i]->getType(),
  1235. Types[j]->getType())) {
  1236. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1237. diag::err_assoc_compatible_types)
  1238. << Types[j]->getTypeLoc().getSourceRange()
  1239. << Types[j]->getType()
  1240. << Types[i]->getType();
  1241. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1242. diag::note_compat_assoc)
  1243. << Types[i]->getTypeLoc().getSourceRange()
  1244. << Types[i]->getType();
  1245. TypeErrorFound = true;
  1246. }
  1247. }
  1248. }
  1249. }
  1250. if (TypeErrorFound)
  1251. return ExprError();
  1252. // If we determined that the generic selection is result-dependent, don't
  1253. // try to compute the result expression.
  1254. if (IsResultDependent)
  1255. return new (Context) GenericSelectionExpr(
  1256. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1257. ContainsUnexpandedParameterPack);
  1258. SmallVector<unsigned, 1> CompatIndices;
  1259. unsigned DefaultIndex = -1U;
  1260. for (unsigned i = 0; i < NumAssocs; ++i) {
  1261. if (!Types[i])
  1262. DefaultIndex = i;
  1263. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1264. Types[i]->getType()))
  1265. CompatIndices.push_back(i);
  1266. }
  1267. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1268. // type compatible with at most one of the types named in its generic
  1269. // association list."
  1270. if (CompatIndices.size() > 1) {
  1271. // We strip parens here because the controlling expression is typically
  1272. // parenthesized in macro definitions.
  1273. ControllingExpr = ControllingExpr->IgnoreParens();
  1274. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
  1275. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1276. << (unsigned)CompatIndices.size();
  1277. for (unsigned I : CompatIndices) {
  1278. Diag(Types[I]->getTypeLoc().getBeginLoc(),
  1279. diag::note_compat_assoc)
  1280. << Types[I]->getTypeLoc().getSourceRange()
  1281. << Types[I]->getType();
  1282. }
  1283. return ExprError();
  1284. }
  1285. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1286. // its controlling expression shall have type compatible with exactly one of
  1287. // the types named in its generic association list."
  1288. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1289. // We strip parens here because the controlling expression is typically
  1290. // parenthesized in macro definitions.
  1291. ControllingExpr = ControllingExpr->IgnoreParens();
  1292. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
  1293. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1294. return ExprError();
  1295. }
  1296. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1297. // type name that is compatible with the type of the controlling expression,
  1298. // then the result expression of the generic selection is the expression
  1299. // in that generic association. Otherwise, the result expression of the
  1300. // generic selection is the expression in the default generic association."
  1301. unsigned ResultIndex =
  1302. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1303. return new (Context) GenericSelectionExpr(
  1304. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1305. ContainsUnexpandedParameterPack, ResultIndex);
  1306. }
  1307. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1308. /// location of the token and the offset of the ud-suffix within it.
  1309. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1310. unsigned Offset) {
  1311. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1312. S.getLangOpts());
  1313. }
  1314. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1315. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1316. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1317. IdentifierInfo *UDSuffix,
  1318. SourceLocation UDSuffixLoc,
  1319. ArrayRef<Expr*> Args,
  1320. SourceLocation LitEndLoc) {
  1321. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1322. QualType ArgTy[2];
  1323. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1324. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1325. if (ArgTy[ArgIdx]->isArrayType())
  1326. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1327. }
  1328. DeclarationName OpName =
  1329. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1330. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1331. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1332. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1333. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1334. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1335. /*AllowStringTemplate*/ false,
  1336. /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
  1337. return ExprError();
  1338. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1339. }
  1340. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1341. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1342. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1343. /// multiple tokens. However, the common case is that StringToks points to one
  1344. /// string.
  1345. ///
  1346. ExprResult
  1347. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1348. assert(!StringToks.empty() && "Must have at least one string!");
  1349. StringLiteralParser Literal(StringToks, PP);
  1350. if (Literal.hadError)
  1351. return ExprError();
  1352. SmallVector<SourceLocation, 4> StringTokLocs;
  1353. for (const Token &Tok : StringToks)
  1354. StringTokLocs.push_back(Tok.getLocation());
  1355. QualType CharTy = Context.CharTy;
  1356. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1357. if (Literal.isWide()) {
  1358. CharTy = Context.getWideCharType();
  1359. Kind = StringLiteral::Wide;
  1360. } else if (Literal.isUTF8()) {
  1361. if (getLangOpts().Char8)
  1362. CharTy = Context.Char8Ty;
  1363. Kind = StringLiteral::UTF8;
  1364. } else if (Literal.isUTF16()) {
  1365. CharTy = Context.Char16Ty;
  1366. Kind = StringLiteral::UTF16;
  1367. } else if (Literal.isUTF32()) {
  1368. CharTy = Context.Char32Ty;
  1369. Kind = StringLiteral::UTF32;
  1370. } else if (Literal.isPascal()) {
  1371. CharTy = Context.UnsignedCharTy;
  1372. }
  1373. QualType CharTyConst = CharTy;
  1374. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  1375. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  1376. CharTyConst.addConst();
  1377. CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
  1378. // Get an array type for the string, according to C99 6.4.5. This includes
  1379. // the nul terminator character as well as the string length for pascal
  1380. // strings.
  1381. QualType StrTy = Context.getConstantArrayType(
  1382. CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
  1383. ArrayType::Normal, 0);
  1384. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1385. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1386. Kind, Literal.Pascal, StrTy,
  1387. &StringTokLocs[0],
  1388. StringTokLocs.size());
  1389. if (Literal.getUDSuffix().empty())
  1390. return Lit;
  1391. // We're building a user-defined literal.
  1392. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1393. SourceLocation UDSuffixLoc =
  1394. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1395. Literal.getUDSuffixOffset());
  1396. // Make sure we're allowed user-defined literals here.
  1397. if (!UDLScope)
  1398. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1399. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1400. // operator "" X (str, len)
  1401. QualType SizeType = Context.getSizeType();
  1402. DeclarationName OpName =
  1403. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1404. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1405. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1406. QualType ArgTy[] = {
  1407. Context.getArrayDecayedType(StrTy), SizeType
  1408. };
  1409. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1410. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1411. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1412. /*AllowStringTemplate*/ true,
  1413. /*DiagnoseMissing*/ true)) {
  1414. case LOLR_Cooked: {
  1415. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1416. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1417. StringTokLocs[0]);
  1418. Expr *Args[] = { Lit, LenArg };
  1419. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1420. }
  1421. case LOLR_StringTemplate: {
  1422. TemplateArgumentListInfo ExplicitArgs;
  1423. unsigned CharBits = Context.getIntWidth(CharTy);
  1424. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1425. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1426. TemplateArgument TypeArg(CharTy);
  1427. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1428. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1429. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1430. Value = Lit->getCodeUnit(I);
  1431. TemplateArgument Arg(Context, Value, CharTy);
  1432. TemplateArgumentLocInfo ArgInfo;
  1433. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1434. }
  1435. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1436. &ExplicitArgs);
  1437. }
  1438. case LOLR_Raw:
  1439. case LOLR_Template:
  1440. case LOLR_ErrorNoDiagnostic:
  1441. llvm_unreachable("unexpected literal operator lookup result");
  1442. case LOLR_Error:
  1443. return ExprError();
  1444. }
  1445. llvm_unreachable("unexpected literal operator lookup result");
  1446. }
  1447. ExprResult
  1448. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1449. SourceLocation Loc,
  1450. const CXXScopeSpec *SS) {
  1451. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1452. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1453. }
  1454. /// BuildDeclRefExpr - Build an expression that references a
  1455. /// declaration that does not require a closure capture.
  1456. ExprResult
  1457. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1458. const DeclarationNameInfo &NameInfo,
  1459. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1460. const TemplateArgumentListInfo *TemplateArgs) {
  1461. bool RefersToCapturedVariable =
  1462. isa<VarDecl>(D) &&
  1463. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1464. DeclRefExpr *E;
  1465. if (isa<VarTemplateSpecializationDecl>(D)) {
  1466. VarTemplateSpecializationDecl *VarSpec =
  1467. cast<VarTemplateSpecializationDecl>(D);
  1468. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1469. : NestedNameSpecifierLoc(),
  1470. VarSpec->getTemplateKeywordLoc(), D,
  1471. RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
  1472. FoundD, TemplateArgs);
  1473. } else {
  1474. assert(!TemplateArgs && "No template arguments for non-variable"
  1475. " template specialization references");
  1476. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1477. : NestedNameSpecifierLoc(),
  1478. SourceLocation(), D, RefersToCapturedVariable,
  1479. NameInfo, Ty, VK, FoundD);
  1480. }
  1481. MarkDeclRefReferenced(E);
  1482. if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
  1483. Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
  1484. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
  1485. getCurFunction()->recordUseOfWeak(E);
  1486. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1487. if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
  1488. FD = IFD->getAnonField();
  1489. if (FD) {
  1490. UnusedPrivateFields.remove(FD);
  1491. // Just in case we're building an illegal pointer-to-member.
  1492. if (FD->isBitField())
  1493. E->setObjectKind(OK_BitField);
  1494. }
  1495. // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
  1496. // designates a bit-field.
  1497. if (auto *BD = dyn_cast<BindingDecl>(D))
  1498. if (auto *BE = BD->getBinding())
  1499. E->setObjectKind(BE->getObjectKind());
  1500. return E;
  1501. }
  1502. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1503. /// possibly a list of template arguments.
  1504. ///
  1505. /// If this produces template arguments, it is permitted to call
  1506. /// DecomposeTemplateName.
  1507. ///
  1508. /// This actually loses a lot of source location information for
  1509. /// non-standard name kinds; we should consider preserving that in
  1510. /// some way.
  1511. void
  1512. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1513. TemplateArgumentListInfo &Buffer,
  1514. DeclarationNameInfo &NameInfo,
  1515. const TemplateArgumentListInfo *&TemplateArgs) {
  1516. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
  1517. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1518. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1519. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1520. Id.TemplateId->NumArgs);
  1521. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1522. TemplateName TName = Id.TemplateId->Template.get();
  1523. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1524. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1525. TemplateArgs = &Buffer;
  1526. } else {
  1527. NameInfo = GetNameFromUnqualifiedId(Id);
  1528. TemplateArgs = nullptr;
  1529. }
  1530. }
  1531. static void emitEmptyLookupTypoDiagnostic(
  1532. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1533. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1534. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1535. DeclContext *Ctx =
  1536. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1537. if (!TC) {
  1538. // Emit a special diagnostic for failed member lookups.
  1539. // FIXME: computing the declaration context might fail here (?)
  1540. if (Ctx)
  1541. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1542. << SS.getRange();
  1543. else
  1544. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1545. return;
  1546. }
  1547. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1548. bool DroppedSpecifier =
  1549. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1550. unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
  1551. ? diag::note_implicit_param_decl
  1552. : diag::note_previous_decl;
  1553. if (!Ctx)
  1554. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1555. SemaRef.PDiag(NoteID));
  1556. else
  1557. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1558. << Typo << Ctx << DroppedSpecifier
  1559. << SS.getRange(),
  1560. SemaRef.PDiag(NoteID));
  1561. }
  1562. /// Diagnose an empty lookup.
  1563. ///
  1564. /// \return false if new lookup candidates were found
  1565. bool
  1566. Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1567. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1568. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1569. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1570. DeclarationName Name = R.getLookupName();
  1571. unsigned diagnostic = diag::err_undeclared_var_use;
  1572. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1573. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1574. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1575. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1576. diagnostic = diag::err_undeclared_use;
  1577. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1578. }
  1579. // If the original lookup was an unqualified lookup, fake an
  1580. // unqualified lookup. This is useful when (for example) the
  1581. // original lookup would not have found something because it was a
  1582. // dependent name.
  1583. DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
  1584. while (DC) {
  1585. if (isa<CXXRecordDecl>(DC)) {
  1586. LookupQualifiedName(R, DC);
  1587. if (!R.empty()) {
  1588. // Don't give errors about ambiguities in this lookup.
  1589. R.suppressDiagnostics();
  1590. // During a default argument instantiation the CurContext points
  1591. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1592. // function parameter list, hence add an explicit check.
  1593. bool isDefaultArgument =
  1594. !CodeSynthesisContexts.empty() &&
  1595. CodeSynthesisContexts.back().Kind ==
  1596. CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
  1597. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1598. bool isInstance = CurMethod &&
  1599. CurMethod->isInstance() &&
  1600. DC == CurMethod->getParent() && !isDefaultArgument;
  1601. // Give a code modification hint to insert 'this->'.
  1602. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1603. // Actually quite difficult!
  1604. if (getLangOpts().MSVCCompat)
  1605. diagnostic = diag::ext_found_via_dependent_bases_lookup;
  1606. if (isInstance) {
  1607. Diag(R.getNameLoc(), diagnostic) << Name
  1608. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1609. CheckCXXThisCapture(R.getNameLoc());
  1610. } else {
  1611. Diag(R.getNameLoc(), diagnostic) << Name;
  1612. }
  1613. // Do we really want to note all of these?
  1614. for (NamedDecl *D : R)
  1615. Diag(D->getLocation(), diag::note_dependent_var_use);
  1616. // Return true if we are inside a default argument instantiation
  1617. // and the found name refers to an instance member function, otherwise
  1618. // the function calling DiagnoseEmptyLookup will try to create an
  1619. // implicit member call and this is wrong for default argument.
  1620. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1621. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1622. return true;
  1623. }
  1624. // Tell the callee to try to recover.
  1625. return false;
  1626. }
  1627. R.clear();
  1628. }
  1629. // In Microsoft mode, if we are performing lookup from within a friend
  1630. // function definition declared at class scope then we must set
  1631. // DC to the lexical parent to be able to search into the parent
  1632. // class.
  1633. if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
  1634. cast<FunctionDecl>(DC)->getFriendObjectKind() &&
  1635. DC->getLexicalParent()->isRecord())
  1636. DC = DC->getLexicalParent();
  1637. else
  1638. DC = DC->getParent();
  1639. }
  1640. // We didn't find anything, so try to correct for a typo.
  1641. TypoCorrection Corrected;
  1642. if (S && Out) {
  1643. SourceLocation TypoLoc = R.getNameLoc();
  1644. assert(!ExplicitTemplateArgs &&
  1645. "Diagnosing an empty lookup with explicit template args!");
  1646. *Out = CorrectTypoDelayed(
  1647. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
  1648. [=](const TypoCorrection &TC) {
  1649. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1650. diagnostic, diagnostic_suggest);
  1651. },
  1652. nullptr, CTK_ErrorRecovery);
  1653. if (*Out)
  1654. return true;
  1655. } else if (S && (Corrected =
  1656. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
  1657. &SS, std::move(CCC), CTK_ErrorRecovery))) {
  1658. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1659. bool DroppedSpecifier =
  1660. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1661. R.setLookupName(Corrected.getCorrection());
  1662. bool AcceptableWithRecovery = false;
  1663. bool AcceptableWithoutRecovery = false;
  1664. NamedDecl *ND = Corrected.getFoundDecl();
  1665. if (ND) {
  1666. if (Corrected.isOverloaded()) {
  1667. OverloadCandidateSet OCS(R.getNameLoc(),
  1668. OverloadCandidateSet::CSK_Normal);
  1669. OverloadCandidateSet::iterator Best;
  1670. for (NamedDecl *CD : Corrected) {
  1671. if (FunctionTemplateDecl *FTD =
  1672. dyn_cast<FunctionTemplateDecl>(CD))
  1673. AddTemplateOverloadCandidate(
  1674. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1675. Args, OCS);
  1676. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  1677. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1678. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1679. Args, OCS);
  1680. }
  1681. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1682. case OR_Success:
  1683. ND = Best->FoundDecl;
  1684. Corrected.setCorrectionDecl(ND);
  1685. break;
  1686. default:
  1687. // FIXME: Arbitrarily pick the first declaration for the note.
  1688. Corrected.setCorrectionDecl(ND);
  1689. break;
  1690. }
  1691. }
  1692. R.addDecl(ND);
  1693. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1694. CXXRecordDecl *Record = nullptr;
  1695. if (Corrected.getCorrectionSpecifier()) {
  1696. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1697. Record = Ty->getAsCXXRecordDecl();
  1698. }
  1699. if (!Record)
  1700. Record = cast<CXXRecordDecl>(
  1701. ND->getDeclContext()->getRedeclContext());
  1702. R.setNamingClass(Record);
  1703. }
  1704. auto *UnderlyingND = ND->getUnderlyingDecl();
  1705. AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
  1706. isa<FunctionTemplateDecl>(UnderlyingND);
  1707. // FIXME: If we ended up with a typo for a type name or
  1708. // Objective-C class name, we're in trouble because the parser
  1709. // is in the wrong place to recover. Suggest the typo
  1710. // correction, but don't make it a fix-it since we're not going
  1711. // to recover well anyway.
  1712. AcceptableWithoutRecovery =
  1713. isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
  1714. } else {
  1715. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1716. // because we aren't able to recover.
  1717. AcceptableWithoutRecovery = true;
  1718. }
  1719. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1720. unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
  1721. ? diag::note_implicit_param_decl
  1722. : diag::note_previous_decl;
  1723. if (SS.isEmpty())
  1724. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1725. PDiag(NoteID), AcceptableWithRecovery);
  1726. else
  1727. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1728. << Name << computeDeclContext(SS, false)
  1729. << DroppedSpecifier << SS.getRange(),
  1730. PDiag(NoteID), AcceptableWithRecovery);
  1731. // Tell the callee whether to try to recover.
  1732. return !AcceptableWithRecovery;
  1733. }
  1734. }
  1735. R.clear();
  1736. // Emit a special diagnostic for failed member lookups.
  1737. // FIXME: computing the declaration context might fail here (?)
  1738. if (!SS.isEmpty()) {
  1739. Diag(R.getNameLoc(), diag::err_no_member)
  1740. << Name << computeDeclContext(SS, false)
  1741. << SS.getRange();
  1742. return true;
  1743. }
  1744. // Give up, we can't recover.
  1745. Diag(R.getNameLoc(), diagnostic) << Name;
  1746. return true;
  1747. }
  1748. /// In Microsoft mode, if we are inside a template class whose parent class has
  1749. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1750. /// assume the identifier is a member of a dependent base class. We can only
  1751. /// recover successfully in static methods, instance methods, and other contexts
  1752. /// where 'this' is available. This doesn't precisely match MSVC's
  1753. /// instantiation model, but it's close enough.
  1754. static Expr *
  1755. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1756. DeclarationNameInfo &NameInfo,
  1757. SourceLocation TemplateKWLoc,
  1758. const TemplateArgumentListInfo *TemplateArgs) {
  1759. // Only try to recover from lookup into dependent bases in static methods or
  1760. // contexts where 'this' is available.
  1761. QualType ThisType = S.getCurrentThisType();
  1762. const CXXRecordDecl *RD = nullptr;
  1763. if (!ThisType.isNull())
  1764. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1765. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1766. RD = MD->getParent();
  1767. if (!RD || !RD->hasAnyDependentBases())
  1768. return nullptr;
  1769. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1770. // is available, suggest inserting 'this->' as a fixit.
  1771. SourceLocation Loc = NameInfo.getLoc();
  1772. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1773. DB << NameInfo.getName() << RD;
  1774. if (!ThisType.isNull()) {
  1775. DB << FixItHint::CreateInsertion(Loc, "this->");
  1776. return CXXDependentScopeMemberExpr::Create(
  1777. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1778. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1779. /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
  1780. }
  1781. // Synthesize a fake NNS that points to the derived class. This will
  1782. // perform name lookup during template instantiation.
  1783. CXXScopeSpec SS;
  1784. auto *NNS =
  1785. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1786. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1787. return DependentScopeDeclRefExpr::Create(
  1788. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1789. TemplateArgs);
  1790. }
  1791. ExprResult
  1792. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1793. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1794. bool HasTrailingLParen, bool IsAddressOfOperand,
  1795. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1796. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1797. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1798. "cannot be direct & operand and have a trailing lparen");
  1799. if (SS.isInvalid())
  1800. return ExprError();
  1801. TemplateArgumentListInfo TemplateArgsBuffer;
  1802. // Decompose the UnqualifiedId into the following data.
  1803. DeclarationNameInfo NameInfo;
  1804. const TemplateArgumentListInfo *TemplateArgs;
  1805. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1806. DeclarationName Name = NameInfo.getName();
  1807. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1808. SourceLocation NameLoc = NameInfo.getLoc();
  1809. if (II && II->isEditorPlaceholder()) {
  1810. // FIXME: When typed placeholders are supported we can create a typed
  1811. // placeholder expression node.
  1812. return ExprError();
  1813. }
  1814. // C++ [temp.dep.expr]p3:
  1815. // An id-expression is type-dependent if it contains:
  1816. // -- an identifier that was declared with a dependent type,
  1817. // (note: handled after lookup)
  1818. // -- a template-id that is dependent,
  1819. // (note: handled in BuildTemplateIdExpr)
  1820. // -- a conversion-function-id that specifies a dependent type,
  1821. // -- a nested-name-specifier that contains a class-name that
  1822. // names a dependent type.
  1823. // Determine whether this is a member of an unknown specialization;
  1824. // we need to handle these differently.
  1825. bool DependentID = false;
  1826. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1827. Name.getCXXNameType()->isDependentType()) {
  1828. DependentID = true;
  1829. } else if (SS.isSet()) {
  1830. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1831. if (RequireCompleteDeclContext(SS, DC))
  1832. return ExprError();
  1833. } else {
  1834. DependentID = true;
  1835. }
  1836. }
  1837. if (DependentID)
  1838. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1839. IsAddressOfOperand, TemplateArgs);
  1840. // Perform the required lookup.
  1841. LookupResult R(*this, NameInfo,
  1842. (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
  1843. ? LookupObjCImplicitSelfParam
  1844. : LookupOrdinaryName);
  1845. if (TemplateKWLoc.isValid() || TemplateArgs) {
  1846. // Lookup the template name again to correctly establish the context in
  1847. // which it was found. This is really unfortunate as we already did the
  1848. // lookup to determine that it was a template name in the first place. If
  1849. // this becomes a performance hit, we can work harder to preserve those
  1850. // results until we get here but it's likely not worth it.
  1851. bool MemberOfUnknownSpecialization;
  1852. if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1853. MemberOfUnknownSpecialization, TemplateKWLoc))
  1854. return ExprError();
  1855. if (MemberOfUnknownSpecialization ||
  1856. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1857. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1858. IsAddressOfOperand, TemplateArgs);
  1859. } else {
  1860. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1861. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1862. // If the result might be in a dependent base class, this is a dependent
  1863. // id-expression.
  1864. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1865. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1866. IsAddressOfOperand, TemplateArgs);
  1867. // If this reference is in an Objective-C method, then we need to do
  1868. // some special Objective-C lookup, too.
  1869. if (IvarLookupFollowUp) {
  1870. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1871. if (E.isInvalid())
  1872. return ExprError();
  1873. if (Expr *Ex = E.getAs<Expr>())
  1874. return Ex;
  1875. }
  1876. }
  1877. if (R.isAmbiguous())
  1878. return ExprError();
  1879. // This could be an implicitly declared function reference (legal in C90,
  1880. // extension in C99, forbidden in C++).
  1881. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  1882. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  1883. if (D) R.addDecl(D);
  1884. }
  1885. // Determine whether this name might be a candidate for
  1886. // argument-dependent lookup.
  1887. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  1888. if (R.empty() && !ADL) {
  1889. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  1890. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  1891. TemplateKWLoc, TemplateArgs))
  1892. return E;
  1893. }
  1894. // Don't diagnose an empty lookup for inline assembly.
  1895. if (IsInlineAsmIdentifier)
  1896. return ExprError();
  1897. // If this name wasn't predeclared and if this is not a function
  1898. // call, diagnose the problem.
  1899. TypoExpr *TE = nullptr;
  1900. auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
  1901. II, SS.isValid() ? SS.getScopeRep() : nullptr);
  1902. DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
  1903. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  1904. "Typo correction callback misconfigured");
  1905. if (CCC) {
  1906. // Make sure the callback knows what the typo being diagnosed is.
  1907. CCC->setTypoName(II);
  1908. if (SS.isValid())
  1909. CCC->setTypoNNS(SS.getScopeRep());
  1910. }
  1911. // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
  1912. // a template name, but we happen to have always already looked up the name
  1913. // before we get here if it must be a template name.
  1914. if (DiagnoseEmptyLookup(S, SS, R,
  1915. CCC ? std::move(CCC) : std::move(DefaultValidator),
  1916. nullptr, None, &TE)) {
  1917. if (TE && KeywordReplacement) {
  1918. auto &State = getTypoExprState(TE);
  1919. auto BestTC = State.Consumer->getNextCorrection();
  1920. if (BestTC.isKeyword()) {
  1921. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  1922. if (State.DiagHandler)
  1923. State.DiagHandler(BestTC);
  1924. KeywordReplacement->startToken();
  1925. KeywordReplacement->setKind(II->getTokenID());
  1926. KeywordReplacement->setIdentifierInfo(II);
  1927. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  1928. // Clean up the state associated with the TypoExpr, since it has
  1929. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  1930. clearDelayedTypo(TE);
  1931. // Signal that a correction to a keyword was performed by returning a
  1932. // valid-but-null ExprResult.
  1933. return (Expr*)nullptr;
  1934. }
  1935. State.Consumer->resetCorrectionStream();
  1936. }
  1937. return TE ? TE : ExprError();
  1938. }
  1939. assert(!R.empty() &&
  1940. "DiagnoseEmptyLookup returned false but added no results");
  1941. // If we found an Objective-C instance variable, let
  1942. // LookupInObjCMethod build the appropriate expression to
  1943. // reference the ivar.
  1944. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  1945. R.clear();
  1946. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  1947. // In a hopelessly buggy code, Objective-C instance variable
  1948. // lookup fails and no expression will be built to reference it.
  1949. if (!E.isInvalid() && !E.get())
  1950. return ExprError();
  1951. return E;
  1952. }
  1953. }
  1954. // This is guaranteed from this point on.
  1955. assert(!R.empty() || ADL);
  1956. // Check whether this might be a C++ implicit instance member access.
  1957. // C++ [class.mfct.non-static]p3:
  1958. // When an id-expression that is not part of a class member access
  1959. // syntax and not used to form a pointer to member is used in the
  1960. // body of a non-static member function of class X, if name lookup
  1961. // resolves the name in the id-expression to a non-static non-type
  1962. // member of some class C, the id-expression is transformed into a
  1963. // class member access expression using (*this) as the
  1964. // postfix-expression to the left of the . operator.
  1965. //
  1966. // But we don't actually need to do this for '&' operands if R
  1967. // resolved to a function or overloaded function set, because the
  1968. // expression is ill-formed if it actually works out to be a
  1969. // non-static member function:
  1970. //
  1971. // C++ [expr.ref]p4:
  1972. // Otherwise, if E1.E2 refers to a non-static member function. . .
  1973. // [t]he expression can be used only as the left-hand operand of a
  1974. // member function call.
  1975. //
  1976. // There are other safeguards against such uses, but it's important
  1977. // to get this right here so that we don't end up making a
  1978. // spuriously dependent expression if we're inside a dependent
  1979. // instance method.
  1980. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  1981. bool MightBeImplicitMember;
  1982. if (!IsAddressOfOperand)
  1983. MightBeImplicitMember = true;
  1984. else if (!SS.isEmpty())
  1985. MightBeImplicitMember = false;
  1986. else if (R.isOverloadedResult())
  1987. MightBeImplicitMember = false;
  1988. else if (R.isUnresolvableResult())
  1989. MightBeImplicitMember = true;
  1990. else
  1991. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  1992. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  1993. isa<MSPropertyDecl>(R.getFoundDecl());
  1994. if (MightBeImplicitMember)
  1995. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  1996. R, TemplateArgs, S);
  1997. }
  1998. if (TemplateArgs || TemplateKWLoc.isValid()) {
  1999. // In C++1y, if this is a variable template id, then check it
  2000. // in BuildTemplateIdExpr().
  2001. // The single lookup result must be a variable template declaration.
  2002. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
  2003. Id.TemplateId->Kind == TNK_Var_template) {
  2004. assert(R.getAsSingle<VarTemplateDecl>() &&
  2005. "There should only be one declaration found.");
  2006. }
  2007. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  2008. }
  2009. return BuildDeclarationNameExpr(SS, R, ADL);
  2010. }
  2011. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2012. /// declaration name, generally during template instantiation.
  2013. /// There's a large number of things which don't need to be done along
  2014. /// this path.
  2015. ExprResult Sema::BuildQualifiedDeclarationNameExpr(
  2016. CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
  2017. bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
  2018. DeclContext *DC = computeDeclContext(SS, false);
  2019. if (!DC)
  2020. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2021. NameInfo, /*TemplateArgs=*/nullptr);
  2022. if (RequireCompleteDeclContext(SS, DC))
  2023. return ExprError();
  2024. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2025. LookupQualifiedName(R, DC);
  2026. if (R.isAmbiguous())
  2027. return ExprError();
  2028. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2029. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2030. NameInfo, /*TemplateArgs=*/nullptr);
  2031. if (R.empty()) {
  2032. Diag(NameInfo.getLoc(), diag::err_no_member)
  2033. << NameInfo.getName() << DC << SS.getRange();
  2034. return ExprError();
  2035. }
  2036. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2037. // Diagnose a missing typename if this resolved unambiguously to a type in
  2038. // a dependent context. If we can recover with a type, downgrade this to
  2039. // a warning in Microsoft compatibility mode.
  2040. unsigned DiagID = diag::err_typename_missing;
  2041. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2042. DiagID = diag::ext_typename_missing;
  2043. SourceLocation Loc = SS.getBeginLoc();
  2044. auto D = Diag(Loc, DiagID);
  2045. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2046. << SourceRange(Loc, NameInfo.getEndLoc());
  2047. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2048. // context.
  2049. if (!RecoveryTSI)
  2050. return ExprError();
  2051. // Only issue the fixit if we're prepared to recover.
  2052. D << FixItHint::CreateInsertion(Loc, "typename ");
  2053. // Recover by pretending this was an elaborated type.
  2054. QualType Ty = Context.getTypeDeclType(TD);
  2055. TypeLocBuilder TLB;
  2056. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2057. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2058. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2059. QTL.setElaboratedKeywordLoc(SourceLocation());
  2060. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2061. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2062. return ExprEmpty();
  2063. }
  2064. // Defend against this resolving to an implicit member access. We usually
  2065. // won't get here if this might be a legitimate a class member (we end up in
  2066. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2067. // a pointer-to-member or in an unevaluated context in C++11.
  2068. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2069. return BuildPossibleImplicitMemberExpr(SS,
  2070. /*TemplateKWLoc=*/SourceLocation(),
  2071. R, /*TemplateArgs=*/nullptr, S);
  2072. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2073. }
  2074. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  2075. /// detected that we're currently inside an ObjC method. Perform some
  2076. /// additional lookup.
  2077. ///
  2078. /// Ideally, most of this would be done by lookup, but there's
  2079. /// actually quite a lot of extra work involved.
  2080. ///
  2081. /// Returns a null sentinel to indicate trivial success.
  2082. ExprResult
  2083. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2084. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2085. SourceLocation Loc = Lookup.getNameLoc();
  2086. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2087. // Check for error condition which is already reported.
  2088. if (!CurMethod)
  2089. return ExprError();
  2090. // There are two cases to handle here. 1) scoped lookup could have failed,
  2091. // in which case we should look for an ivar. 2) scoped lookup could have
  2092. // found a decl, but that decl is outside the current instance method (i.e.
  2093. // a global variable). In these two cases, we do a lookup for an ivar with
  2094. // this name, if the lookup sucedes, we replace it our current decl.
  2095. // If we're in a class method, we don't normally want to look for
  2096. // ivars. But if we don't find anything else, and there's an
  2097. // ivar, that's an error.
  2098. bool IsClassMethod = CurMethod->isClassMethod();
  2099. bool LookForIvars;
  2100. if (Lookup.empty())
  2101. LookForIvars = true;
  2102. else if (IsClassMethod)
  2103. LookForIvars = false;
  2104. else
  2105. LookForIvars = (Lookup.isSingleResult() &&
  2106. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2107. ObjCInterfaceDecl *IFace = nullptr;
  2108. if (LookForIvars) {
  2109. IFace = CurMethod->getClassInterface();
  2110. ObjCInterfaceDecl *ClassDeclared;
  2111. ObjCIvarDecl *IV = nullptr;
  2112. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2113. // Diagnose using an ivar in a class method.
  2114. if (IsClassMethod)
  2115. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2116. << IV->getDeclName());
  2117. // If we're referencing an invalid decl, just return this as a silent
  2118. // error node. The error diagnostic was already emitted on the decl.
  2119. if (IV->isInvalidDecl())
  2120. return ExprError();
  2121. // Check if referencing a field with __attribute__((deprecated)).
  2122. if (DiagnoseUseOfDecl(IV, Loc))
  2123. return ExprError();
  2124. // Diagnose the use of an ivar outside of the declaring class.
  2125. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2126. !declaresSameEntity(ClassDeclared, IFace) &&
  2127. !getLangOpts().DebuggerSupport)
  2128. Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
  2129. // FIXME: This should use a new expr for a direct reference, don't
  2130. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2131. IdentifierInfo &II = Context.Idents.get("self");
  2132. UnqualifiedId SelfName;
  2133. SelfName.setIdentifier(&II, SourceLocation());
  2134. SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
  2135. CXXScopeSpec SelfScopeSpec;
  2136. SourceLocation TemplateKWLoc;
  2137. ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
  2138. SelfName, false, false);
  2139. if (SelfExpr.isInvalid())
  2140. return ExprError();
  2141. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2142. if (SelfExpr.isInvalid())
  2143. return ExprError();
  2144. MarkAnyDeclReferenced(Loc, IV, true);
  2145. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2146. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2147. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2148. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2149. ObjCIvarRefExpr *Result = new (Context)
  2150. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2151. IV->getLocation(), SelfExpr.get(), true, true);
  2152. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2153. if (!isUnevaluatedContext() &&
  2154. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2155. getCurFunction()->recordUseOfWeak(Result);
  2156. }
  2157. if (getLangOpts().ObjCAutoRefCount) {
  2158. if (CurContext->isClosure())
  2159. Diag(Loc, diag::warn_implicitly_retains_self)
  2160. << FixItHint::CreateInsertion(Loc, "self->");
  2161. }
  2162. return Result;
  2163. }
  2164. } else if (CurMethod->isInstanceMethod()) {
  2165. // We should warn if a local variable hides an ivar.
  2166. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2167. ObjCInterfaceDecl *ClassDeclared;
  2168. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2169. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2170. declaresSameEntity(IFace, ClassDeclared))
  2171. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2172. }
  2173. }
  2174. } else if (Lookup.isSingleResult() &&
  2175. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2176. // If accessing a stand-alone ivar in a class method, this is an error.
  2177. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  2178. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2179. << IV->getDeclName());
  2180. }
  2181. if (Lookup.empty() && II && AllowBuiltinCreation) {
  2182. // FIXME. Consolidate this with similar code in LookupName.
  2183. if (unsigned BuiltinID = II->getBuiltinID()) {
  2184. if (!(getLangOpts().CPlusPlus &&
  2185. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  2186. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  2187. S, Lookup.isForRedeclaration(),
  2188. Lookup.getNameLoc());
  2189. if (D) Lookup.addDecl(D);
  2190. }
  2191. }
  2192. }
  2193. // Sentinel value saying that we didn't do anything special.
  2194. return ExprResult((Expr *)nullptr);
  2195. }
  2196. /// Cast a base object to a member's actual type.
  2197. ///
  2198. /// Logically this happens in three phases:
  2199. ///
  2200. /// * First we cast from the base type to the naming class.
  2201. /// The naming class is the class into which we were looking
  2202. /// when we found the member; it's the qualifier type if a
  2203. /// qualifier was provided, and otherwise it's the base type.
  2204. ///
  2205. /// * Next we cast from the naming class to the declaring class.
  2206. /// If the member we found was brought into a class's scope by
  2207. /// a using declaration, this is that class; otherwise it's
  2208. /// the class declaring the member.
  2209. ///
  2210. /// * Finally we cast from the declaring class to the "true"
  2211. /// declaring class of the member. This conversion does not
  2212. /// obey access control.
  2213. ExprResult
  2214. Sema::PerformObjectMemberConversion(Expr *From,
  2215. NestedNameSpecifier *Qualifier,
  2216. NamedDecl *FoundDecl,
  2217. NamedDecl *Member) {
  2218. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2219. if (!RD)
  2220. return From;
  2221. QualType DestRecordType;
  2222. QualType DestType;
  2223. QualType FromRecordType;
  2224. QualType FromType = From->getType();
  2225. bool PointerConversions = false;
  2226. if (isa<FieldDecl>(Member)) {
  2227. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2228. if (FromType->getAs<PointerType>()) {
  2229. DestType = Context.getPointerType(DestRecordType);
  2230. FromRecordType = FromType->getPointeeType();
  2231. PointerConversions = true;
  2232. } else {
  2233. DestType = DestRecordType;
  2234. FromRecordType = FromType;
  2235. }
  2236. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2237. if (Method->isStatic())
  2238. return From;
  2239. DestType = Method->getThisType(Context);
  2240. DestRecordType = DestType->getPointeeType();
  2241. if (FromType->getAs<PointerType>()) {
  2242. FromRecordType = FromType->getPointeeType();
  2243. PointerConversions = true;
  2244. } else {
  2245. FromRecordType = FromType;
  2246. DestType = DestRecordType;
  2247. }
  2248. } else {
  2249. // No conversion necessary.
  2250. return From;
  2251. }
  2252. if (DestType->isDependentType() || FromType->isDependentType())
  2253. return From;
  2254. // If the unqualified types are the same, no conversion is necessary.
  2255. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2256. return From;
  2257. SourceRange FromRange = From->getSourceRange();
  2258. SourceLocation FromLoc = FromRange.getBegin();
  2259. ExprValueKind VK = From->getValueKind();
  2260. // C++ [class.member.lookup]p8:
  2261. // [...] Ambiguities can often be resolved by qualifying a name with its
  2262. // class name.
  2263. //
  2264. // If the member was a qualified name and the qualified referred to a
  2265. // specific base subobject type, we'll cast to that intermediate type
  2266. // first and then to the object in which the member is declared. That allows
  2267. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2268. //
  2269. // class Base { public: int x; };
  2270. // class Derived1 : public Base { };
  2271. // class Derived2 : public Base { };
  2272. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2273. //
  2274. // void VeryDerived::f() {
  2275. // x = 17; // error: ambiguous base subobjects
  2276. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2277. // }
  2278. if (Qualifier && Qualifier->getAsType()) {
  2279. QualType QType = QualType(Qualifier->getAsType(), 0);
  2280. assert(QType->isRecordType() && "lookup done with non-record type");
  2281. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2282. // In C++98, the qualifier type doesn't actually have to be a base
  2283. // type of the object type, in which case we just ignore it.
  2284. // Otherwise build the appropriate casts.
  2285. if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
  2286. CXXCastPath BasePath;
  2287. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2288. FromLoc, FromRange, &BasePath))
  2289. return ExprError();
  2290. if (PointerConversions)
  2291. QType = Context.getPointerType(QType);
  2292. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2293. VK, &BasePath).get();
  2294. FromType = QType;
  2295. FromRecordType = QRecordType;
  2296. // If the qualifier type was the same as the destination type,
  2297. // we're done.
  2298. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2299. return From;
  2300. }
  2301. }
  2302. bool IgnoreAccess = false;
  2303. // If we actually found the member through a using declaration, cast
  2304. // down to the using declaration's type.
  2305. //
  2306. // Pointer equality is fine here because only one declaration of a
  2307. // class ever has member declarations.
  2308. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2309. assert(isa<UsingShadowDecl>(FoundDecl));
  2310. QualType URecordType = Context.getTypeDeclType(
  2311. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2312. // We only need to do this if the naming-class to declaring-class
  2313. // conversion is non-trivial.
  2314. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2315. assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
  2316. CXXCastPath BasePath;
  2317. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2318. FromLoc, FromRange, &BasePath))
  2319. return ExprError();
  2320. QualType UType = URecordType;
  2321. if (PointerConversions)
  2322. UType = Context.getPointerType(UType);
  2323. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2324. VK, &BasePath).get();
  2325. FromType = UType;
  2326. FromRecordType = URecordType;
  2327. }
  2328. // We don't do access control for the conversion from the
  2329. // declaring class to the true declaring class.
  2330. IgnoreAccess = true;
  2331. }
  2332. CXXCastPath BasePath;
  2333. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2334. FromLoc, FromRange, &BasePath,
  2335. IgnoreAccess))
  2336. return ExprError();
  2337. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2338. VK, &BasePath);
  2339. }
  2340. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2341. const LookupResult &R,
  2342. bool HasTrailingLParen) {
  2343. // Only when used directly as the postfix-expression of a call.
  2344. if (!HasTrailingLParen)
  2345. return false;
  2346. // Never if a scope specifier was provided.
  2347. if (SS.isSet())
  2348. return false;
  2349. // Only in C++ or ObjC++.
  2350. if (!getLangOpts().CPlusPlus)
  2351. return false;
  2352. // Turn off ADL when we find certain kinds of declarations during
  2353. // normal lookup:
  2354. for (NamedDecl *D : R) {
  2355. // C++0x [basic.lookup.argdep]p3:
  2356. // -- a declaration of a class member
  2357. // Since using decls preserve this property, we check this on the
  2358. // original decl.
  2359. if (D->isCXXClassMember())
  2360. return false;
  2361. // C++0x [basic.lookup.argdep]p3:
  2362. // -- a block-scope function declaration that is not a
  2363. // using-declaration
  2364. // NOTE: we also trigger this for function templates (in fact, we
  2365. // don't check the decl type at all, since all other decl types
  2366. // turn off ADL anyway).
  2367. if (isa<UsingShadowDecl>(D))
  2368. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2369. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2370. return false;
  2371. // C++0x [basic.lookup.argdep]p3:
  2372. // -- a declaration that is neither a function or a function
  2373. // template
  2374. // And also for builtin functions.
  2375. if (isa<FunctionDecl>(D)) {
  2376. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2377. // But also builtin functions.
  2378. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2379. return false;
  2380. } else if (!isa<FunctionTemplateDecl>(D))
  2381. return false;
  2382. }
  2383. return true;
  2384. }
  2385. /// Diagnoses obvious problems with the use of the given declaration
  2386. /// as an expression. This is only actually called for lookups that
  2387. /// were not overloaded, and it doesn't promise that the declaration
  2388. /// will in fact be used.
  2389. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2390. if (D->isInvalidDecl())
  2391. return true;
  2392. if (isa<TypedefNameDecl>(D)) {
  2393. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2394. return true;
  2395. }
  2396. if (isa<ObjCInterfaceDecl>(D)) {
  2397. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2398. return true;
  2399. }
  2400. if (isa<NamespaceDecl>(D)) {
  2401. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2402. return true;
  2403. }
  2404. return false;
  2405. }
  2406. // Certain multiversion types should be treated as overloaded even when there is
  2407. // only one result.
  2408. static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
  2409. assert(R.isSingleResult() && "Expected only a single result");
  2410. const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  2411. return FD &&
  2412. (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
  2413. }
  2414. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2415. LookupResult &R, bool NeedsADL,
  2416. bool AcceptInvalidDecl) {
  2417. // If this is a single, fully-resolved result and we don't need ADL,
  2418. // just build an ordinary singleton decl ref.
  2419. if (!NeedsADL && R.isSingleResult() &&
  2420. !R.getAsSingle<FunctionTemplateDecl>() &&
  2421. !ShouldLookupResultBeMultiVersionOverload(R))
  2422. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2423. R.getRepresentativeDecl(), nullptr,
  2424. AcceptInvalidDecl);
  2425. // We only need to check the declaration if there's exactly one
  2426. // result, because in the overloaded case the results can only be
  2427. // functions and function templates.
  2428. if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
  2429. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2430. return ExprError();
  2431. // Otherwise, just build an unresolved lookup expression. Suppress
  2432. // any lookup-related diagnostics; we'll hash these out later, when
  2433. // we've picked a target.
  2434. R.suppressDiagnostics();
  2435. UnresolvedLookupExpr *ULE
  2436. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2437. SS.getWithLocInContext(Context),
  2438. R.getLookupNameInfo(),
  2439. NeedsADL, R.isOverloadedResult(),
  2440. R.begin(), R.end());
  2441. return ULE;
  2442. }
  2443. static void
  2444. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  2445. ValueDecl *var, DeclContext *DC);
  2446. /// Complete semantic analysis for a reference to the given declaration.
  2447. ExprResult Sema::BuildDeclarationNameExpr(
  2448. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2449. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2450. bool AcceptInvalidDecl) {
  2451. assert(D && "Cannot refer to a NULL declaration");
  2452. assert(!isa<FunctionTemplateDecl>(D) &&
  2453. "Cannot refer unambiguously to a function template");
  2454. SourceLocation Loc = NameInfo.getLoc();
  2455. if (CheckDeclInExpr(*this, Loc, D))
  2456. return ExprError();
  2457. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2458. // Specifically diagnose references to class templates that are missing
  2459. // a template argument list.
  2460. diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
  2461. return ExprError();
  2462. }
  2463. // Make sure that we're referring to a value.
  2464. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2465. if (!VD) {
  2466. Diag(Loc, diag::err_ref_non_value)
  2467. << D << SS.getRange();
  2468. Diag(D->getLocation(), diag::note_declared_at);
  2469. return ExprError();
  2470. }
  2471. // Check whether this declaration can be used. Note that we suppress
  2472. // this check when we're going to perform argument-dependent lookup
  2473. // on this function name, because this might not be the function
  2474. // that overload resolution actually selects.
  2475. if (DiagnoseUseOfDecl(VD, Loc))
  2476. return ExprError();
  2477. // Only create DeclRefExpr's for valid Decl's.
  2478. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2479. return ExprError();
  2480. // Handle members of anonymous structs and unions. If we got here,
  2481. // and the reference is to a class member indirect field, then this
  2482. // must be the subject of a pointer-to-member expression.
  2483. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2484. if (!indirectField->isCXXClassMember())
  2485. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2486. indirectField);
  2487. {
  2488. QualType type = VD->getType();
  2489. if (type.isNull())
  2490. return ExprError();
  2491. if (auto *FPT = type->getAs<FunctionProtoType>()) {
  2492. // C++ [except.spec]p17:
  2493. // An exception-specification is considered to be needed when:
  2494. // - in an expression, the function is the unique lookup result or
  2495. // the selected member of a set of overloaded functions.
  2496. ResolveExceptionSpec(Loc, FPT);
  2497. type = VD->getType();
  2498. }
  2499. ExprValueKind valueKind = VK_RValue;
  2500. switch (D->getKind()) {
  2501. // Ignore all the non-ValueDecl kinds.
  2502. #define ABSTRACT_DECL(kind)
  2503. #define VALUE(type, base)
  2504. #define DECL(type, base) \
  2505. case Decl::type:
  2506. #include "clang/AST/DeclNodes.inc"
  2507. llvm_unreachable("invalid value decl kind");
  2508. // These shouldn't make it here.
  2509. case Decl::ObjCAtDefsField:
  2510. case Decl::ObjCIvar:
  2511. llvm_unreachable("forming non-member reference to ivar?");
  2512. // Enum constants are always r-values and never references.
  2513. // Unresolved using declarations are dependent.
  2514. case Decl::EnumConstant:
  2515. case Decl::UnresolvedUsingValue:
  2516. case Decl::OMPDeclareReduction:
  2517. valueKind = VK_RValue;
  2518. break;
  2519. // Fields and indirect fields that got here must be for
  2520. // pointer-to-member expressions; we just call them l-values for
  2521. // internal consistency, because this subexpression doesn't really
  2522. // exist in the high-level semantics.
  2523. case Decl::Field:
  2524. case Decl::IndirectField:
  2525. assert(getLangOpts().CPlusPlus &&
  2526. "building reference to field in C?");
  2527. // These can't have reference type in well-formed programs, but
  2528. // for internal consistency we do this anyway.
  2529. type = type.getNonReferenceType();
  2530. valueKind = VK_LValue;
  2531. break;
  2532. // Non-type template parameters are either l-values or r-values
  2533. // depending on the type.
  2534. case Decl::NonTypeTemplateParm: {
  2535. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2536. type = reftype->getPointeeType();
  2537. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2538. break;
  2539. }
  2540. // For non-references, we need to strip qualifiers just in case
  2541. // the template parameter was declared as 'const int' or whatever.
  2542. valueKind = VK_RValue;
  2543. type = type.getUnqualifiedType();
  2544. break;
  2545. }
  2546. case Decl::Var:
  2547. case Decl::VarTemplateSpecialization:
  2548. case Decl::VarTemplatePartialSpecialization:
  2549. case Decl::Decomposition:
  2550. case Decl::OMPCapturedExpr:
  2551. // In C, "extern void blah;" is valid and is an r-value.
  2552. if (!getLangOpts().CPlusPlus &&
  2553. !type.hasQualifiers() &&
  2554. type->isVoidType()) {
  2555. valueKind = VK_RValue;
  2556. break;
  2557. }
  2558. LLVM_FALLTHROUGH;
  2559. case Decl::ImplicitParam:
  2560. case Decl::ParmVar: {
  2561. // These are always l-values.
  2562. valueKind = VK_LValue;
  2563. type = type.getNonReferenceType();
  2564. // FIXME: Does the addition of const really only apply in
  2565. // potentially-evaluated contexts? Since the variable isn't actually
  2566. // captured in an unevaluated context, it seems that the answer is no.
  2567. if (!isUnevaluatedContext()) {
  2568. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2569. if (!CapturedType.isNull())
  2570. type = CapturedType;
  2571. }
  2572. break;
  2573. }
  2574. case Decl::Binding: {
  2575. // These are always lvalues.
  2576. valueKind = VK_LValue;
  2577. type = type.getNonReferenceType();
  2578. // FIXME: Support lambda-capture of BindingDecls, once CWG actually
  2579. // decides how that's supposed to work.
  2580. auto *BD = cast<BindingDecl>(VD);
  2581. if (BD->getDeclContext()->isFunctionOrMethod() &&
  2582. BD->getDeclContext() != CurContext)
  2583. diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
  2584. break;
  2585. }
  2586. case Decl::Function: {
  2587. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2588. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2589. type = Context.BuiltinFnTy;
  2590. valueKind = VK_RValue;
  2591. break;
  2592. }
  2593. }
  2594. const FunctionType *fty = type->castAs<FunctionType>();
  2595. // If we're referring to a function with an __unknown_anytype
  2596. // result type, make the entire expression __unknown_anytype.
  2597. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2598. type = Context.UnknownAnyTy;
  2599. valueKind = VK_RValue;
  2600. break;
  2601. }
  2602. // Functions are l-values in C++.
  2603. if (getLangOpts().CPlusPlus) {
  2604. valueKind = VK_LValue;
  2605. break;
  2606. }
  2607. // C99 DR 316 says that, if a function type comes from a
  2608. // function definition (without a prototype), that type is only
  2609. // used for checking compatibility. Therefore, when referencing
  2610. // the function, we pretend that we don't have the full function
  2611. // type.
  2612. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2613. isa<FunctionProtoType>(fty))
  2614. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2615. fty->getExtInfo());
  2616. // Functions are r-values in C.
  2617. valueKind = VK_RValue;
  2618. break;
  2619. }
  2620. case Decl::CXXDeductionGuide:
  2621. llvm_unreachable("building reference to deduction guide");
  2622. case Decl::MSProperty:
  2623. valueKind = VK_LValue;
  2624. break;
  2625. case Decl::CXXMethod:
  2626. // If we're referring to a method with an __unknown_anytype
  2627. // result type, make the entire expression __unknown_anytype.
  2628. // This should only be possible with a type written directly.
  2629. if (const FunctionProtoType *proto
  2630. = dyn_cast<FunctionProtoType>(VD->getType()))
  2631. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2632. type = Context.UnknownAnyTy;
  2633. valueKind = VK_RValue;
  2634. break;
  2635. }
  2636. // C++ methods are l-values if static, r-values if non-static.
  2637. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2638. valueKind = VK_LValue;
  2639. break;
  2640. }
  2641. LLVM_FALLTHROUGH;
  2642. case Decl::CXXConversion:
  2643. case Decl::CXXDestructor:
  2644. case Decl::CXXConstructor:
  2645. valueKind = VK_RValue;
  2646. break;
  2647. }
  2648. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2649. TemplateArgs);
  2650. }
  2651. }
  2652. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2653. SmallString<32> &Target) {
  2654. Target.resize(CharByteWidth * (Source.size() + 1));
  2655. char *ResultPtr = &Target[0];
  2656. const llvm::UTF8 *ErrorPtr;
  2657. bool success =
  2658. llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2659. (void)success;
  2660. assert(success);
  2661. Target.resize(ResultPtr - &Target[0]);
  2662. }
  2663. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2664. PredefinedExpr::IdentKind IK) {
  2665. // Pick the current block, lambda, captured statement or function.
  2666. Decl *currentDecl = nullptr;
  2667. if (const BlockScopeInfo *BSI = getCurBlock())
  2668. currentDecl = BSI->TheDecl;
  2669. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2670. currentDecl = LSI->CallOperator;
  2671. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2672. currentDecl = CSI->TheCapturedDecl;
  2673. else
  2674. currentDecl = getCurFunctionOrMethodDecl();
  2675. if (!currentDecl) {
  2676. Diag(Loc, diag::ext_predef_outside_function);
  2677. currentDecl = Context.getTranslationUnitDecl();
  2678. }
  2679. QualType ResTy;
  2680. StringLiteral *SL = nullptr;
  2681. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2682. ResTy = Context.DependentTy;
  2683. else {
  2684. // Pre-defined identifiers are of type char[x], where x is the length of
  2685. // the string.
  2686. auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
  2687. unsigned Length = Str.length();
  2688. llvm::APInt LengthI(32, Length + 1);
  2689. if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
  2690. ResTy =
  2691. Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
  2692. SmallString<32> RawChars;
  2693. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2694. Str, RawChars);
  2695. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2696. /*IndexTypeQuals*/ 0);
  2697. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2698. /*Pascal*/ false, ResTy, Loc);
  2699. } else {
  2700. ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
  2701. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2702. /*IndexTypeQuals*/ 0);
  2703. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2704. /*Pascal*/ false, ResTy, Loc);
  2705. }
  2706. }
  2707. return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
  2708. }
  2709. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2710. PredefinedExpr::IdentKind IK;
  2711. switch (Kind) {
  2712. default: llvm_unreachable("Unknown simple primary expr!");
  2713. case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2714. case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
  2715. case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
  2716. case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
  2717. case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
  2718. case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
  2719. case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
  2720. }
  2721. return BuildPredefinedExpr(Loc, IK);
  2722. }
  2723. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2724. SmallString<16> CharBuffer;
  2725. bool Invalid = false;
  2726. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2727. if (Invalid)
  2728. return ExprError();
  2729. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2730. PP, Tok.getKind());
  2731. if (Literal.hadError())
  2732. return ExprError();
  2733. QualType Ty;
  2734. if (Literal.isWide())
  2735. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2736. else if (Literal.isUTF8() && getLangOpts().Char8)
  2737. Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
  2738. else if (Literal.isUTF16())
  2739. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2740. else if (Literal.isUTF32())
  2741. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2742. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2743. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2744. else
  2745. Ty = Context.CharTy; // 'x' -> char in C++
  2746. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2747. if (Literal.isWide())
  2748. Kind = CharacterLiteral::Wide;
  2749. else if (Literal.isUTF16())
  2750. Kind = CharacterLiteral::UTF16;
  2751. else if (Literal.isUTF32())
  2752. Kind = CharacterLiteral::UTF32;
  2753. else if (Literal.isUTF8())
  2754. Kind = CharacterLiteral::UTF8;
  2755. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2756. Tok.getLocation());
  2757. if (Literal.getUDSuffix().empty())
  2758. return Lit;
  2759. // We're building a user-defined literal.
  2760. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2761. SourceLocation UDSuffixLoc =
  2762. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2763. // Make sure we're allowed user-defined literals here.
  2764. if (!UDLScope)
  2765. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2766. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2767. // operator "" X (ch)
  2768. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2769. Lit, Tok.getLocation());
  2770. }
  2771. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2772. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2773. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2774. Context.IntTy, Loc);
  2775. }
  2776. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2777. QualType Ty, SourceLocation Loc) {
  2778. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2779. using llvm::APFloat;
  2780. APFloat Val(Format);
  2781. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2782. // Overflow is always an error, but underflow is only an error if
  2783. // we underflowed to zero (APFloat reports denormals as underflow).
  2784. if ((result & APFloat::opOverflow) ||
  2785. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2786. unsigned diagnostic;
  2787. SmallString<20> buffer;
  2788. if (result & APFloat::opOverflow) {
  2789. diagnostic = diag::warn_float_overflow;
  2790. APFloat::getLargest(Format).toString(buffer);
  2791. } else {
  2792. diagnostic = diag::warn_float_underflow;
  2793. APFloat::getSmallest(Format).toString(buffer);
  2794. }
  2795. S.Diag(Loc, diagnostic)
  2796. << Ty
  2797. << StringRef(buffer.data(), buffer.size());
  2798. }
  2799. bool isExact = (result == APFloat::opOK);
  2800. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2801. }
  2802. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2803. assert(E && "Invalid expression");
  2804. if (E->isValueDependent())
  2805. return false;
  2806. QualType QT = E->getType();
  2807. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2808. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2809. return true;
  2810. }
  2811. llvm::APSInt ValueAPS;
  2812. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2813. if (R.isInvalid())
  2814. return true;
  2815. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2816. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2817. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2818. << ValueAPS.toString(10) << ValueIsPositive;
  2819. return true;
  2820. }
  2821. return false;
  2822. }
  2823. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2824. // Fast path for a single digit (which is quite common). A single digit
  2825. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2826. if (Tok.getLength() == 1) {
  2827. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2828. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2829. }
  2830. SmallString<128> SpellingBuffer;
  2831. // NumericLiteralParser wants to overread by one character. Add padding to
  2832. // the buffer in case the token is copied to the buffer. If getSpelling()
  2833. // returns a StringRef to the memory buffer, it should have a null char at
  2834. // the EOF, so it is also safe.
  2835. SpellingBuffer.resize(Tok.getLength() + 1);
  2836. // Get the spelling of the token, which eliminates trigraphs, etc.
  2837. bool Invalid = false;
  2838. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2839. if (Invalid)
  2840. return ExprError();
  2841. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2842. if (Literal.hadError)
  2843. return ExprError();
  2844. if (Literal.hasUDSuffix()) {
  2845. // We're building a user-defined literal.
  2846. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2847. SourceLocation UDSuffixLoc =
  2848. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2849. // Make sure we're allowed user-defined literals here.
  2850. if (!UDLScope)
  2851. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2852. QualType CookedTy;
  2853. if (Literal.isFloatingLiteral()) {
  2854. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2855. // long double, the literal is treated as a call of the form
  2856. // operator "" X (f L)
  2857. CookedTy = Context.LongDoubleTy;
  2858. } else {
  2859. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2860. // unsigned long long, the literal is treated as a call of the form
  2861. // operator "" X (n ULL)
  2862. CookedTy = Context.UnsignedLongLongTy;
  2863. }
  2864. DeclarationName OpName =
  2865. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  2866. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  2867. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  2868. SourceLocation TokLoc = Tok.getLocation();
  2869. // Perform literal operator lookup to determine if we're building a raw
  2870. // literal or a cooked one.
  2871. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  2872. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  2873. /*AllowRaw*/ true, /*AllowTemplate*/ true,
  2874. /*AllowStringTemplate*/ false,
  2875. /*DiagnoseMissing*/ !Literal.isImaginary)) {
  2876. case LOLR_ErrorNoDiagnostic:
  2877. // Lookup failure for imaginary constants isn't fatal, there's still the
  2878. // GNU extension producing _Complex types.
  2879. break;
  2880. case LOLR_Error:
  2881. return ExprError();
  2882. case LOLR_Cooked: {
  2883. Expr *Lit;
  2884. if (Literal.isFloatingLiteral()) {
  2885. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  2886. } else {
  2887. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  2888. if (Literal.GetIntegerValue(ResultVal))
  2889. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2890. << /* Unsigned */ 1;
  2891. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  2892. Tok.getLocation());
  2893. }
  2894. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2895. }
  2896. case LOLR_Raw: {
  2897. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  2898. // literal is treated as a call of the form
  2899. // operator "" X ("n")
  2900. unsigned Length = Literal.getUDSuffixOffset();
  2901. QualType StrTy = Context.getConstantArrayType(
  2902. Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
  2903. llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
  2904. Expr *Lit = StringLiteral::Create(
  2905. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  2906. /*Pascal*/false, StrTy, &TokLoc, 1);
  2907. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2908. }
  2909. case LOLR_Template: {
  2910. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  2911. // template), L is treated as a call fo the form
  2912. // operator "" X <'c1', 'c2', ... 'ck'>()
  2913. // where n is the source character sequence c1 c2 ... ck.
  2914. TemplateArgumentListInfo ExplicitArgs;
  2915. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  2916. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  2917. llvm::APSInt Value(CharBits, CharIsUnsigned);
  2918. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  2919. Value = TokSpelling[I];
  2920. TemplateArgument Arg(Context, Value, Context.CharTy);
  2921. TemplateArgumentLocInfo ArgInfo;
  2922. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  2923. }
  2924. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  2925. &ExplicitArgs);
  2926. }
  2927. case LOLR_StringTemplate:
  2928. llvm_unreachable("unexpected literal operator lookup result");
  2929. }
  2930. }
  2931. Expr *Res;
  2932. if (Literal.isFixedPointLiteral()) {
  2933. QualType Ty;
  2934. if (Literal.isAccum) {
  2935. if (Literal.isHalf) {
  2936. Ty = Context.ShortAccumTy;
  2937. } else if (Literal.isLong) {
  2938. Ty = Context.LongAccumTy;
  2939. } else {
  2940. Ty = Context.AccumTy;
  2941. }
  2942. } else if (Literal.isFract) {
  2943. if (Literal.isHalf) {
  2944. Ty = Context.ShortFractTy;
  2945. } else if (Literal.isLong) {
  2946. Ty = Context.LongFractTy;
  2947. } else {
  2948. Ty = Context.FractTy;
  2949. }
  2950. }
  2951. if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
  2952. bool isSigned = !Literal.isUnsigned;
  2953. unsigned scale = Context.getFixedPointScale(Ty);
  2954. unsigned bit_width = Context.getTypeInfo(Ty).Width;
  2955. llvm::APInt Val(bit_width, 0, isSigned);
  2956. bool Overflowed = Literal.GetFixedPointValue(Val, scale);
  2957. bool ValIsZero = Val.isNullValue() && !Overflowed;
  2958. auto MaxVal = Context.getFixedPointMax(Ty).getValue();
  2959. if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
  2960. // Clause 6.4.4 - The value of a constant shall be in the range of
  2961. // representable values for its type, with exception for constants of a
  2962. // fract type with a value of exactly 1; such a constant shall denote
  2963. // the maximal value for the type.
  2964. --Val;
  2965. else if (Val.ugt(MaxVal) || Overflowed)
  2966. Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
  2967. Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
  2968. Tok.getLocation(), scale);
  2969. } else if (Literal.isFloatingLiteral()) {
  2970. QualType Ty;
  2971. if (Literal.isHalf){
  2972. if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
  2973. Ty = Context.HalfTy;
  2974. else {
  2975. Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
  2976. return ExprError();
  2977. }
  2978. } else if (Literal.isFloat)
  2979. Ty = Context.FloatTy;
  2980. else if (Literal.isLong)
  2981. Ty = Context.LongDoubleTy;
  2982. else if (Literal.isFloat16)
  2983. Ty = Context.Float16Ty;
  2984. else if (Literal.isFloat128)
  2985. Ty = Context.Float128Ty;
  2986. else
  2987. Ty = Context.DoubleTy;
  2988. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  2989. if (Ty == Context.DoubleTy) {
  2990. if (getLangOpts().SinglePrecisionConstants) {
  2991. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  2992. if (BTy->getKind() != BuiltinType::Float) {
  2993. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2994. }
  2995. } else if (getLangOpts().OpenCL &&
  2996. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  2997. // Impose single-precision float type when cl_khr_fp64 is not enabled.
  2998. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  2999. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3000. }
  3001. }
  3002. } else if (!Literal.isIntegerLiteral()) {
  3003. return ExprError();
  3004. } else {
  3005. QualType Ty;
  3006. // 'long long' is a C99 or C++11 feature.
  3007. if (!getLangOpts().C99 && Literal.isLongLong) {
  3008. if (getLangOpts().CPlusPlus)
  3009. Diag(Tok.getLocation(),
  3010. getLangOpts().CPlusPlus11 ?
  3011. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  3012. else
  3013. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  3014. }
  3015. // Get the value in the widest-possible width.
  3016. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  3017. llvm::APInt ResultVal(MaxWidth, 0);
  3018. if (Literal.GetIntegerValue(ResultVal)) {
  3019. // If this value didn't fit into uintmax_t, error and force to ull.
  3020. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3021. << /* Unsigned */ 1;
  3022. Ty = Context.UnsignedLongLongTy;
  3023. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  3024. "long long is not intmax_t?");
  3025. } else {
  3026. // If this value fits into a ULL, try to figure out what else it fits into
  3027. // according to the rules of C99 6.4.4.1p5.
  3028. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  3029. // be an unsigned int.
  3030. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  3031. // Check from smallest to largest, picking the smallest type we can.
  3032. unsigned Width = 0;
  3033. // Microsoft specific integer suffixes are explicitly sized.
  3034. if (Literal.MicrosoftInteger) {
  3035. if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  3036. Width = 8;
  3037. Ty = Context.CharTy;
  3038. } else {
  3039. Width = Literal.MicrosoftInteger;
  3040. Ty = Context.getIntTypeForBitwidth(Width,
  3041. /*Signed=*/!Literal.isUnsigned);
  3042. }
  3043. }
  3044. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  3045. // Are int/unsigned possibilities?
  3046. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3047. // Does it fit in a unsigned int?
  3048. if (ResultVal.isIntN(IntSize)) {
  3049. // Does it fit in a signed int?
  3050. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  3051. Ty = Context.IntTy;
  3052. else if (AllowUnsigned)
  3053. Ty = Context.UnsignedIntTy;
  3054. Width = IntSize;
  3055. }
  3056. }
  3057. // Are long/unsigned long possibilities?
  3058. if (Ty.isNull() && !Literal.isLongLong) {
  3059. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  3060. // Does it fit in a unsigned long?
  3061. if (ResultVal.isIntN(LongSize)) {
  3062. // Does it fit in a signed long?
  3063. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  3064. Ty = Context.LongTy;
  3065. else if (AllowUnsigned)
  3066. Ty = Context.UnsignedLongTy;
  3067. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  3068. // is compatible.
  3069. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3070. const unsigned LongLongSize =
  3071. Context.getTargetInfo().getLongLongWidth();
  3072. Diag(Tok.getLocation(),
  3073. getLangOpts().CPlusPlus
  3074. ? Literal.isLong
  3075. ? diag::warn_old_implicitly_unsigned_long_cxx
  3076. : /*C++98 UB*/ diag::
  3077. ext_old_implicitly_unsigned_long_cxx
  3078. : diag::warn_old_implicitly_unsigned_long)
  3079. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3080. : /*will be ill-formed*/ 1);
  3081. Ty = Context.UnsignedLongTy;
  3082. }
  3083. Width = LongSize;
  3084. }
  3085. }
  3086. // Check long long if needed.
  3087. if (Ty.isNull()) {
  3088. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3089. // Does it fit in a unsigned long long?
  3090. if (ResultVal.isIntN(LongLongSize)) {
  3091. // Does it fit in a signed long long?
  3092. // To be compatible with MSVC, hex integer literals ending with the
  3093. // LL or i64 suffix are always signed in Microsoft mode.
  3094. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3095. (getLangOpts().MSVCCompat && Literal.isLongLong)))
  3096. Ty = Context.LongLongTy;
  3097. else if (AllowUnsigned)
  3098. Ty = Context.UnsignedLongLongTy;
  3099. Width = LongLongSize;
  3100. }
  3101. }
  3102. // If we still couldn't decide a type, we probably have something that
  3103. // does not fit in a signed long long, but has no U suffix.
  3104. if (Ty.isNull()) {
  3105. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3106. Ty = Context.UnsignedLongLongTy;
  3107. Width = Context.getTargetInfo().getLongLongWidth();
  3108. }
  3109. if (ResultVal.getBitWidth() != Width)
  3110. ResultVal = ResultVal.trunc(Width);
  3111. }
  3112. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3113. }
  3114. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3115. if (Literal.isImaginary) {
  3116. Res = new (Context) ImaginaryLiteral(Res,
  3117. Context.getComplexType(Res->getType()));
  3118. Diag(Tok.getLocation(), diag::ext_imaginary_constant);
  3119. }
  3120. return Res;
  3121. }
  3122. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3123. assert(E && "ActOnParenExpr() missing expr");
  3124. return new (Context) ParenExpr(L, R, E);
  3125. }
  3126. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3127. SourceLocation Loc,
  3128. SourceRange ArgRange) {
  3129. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3130. // scalar or vector data type argument..."
  3131. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3132. // type (C99 6.2.5p18) or void.
  3133. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3134. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3135. << T << ArgRange;
  3136. return true;
  3137. }
  3138. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3139. "Scalar types should always be complete");
  3140. return false;
  3141. }
  3142. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3143. SourceLocation Loc,
  3144. SourceRange ArgRange,
  3145. UnaryExprOrTypeTrait TraitKind) {
  3146. // Invalid types must be hard errors for SFINAE in C++.
  3147. if (S.LangOpts.CPlusPlus)
  3148. return true;
  3149. // C99 6.5.3.4p1:
  3150. if (T->isFunctionType() &&
  3151. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
  3152. TraitKind == UETT_PreferredAlignOf)) {
  3153. // sizeof(function)/alignof(function) is allowed as an extension.
  3154. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3155. << TraitKind << ArgRange;
  3156. return false;
  3157. }
  3158. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3159. // this is an error (OpenCL v1.1 s6.3.k)
  3160. if (T->isVoidType()) {
  3161. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3162. : diag::ext_sizeof_alignof_void_type;
  3163. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3164. return false;
  3165. }
  3166. return true;
  3167. }
  3168. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3169. SourceLocation Loc,
  3170. SourceRange ArgRange,
  3171. UnaryExprOrTypeTrait TraitKind) {
  3172. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3173. // runtime doesn't allow it.
  3174. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3175. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3176. << T << (TraitKind == UETT_SizeOf)
  3177. << ArgRange;
  3178. return true;
  3179. }
  3180. return false;
  3181. }
  3182. /// Check whether E is a pointer from a decayed array type (the decayed
  3183. /// pointer type is equal to T) and emit a warning if it is.
  3184. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3185. Expr *E) {
  3186. // Don't warn if the operation changed the type.
  3187. if (T != E->getType())
  3188. return;
  3189. // Now look for array decays.
  3190. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3191. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3192. return;
  3193. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3194. << ICE->getType()
  3195. << ICE->getSubExpr()->getType();
  3196. }
  3197. /// Check the constraints on expression operands to unary type expression
  3198. /// and type traits.
  3199. ///
  3200. /// Completes any types necessary and validates the constraints on the operand
  3201. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3202. /// the expression as it completes the type for that expression through template
  3203. /// instantiation, etc.
  3204. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3205. UnaryExprOrTypeTrait ExprKind) {
  3206. QualType ExprTy = E->getType();
  3207. assert(!ExprTy->isReferenceType());
  3208. if (ExprKind == UETT_VecStep)
  3209. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3210. E->getSourceRange());
  3211. // Whitelist some types as extensions
  3212. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3213. E->getSourceRange(), ExprKind))
  3214. return false;
  3215. // 'alignof' applied to an expression only requires the base element type of
  3216. // the expression to be complete. 'sizeof' requires the expression's type to
  3217. // be complete (and will attempt to complete it if it's an array of unknown
  3218. // bound).
  3219. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3220. if (RequireCompleteType(E->getExprLoc(),
  3221. Context.getBaseElementType(E->getType()),
  3222. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3223. E->getSourceRange()))
  3224. return true;
  3225. } else {
  3226. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3227. ExprKind, E->getSourceRange()))
  3228. return true;
  3229. }
  3230. // Completing the expression's type may have changed it.
  3231. ExprTy = E->getType();
  3232. assert(!ExprTy->isReferenceType());
  3233. if (ExprTy->isFunctionType()) {
  3234. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3235. << ExprKind << E->getSourceRange();
  3236. return true;
  3237. }
  3238. // The operand for sizeof and alignof is in an unevaluated expression context,
  3239. // so side effects could result in unintended consequences.
  3240. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
  3241. ExprKind == UETT_PreferredAlignOf) &&
  3242. !inTemplateInstantiation() && E->HasSideEffects(Context, false))
  3243. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3244. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3245. E->getSourceRange(), ExprKind))
  3246. return true;
  3247. if (ExprKind == UETT_SizeOf) {
  3248. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3249. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3250. QualType OType = PVD->getOriginalType();
  3251. QualType Type = PVD->getType();
  3252. if (Type->isPointerType() && OType->isArrayType()) {
  3253. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3254. << Type << OType;
  3255. Diag(PVD->getLocation(), diag::note_declared_at);
  3256. }
  3257. }
  3258. }
  3259. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3260. // decays into a pointer and returns an unintended result. This is most
  3261. // likely a typo for "sizeof(array) op x".
  3262. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3263. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3264. BO->getLHS());
  3265. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3266. BO->getRHS());
  3267. }
  3268. }
  3269. return false;
  3270. }
  3271. /// Check the constraints on operands to unary expression and type
  3272. /// traits.
  3273. ///
  3274. /// This will complete any types necessary, and validate the various constraints
  3275. /// on those operands.
  3276. ///
  3277. /// The UsualUnaryConversions() function is *not* called by this routine.
  3278. /// C99 6.3.2.1p[2-4] all state:
  3279. /// Except when it is the operand of the sizeof operator ...
  3280. ///
  3281. /// C++ [expr.sizeof]p4
  3282. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3283. /// standard conversions are not applied to the operand of sizeof.
  3284. ///
  3285. /// This policy is followed for all of the unary trait expressions.
  3286. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3287. SourceLocation OpLoc,
  3288. SourceRange ExprRange,
  3289. UnaryExprOrTypeTrait ExprKind) {
  3290. if (ExprType->isDependentType())
  3291. return false;
  3292. // C++ [expr.sizeof]p2:
  3293. // When applied to a reference or a reference type, the result
  3294. // is the size of the referenced type.
  3295. // C++11 [expr.alignof]p3:
  3296. // When alignof is applied to a reference type, the result
  3297. // shall be the alignment of the referenced type.
  3298. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3299. ExprType = Ref->getPointeeType();
  3300. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3301. // When alignof or _Alignof is applied to an array type, the result
  3302. // is the alignment of the element type.
  3303. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
  3304. ExprKind == UETT_OpenMPRequiredSimdAlign)
  3305. ExprType = Context.getBaseElementType(ExprType);
  3306. if (ExprKind == UETT_VecStep)
  3307. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3308. // Whitelist some types as extensions
  3309. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3310. ExprKind))
  3311. return false;
  3312. if (RequireCompleteType(OpLoc, ExprType,
  3313. diag::err_sizeof_alignof_incomplete_type,
  3314. ExprKind, ExprRange))
  3315. return true;
  3316. if (ExprType->isFunctionType()) {
  3317. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3318. << ExprKind << ExprRange;
  3319. return true;
  3320. }
  3321. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3322. ExprKind))
  3323. return true;
  3324. return false;
  3325. }
  3326. static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
  3327. E = E->IgnoreParens();
  3328. // Cannot know anything else if the expression is dependent.
  3329. if (E->isTypeDependent())
  3330. return false;
  3331. if (E->getObjectKind() == OK_BitField) {
  3332. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
  3333. << 1 << E->getSourceRange();
  3334. return true;
  3335. }
  3336. ValueDecl *D = nullptr;
  3337. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3338. D = DRE->getDecl();
  3339. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3340. D = ME->getMemberDecl();
  3341. }
  3342. // If it's a field, require the containing struct to have a
  3343. // complete definition so that we can compute the layout.
  3344. //
  3345. // This can happen in C++11 onwards, either by naming the member
  3346. // in a way that is not transformed into a member access expression
  3347. // (in an unevaluated operand, for instance), or by naming the member
  3348. // in a trailing-return-type.
  3349. //
  3350. // For the record, since __alignof__ on expressions is a GCC
  3351. // extension, GCC seems to permit this but always gives the
  3352. // nonsensical answer 0.
  3353. //
  3354. // We don't really need the layout here --- we could instead just
  3355. // directly check for all the appropriate alignment-lowing
  3356. // attributes --- but that would require duplicating a lot of
  3357. // logic that just isn't worth duplicating for such a marginal
  3358. // use-case.
  3359. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3360. // Fast path this check, since we at least know the record has a
  3361. // definition if we can find a member of it.
  3362. if (!FD->getParent()->isCompleteDefinition()) {
  3363. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3364. << E->getSourceRange();
  3365. return true;
  3366. }
  3367. // Otherwise, if it's a field, and the field doesn't have
  3368. // reference type, then it must have a complete type (or be a
  3369. // flexible array member, which we explicitly want to
  3370. // white-list anyway), which makes the following checks trivial.
  3371. if (!FD->getType()->isReferenceType())
  3372. return false;
  3373. }
  3374. return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
  3375. }
  3376. bool Sema::CheckVecStepExpr(Expr *E) {
  3377. E = E->IgnoreParens();
  3378. // Cannot know anything else if the expression is dependent.
  3379. if (E->isTypeDependent())
  3380. return false;
  3381. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3382. }
  3383. static void captureVariablyModifiedType(ASTContext &Context, QualType T,
  3384. CapturingScopeInfo *CSI) {
  3385. assert(T->isVariablyModifiedType());
  3386. assert(CSI != nullptr);
  3387. // We're going to walk down into the type and look for VLA expressions.
  3388. do {
  3389. const Type *Ty = T.getTypePtr();
  3390. switch (Ty->getTypeClass()) {
  3391. #define TYPE(Class, Base)
  3392. #define ABSTRACT_TYPE(Class, Base)
  3393. #define NON_CANONICAL_TYPE(Class, Base)
  3394. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  3395. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  3396. #include "clang/AST/TypeNodes.def"
  3397. T = QualType();
  3398. break;
  3399. // These types are never variably-modified.
  3400. case Type::Builtin:
  3401. case Type::Complex:
  3402. case Type::Vector:
  3403. case Type::ExtVector:
  3404. case Type::Record:
  3405. case Type::Enum:
  3406. case Type::Elaborated:
  3407. case Type::TemplateSpecialization:
  3408. case Type::ObjCObject:
  3409. case Type::ObjCInterface:
  3410. case Type::ObjCObjectPointer:
  3411. case Type::ObjCTypeParam:
  3412. case Type::Pipe:
  3413. llvm_unreachable("type class is never variably-modified!");
  3414. case Type::Adjusted:
  3415. T = cast<AdjustedType>(Ty)->getOriginalType();
  3416. break;
  3417. case Type::Decayed:
  3418. T = cast<DecayedType>(Ty)->getPointeeType();
  3419. break;
  3420. case Type::Pointer:
  3421. T = cast<PointerType>(Ty)->getPointeeType();
  3422. break;
  3423. case Type::BlockPointer:
  3424. T = cast<BlockPointerType>(Ty)->getPointeeType();
  3425. break;
  3426. case Type::LValueReference:
  3427. case Type::RValueReference:
  3428. T = cast<ReferenceType>(Ty)->getPointeeType();
  3429. break;
  3430. case Type::MemberPointer:
  3431. T = cast<MemberPointerType>(Ty)->getPointeeType();
  3432. break;
  3433. case Type::ConstantArray:
  3434. case Type::IncompleteArray:
  3435. // Losing element qualification here is fine.
  3436. T = cast<ArrayType>(Ty)->getElementType();
  3437. break;
  3438. case Type::VariableArray: {
  3439. // Losing element qualification here is fine.
  3440. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  3441. // Unknown size indication requires no size computation.
  3442. // Otherwise, evaluate and record it.
  3443. if (auto Size = VAT->getSizeExpr()) {
  3444. if (!CSI->isVLATypeCaptured(VAT)) {
  3445. RecordDecl *CapRecord = nullptr;
  3446. if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
  3447. CapRecord = LSI->Lambda;
  3448. } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  3449. CapRecord = CRSI->TheRecordDecl;
  3450. }
  3451. if (CapRecord) {
  3452. auto ExprLoc = Size->getExprLoc();
  3453. auto SizeType = Context.getSizeType();
  3454. // Build the non-static data member.
  3455. auto Field =
  3456. FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
  3457. /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
  3458. /*BW*/ nullptr, /*Mutable*/ false,
  3459. /*InitStyle*/ ICIS_NoInit);
  3460. Field->setImplicit(true);
  3461. Field->setAccess(AS_private);
  3462. Field->setCapturedVLAType(VAT);
  3463. CapRecord->addDecl(Field);
  3464. CSI->addVLATypeCapture(ExprLoc, SizeType);
  3465. }
  3466. }
  3467. }
  3468. T = VAT->getElementType();
  3469. break;
  3470. }
  3471. case Type::FunctionProto:
  3472. case Type::FunctionNoProto:
  3473. T = cast<FunctionType>(Ty)->getReturnType();
  3474. break;
  3475. case Type::Paren:
  3476. case Type::TypeOf:
  3477. case Type::UnaryTransform:
  3478. case Type::Attributed:
  3479. case Type::SubstTemplateTypeParm:
  3480. case Type::PackExpansion:
  3481. // Keep walking after single level desugaring.
  3482. T = T.getSingleStepDesugaredType(Context);
  3483. break;
  3484. case Type::Typedef:
  3485. T = cast<TypedefType>(Ty)->desugar();
  3486. break;
  3487. case Type::Decltype:
  3488. T = cast<DecltypeType>(Ty)->desugar();
  3489. break;
  3490. case Type::Auto:
  3491. case Type::DeducedTemplateSpecialization:
  3492. T = cast<DeducedType>(Ty)->getDeducedType();
  3493. break;
  3494. case Type::TypeOfExpr:
  3495. T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  3496. break;
  3497. case Type::Atomic:
  3498. T = cast<AtomicType>(Ty)->getValueType();
  3499. break;
  3500. }
  3501. } while (!T.isNull() && T->isVariablyModifiedType());
  3502. }
  3503. /// Build a sizeof or alignof expression given a type operand.
  3504. ExprResult
  3505. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3506. SourceLocation OpLoc,
  3507. UnaryExprOrTypeTrait ExprKind,
  3508. SourceRange R) {
  3509. if (!TInfo)
  3510. return ExprError();
  3511. QualType T = TInfo->getType();
  3512. if (!T->isDependentType() &&
  3513. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3514. return ExprError();
  3515. if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
  3516. if (auto *TT = T->getAs<TypedefType>()) {
  3517. for (auto I = FunctionScopes.rbegin(),
  3518. E = std::prev(FunctionScopes.rend());
  3519. I != E; ++I) {
  3520. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  3521. if (CSI == nullptr)
  3522. break;
  3523. DeclContext *DC = nullptr;
  3524. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  3525. DC = LSI->CallOperator;
  3526. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  3527. DC = CRSI->TheCapturedDecl;
  3528. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  3529. DC = BSI->TheDecl;
  3530. if (DC) {
  3531. if (DC->containsDecl(TT->getDecl()))
  3532. break;
  3533. captureVariablyModifiedType(Context, T, CSI);
  3534. }
  3535. }
  3536. }
  3537. }
  3538. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3539. return new (Context) UnaryExprOrTypeTraitExpr(
  3540. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3541. }
  3542. /// Build a sizeof or alignof expression given an expression
  3543. /// operand.
  3544. ExprResult
  3545. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3546. UnaryExprOrTypeTrait ExprKind) {
  3547. ExprResult PE = CheckPlaceholderExpr(E);
  3548. if (PE.isInvalid())
  3549. return ExprError();
  3550. E = PE.get();
  3551. // Verify that the operand is valid.
  3552. bool isInvalid = false;
  3553. if (E->isTypeDependent()) {
  3554. // Delay type-checking for type-dependent expressions.
  3555. } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3556. isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
  3557. } else if (ExprKind == UETT_VecStep) {
  3558. isInvalid = CheckVecStepExpr(E);
  3559. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3560. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3561. isInvalid = true;
  3562. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3563. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
  3564. isInvalid = true;
  3565. } else {
  3566. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3567. }
  3568. if (isInvalid)
  3569. return ExprError();
  3570. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3571. PE = TransformToPotentiallyEvaluated(E);
  3572. if (PE.isInvalid()) return ExprError();
  3573. E = PE.get();
  3574. }
  3575. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3576. return new (Context) UnaryExprOrTypeTraitExpr(
  3577. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3578. }
  3579. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3580. /// expr and the same for @c alignof and @c __alignof
  3581. /// Note that the ArgRange is invalid if isType is false.
  3582. ExprResult
  3583. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3584. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3585. void *TyOrEx, SourceRange ArgRange) {
  3586. // If error parsing type, ignore.
  3587. if (!TyOrEx) return ExprError();
  3588. if (IsType) {
  3589. TypeSourceInfo *TInfo;
  3590. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3591. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3592. }
  3593. Expr *ArgEx = (Expr *)TyOrEx;
  3594. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3595. return Result;
  3596. }
  3597. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3598. bool IsReal) {
  3599. if (V.get()->isTypeDependent())
  3600. return S.Context.DependentTy;
  3601. // _Real and _Imag are only l-values for normal l-values.
  3602. if (V.get()->getObjectKind() != OK_Ordinary) {
  3603. V = S.DefaultLvalueConversion(V.get());
  3604. if (V.isInvalid())
  3605. return QualType();
  3606. }
  3607. // These operators return the element type of a complex type.
  3608. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3609. return CT->getElementType();
  3610. // Otherwise they pass through real integer and floating point types here.
  3611. if (V.get()->getType()->isArithmeticType())
  3612. return V.get()->getType();
  3613. // Test for placeholders.
  3614. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3615. if (PR.isInvalid()) return QualType();
  3616. if (PR.get() != V.get()) {
  3617. V = PR;
  3618. return CheckRealImagOperand(S, V, Loc, IsReal);
  3619. }
  3620. // Reject anything else.
  3621. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3622. << (IsReal ? "__real" : "__imag");
  3623. return QualType();
  3624. }
  3625. ExprResult
  3626. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3627. tok::TokenKind Kind, Expr *Input) {
  3628. UnaryOperatorKind Opc;
  3629. switch (Kind) {
  3630. default: llvm_unreachable("Unknown unary op!");
  3631. case tok::plusplus: Opc = UO_PostInc; break;
  3632. case tok::minusminus: Opc = UO_PostDec; break;
  3633. }
  3634. // Since this might is a postfix expression, get rid of ParenListExprs.
  3635. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3636. if (Result.isInvalid()) return ExprError();
  3637. Input = Result.get();
  3638. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3639. }
  3640. /// Diagnose if arithmetic on the given ObjC pointer is illegal.
  3641. ///
  3642. /// \return true on error
  3643. static bool checkArithmeticOnObjCPointer(Sema &S,
  3644. SourceLocation opLoc,
  3645. Expr *op) {
  3646. assert(op->getType()->isObjCObjectPointerType());
  3647. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3648. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3649. return false;
  3650. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3651. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3652. << op->getSourceRange();
  3653. return true;
  3654. }
  3655. static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
  3656. auto *BaseNoParens = Base->IgnoreParens();
  3657. if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
  3658. return MSProp->getPropertyDecl()->getType()->isArrayType();
  3659. return isa<MSPropertySubscriptExpr>(BaseNoParens);
  3660. }
  3661. ExprResult
  3662. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3663. Expr *idx, SourceLocation rbLoc) {
  3664. if (base && !base->getType().isNull() &&
  3665. base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
  3666. return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
  3667. /*Length=*/nullptr, rbLoc);
  3668. // Since this might be a postfix expression, get rid of ParenListExprs.
  3669. if (isa<ParenListExpr>(base)) {
  3670. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3671. if (result.isInvalid()) return ExprError();
  3672. base = result.get();
  3673. }
  3674. // Handle any non-overload placeholder types in the base and index
  3675. // expressions. We can't handle overloads here because the other
  3676. // operand might be an overloadable type, in which case the overload
  3677. // resolution for the operator overload should get the first crack
  3678. // at the overload.
  3679. bool IsMSPropertySubscript = false;
  3680. if (base->getType()->isNonOverloadPlaceholderType()) {
  3681. IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
  3682. if (!IsMSPropertySubscript) {
  3683. ExprResult result = CheckPlaceholderExpr(base);
  3684. if (result.isInvalid())
  3685. return ExprError();
  3686. base = result.get();
  3687. }
  3688. }
  3689. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3690. ExprResult result = CheckPlaceholderExpr(idx);
  3691. if (result.isInvalid()) return ExprError();
  3692. idx = result.get();
  3693. }
  3694. // Build an unanalyzed expression if either operand is type-dependent.
  3695. if (getLangOpts().CPlusPlus &&
  3696. (base->isTypeDependent() || idx->isTypeDependent())) {
  3697. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3698. VK_LValue, OK_Ordinary, rbLoc);
  3699. }
  3700. // MSDN, property (C++)
  3701. // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
  3702. // This attribute can also be used in the declaration of an empty array in a
  3703. // class or structure definition. For example:
  3704. // __declspec(property(get=GetX, put=PutX)) int x[];
  3705. // The above statement indicates that x[] can be used with one or more array
  3706. // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
  3707. // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
  3708. if (IsMSPropertySubscript) {
  3709. // Build MS property subscript expression if base is MS property reference
  3710. // or MS property subscript.
  3711. return new (Context) MSPropertySubscriptExpr(
  3712. base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
  3713. }
  3714. // Use C++ overloaded-operator rules if either operand has record
  3715. // type. The spec says to do this if either type is *overloadable*,
  3716. // but enum types can't declare subscript operators or conversion
  3717. // operators, so there's nothing interesting for overload resolution
  3718. // to do if there aren't any record types involved.
  3719. //
  3720. // ObjC pointers have their own subscripting logic that is not tied
  3721. // to overload resolution and so should not take this path.
  3722. if (getLangOpts().CPlusPlus &&
  3723. (base->getType()->isRecordType() ||
  3724. (!base->getType()->isObjCObjectPointerType() &&
  3725. idx->getType()->isRecordType()))) {
  3726. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3727. }
  3728. return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3729. }
  3730. ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
  3731. Expr *LowerBound,
  3732. SourceLocation ColonLoc, Expr *Length,
  3733. SourceLocation RBLoc) {
  3734. if (Base->getType()->isPlaceholderType() &&
  3735. !Base->getType()->isSpecificPlaceholderType(
  3736. BuiltinType::OMPArraySection)) {
  3737. ExprResult Result = CheckPlaceholderExpr(Base);
  3738. if (Result.isInvalid())
  3739. return ExprError();
  3740. Base = Result.get();
  3741. }
  3742. if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
  3743. ExprResult Result = CheckPlaceholderExpr(LowerBound);
  3744. if (Result.isInvalid())
  3745. return ExprError();
  3746. Result = DefaultLvalueConversion(Result.get());
  3747. if (Result.isInvalid())
  3748. return ExprError();
  3749. LowerBound = Result.get();
  3750. }
  3751. if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
  3752. ExprResult Result = CheckPlaceholderExpr(Length);
  3753. if (Result.isInvalid())
  3754. return ExprError();
  3755. Result = DefaultLvalueConversion(Result.get());
  3756. if (Result.isInvalid())
  3757. return ExprError();
  3758. Length = Result.get();
  3759. }
  3760. // Build an unanalyzed expression if either operand is type-dependent.
  3761. if (Base->isTypeDependent() ||
  3762. (LowerBound &&
  3763. (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
  3764. (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
  3765. return new (Context)
  3766. OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
  3767. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3768. }
  3769. // Perform default conversions.
  3770. QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
  3771. QualType ResultTy;
  3772. if (OriginalTy->isAnyPointerType()) {
  3773. ResultTy = OriginalTy->getPointeeType();
  3774. } else if (OriginalTy->isArrayType()) {
  3775. ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
  3776. } else {
  3777. return ExprError(
  3778. Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
  3779. << Base->getSourceRange());
  3780. }
  3781. // C99 6.5.2.1p1
  3782. if (LowerBound) {
  3783. auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
  3784. LowerBound);
  3785. if (Res.isInvalid())
  3786. return ExprError(Diag(LowerBound->getExprLoc(),
  3787. diag::err_omp_typecheck_section_not_integer)
  3788. << 0 << LowerBound->getSourceRange());
  3789. LowerBound = Res.get();
  3790. if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3791. LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3792. Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
  3793. << 0 << LowerBound->getSourceRange();
  3794. }
  3795. if (Length) {
  3796. auto Res =
  3797. PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
  3798. if (Res.isInvalid())
  3799. return ExprError(Diag(Length->getExprLoc(),
  3800. diag::err_omp_typecheck_section_not_integer)
  3801. << 1 << Length->getSourceRange());
  3802. Length = Res.get();
  3803. if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3804. Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3805. Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
  3806. << 1 << Length->getSourceRange();
  3807. }
  3808. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3809. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3810. // type. Note that functions are not objects, and that (in C99 parlance)
  3811. // incomplete types are not object types.
  3812. if (ResultTy->isFunctionType()) {
  3813. Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
  3814. << ResultTy << Base->getSourceRange();
  3815. return ExprError();
  3816. }
  3817. if (RequireCompleteType(Base->getExprLoc(), ResultTy,
  3818. diag::err_omp_section_incomplete_type, Base))
  3819. return ExprError();
  3820. if (LowerBound && !OriginalTy->isAnyPointerType()) {
  3821. llvm::APSInt LowerBoundValue;
  3822. if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
  3823. // OpenMP 4.5, [2.4 Array Sections]
  3824. // The array section must be a subset of the original array.
  3825. if (LowerBoundValue.isNegative()) {
  3826. Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
  3827. << LowerBound->getSourceRange();
  3828. return ExprError();
  3829. }
  3830. }
  3831. }
  3832. if (Length) {
  3833. llvm::APSInt LengthValue;
  3834. if (Length->EvaluateAsInt(LengthValue, Context)) {
  3835. // OpenMP 4.5, [2.4 Array Sections]
  3836. // The length must evaluate to non-negative integers.
  3837. if (LengthValue.isNegative()) {
  3838. Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
  3839. << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
  3840. << Length->getSourceRange();
  3841. return ExprError();
  3842. }
  3843. }
  3844. } else if (ColonLoc.isValid() &&
  3845. (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
  3846. !OriginalTy->isVariableArrayType()))) {
  3847. // OpenMP 4.5, [2.4 Array Sections]
  3848. // When the size of the array dimension is not known, the length must be
  3849. // specified explicitly.
  3850. Diag(ColonLoc, diag::err_omp_section_length_undefined)
  3851. << (!OriginalTy.isNull() && OriginalTy->isArrayType());
  3852. return ExprError();
  3853. }
  3854. if (!Base->getType()->isSpecificPlaceholderType(
  3855. BuiltinType::OMPArraySection)) {
  3856. ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
  3857. if (Result.isInvalid())
  3858. return ExprError();
  3859. Base = Result.get();
  3860. }
  3861. return new (Context)
  3862. OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
  3863. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3864. }
  3865. ExprResult
  3866. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  3867. Expr *Idx, SourceLocation RLoc) {
  3868. Expr *LHSExp = Base;
  3869. Expr *RHSExp = Idx;
  3870. ExprValueKind VK = VK_LValue;
  3871. ExprObjectKind OK = OK_Ordinary;
  3872. // Per C++ core issue 1213, the result is an xvalue if either operand is
  3873. // a non-lvalue array, and an lvalue otherwise.
  3874. if (getLangOpts().CPlusPlus11) {
  3875. for (auto *Op : {LHSExp, RHSExp}) {
  3876. Op = Op->IgnoreImplicit();
  3877. if (Op->getType()->isArrayType() && !Op->isLValue())
  3878. VK = VK_XValue;
  3879. }
  3880. }
  3881. // Perform default conversions.
  3882. if (!LHSExp->getType()->getAs<VectorType>()) {
  3883. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  3884. if (Result.isInvalid())
  3885. return ExprError();
  3886. LHSExp = Result.get();
  3887. }
  3888. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  3889. if (Result.isInvalid())
  3890. return ExprError();
  3891. RHSExp = Result.get();
  3892. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  3893. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  3894. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  3895. // in the subscript position. As a result, we need to derive the array base
  3896. // and index from the expression types.
  3897. Expr *BaseExpr, *IndexExpr;
  3898. QualType ResultType;
  3899. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  3900. BaseExpr = LHSExp;
  3901. IndexExpr = RHSExp;
  3902. ResultType = Context.DependentTy;
  3903. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  3904. BaseExpr = LHSExp;
  3905. IndexExpr = RHSExp;
  3906. ResultType = PTy->getPointeeType();
  3907. } else if (const ObjCObjectPointerType *PTy =
  3908. LHSTy->getAs<ObjCObjectPointerType>()) {
  3909. BaseExpr = LHSExp;
  3910. IndexExpr = RHSExp;
  3911. // Use custom logic if this should be the pseudo-object subscript
  3912. // expression.
  3913. if (!LangOpts.isSubscriptPointerArithmetic())
  3914. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  3915. nullptr);
  3916. ResultType = PTy->getPointeeType();
  3917. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  3918. // Handle the uncommon case of "123[Ptr]".
  3919. BaseExpr = RHSExp;
  3920. IndexExpr = LHSExp;
  3921. ResultType = PTy->getPointeeType();
  3922. } else if (const ObjCObjectPointerType *PTy =
  3923. RHSTy->getAs<ObjCObjectPointerType>()) {
  3924. // Handle the uncommon case of "123[Ptr]".
  3925. BaseExpr = RHSExp;
  3926. IndexExpr = LHSExp;
  3927. ResultType = PTy->getPointeeType();
  3928. if (!LangOpts.isSubscriptPointerArithmetic()) {
  3929. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  3930. << ResultType << BaseExpr->getSourceRange();
  3931. return ExprError();
  3932. }
  3933. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  3934. BaseExpr = LHSExp; // vectors: V[123]
  3935. IndexExpr = RHSExp;
  3936. // We apply C++ DR1213 to vector subscripting too.
  3937. if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
  3938. ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
  3939. if (Materialized.isInvalid())
  3940. return ExprError();
  3941. LHSExp = Materialized.get();
  3942. }
  3943. VK = LHSExp->getValueKind();
  3944. if (VK != VK_RValue)
  3945. OK = OK_VectorComponent;
  3946. ResultType = VTy->getElementType();
  3947. QualType BaseType = BaseExpr->getType();
  3948. Qualifiers BaseQuals = BaseType.getQualifiers();
  3949. Qualifiers MemberQuals = ResultType.getQualifiers();
  3950. Qualifiers Combined = BaseQuals + MemberQuals;
  3951. if (Combined != MemberQuals)
  3952. ResultType = Context.getQualifiedType(ResultType, Combined);
  3953. } else if (LHSTy->isArrayType()) {
  3954. // If we see an array that wasn't promoted by
  3955. // DefaultFunctionArrayLvalueConversion, it must be an array that
  3956. // wasn't promoted because of the C90 rule that doesn't
  3957. // allow promoting non-lvalue arrays. Warn, then
  3958. // force the promotion here.
  3959. Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  3960. << LHSExp->getSourceRange();
  3961. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  3962. CK_ArrayToPointerDecay).get();
  3963. LHSTy = LHSExp->getType();
  3964. BaseExpr = LHSExp;
  3965. IndexExpr = RHSExp;
  3966. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  3967. } else if (RHSTy->isArrayType()) {
  3968. // Same as previous, except for 123[f().a] case
  3969. Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  3970. << RHSExp->getSourceRange();
  3971. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  3972. CK_ArrayToPointerDecay).get();
  3973. RHSTy = RHSExp->getType();
  3974. BaseExpr = RHSExp;
  3975. IndexExpr = LHSExp;
  3976. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  3977. } else {
  3978. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  3979. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  3980. }
  3981. // C99 6.5.2.1p1
  3982. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  3983. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  3984. << IndexExpr->getSourceRange());
  3985. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3986. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3987. && !IndexExpr->isTypeDependent())
  3988. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  3989. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3990. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3991. // type. Note that Functions are not objects, and that (in C99 parlance)
  3992. // incomplete types are not object types.
  3993. if (ResultType->isFunctionType()) {
  3994. Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
  3995. << ResultType << BaseExpr->getSourceRange();
  3996. return ExprError();
  3997. }
  3998. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  3999. // GNU extension: subscripting on pointer to void
  4000. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  4001. << BaseExpr->getSourceRange();
  4002. // C forbids expressions of unqualified void type from being l-values.
  4003. // See IsCForbiddenLValueType.
  4004. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  4005. } else if (!ResultType->isDependentType() &&
  4006. RequireCompleteType(LLoc, ResultType,
  4007. diag::err_subscript_incomplete_type, BaseExpr))
  4008. return ExprError();
  4009. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  4010. !ResultType.isCForbiddenLValueType());
  4011. return new (Context)
  4012. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  4013. }
  4014. bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
  4015. ParmVarDecl *Param) {
  4016. if (Param->hasUnparsedDefaultArg()) {
  4017. Diag(CallLoc,
  4018. diag::err_use_of_default_argument_to_function_declared_later) <<
  4019. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  4020. Diag(UnparsedDefaultArgLocs[Param],
  4021. diag::note_default_argument_declared_here);
  4022. return true;
  4023. }
  4024. if (Param->hasUninstantiatedDefaultArg()) {
  4025. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  4026. EnterExpressionEvaluationContext EvalContext(
  4027. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  4028. // Instantiate the expression.
  4029. //
  4030. // FIXME: Pass in a correct Pattern argument, otherwise
  4031. // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
  4032. //
  4033. // template<typename T>
  4034. // struct A {
  4035. // static int FooImpl();
  4036. //
  4037. // template<typename Tp>
  4038. // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
  4039. // // template argument list [[T], [Tp]], should be [[Tp]].
  4040. // friend A<Tp> Foo(int a);
  4041. // };
  4042. //
  4043. // template<typename T>
  4044. // A<T> Foo(int a = A<T>::FooImpl());
  4045. MultiLevelTemplateArgumentList MutiLevelArgList
  4046. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  4047. InstantiatingTemplate Inst(*this, CallLoc, Param,
  4048. MutiLevelArgList.getInnermost());
  4049. if (Inst.isInvalid())
  4050. return true;
  4051. if (Inst.isAlreadyInstantiating()) {
  4052. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  4053. Param->setInvalidDecl();
  4054. return true;
  4055. }
  4056. ExprResult Result;
  4057. {
  4058. // C++ [dcl.fct.default]p5:
  4059. // The names in the [default argument] expression are bound, and
  4060. // the semantic constraints are checked, at the point where the
  4061. // default argument expression appears.
  4062. ContextRAII SavedContext(*this, FD);
  4063. LocalInstantiationScope Local(*this);
  4064. Result = SubstInitializer(UninstExpr, MutiLevelArgList,
  4065. /*DirectInit*/false);
  4066. }
  4067. if (Result.isInvalid())
  4068. return true;
  4069. // Check the expression as an initializer for the parameter.
  4070. InitializedEntity Entity
  4071. = InitializedEntity::InitializeParameter(Context, Param);
  4072. InitializationKind Kind = InitializationKind::CreateCopy(
  4073. Param->getLocation(),
  4074. /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
  4075. Expr *ResultE = Result.getAs<Expr>();
  4076. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  4077. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  4078. if (Result.isInvalid())
  4079. return true;
  4080. Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
  4081. Param->getOuterLocStart());
  4082. if (Result.isInvalid())
  4083. return true;
  4084. // Remember the instantiated default argument.
  4085. Param->setDefaultArg(Result.getAs<Expr>());
  4086. if (ASTMutationListener *L = getASTMutationListener()) {
  4087. L->DefaultArgumentInstantiated(Param);
  4088. }
  4089. }
  4090. // If the default argument expression is not set yet, we are building it now.
  4091. if (!Param->hasInit()) {
  4092. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  4093. Param->setInvalidDecl();
  4094. return true;
  4095. }
  4096. // If the default expression creates temporaries, we need to
  4097. // push them to the current stack of expression temporaries so they'll
  4098. // be properly destroyed.
  4099. // FIXME: We should really be rebuilding the default argument with new
  4100. // bound temporaries; see the comment in PR5810.
  4101. // We don't need to do that with block decls, though, because
  4102. // blocks in default argument expression can never capture anything.
  4103. if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
  4104. // Set the "needs cleanups" bit regardless of whether there are
  4105. // any explicit objects.
  4106. Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
  4107. // Append all the objects to the cleanup list. Right now, this
  4108. // should always be a no-op, because blocks in default argument
  4109. // expressions should never be able to capture anything.
  4110. assert(!Init->getNumObjects() &&
  4111. "default argument expression has capturing blocks?");
  4112. }
  4113. // We already type-checked the argument, so we know it works.
  4114. // Just mark all of the declarations in this potentially-evaluated expression
  4115. // as being "referenced".
  4116. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  4117. /*SkipLocalVariables=*/true);
  4118. return false;
  4119. }
  4120. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  4121. FunctionDecl *FD, ParmVarDecl *Param) {
  4122. if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
  4123. return ExprError();
  4124. return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
  4125. }
  4126. Sema::VariadicCallType
  4127. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  4128. Expr *Fn) {
  4129. if (Proto && Proto->isVariadic()) {
  4130. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  4131. return VariadicConstructor;
  4132. else if (Fn && Fn->getType()->isBlockPointerType())
  4133. return VariadicBlock;
  4134. else if (FDecl) {
  4135. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4136. if (Method->isInstance())
  4137. return VariadicMethod;
  4138. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  4139. return VariadicMethod;
  4140. return VariadicFunction;
  4141. }
  4142. return VariadicDoesNotApply;
  4143. }
  4144. namespace {
  4145. class FunctionCallCCC : public FunctionCallFilterCCC {
  4146. public:
  4147. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  4148. unsigned NumArgs, MemberExpr *ME)
  4149. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  4150. FunctionName(FuncName) {}
  4151. bool ValidateCandidate(const TypoCorrection &candidate) override {
  4152. if (!candidate.getCorrectionSpecifier() ||
  4153. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  4154. return false;
  4155. }
  4156. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  4157. }
  4158. private:
  4159. const IdentifierInfo *const FunctionName;
  4160. };
  4161. }
  4162. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  4163. FunctionDecl *FDecl,
  4164. ArrayRef<Expr *> Args) {
  4165. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  4166. DeclarationName FuncName = FDecl->getDeclName();
  4167. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
  4168. if (TypoCorrection Corrected = S.CorrectTypo(
  4169. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  4170. S.getScopeForContext(S.CurContext), nullptr,
  4171. llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
  4172. Args.size(), ME),
  4173. Sema::CTK_ErrorRecovery)) {
  4174. if (NamedDecl *ND = Corrected.getFoundDecl()) {
  4175. if (Corrected.isOverloaded()) {
  4176. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  4177. OverloadCandidateSet::iterator Best;
  4178. for (NamedDecl *CD : Corrected) {
  4179. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  4180. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  4181. OCS);
  4182. }
  4183. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  4184. case OR_Success:
  4185. ND = Best->FoundDecl;
  4186. Corrected.setCorrectionDecl(ND);
  4187. break;
  4188. default:
  4189. break;
  4190. }
  4191. }
  4192. ND = ND->getUnderlyingDecl();
  4193. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
  4194. return Corrected;
  4195. }
  4196. }
  4197. return TypoCorrection();
  4198. }
  4199. /// ConvertArgumentsForCall - Converts the arguments specified in
  4200. /// Args/NumArgs to the parameter types of the function FDecl with
  4201. /// function prototype Proto. Call is the call expression itself, and
  4202. /// Fn is the function expression. For a C++ member function, this
  4203. /// routine does not attempt to convert the object argument. Returns
  4204. /// true if the call is ill-formed.
  4205. bool
  4206. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  4207. FunctionDecl *FDecl,
  4208. const FunctionProtoType *Proto,
  4209. ArrayRef<Expr *> Args,
  4210. SourceLocation RParenLoc,
  4211. bool IsExecConfig) {
  4212. // Bail out early if calling a builtin with custom typechecking.
  4213. if (FDecl)
  4214. if (unsigned ID = FDecl->getBuiltinID())
  4215. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  4216. return false;
  4217. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  4218. // assignment, to the types of the corresponding parameter, ...
  4219. unsigned NumParams = Proto->getNumParams();
  4220. bool Invalid = false;
  4221. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  4222. unsigned FnKind = Fn->getType()->isBlockPointerType()
  4223. ? 1 /* block */
  4224. : (IsExecConfig ? 3 /* kernel function (exec config) */
  4225. : 0 /* function */);
  4226. // If too few arguments are available (and we don't have default
  4227. // arguments for the remaining parameters), don't make the call.
  4228. if (Args.size() < NumParams) {
  4229. if (Args.size() < MinArgs) {
  4230. TypoCorrection TC;
  4231. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4232. unsigned diag_id =
  4233. MinArgs == NumParams && !Proto->isVariadic()
  4234. ? diag::err_typecheck_call_too_few_args_suggest
  4235. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  4236. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  4237. << static_cast<unsigned>(Args.size())
  4238. << TC.getCorrectionRange());
  4239. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  4240. Diag(RParenLoc,
  4241. MinArgs == NumParams && !Proto->isVariadic()
  4242. ? diag::err_typecheck_call_too_few_args_one
  4243. : diag::err_typecheck_call_too_few_args_at_least_one)
  4244. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  4245. else
  4246. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  4247. ? diag::err_typecheck_call_too_few_args
  4248. : diag::err_typecheck_call_too_few_args_at_least)
  4249. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  4250. << Fn->getSourceRange();
  4251. // Emit the location of the prototype.
  4252. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4253. Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
  4254. return true;
  4255. }
  4256. Call->setNumArgs(Context, NumParams);
  4257. }
  4258. // If too many are passed and not variadic, error on the extras and drop
  4259. // them.
  4260. if (Args.size() > NumParams) {
  4261. if (!Proto->isVariadic()) {
  4262. TypoCorrection TC;
  4263. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4264. unsigned diag_id =
  4265. MinArgs == NumParams && !Proto->isVariadic()
  4266. ? diag::err_typecheck_call_too_many_args_suggest
  4267. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  4268. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  4269. << static_cast<unsigned>(Args.size())
  4270. << TC.getCorrectionRange());
  4271. } else if (NumParams == 1 && FDecl &&
  4272. FDecl->getParamDecl(0)->getDeclName())
  4273. Diag(Args[NumParams]->getBeginLoc(),
  4274. MinArgs == NumParams
  4275. ? diag::err_typecheck_call_too_many_args_one
  4276. : diag::err_typecheck_call_too_many_args_at_most_one)
  4277. << FnKind << FDecl->getParamDecl(0)
  4278. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  4279. << SourceRange(Args[NumParams]->getBeginLoc(),
  4280. Args.back()->getEndLoc());
  4281. else
  4282. Diag(Args[NumParams]->getBeginLoc(),
  4283. MinArgs == NumParams
  4284. ? diag::err_typecheck_call_too_many_args
  4285. : diag::err_typecheck_call_too_many_args_at_most)
  4286. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  4287. << Fn->getSourceRange()
  4288. << SourceRange(Args[NumParams]->getBeginLoc(),
  4289. Args.back()->getEndLoc());
  4290. // Emit the location of the prototype.
  4291. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4292. Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
  4293. // This deletes the extra arguments.
  4294. Call->setNumArgs(Context, NumParams);
  4295. return true;
  4296. }
  4297. }
  4298. SmallVector<Expr *, 8> AllArgs;
  4299. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  4300. Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
  4301. AllArgs, CallType);
  4302. if (Invalid)
  4303. return true;
  4304. unsigned TotalNumArgs = AllArgs.size();
  4305. for (unsigned i = 0; i < TotalNumArgs; ++i)
  4306. Call->setArg(i, AllArgs[i]);
  4307. return false;
  4308. }
  4309. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  4310. const FunctionProtoType *Proto,
  4311. unsigned FirstParam, ArrayRef<Expr *> Args,
  4312. SmallVectorImpl<Expr *> &AllArgs,
  4313. VariadicCallType CallType, bool AllowExplicit,
  4314. bool IsListInitialization) {
  4315. unsigned NumParams = Proto->getNumParams();
  4316. bool Invalid = false;
  4317. size_t ArgIx = 0;
  4318. // Continue to check argument types (even if we have too few/many args).
  4319. for (unsigned i = FirstParam; i < NumParams; i++) {
  4320. QualType ProtoArgType = Proto->getParamType(i);
  4321. Expr *Arg;
  4322. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  4323. if (ArgIx < Args.size()) {
  4324. Arg = Args[ArgIx++];
  4325. if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
  4326. diag::err_call_incomplete_argument, Arg))
  4327. return true;
  4328. // Strip the unbridged-cast placeholder expression off, if applicable.
  4329. bool CFAudited = false;
  4330. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  4331. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4332. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4333. Arg = stripARCUnbridgedCast(Arg);
  4334. else if (getLangOpts().ObjCAutoRefCount &&
  4335. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4336. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4337. CFAudited = true;
  4338. if (Proto->getExtParameterInfo(i).isNoEscape())
  4339. if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
  4340. BE->getBlockDecl()->setDoesNotEscape();
  4341. InitializedEntity Entity =
  4342. Param ? InitializedEntity::InitializeParameter(Context, Param,
  4343. ProtoArgType)
  4344. : InitializedEntity::InitializeParameter(
  4345. Context, ProtoArgType, Proto->isParamConsumed(i));
  4346. // Remember that parameter belongs to a CF audited API.
  4347. if (CFAudited)
  4348. Entity.setParameterCFAudited();
  4349. ExprResult ArgE = PerformCopyInitialization(
  4350. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  4351. if (ArgE.isInvalid())
  4352. return true;
  4353. Arg = ArgE.getAs<Expr>();
  4354. } else {
  4355. assert(Param && "can't use default arguments without a known callee");
  4356. ExprResult ArgExpr =
  4357. BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  4358. if (ArgExpr.isInvalid())
  4359. return true;
  4360. Arg = ArgExpr.getAs<Expr>();
  4361. }
  4362. // Check for array bounds violations for each argument to the call. This
  4363. // check only triggers warnings when the argument isn't a more complex Expr
  4364. // with its own checking, such as a BinaryOperator.
  4365. CheckArrayAccess(Arg);
  4366. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  4367. CheckStaticArrayArgument(CallLoc, Param, Arg);
  4368. AllArgs.push_back(Arg);
  4369. }
  4370. // If this is a variadic call, handle args passed through "...".
  4371. if (CallType != VariadicDoesNotApply) {
  4372. // Assume that extern "C" functions with variadic arguments that
  4373. // return __unknown_anytype aren't *really* variadic.
  4374. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  4375. FDecl->isExternC()) {
  4376. for (Expr *A : Args.slice(ArgIx)) {
  4377. QualType paramType; // ignored
  4378. ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
  4379. Invalid |= arg.isInvalid();
  4380. AllArgs.push_back(arg.get());
  4381. }
  4382. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  4383. } else {
  4384. for (Expr *A : Args.slice(ArgIx)) {
  4385. ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
  4386. Invalid |= Arg.isInvalid();
  4387. AllArgs.push_back(Arg.get());
  4388. }
  4389. }
  4390. // Check for array bounds violations.
  4391. for (Expr *A : Args.slice(ArgIx))
  4392. CheckArrayAccess(A);
  4393. }
  4394. return Invalid;
  4395. }
  4396. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  4397. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  4398. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  4399. TL = DTL.getOriginalLoc();
  4400. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  4401. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  4402. << ATL.getLocalSourceRange();
  4403. }
  4404. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  4405. /// array parameter, check that it is non-null, and that if it is formed by
  4406. /// array-to-pointer decay, the underlying array is sufficiently large.
  4407. ///
  4408. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  4409. /// array type derivation, then for each call to the function, the value of the
  4410. /// corresponding actual argument shall provide access to the first element of
  4411. /// an array with at least as many elements as specified by the size expression.
  4412. void
  4413. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  4414. ParmVarDecl *Param,
  4415. const Expr *ArgExpr) {
  4416. // Static array parameters are not supported in C++.
  4417. if (!Param || getLangOpts().CPlusPlus)
  4418. return;
  4419. QualType OrigTy = Param->getOriginalType();
  4420. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  4421. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  4422. return;
  4423. if (ArgExpr->isNullPointerConstant(Context,
  4424. Expr::NPC_NeverValueDependent)) {
  4425. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  4426. DiagnoseCalleeStaticArrayParam(*this, Param);
  4427. return;
  4428. }
  4429. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  4430. if (!CAT)
  4431. return;
  4432. const ConstantArrayType *ArgCAT =
  4433. Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
  4434. if (!ArgCAT)
  4435. return;
  4436. if (ArgCAT->getSize().ult(CAT->getSize())) {
  4437. Diag(CallLoc, diag::warn_static_array_too_small)
  4438. << ArgExpr->getSourceRange()
  4439. << (unsigned) ArgCAT->getSize().getZExtValue()
  4440. << (unsigned) CAT->getSize().getZExtValue();
  4441. DiagnoseCalleeStaticArrayParam(*this, Param);
  4442. }
  4443. }
  4444. /// Given a function expression of unknown-any type, try to rebuild it
  4445. /// to have a function type.
  4446. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4447. /// Is the given type a placeholder that we need to lower out
  4448. /// immediately during argument processing?
  4449. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4450. // Placeholders are never sugared.
  4451. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4452. if (!placeholder) return false;
  4453. switch (placeholder->getKind()) {
  4454. // Ignore all the non-placeholder types.
  4455. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  4456. case BuiltinType::Id:
  4457. #include "clang/Basic/OpenCLImageTypes.def"
  4458. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  4459. case BuiltinType::Id:
  4460. #include "clang/Basic/OpenCLExtensionTypes.def"
  4461. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4462. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4463. #include "clang/AST/BuiltinTypes.def"
  4464. return false;
  4465. // We cannot lower out overload sets; they might validly be resolved
  4466. // by the call machinery.
  4467. case BuiltinType::Overload:
  4468. return false;
  4469. // Unbridged casts in ARC can be handled in some call positions and
  4470. // should be left in place.
  4471. case BuiltinType::ARCUnbridgedCast:
  4472. return false;
  4473. // Pseudo-objects should be converted as soon as possible.
  4474. case BuiltinType::PseudoObject:
  4475. return true;
  4476. // The debugger mode could theoretically but currently does not try
  4477. // to resolve unknown-typed arguments based on known parameter types.
  4478. case BuiltinType::UnknownAny:
  4479. return true;
  4480. // These are always invalid as call arguments and should be reported.
  4481. case BuiltinType::BoundMember:
  4482. case BuiltinType::BuiltinFn:
  4483. case BuiltinType::OMPArraySection:
  4484. return true;
  4485. }
  4486. llvm_unreachable("bad builtin type kind");
  4487. }
  4488. /// Check an argument list for placeholders that we won't try to
  4489. /// handle later.
  4490. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4491. // Apply this processing to all the arguments at once instead of
  4492. // dying at the first failure.
  4493. bool hasInvalid = false;
  4494. for (size_t i = 0, e = args.size(); i != e; i++) {
  4495. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4496. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4497. if (result.isInvalid()) hasInvalid = true;
  4498. else args[i] = result.get();
  4499. } else if (hasInvalid) {
  4500. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4501. }
  4502. }
  4503. return hasInvalid;
  4504. }
  4505. /// If a builtin function has a pointer argument with no explicit address
  4506. /// space, then it should be able to accept a pointer to any address
  4507. /// space as input. In order to do this, we need to replace the
  4508. /// standard builtin declaration with one that uses the same address space
  4509. /// as the call.
  4510. ///
  4511. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4512. /// it does not contain any pointer arguments without
  4513. /// an address space qualifer. Otherwise the rewritten
  4514. /// FunctionDecl is returned.
  4515. /// TODO: Handle pointer return types.
  4516. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4517. const FunctionDecl *FDecl,
  4518. MultiExprArg ArgExprs) {
  4519. QualType DeclType = FDecl->getType();
  4520. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4521. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
  4522. !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
  4523. return nullptr;
  4524. bool NeedsNewDecl = false;
  4525. unsigned i = 0;
  4526. SmallVector<QualType, 8> OverloadParams;
  4527. for (QualType ParamType : FT->param_types()) {
  4528. // Convert array arguments to pointer to simplify type lookup.
  4529. ExprResult ArgRes =
  4530. Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
  4531. if (ArgRes.isInvalid())
  4532. return nullptr;
  4533. Expr *Arg = ArgRes.get();
  4534. QualType ArgType = Arg->getType();
  4535. if (!ParamType->isPointerType() ||
  4536. ParamType.getQualifiers().hasAddressSpace() ||
  4537. !ArgType->isPointerType() ||
  4538. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4539. OverloadParams.push_back(ParamType);
  4540. continue;
  4541. }
  4542. QualType PointeeType = ParamType->getPointeeType();
  4543. if (PointeeType.getQualifiers().hasAddressSpace())
  4544. continue;
  4545. NeedsNewDecl = true;
  4546. LangAS AS = ArgType->getPointeeType().getAddressSpace();
  4547. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4548. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4549. }
  4550. if (!NeedsNewDecl)
  4551. return nullptr;
  4552. FunctionProtoType::ExtProtoInfo EPI;
  4553. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4554. OverloadParams, EPI);
  4555. DeclContext *Parent = Context.getTranslationUnitDecl();
  4556. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4557. FDecl->getLocation(),
  4558. FDecl->getLocation(),
  4559. FDecl->getIdentifier(),
  4560. OverloadTy,
  4561. /*TInfo=*/nullptr,
  4562. SC_Extern, false,
  4563. /*hasPrototype=*/true);
  4564. SmallVector<ParmVarDecl*, 16> Params;
  4565. FT = cast<FunctionProtoType>(OverloadTy);
  4566. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4567. QualType ParamType = FT->getParamType(i);
  4568. ParmVarDecl *Parm =
  4569. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4570. SourceLocation(), nullptr, ParamType,
  4571. /*TInfo=*/nullptr, SC_None, nullptr);
  4572. Parm->setScopeInfo(0, i);
  4573. Params.push_back(Parm);
  4574. }
  4575. OverloadDecl->setParams(Params);
  4576. return OverloadDecl;
  4577. }
  4578. static void checkDirectCallValidity(Sema &S, const Expr *Fn,
  4579. FunctionDecl *Callee,
  4580. MultiExprArg ArgExprs) {
  4581. // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
  4582. // similar attributes) really don't like it when functions are called with an
  4583. // invalid number of args.
  4584. if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
  4585. /*PartialOverloading=*/false) &&
  4586. !Callee->isVariadic())
  4587. return;
  4588. if (Callee->getMinRequiredArguments() > ArgExprs.size())
  4589. return;
  4590. if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
  4591. S.Diag(Fn->getBeginLoc(),
  4592. isa<CXXMethodDecl>(Callee)
  4593. ? diag::err_ovl_no_viable_member_function_in_call
  4594. : diag::err_ovl_no_viable_function_in_call)
  4595. << Callee << Callee->getSourceRange();
  4596. S.Diag(Callee->getLocation(),
  4597. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  4598. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4599. return;
  4600. }
  4601. }
  4602. static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
  4603. const UnresolvedMemberExpr *const UME, Sema &S) {
  4604. const auto GetFunctionLevelDCIfCXXClass =
  4605. [](Sema &S) -> const CXXRecordDecl * {
  4606. const DeclContext *const DC = S.getFunctionLevelDeclContext();
  4607. if (!DC || !DC->getParent())
  4608. return nullptr;
  4609. // If the call to some member function was made from within a member
  4610. // function body 'M' return return 'M's parent.
  4611. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  4612. return MD->getParent()->getCanonicalDecl();
  4613. // else the call was made from within a default member initializer of a
  4614. // class, so return the class.
  4615. if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
  4616. return RD->getCanonicalDecl();
  4617. return nullptr;
  4618. };
  4619. // If our DeclContext is neither a member function nor a class (in the
  4620. // case of a lambda in a default member initializer), we can't have an
  4621. // enclosing 'this'.
  4622. const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
  4623. if (!CurParentClass)
  4624. return false;
  4625. // The naming class for implicit member functions call is the class in which
  4626. // name lookup starts.
  4627. const CXXRecordDecl *const NamingClass =
  4628. UME->getNamingClass()->getCanonicalDecl();
  4629. assert(NamingClass && "Must have naming class even for implicit access");
  4630. // If the unresolved member functions were found in a 'naming class' that is
  4631. // related (either the same or derived from) to the class that contains the
  4632. // member function that itself contained the implicit member access.
  4633. return CurParentClass == NamingClass ||
  4634. CurParentClass->isDerivedFrom(NamingClass);
  4635. }
  4636. static void
  4637. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4638. Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
  4639. if (!UME)
  4640. return;
  4641. LambdaScopeInfo *const CurLSI = S.getCurLambda();
  4642. // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
  4643. // already been captured, or if this is an implicit member function call (if
  4644. // it isn't, an attempt to capture 'this' should already have been made).
  4645. if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
  4646. !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
  4647. return;
  4648. // Check if the naming class in which the unresolved members were found is
  4649. // related (same as or is a base of) to the enclosing class.
  4650. if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
  4651. return;
  4652. DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
  4653. // If the enclosing function is not dependent, then this lambda is
  4654. // capture ready, so if we can capture this, do so.
  4655. if (!EnclosingFunctionCtx->isDependentContext()) {
  4656. // If the current lambda and all enclosing lambdas can capture 'this' -
  4657. // then go ahead and capture 'this' (since our unresolved overload set
  4658. // contains at least one non-static member function).
  4659. if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
  4660. S.CheckCXXThisCapture(CallLoc);
  4661. } else if (S.CurContext->isDependentContext()) {
  4662. // ... since this is an implicit member reference, that might potentially
  4663. // involve a 'this' capture, mark 'this' for potential capture in
  4664. // enclosing lambdas.
  4665. if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
  4666. CurLSI->addPotentialThisCapture(CallLoc);
  4667. }
  4668. }
  4669. /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
  4670. /// This provides the location of the left/right parens and a list of comma
  4671. /// locations.
  4672. ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  4673. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4674. Expr *ExecConfig, bool IsExecConfig) {
  4675. // Since this might be a postfix expression, get rid of ParenListExprs.
  4676. ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
  4677. if (Result.isInvalid()) return ExprError();
  4678. Fn = Result.get();
  4679. if (checkArgsForPlaceholders(*this, ArgExprs))
  4680. return ExprError();
  4681. if (getLangOpts().CPlusPlus) {
  4682. // If this is a pseudo-destructor expression, build the call immediately.
  4683. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4684. if (!ArgExprs.empty()) {
  4685. // Pseudo-destructor calls should not have any arguments.
  4686. Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
  4687. << FixItHint::CreateRemoval(
  4688. SourceRange(ArgExprs.front()->getBeginLoc(),
  4689. ArgExprs.back()->getEndLoc()));
  4690. }
  4691. return new (Context)
  4692. CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
  4693. }
  4694. if (Fn->getType() == Context.PseudoObjectTy) {
  4695. ExprResult result = CheckPlaceholderExpr(Fn);
  4696. if (result.isInvalid()) return ExprError();
  4697. Fn = result.get();
  4698. }
  4699. // Determine whether this is a dependent call inside a C++ template,
  4700. // in which case we won't do any semantic analysis now.
  4701. if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
  4702. if (ExecConfig) {
  4703. return new (Context) CUDAKernelCallExpr(
  4704. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4705. Context.DependentTy, VK_RValue, RParenLoc);
  4706. } else {
  4707. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4708. *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
  4709. Fn->getBeginLoc());
  4710. return new (Context) CallExpr(
  4711. Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
  4712. }
  4713. }
  4714. // Determine whether this is a call to an object (C++ [over.call.object]).
  4715. if (Fn->getType()->isRecordType())
  4716. return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
  4717. RParenLoc);
  4718. if (Fn->getType() == Context.UnknownAnyTy) {
  4719. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4720. if (result.isInvalid()) return ExprError();
  4721. Fn = result.get();
  4722. }
  4723. if (Fn->getType() == Context.BoundMemberTy) {
  4724. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4725. RParenLoc);
  4726. }
  4727. }
  4728. // Check for overloaded calls. This can happen even in C due to extensions.
  4729. if (Fn->getType() == Context.OverloadTy) {
  4730. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4731. // We aren't supposed to apply this logic if there's an '&' involved.
  4732. if (!find.HasFormOfMemberPointer) {
  4733. if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4734. return new (Context) CallExpr(
  4735. Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
  4736. OverloadExpr *ovl = find.Expression;
  4737. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
  4738. return BuildOverloadedCallExpr(
  4739. Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
  4740. /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
  4741. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4742. RParenLoc);
  4743. }
  4744. }
  4745. // If we're directly calling a function, get the appropriate declaration.
  4746. if (Fn->getType() == Context.UnknownAnyTy) {
  4747. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4748. if (result.isInvalid()) return ExprError();
  4749. Fn = result.get();
  4750. }
  4751. Expr *NakedFn = Fn->IgnoreParens();
  4752. bool CallingNDeclIndirectly = false;
  4753. NamedDecl *NDecl = nullptr;
  4754. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
  4755. if (UnOp->getOpcode() == UO_AddrOf) {
  4756. CallingNDeclIndirectly = true;
  4757. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4758. }
  4759. }
  4760. if (isa<DeclRefExpr>(NakedFn)) {
  4761. NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
  4762. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  4763. if (FDecl && FDecl->getBuiltinID()) {
  4764. // Rewrite the function decl for this builtin by replacing parameters
  4765. // with no explicit address space with the address space of the arguments
  4766. // in ArgExprs.
  4767. if ((FDecl =
  4768. rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  4769. NDecl = FDecl;
  4770. Fn = DeclRefExpr::Create(
  4771. Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
  4772. SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
  4773. }
  4774. }
  4775. } else if (isa<MemberExpr>(NakedFn))
  4776. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  4777. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  4778. if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
  4779. FD, /*Complain=*/true, Fn->getBeginLoc()))
  4780. return ExprError();
  4781. if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
  4782. return ExprError();
  4783. checkDirectCallValidity(*this, Fn, FD, ArgExprs);
  4784. }
  4785. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  4786. ExecConfig, IsExecConfig);
  4787. }
  4788. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  4789. ///
  4790. /// __builtin_astype( value, dst type )
  4791. ///
  4792. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  4793. SourceLocation BuiltinLoc,
  4794. SourceLocation RParenLoc) {
  4795. ExprValueKind VK = VK_RValue;
  4796. ExprObjectKind OK = OK_Ordinary;
  4797. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  4798. QualType SrcTy = E->getType();
  4799. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  4800. return ExprError(Diag(BuiltinLoc,
  4801. diag::err_invalid_astype_of_different_size)
  4802. << DstTy
  4803. << SrcTy
  4804. << E->getSourceRange());
  4805. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  4806. }
  4807. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  4808. /// provided arguments.
  4809. ///
  4810. /// __builtin_convertvector( value, dst type )
  4811. ///
  4812. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  4813. SourceLocation BuiltinLoc,
  4814. SourceLocation RParenLoc) {
  4815. TypeSourceInfo *TInfo;
  4816. GetTypeFromParser(ParsedDestTy, &TInfo);
  4817. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  4818. }
  4819. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  4820. /// i.e. an expression not of \p OverloadTy. The expression should
  4821. /// unary-convert to an expression of function-pointer or
  4822. /// block-pointer type.
  4823. ///
  4824. /// \param NDecl the declaration being called, if available
  4825. ExprResult
  4826. Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  4827. SourceLocation LParenLoc,
  4828. ArrayRef<Expr *> Args,
  4829. SourceLocation RParenLoc,
  4830. Expr *Config, bool IsExecConfig) {
  4831. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  4832. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  4833. // Functions with 'interrupt' attribute cannot be called directly.
  4834. if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
  4835. Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
  4836. return ExprError();
  4837. }
  4838. // Interrupt handlers don't save off the VFP regs automatically on ARM,
  4839. // so there's some risk when calling out to non-interrupt handler functions
  4840. // that the callee might not preserve them. This is easy to diagnose here,
  4841. // but can be very challenging to debug.
  4842. if (auto *Caller = getCurFunctionDecl())
  4843. if (Caller->hasAttr<ARMInterruptAttr>()) {
  4844. bool VFP = Context.getTargetInfo().hasFeature("vfp");
  4845. if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
  4846. Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
  4847. }
  4848. // Promote the function operand.
  4849. // We special-case function promotion here because we only allow promoting
  4850. // builtin functions to function pointers in the callee of a call.
  4851. ExprResult Result;
  4852. if (BuiltinID &&
  4853. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  4854. Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
  4855. CK_BuiltinFnToFnPtr).get();
  4856. } else {
  4857. Result = CallExprUnaryConversions(Fn);
  4858. }
  4859. if (Result.isInvalid())
  4860. return ExprError();
  4861. Fn = Result.get();
  4862. // Make the call expr early, before semantic checks. This guarantees cleanup
  4863. // of arguments and function on error.
  4864. CallExpr *TheCall;
  4865. if (Config)
  4866. TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
  4867. cast<CallExpr>(Config), Args,
  4868. Context.BoolTy, VK_RValue,
  4869. RParenLoc);
  4870. else
  4871. TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
  4872. VK_RValue, RParenLoc);
  4873. if (!getLangOpts().CPlusPlus) {
  4874. // C cannot always handle TypoExpr nodes in builtin calls and direct
  4875. // function calls as their argument checking don't necessarily handle
  4876. // dependent types properly, so make sure any TypoExprs have been
  4877. // dealt with.
  4878. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  4879. if (!Result.isUsable()) return ExprError();
  4880. TheCall = dyn_cast<CallExpr>(Result.get());
  4881. if (!TheCall) return Result;
  4882. Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
  4883. }
  4884. // Bail out early if calling a builtin with custom typechecking.
  4885. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  4886. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4887. retry:
  4888. const FunctionType *FuncT;
  4889. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  4890. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  4891. // have type pointer to function".
  4892. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  4893. if (!FuncT)
  4894. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4895. << Fn->getType() << Fn->getSourceRange());
  4896. } else if (const BlockPointerType *BPT =
  4897. Fn->getType()->getAs<BlockPointerType>()) {
  4898. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  4899. } else {
  4900. // Handle calls to expressions of unknown-any type.
  4901. if (Fn->getType() == Context.UnknownAnyTy) {
  4902. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  4903. if (rewrite.isInvalid()) return ExprError();
  4904. Fn = rewrite.get();
  4905. TheCall->setCallee(Fn);
  4906. goto retry;
  4907. }
  4908. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4909. << Fn->getType() << Fn->getSourceRange());
  4910. }
  4911. if (getLangOpts().CUDA) {
  4912. if (Config) {
  4913. // CUDA: Kernel calls must be to global functions
  4914. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  4915. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  4916. << FDecl << Fn->getSourceRange());
  4917. // CUDA: Kernel function must have 'void' return type
  4918. if (!FuncT->getReturnType()->isVoidType())
  4919. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  4920. << Fn->getType() << Fn->getSourceRange());
  4921. } else {
  4922. // CUDA: Calls to global functions must be configured
  4923. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  4924. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  4925. << FDecl << Fn->getSourceRange());
  4926. }
  4927. }
  4928. // Check for a valid return type
  4929. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
  4930. FDecl))
  4931. return ExprError();
  4932. // We know the result type of the call, set it.
  4933. TheCall->setType(FuncT->getCallResultType(Context));
  4934. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  4935. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
  4936. if (Proto) {
  4937. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  4938. IsExecConfig))
  4939. return ExprError();
  4940. } else {
  4941. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  4942. if (FDecl) {
  4943. // Check if we have too few/too many template arguments, based
  4944. // on our knowledge of the function definition.
  4945. const FunctionDecl *Def = nullptr;
  4946. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  4947. Proto = Def->getType()->getAs<FunctionProtoType>();
  4948. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  4949. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  4950. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  4951. }
  4952. // If the function we're calling isn't a function prototype, but we have
  4953. // a function prototype from a prior declaratiom, use that prototype.
  4954. if (!FDecl->hasPrototype())
  4955. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  4956. }
  4957. // Promote the arguments (C99 6.5.2.2p6).
  4958. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  4959. Expr *Arg = Args[i];
  4960. if (Proto && i < Proto->getNumParams()) {
  4961. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4962. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  4963. ExprResult ArgE =
  4964. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4965. if (ArgE.isInvalid())
  4966. return true;
  4967. Arg = ArgE.getAs<Expr>();
  4968. } else {
  4969. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  4970. if (ArgE.isInvalid())
  4971. return true;
  4972. Arg = ArgE.getAs<Expr>();
  4973. }
  4974. if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
  4975. diag::err_call_incomplete_argument, Arg))
  4976. return ExprError();
  4977. TheCall->setArg(i, Arg);
  4978. }
  4979. }
  4980. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4981. if (!Method->isStatic())
  4982. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  4983. << Fn->getSourceRange());
  4984. // Check for sentinels
  4985. if (NDecl)
  4986. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  4987. // Do special checking on direct calls to functions.
  4988. if (FDecl) {
  4989. if (CheckFunctionCall(FDecl, TheCall, Proto))
  4990. return ExprError();
  4991. if (BuiltinID)
  4992. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4993. } else if (NDecl) {
  4994. if (CheckPointerCall(NDecl, TheCall, Proto))
  4995. return ExprError();
  4996. } else {
  4997. if (CheckOtherCall(TheCall, Proto))
  4998. return ExprError();
  4999. }
  5000. return MaybeBindToTemporary(TheCall);
  5001. }
  5002. ExprResult
  5003. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  5004. SourceLocation RParenLoc, Expr *InitExpr) {
  5005. assert(Ty && "ActOnCompoundLiteral(): missing type");
  5006. assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
  5007. TypeSourceInfo *TInfo;
  5008. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  5009. if (!TInfo)
  5010. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  5011. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  5012. }
  5013. ExprResult
  5014. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  5015. SourceLocation RParenLoc, Expr *LiteralExpr) {
  5016. QualType literalType = TInfo->getType();
  5017. if (literalType->isArrayType()) {
  5018. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  5019. diag::err_illegal_decl_array_incomplete_type,
  5020. SourceRange(LParenLoc,
  5021. LiteralExpr->getSourceRange().getEnd())))
  5022. return ExprError();
  5023. if (literalType->isVariableArrayType())
  5024. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  5025. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  5026. } else if (!literalType->isDependentType() &&
  5027. RequireCompleteType(LParenLoc, literalType,
  5028. diag::err_typecheck_decl_incomplete_type,
  5029. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  5030. return ExprError();
  5031. InitializedEntity Entity
  5032. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  5033. InitializationKind Kind
  5034. = InitializationKind::CreateCStyleCast(LParenLoc,
  5035. SourceRange(LParenLoc, RParenLoc),
  5036. /*InitList=*/true);
  5037. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  5038. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  5039. &literalType);
  5040. if (Result.isInvalid())
  5041. return ExprError();
  5042. LiteralExpr = Result.get();
  5043. bool isFileScope = !CurContext->isFunctionOrMethod();
  5044. if (isFileScope) {
  5045. if (!LiteralExpr->isTypeDependent() &&
  5046. !LiteralExpr->isValueDependent() &&
  5047. !literalType->isDependentType()) // C99 6.5.2.5p3
  5048. if (CheckForConstantInitializer(LiteralExpr, literalType))
  5049. return ExprError();
  5050. } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
  5051. literalType.getAddressSpace() != LangAS::Default) {
  5052. // Embedded-C extensions to C99 6.5.2.5:
  5053. // "If the compound literal occurs inside the body of a function, the
  5054. // type name shall not be qualified by an address-space qualifier."
  5055. Diag(LParenLoc, diag::err_compound_literal_with_address_space)
  5056. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
  5057. return ExprError();
  5058. }
  5059. // In C, compound literals are l-values for some reason.
  5060. // For GCC compatibility, in C++, file-scope array compound literals with
  5061. // constant initializers are also l-values, and compound literals are
  5062. // otherwise prvalues.
  5063. //
  5064. // (GCC also treats C++ list-initialized file-scope array prvalues with
  5065. // constant initializers as l-values, but that's non-conforming, so we don't
  5066. // follow it there.)
  5067. //
  5068. // FIXME: It would be better to handle the lvalue cases as materializing and
  5069. // lifetime-extending a temporary object, but our materialized temporaries
  5070. // representation only supports lifetime extension from a variable, not "out
  5071. // of thin air".
  5072. // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
  5073. // is bound to the result of applying array-to-pointer decay to the compound
  5074. // literal.
  5075. // FIXME: GCC supports compound literals of reference type, which should
  5076. // obviously have a value kind derived from the kind of reference involved.
  5077. ExprValueKind VK =
  5078. (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
  5079. ? VK_RValue
  5080. : VK_LValue;
  5081. return MaybeBindToTemporary(
  5082. new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  5083. VK, LiteralExpr, isFileScope));
  5084. }
  5085. ExprResult
  5086. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  5087. SourceLocation RBraceLoc) {
  5088. // Immediately handle non-overload placeholders. Overloads can be
  5089. // resolved contextually, but everything else here can't.
  5090. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  5091. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  5092. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  5093. // Ignore failures; dropping the entire initializer list because
  5094. // of one failure would be terrible for indexing/etc.
  5095. if (result.isInvalid()) continue;
  5096. InitArgList[I] = result.get();
  5097. }
  5098. }
  5099. // Semantic analysis for initializers is done by ActOnDeclarator() and
  5100. // CheckInitializer() - it requires knowledge of the object being initialized.
  5101. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  5102. RBraceLoc);
  5103. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  5104. return E;
  5105. }
  5106. /// Do an explicit extend of the given block pointer if we're in ARC.
  5107. void Sema::maybeExtendBlockObject(ExprResult &E) {
  5108. assert(E.get()->getType()->isBlockPointerType());
  5109. assert(E.get()->isRValue());
  5110. // Only do this in an r-value context.
  5111. if (!getLangOpts().ObjCAutoRefCount) return;
  5112. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  5113. CK_ARCExtendBlockObject, E.get(),
  5114. /*base path*/ nullptr, VK_RValue);
  5115. Cleanup.setExprNeedsCleanups(true);
  5116. }
  5117. /// Prepare a conversion of the given expression to an ObjC object
  5118. /// pointer type.
  5119. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  5120. QualType type = E.get()->getType();
  5121. if (type->isObjCObjectPointerType()) {
  5122. return CK_BitCast;
  5123. } else if (type->isBlockPointerType()) {
  5124. maybeExtendBlockObject(E);
  5125. return CK_BlockPointerToObjCPointerCast;
  5126. } else {
  5127. assert(type->isPointerType());
  5128. return CK_CPointerToObjCPointerCast;
  5129. }
  5130. }
  5131. /// Prepares for a scalar cast, performing all the necessary stages
  5132. /// except the final cast and returning the kind required.
  5133. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  5134. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  5135. // Also, callers should have filtered out the invalid cases with
  5136. // pointers. Everything else should be possible.
  5137. QualType SrcTy = Src.get()->getType();
  5138. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  5139. return CK_NoOp;
  5140. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  5141. case Type::STK_MemberPointer:
  5142. llvm_unreachable("member pointer type in C");
  5143. case Type::STK_CPointer:
  5144. case Type::STK_BlockPointer:
  5145. case Type::STK_ObjCObjectPointer:
  5146. switch (DestTy->getScalarTypeKind()) {
  5147. case Type::STK_CPointer: {
  5148. LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
  5149. LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
  5150. if (SrcAS != DestAS)
  5151. return CK_AddressSpaceConversion;
  5152. if (Context.hasCvrSimilarType(SrcTy, DestTy))
  5153. return CK_NoOp;
  5154. return CK_BitCast;
  5155. }
  5156. case Type::STK_BlockPointer:
  5157. return (SrcKind == Type::STK_BlockPointer
  5158. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  5159. case Type::STK_ObjCObjectPointer:
  5160. if (SrcKind == Type::STK_ObjCObjectPointer)
  5161. return CK_BitCast;
  5162. if (SrcKind == Type::STK_CPointer)
  5163. return CK_CPointerToObjCPointerCast;
  5164. maybeExtendBlockObject(Src);
  5165. return CK_BlockPointerToObjCPointerCast;
  5166. case Type::STK_Bool:
  5167. return CK_PointerToBoolean;
  5168. case Type::STK_Integral:
  5169. return CK_PointerToIntegral;
  5170. case Type::STK_Floating:
  5171. case Type::STK_FloatingComplex:
  5172. case Type::STK_IntegralComplex:
  5173. case Type::STK_MemberPointer:
  5174. case Type::STK_FixedPoint:
  5175. llvm_unreachable("illegal cast from pointer");
  5176. }
  5177. llvm_unreachable("Should have returned before this");
  5178. case Type::STK_FixedPoint:
  5179. switch (DestTy->getScalarTypeKind()) {
  5180. case Type::STK_FixedPoint:
  5181. return CK_FixedPointCast;
  5182. case Type::STK_Bool:
  5183. return CK_FixedPointToBoolean;
  5184. case Type::STK_Integral:
  5185. case Type::STK_Floating:
  5186. case Type::STK_IntegralComplex:
  5187. case Type::STK_FloatingComplex:
  5188. Diag(Src.get()->getExprLoc(),
  5189. diag::err_unimplemented_conversion_with_fixed_point_type)
  5190. << DestTy;
  5191. return CK_IntegralCast;
  5192. case Type::STK_CPointer:
  5193. case Type::STK_ObjCObjectPointer:
  5194. case Type::STK_BlockPointer:
  5195. case Type::STK_MemberPointer:
  5196. llvm_unreachable("illegal cast to pointer type");
  5197. }
  5198. llvm_unreachable("Should have returned before this");
  5199. case Type::STK_Bool: // casting from bool is like casting from an integer
  5200. case Type::STK_Integral:
  5201. switch (DestTy->getScalarTypeKind()) {
  5202. case Type::STK_CPointer:
  5203. case Type::STK_ObjCObjectPointer:
  5204. case Type::STK_BlockPointer:
  5205. if (Src.get()->isNullPointerConstant(Context,
  5206. Expr::NPC_ValueDependentIsNull))
  5207. return CK_NullToPointer;
  5208. return CK_IntegralToPointer;
  5209. case Type::STK_Bool:
  5210. return CK_IntegralToBoolean;
  5211. case Type::STK_Integral:
  5212. return CK_IntegralCast;
  5213. case Type::STK_Floating:
  5214. return CK_IntegralToFloating;
  5215. case Type::STK_IntegralComplex:
  5216. Src = ImpCastExprToType(Src.get(),
  5217. DestTy->castAs<ComplexType>()->getElementType(),
  5218. CK_IntegralCast);
  5219. return CK_IntegralRealToComplex;
  5220. case Type::STK_FloatingComplex:
  5221. Src = ImpCastExprToType(Src.get(),
  5222. DestTy->castAs<ComplexType>()->getElementType(),
  5223. CK_IntegralToFloating);
  5224. return CK_FloatingRealToComplex;
  5225. case Type::STK_MemberPointer:
  5226. llvm_unreachable("member pointer type in C");
  5227. case Type::STK_FixedPoint:
  5228. Diag(Src.get()->getExprLoc(),
  5229. diag::err_unimplemented_conversion_with_fixed_point_type)
  5230. << SrcTy;
  5231. return CK_IntegralCast;
  5232. }
  5233. llvm_unreachable("Should have returned before this");
  5234. case Type::STK_Floating:
  5235. switch (DestTy->getScalarTypeKind()) {
  5236. case Type::STK_Floating:
  5237. return CK_FloatingCast;
  5238. case Type::STK_Bool:
  5239. return CK_FloatingToBoolean;
  5240. case Type::STK_Integral:
  5241. return CK_FloatingToIntegral;
  5242. case Type::STK_FloatingComplex:
  5243. Src = ImpCastExprToType(Src.get(),
  5244. DestTy->castAs<ComplexType>()->getElementType(),
  5245. CK_FloatingCast);
  5246. return CK_FloatingRealToComplex;
  5247. case Type::STK_IntegralComplex:
  5248. Src = ImpCastExprToType(Src.get(),
  5249. DestTy->castAs<ComplexType>()->getElementType(),
  5250. CK_FloatingToIntegral);
  5251. return CK_IntegralRealToComplex;
  5252. case Type::STK_CPointer:
  5253. case Type::STK_ObjCObjectPointer:
  5254. case Type::STK_BlockPointer:
  5255. llvm_unreachable("valid float->pointer cast?");
  5256. case Type::STK_MemberPointer:
  5257. llvm_unreachable("member pointer type in C");
  5258. case Type::STK_FixedPoint:
  5259. Diag(Src.get()->getExprLoc(),
  5260. diag::err_unimplemented_conversion_with_fixed_point_type)
  5261. << SrcTy;
  5262. return CK_IntegralCast;
  5263. }
  5264. llvm_unreachable("Should have returned before this");
  5265. case Type::STK_FloatingComplex:
  5266. switch (DestTy->getScalarTypeKind()) {
  5267. case Type::STK_FloatingComplex:
  5268. return CK_FloatingComplexCast;
  5269. case Type::STK_IntegralComplex:
  5270. return CK_FloatingComplexToIntegralComplex;
  5271. case Type::STK_Floating: {
  5272. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5273. if (Context.hasSameType(ET, DestTy))
  5274. return CK_FloatingComplexToReal;
  5275. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  5276. return CK_FloatingCast;
  5277. }
  5278. case Type::STK_Bool:
  5279. return CK_FloatingComplexToBoolean;
  5280. case Type::STK_Integral:
  5281. Src = ImpCastExprToType(Src.get(),
  5282. SrcTy->castAs<ComplexType>()->getElementType(),
  5283. CK_FloatingComplexToReal);
  5284. return CK_FloatingToIntegral;
  5285. case Type::STK_CPointer:
  5286. case Type::STK_ObjCObjectPointer:
  5287. case Type::STK_BlockPointer:
  5288. llvm_unreachable("valid complex float->pointer cast?");
  5289. case Type::STK_MemberPointer:
  5290. llvm_unreachable("member pointer type in C");
  5291. case Type::STK_FixedPoint:
  5292. Diag(Src.get()->getExprLoc(),
  5293. diag::err_unimplemented_conversion_with_fixed_point_type)
  5294. << SrcTy;
  5295. return CK_IntegralCast;
  5296. }
  5297. llvm_unreachable("Should have returned before this");
  5298. case Type::STK_IntegralComplex:
  5299. switch (DestTy->getScalarTypeKind()) {
  5300. case Type::STK_FloatingComplex:
  5301. return CK_IntegralComplexToFloatingComplex;
  5302. case Type::STK_IntegralComplex:
  5303. return CK_IntegralComplexCast;
  5304. case Type::STK_Integral: {
  5305. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5306. if (Context.hasSameType(ET, DestTy))
  5307. return CK_IntegralComplexToReal;
  5308. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  5309. return CK_IntegralCast;
  5310. }
  5311. case Type::STK_Bool:
  5312. return CK_IntegralComplexToBoolean;
  5313. case Type::STK_Floating:
  5314. Src = ImpCastExprToType(Src.get(),
  5315. SrcTy->castAs<ComplexType>()->getElementType(),
  5316. CK_IntegralComplexToReal);
  5317. return CK_IntegralToFloating;
  5318. case Type::STK_CPointer:
  5319. case Type::STK_ObjCObjectPointer:
  5320. case Type::STK_BlockPointer:
  5321. llvm_unreachable("valid complex int->pointer cast?");
  5322. case Type::STK_MemberPointer:
  5323. llvm_unreachable("member pointer type in C");
  5324. case Type::STK_FixedPoint:
  5325. Diag(Src.get()->getExprLoc(),
  5326. diag::err_unimplemented_conversion_with_fixed_point_type)
  5327. << SrcTy;
  5328. return CK_IntegralCast;
  5329. }
  5330. llvm_unreachable("Should have returned before this");
  5331. }
  5332. llvm_unreachable("Unhandled scalar cast");
  5333. }
  5334. static bool breakDownVectorType(QualType type, uint64_t &len,
  5335. QualType &eltType) {
  5336. // Vectors are simple.
  5337. if (const VectorType *vecType = type->getAs<VectorType>()) {
  5338. len = vecType->getNumElements();
  5339. eltType = vecType->getElementType();
  5340. assert(eltType->isScalarType());
  5341. return true;
  5342. }
  5343. // We allow lax conversion to and from non-vector types, but only if
  5344. // they're real types (i.e. non-complex, non-pointer scalar types).
  5345. if (!type->isRealType()) return false;
  5346. len = 1;
  5347. eltType = type;
  5348. return true;
  5349. }
  5350. /// Are the two types lax-compatible vector types? That is, given
  5351. /// that one of them is a vector, do they have equal storage sizes,
  5352. /// where the storage size is the number of elements times the element
  5353. /// size?
  5354. ///
  5355. /// This will also return false if either of the types is neither a
  5356. /// vector nor a real type.
  5357. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
  5358. assert(destTy->isVectorType() || srcTy->isVectorType());
  5359. // Disallow lax conversions between scalars and ExtVectors (these
  5360. // conversions are allowed for other vector types because common headers
  5361. // depend on them). Most scalar OP ExtVector cases are handled by the
  5362. // splat path anyway, which does what we want (convert, not bitcast).
  5363. // What this rules out for ExtVectors is crazy things like char4*float.
  5364. if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
  5365. if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
  5366. uint64_t srcLen, destLen;
  5367. QualType srcEltTy, destEltTy;
  5368. if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
  5369. if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
  5370. // ASTContext::getTypeSize will return the size rounded up to a
  5371. // power of 2, so instead of using that, we need to use the raw
  5372. // element size multiplied by the element count.
  5373. uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
  5374. uint64_t destEltSize = Context.getTypeSize(destEltTy);
  5375. return (srcLen * srcEltSize == destLen * destEltSize);
  5376. }
  5377. /// Is this a legal conversion between two types, one of which is
  5378. /// known to be a vector type?
  5379. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  5380. assert(destTy->isVectorType() || srcTy->isVectorType());
  5381. if (!Context.getLangOpts().LaxVectorConversions)
  5382. return false;
  5383. return areLaxCompatibleVectorTypes(srcTy, destTy);
  5384. }
  5385. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  5386. CastKind &Kind) {
  5387. assert(VectorTy->isVectorType() && "Not a vector type!");
  5388. if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
  5389. if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
  5390. return Diag(R.getBegin(),
  5391. Ty->isVectorType() ?
  5392. diag::err_invalid_conversion_between_vectors :
  5393. diag::err_invalid_conversion_between_vector_and_integer)
  5394. << VectorTy << Ty << R;
  5395. } else
  5396. return Diag(R.getBegin(),
  5397. diag::err_invalid_conversion_between_vector_and_scalar)
  5398. << VectorTy << Ty << R;
  5399. Kind = CK_BitCast;
  5400. return false;
  5401. }
  5402. ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
  5403. QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
  5404. if (DestElemTy == SplattedExpr->getType())
  5405. return SplattedExpr;
  5406. assert(DestElemTy->isFloatingType() ||
  5407. DestElemTy->isIntegralOrEnumerationType());
  5408. CastKind CK;
  5409. if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
  5410. // OpenCL requires that we convert `true` boolean expressions to -1, but
  5411. // only when splatting vectors.
  5412. if (DestElemTy->isFloatingType()) {
  5413. // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
  5414. // in two steps: boolean to signed integral, then to floating.
  5415. ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
  5416. CK_BooleanToSignedIntegral);
  5417. SplattedExpr = CastExprRes.get();
  5418. CK = CK_IntegralToFloating;
  5419. } else {
  5420. CK = CK_BooleanToSignedIntegral;
  5421. }
  5422. } else {
  5423. ExprResult CastExprRes = SplattedExpr;
  5424. CK = PrepareScalarCast(CastExprRes, DestElemTy);
  5425. if (CastExprRes.isInvalid())
  5426. return ExprError();
  5427. SplattedExpr = CastExprRes.get();
  5428. }
  5429. return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
  5430. }
  5431. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  5432. Expr *CastExpr, CastKind &Kind) {
  5433. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  5434. QualType SrcTy = CastExpr->getType();
  5435. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  5436. // an ExtVectorType.
  5437. // In OpenCL, casts between vectors of different types are not allowed.
  5438. // (See OpenCL 6.2).
  5439. if (SrcTy->isVectorType()) {
  5440. if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
  5441. (getLangOpts().OpenCL &&
  5442. !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
  5443. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  5444. << DestTy << SrcTy << R;
  5445. return ExprError();
  5446. }
  5447. Kind = CK_BitCast;
  5448. return CastExpr;
  5449. }
  5450. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  5451. // conversion will take place first from scalar to elt type, and then
  5452. // splat from elt type to vector.
  5453. if (SrcTy->isPointerType())
  5454. return Diag(R.getBegin(),
  5455. diag::err_invalid_conversion_between_vector_and_scalar)
  5456. << DestTy << SrcTy << R;
  5457. Kind = CK_VectorSplat;
  5458. return prepareVectorSplat(DestTy, CastExpr);
  5459. }
  5460. ExprResult
  5461. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  5462. Declarator &D, ParsedType &Ty,
  5463. SourceLocation RParenLoc, Expr *CastExpr) {
  5464. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  5465. "ActOnCastExpr(): missing type or expr");
  5466. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  5467. if (D.isInvalidType())
  5468. return ExprError();
  5469. if (getLangOpts().CPlusPlus) {
  5470. // Check that there are no default arguments (C++ only).
  5471. CheckExtraCXXDefaultArguments(D);
  5472. } else {
  5473. // Make sure any TypoExprs have been dealt with.
  5474. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  5475. if (!Res.isUsable())
  5476. return ExprError();
  5477. CastExpr = Res.get();
  5478. }
  5479. checkUnusedDeclAttributes(D);
  5480. QualType castType = castTInfo->getType();
  5481. Ty = CreateParsedType(castType, castTInfo);
  5482. bool isVectorLiteral = false;
  5483. // Check for an altivec or OpenCL literal,
  5484. // i.e. all the elements are integer constants.
  5485. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  5486. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  5487. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  5488. && castType->isVectorType() && (PE || PLE)) {
  5489. if (PLE && PLE->getNumExprs() == 0) {
  5490. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  5491. return ExprError();
  5492. }
  5493. if (PE || PLE->getNumExprs() == 1) {
  5494. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  5495. if (!E->getType()->isVectorType())
  5496. isVectorLiteral = true;
  5497. }
  5498. else
  5499. isVectorLiteral = true;
  5500. }
  5501. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  5502. // then handle it as such.
  5503. if (isVectorLiteral)
  5504. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  5505. // If the Expr being casted is a ParenListExpr, handle it specially.
  5506. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  5507. // sequence of BinOp comma operators.
  5508. if (isa<ParenListExpr>(CastExpr)) {
  5509. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  5510. if (Result.isInvalid()) return ExprError();
  5511. CastExpr = Result.get();
  5512. }
  5513. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  5514. !getSourceManager().isInSystemMacro(LParenLoc))
  5515. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  5516. CheckTollFreeBridgeCast(castType, CastExpr);
  5517. CheckObjCBridgeRelatedCast(castType, CastExpr);
  5518. DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
  5519. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  5520. }
  5521. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  5522. SourceLocation RParenLoc, Expr *E,
  5523. TypeSourceInfo *TInfo) {
  5524. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  5525. "Expected paren or paren list expression");
  5526. Expr **exprs;
  5527. unsigned numExprs;
  5528. Expr *subExpr;
  5529. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  5530. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  5531. LiteralLParenLoc = PE->getLParenLoc();
  5532. LiteralRParenLoc = PE->getRParenLoc();
  5533. exprs = PE->getExprs();
  5534. numExprs = PE->getNumExprs();
  5535. } else { // isa<ParenExpr> by assertion at function entrance
  5536. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  5537. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  5538. subExpr = cast<ParenExpr>(E)->getSubExpr();
  5539. exprs = &subExpr;
  5540. numExprs = 1;
  5541. }
  5542. QualType Ty = TInfo->getType();
  5543. assert(Ty->isVectorType() && "Expected vector type");
  5544. SmallVector<Expr *, 8> initExprs;
  5545. const VectorType *VTy = Ty->getAs<VectorType>();
  5546. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  5547. // '(...)' form of vector initialization in AltiVec: the number of
  5548. // initializers must be one or must match the size of the vector.
  5549. // If a single value is specified in the initializer then it will be
  5550. // replicated to all the components of the vector
  5551. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  5552. // The number of initializers must be one or must match the size of the
  5553. // vector. If a single value is specified in the initializer then it will
  5554. // be replicated to all the components of the vector
  5555. if (numExprs == 1) {
  5556. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5557. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5558. if (Literal.isInvalid())
  5559. return ExprError();
  5560. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5561. PrepareScalarCast(Literal, ElemTy));
  5562. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5563. }
  5564. else if (numExprs < numElems) {
  5565. Diag(E->getExprLoc(),
  5566. diag::err_incorrect_number_of_vector_initializers);
  5567. return ExprError();
  5568. }
  5569. else
  5570. initExprs.append(exprs, exprs + numExprs);
  5571. }
  5572. else {
  5573. // For OpenCL, when the number of initializers is a single value,
  5574. // it will be replicated to all components of the vector.
  5575. if (getLangOpts().OpenCL &&
  5576. VTy->getVectorKind() == VectorType::GenericVector &&
  5577. numExprs == 1) {
  5578. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5579. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5580. if (Literal.isInvalid())
  5581. return ExprError();
  5582. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5583. PrepareScalarCast(Literal, ElemTy));
  5584. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5585. }
  5586. initExprs.append(exprs, exprs + numExprs);
  5587. }
  5588. // FIXME: This means that pretty-printing the final AST will produce curly
  5589. // braces instead of the original commas.
  5590. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  5591. initExprs, LiteralRParenLoc);
  5592. initE->setType(Ty);
  5593. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  5594. }
  5595. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  5596. /// the ParenListExpr into a sequence of comma binary operators.
  5597. ExprResult
  5598. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  5599. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  5600. if (!E)
  5601. return OrigExpr;
  5602. ExprResult Result(E->getExpr(0));
  5603. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  5604. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  5605. E->getExpr(i));
  5606. if (Result.isInvalid()) return ExprError();
  5607. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  5608. }
  5609. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  5610. SourceLocation R,
  5611. MultiExprArg Val) {
  5612. Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
  5613. return expr;
  5614. }
  5615. /// Emit a specialized diagnostic when one expression is a null pointer
  5616. /// constant and the other is not a pointer. Returns true if a diagnostic is
  5617. /// emitted.
  5618. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  5619. SourceLocation QuestionLoc) {
  5620. Expr *NullExpr = LHSExpr;
  5621. Expr *NonPointerExpr = RHSExpr;
  5622. Expr::NullPointerConstantKind NullKind =
  5623. NullExpr->isNullPointerConstant(Context,
  5624. Expr::NPC_ValueDependentIsNotNull);
  5625. if (NullKind == Expr::NPCK_NotNull) {
  5626. NullExpr = RHSExpr;
  5627. NonPointerExpr = LHSExpr;
  5628. NullKind =
  5629. NullExpr->isNullPointerConstant(Context,
  5630. Expr::NPC_ValueDependentIsNotNull);
  5631. }
  5632. if (NullKind == Expr::NPCK_NotNull)
  5633. return false;
  5634. if (NullKind == Expr::NPCK_ZeroExpression)
  5635. return false;
  5636. if (NullKind == Expr::NPCK_ZeroLiteral) {
  5637. // In this case, check to make sure that we got here from a "NULL"
  5638. // string in the source code.
  5639. NullExpr = NullExpr->IgnoreParenImpCasts();
  5640. SourceLocation loc = NullExpr->getExprLoc();
  5641. if (!findMacroSpelling(loc, "NULL"))
  5642. return false;
  5643. }
  5644. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  5645. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  5646. << NonPointerExpr->getType() << DiagType
  5647. << NonPointerExpr->getSourceRange();
  5648. return true;
  5649. }
  5650. /// Return false if the condition expression is valid, true otherwise.
  5651. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  5652. QualType CondTy = Cond->getType();
  5653. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  5654. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  5655. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5656. << CondTy << Cond->getSourceRange();
  5657. return true;
  5658. }
  5659. // C99 6.5.15p2
  5660. if (CondTy->isScalarType()) return false;
  5661. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  5662. << CondTy << Cond->getSourceRange();
  5663. return true;
  5664. }
  5665. /// Handle when one or both operands are void type.
  5666. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  5667. ExprResult &RHS) {
  5668. Expr *LHSExpr = LHS.get();
  5669. Expr *RHSExpr = RHS.get();
  5670. if (!LHSExpr->getType()->isVoidType())
  5671. S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  5672. << RHSExpr->getSourceRange();
  5673. if (!RHSExpr->getType()->isVoidType())
  5674. S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  5675. << LHSExpr->getSourceRange();
  5676. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  5677. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  5678. return S.Context.VoidTy;
  5679. }
  5680. /// Return false if the NullExpr can be promoted to PointerTy,
  5681. /// true otherwise.
  5682. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  5683. QualType PointerTy) {
  5684. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  5685. !NullExpr.get()->isNullPointerConstant(S.Context,
  5686. Expr::NPC_ValueDependentIsNull))
  5687. return true;
  5688. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  5689. return false;
  5690. }
  5691. /// Checks compatibility between two pointers and return the resulting
  5692. /// type.
  5693. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  5694. ExprResult &RHS,
  5695. SourceLocation Loc) {
  5696. QualType LHSTy = LHS.get()->getType();
  5697. QualType RHSTy = RHS.get()->getType();
  5698. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  5699. // Two identical pointers types are always compatible.
  5700. return LHSTy;
  5701. }
  5702. QualType lhptee, rhptee;
  5703. // Get the pointee types.
  5704. bool IsBlockPointer = false;
  5705. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  5706. lhptee = LHSBTy->getPointeeType();
  5707. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  5708. IsBlockPointer = true;
  5709. } else {
  5710. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  5711. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  5712. }
  5713. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  5714. // differently qualified versions of compatible types, the result type is
  5715. // a pointer to an appropriately qualified version of the composite
  5716. // type.
  5717. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  5718. // clause doesn't make sense for our extensions. E.g. address space 2 should
  5719. // be incompatible with address space 3: they may live on different devices or
  5720. // anything.
  5721. Qualifiers lhQual = lhptee.getQualifiers();
  5722. Qualifiers rhQual = rhptee.getQualifiers();
  5723. LangAS ResultAddrSpace = LangAS::Default;
  5724. LangAS LAddrSpace = lhQual.getAddressSpace();
  5725. LangAS RAddrSpace = rhQual.getAddressSpace();
  5726. // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
  5727. // spaces is disallowed.
  5728. if (lhQual.isAddressSpaceSupersetOf(rhQual))
  5729. ResultAddrSpace = LAddrSpace;
  5730. else if (rhQual.isAddressSpaceSupersetOf(lhQual))
  5731. ResultAddrSpace = RAddrSpace;
  5732. else {
  5733. S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  5734. << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
  5735. << RHS.get()->getSourceRange();
  5736. return QualType();
  5737. }
  5738. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  5739. auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
  5740. lhQual.removeCVRQualifiers();
  5741. rhQual.removeCVRQualifiers();
  5742. // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
  5743. // (C99 6.7.3) for address spaces. We assume that the check should behave in
  5744. // the same manner as it's defined for CVR qualifiers, so for OpenCL two
  5745. // qual types are compatible iff
  5746. // * corresponded types are compatible
  5747. // * CVR qualifiers are equal
  5748. // * address spaces are equal
  5749. // Thus for conditional operator we merge CVR and address space unqualified
  5750. // pointees and if there is a composite type we return a pointer to it with
  5751. // merged qualifiers.
  5752. LHSCastKind =
  5753. LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  5754. RHSCastKind =
  5755. RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  5756. lhQual.removeAddressSpace();
  5757. rhQual.removeAddressSpace();
  5758. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  5759. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  5760. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  5761. if (CompositeTy.isNull()) {
  5762. // In this situation, we assume void* type. No especially good
  5763. // reason, but this is what gcc does, and we do have to pick
  5764. // to get a consistent AST.
  5765. QualType incompatTy;
  5766. incompatTy = S.Context.getPointerType(
  5767. S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
  5768. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
  5769. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
  5770. // FIXME: For OpenCL the warning emission and cast to void* leaves a room
  5771. // for casts between types with incompatible address space qualifiers.
  5772. // For the following code the compiler produces casts between global and
  5773. // local address spaces of the corresponded innermost pointees:
  5774. // local int *global *a;
  5775. // global int *global *b;
  5776. // a = (0 ? a : b); // see C99 6.5.16.1.p1.
  5777. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  5778. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5779. << RHS.get()->getSourceRange();
  5780. return incompatTy;
  5781. }
  5782. // The pointer types are compatible.
  5783. // In case of OpenCL ResultTy should have the address space qualifier
  5784. // which is a superset of address spaces of both the 2nd and the 3rd
  5785. // operands of the conditional operator.
  5786. QualType ResultTy = [&, ResultAddrSpace]() {
  5787. if (S.getLangOpts().OpenCL) {
  5788. Qualifiers CompositeQuals = CompositeTy.getQualifiers();
  5789. CompositeQuals.setAddressSpace(ResultAddrSpace);
  5790. return S.Context
  5791. .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
  5792. .withCVRQualifiers(MergedCVRQual);
  5793. }
  5794. return CompositeTy.withCVRQualifiers(MergedCVRQual);
  5795. }();
  5796. if (IsBlockPointer)
  5797. ResultTy = S.Context.getBlockPointerType(ResultTy);
  5798. else
  5799. ResultTy = S.Context.getPointerType(ResultTy);
  5800. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
  5801. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
  5802. return ResultTy;
  5803. }
  5804. /// Return the resulting type when the operands are both block pointers.
  5805. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  5806. ExprResult &LHS,
  5807. ExprResult &RHS,
  5808. SourceLocation Loc) {
  5809. QualType LHSTy = LHS.get()->getType();
  5810. QualType RHSTy = RHS.get()->getType();
  5811. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  5812. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  5813. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  5814. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5815. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5816. return destType;
  5817. }
  5818. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  5819. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5820. << RHS.get()->getSourceRange();
  5821. return QualType();
  5822. }
  5823. // We have 2 block pointer types.
  5824. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5825. }
  5826. /// Return the resulting type when the operands are both pointers.
  5827. static QualType
  5828. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  5829. ExprResult &RHS,
  5830. SourceLocation Loc) {
  5831. // get the pointer types
  5832. QualType LHSTy = LHS.get()->getType();
  5833. QualType RHSTy = RHS.get()->getType();
  5834. // get the "pointed to" types
  5835. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5836. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5837. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  5838. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  5839. // Figure out necessary qualifiers (C99 6.5.15p6)
  5840. QualType destPointee
  5841. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5842. QualType destType = S.Context.getPointerType(destPointee);
  5843. // Add qualifiers if necessary.
  5844. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5845. // Promote to void*.
  5846. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5847. return destType;
  5848. }
  5849. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  5850. QualType destPointee
  5851. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5852. QualType destType = S.Context.getPointerType(destPointee);
  5853. // Add qualifiers if necessary.
  5854. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5855. // Promote to void*.
  5856. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5857. return destType;
  5858. }
  5859. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5860. }
  5861. /// Return false if the first expression is not an integer and the second
  5862. /// expression is not a pointer, true otherwise.
  5863. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  5864. Expr* PointerExpr, SourceLocation Loc,
  5865. bool IsIntFirstExpr) {
  5866. if (!PointerExpr->getType()->isPointerType() ||
  5867. !Int.get()->getType()->isIntegerType())
  5868. return false;
  5869. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  5870. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  5871. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  5872. << Expr1->getType() << Expr2->getType()
  5873. << Expr1->getSourceRange() << Expr2->getSourceRange();
  5874. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  5875. CK_IntegralToPointer);
  5876. return true;
  5877. }
  5878. /// Simple conversion between integer and floating point types.
  5879. ///
  5880. /// Used when handling the OpenCL conditional operator where the
  5881. /// condition is a vector while the other operands are scalar.
  5882. ///
  5883. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  5884. /// types are either integer or floating type. Between the two
  5885. /// operands, the type with the higher rank is defined as the "result
  5886. /// type". The other operand needs to be promoted to the same type. No
  5887. /// other type promotion is allowed. We cannot use
  5888. /// UsualArithmeticConversions() for this purpose, since it always
  5889. /// promotes promotable types.
  5890. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  5891. ExprResult &RHS,
  5892. SourceLocation QuestionLoc) {
  5893. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  5894. if (LHS.isInvalid())
  5895. return QualType();
  5896. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  5897. if (RHS.isInvalid())
  5898. return QualType();
  5899. // For conversion purposes, we ignore any qualifiers.
  5900. // For example, "const float" and "float" are equivalent.
  5901. QualType LHSType =
  5902. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  5903. QualType RHSType =
  5904. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  5905. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  5906. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5907. << LHSType << LHS.get()->getSourceRange();
  5908. return QualType();
  5909. }
  5910. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  5911. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5912. << RHSType << RHS.get()->getSourceRange();
  5913. return QualType();
  5914. }
  5915. // If both types are identical, no conversion is needed.
  5916. if (LHSType == RHSType)
  5917. return LHSType;
  5918. // Now handle "real" floating types (i.e. float, double, long double).
  5919. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  5920. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  5921. /*IsCompAssign = */ false);
  5922. // Finally, we have two differing integer types.
  5923. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  5924. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  5925. }
  5926. /// Convert scalar operands to a vector that matches the
  5927. /// condition in length.
  5928. ///
  5929. /// Used when handling the OpenCL conditional operator where the
  5930. /// condition is a vector while the other operands are scalar.
  5931. ///
  5932. /// We first compute the "result type" for the scalar operands
  5933. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  5934. /// into a vector of that type where the length matches the condition
  5935. /// vector type. s6.11.6 requires that the element types of the result
  5936. /// and the condition must have the same number of bits.
  5937. static QualType
  5938. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  5939. QualType CondTy, SourceLocation QuestionLoc) {
  5940. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  5941. if (ResTy.isNull()) return QualType();
  5942. const VectorType *CV = CondTy->getAs<VectorType>();
  5943. assert(CV);
  5944. // Determine the vector result type
  5945. unsigned NumElements = CV->getNumElements();
  5946. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  5947. // Ensure that all types have the same number of bits
  5948. if (S.Context.getTypeSize(CV->getElementType())
  5949. != S.Context.getTypeSize(ResTy)) {
  5950. // Since VectorTy is created internally, it does not pretty print
  5951. // with an OpenCL name. Instead, we just print a description.
  5952. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  5953. SmallString<64> Str;
  5954. llvm::raw_svector_ostream OS(Str);
  5955. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  5956. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5957. << CondTy << OS.str();
  5958. return QualType();
  5959. }
  5960. // Convert operands to the vector result type
  5961. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  5962. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  5963. return VectorTy;
  5964. }
  5965. /// Return false if this is a valid OpenCL condition vector
  5966. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  5967. SourceLocation QuestionLoc) {
  5968. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  5969. // integral type.
  5970. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  5971. assert(CondTy);
  5972. QualType EleTy = CondTy->getElementType();
  5973. if (EleTy->isIntegerType()) return false;
  5974. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5975. << Cond->getType() << Cond->getSourceRange();
  5976. return true;
  5977. }
  5978. /// Return false if the vector condition type and the vector
  5979. /// result type are compatible.
  5980. ///
  5981. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  5982. /// number of elements, and their element types have the same number
  5983. /// of bits.
  5984. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  5985. SourceLocation QuestionLoc) {
  5986. const VectorType *CV = CondTy->getAs<VectorType>();
  5987. const VectorType *RV = VecResTy->getAs<VectorType>();
  5988. assert(CV && RV);
  5989. if (CV->getNumElements() != RV->getNumElements()) {
  5990. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  5991. << CondTy << VecResTy;
  5992. return true;
  5993. }
  5994. QualType CVE = CV->getElementType();
  5995. QualType RVE = RV->getElementType();
  5996. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  5997. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5998. << CondTy << VecResTy;
  5999. return true;
  6000. }
  6001. return false;
  6002. }
  6003. /// Return the resulting type for the conditional operator in
  6004. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  6005. /// s6.3.i) when the condition is a vector type.
  6006. static QualType
  6007. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  6008. ExprResult &LHS, ExprResult &RHS,
  6009. SourceLocation QuestionLoc) {
  6010. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  6011. if (Cond.isInvalid())
  6012. return QualType();
  6013. QualType CondTy = Cond.get()->getType();
  6014. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  6015. return QualType();
  6016. // If either operand is a vector then find the vector type of the
  6017. // result as specified in OpenCL v1.1 s6.3.i.
  6018. if (LHS.get()->getType()->isVectorType() ||
  6019. RHS.get()->getType()->isVectorType()) {
  6020. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  6021. /*isCompAssign*/false,
  6022. /*AllowBothBool*/true,
  6023. /*AllowBoolConversions*/false);
  6024. if (VecResTy.isNull()) return QualType();
  6025. // The result type must match the condition type as specified in
  6026. // OpenCL v1.1 s6.11.6.
  6027. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  6028. return QualType();
  6029. return VecResTy;
  6030. }
  6031. // Both operands are scalar.
  6032. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  6033. }
  6034. /// Return true if the Expr is block type
  6035. static bool checkBlockType(Sema &S, const Expr *E) {
  6036. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  6037. QualType Ty = CE->getCallee()->getType();
  6038. if (Ty->isBlockPointerType()) {
  6039. S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
  6040. return true;
  6041. }
  6042. }
  6043. return false;
  6044. }
  6045. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  6046. /// In that case, LHS = cond.
  6047. /// C99 6.5.15
  6048. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  6049. ExprResult &RHS, ExprValueKind &VK,
  6050. ExprObjectKind &OK,
  6051. SourceLocation QuestionLoc) {
  6052. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  6053. if (!LHSResult.isUsable()) return QualType();
  6054. LHS = LHSResult;
  6055. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  6056. if (!RHSResult.isUsable()) return QualType();
  6057. RHS = RHSResult;
  6058. // C++ is sufficiently different to merit its own checker.
  6059. if (getLangOpts().CPlusPlus)
  6060. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  6061. VK = VK_RValue;
  6062. OK = OK_Ordinary;
  6063. // The OpenCL operator with a vector condition is sufficiently
  6064. // different to merit its own checker.
  6065. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  6066. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  6067. // First, check the condition.
  6068. Cond = UsualUnaryConversions(Cond.get());
  6069. if (Cond.isInvalid())
  6070. return QualType();
  6071. if (checkCondition(*this, Cond.get(), QuestionLoc))
  6072. return QualType();
  6073. // Now check the two expressions.
  6074. if (LHS.get()->getType()->isVectorType() ||
  6075. RHS.get()->getType()->isVectorType())
  6076. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  6077. /*AllowBothBool*/true,
  6078. /*AllowBoolConversions*/false);
  6079. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  6080. if (LHS.isInvalid() || RHS.isInvalid())
  6081. return QualType();
  6082. QualType LHSTy = LHS.get()->getType();
  6083. QualType RHSTy = RHS.get()->getType();
  6084. // Diagnose attempts to convert between __float128 and long double where
  6085. // such conversions currently can't be handled.
  6086. if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
  6087. Diag(QuestionLoc,
  6088. diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
  6089. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6090. return QualType();
  6091. }
  6092. // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
  6093. // selection operator (?:).
  6094. if (getLangOpts().OpenCL &&
  6095. (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
  6096. return QualType();
  6097. }
  6098. // If both operands have arithmetic type, do the usual arithmetic conversions
  6099. // to find a common type: C99 6.5.15p3,5.
  6100. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  6101. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  6102. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  6103. return ResTy;
  6104. }
  6105. // If both operands are the same structure or union type, the result is that
  6106. // type.
  6107. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  6108. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  6109. if (LHSRT->getDecl() == RHSRT->getDecl())
  6110. // "If both the operands have structure or union type, the result has
  6111. // that type." This implies that CV qualifiers are dropped.
  6112. return LHSTy.getUnqualifiedType();
  6113. // FIXME: Type of conditional expression must be complete in C mode.
  6114. }
  6115. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  6116. // The following || allows only one side to be void (a GCC-ism).
  6117. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  6118. return checkConditionalVoidType(*this, LHS, RHS);
  6119. }
  6120. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  6121. // the type of the other operand."
  6122. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  6123. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  6124. // All objective-c pointer type analysis is done here.
  6125. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  6126. QuestionLoc);
  6127. if (LHS.isInvalid() || RHS.isInvalid())
  6128. return QualType();
  6129. if (!compositeType.isNull())
  6130. return compositeType;
  6131. // Handle block pointer types.
  6132. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  6133. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  6134. QuestionLoc);
  6135. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  6136. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  6137. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  6138. QuestionLoc);
  6139. // GCC compatibility: soften pointer/integer mismatch. Note that
  6140. // null pointers have been filtered out by this point.
  6141. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  6142. /*isIntFirstExpr=*/true))
  6143. return RHSTy;
  6144. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  6145. /*isIntFirstExpr=*/false))
  6146. return LHSTy;
  6147. // Emit a better diagnostic if one of the expressions is a null pointer
  6148. // constant and the other is not a pointer type. In this case, the user most
  6149. // likely forgot to take the address of the other expression.
  6150. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  6151. return QualType();
  6152. // Otherwise, the operands are not compatible.
  6153. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  6154. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6155. << RHS.get()->getSourceRange();
  6156. return QualType();
  6157. }
  6158. /// FindCompositeObjCPointerType - Helper method to find composite type of
  6159. /// two objective-c pointer types of the two input expressions.
  6160. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  6161. SourceLocation QuestionLoc) {
  6162. QualType LHSTy = LHS.get()->getType();
  6163. QualType RHSTy = RHS.get()->getType();
  6164. // Handle things like Class and struct objc_class*. Here we case the result
  6165. // to the pseudo-builtin, because that will be implicitly cast back to the
  6166. // redefinition type if an attempt is made to access its fields.
  6167. if (LHSTy->isObjCClassType() &&
  6168. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  6169. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6170. return LHSTy;
  6171. }
  6172. if (RHSTy->isObjCClassType() &&
  6173. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  6174. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6175. return RHSTy;
  6176. }
  6177. // And the same for struct objc_object* / id
  6178. if (LHSTy->isObjCIdType() &&
  6179. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  6180. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6181. return LHSTy;
  6182. }
  6183. if (RHSTy->isObjCIdType() &&
  6184. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  6185. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6186. return RHSTy;
  6187. }
  6188. // And the same for struct objc_selector* / SEL
  6189. if (Context.isObjCSelType(LHSTy) &&
  6190. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  6191. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  6192. return LHSTy;
  6193. }
  6194. if (Context.isObjCSelType(RHSTy) &&
  6195. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  6196. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  6197. return RHSTy;
  6198. }
  6199. // Check constraints for Objective-C object pointers types.
  6200. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  6201. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  6202. // Two identical object pointer types are always compatible.
  6203. return LHSTy;
  6204. }
  6205. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  6206. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  6207. QualType compositeType = LHSTy;
  6208. // If both operands are interfaces and either operand can be
  6209. // assigned to the other, use that type as the composite
  6210. // type. This allows
  6211. // xxx ? (A*) a : (B*) b
  6212. // where B is a subclass of A.
  6213. //
  6214. // Additionally, as for assignment, if either type is 'id'
  6215. // allow silent coercion. Finally, if the types are
  6216. // incompatible then make sure to use 'id' as the composite
  6217. // type so the result is acceptable for sending messages to.
  6218. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  6219. // It could return the composite type.
  6220. if (!(compositeType =
  6221. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  6222. // Nothing more to do.
  6223. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  6224. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  6225. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  6226. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  6227. } else if ((LHSTy->isObjCQualifiedIdType() ||
  6228. RHSTy->isObjCQualifiedIdType()) &&
  6229. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  6230. // Need to handle "id<xx>" explicitly.
  6231. // GCC allows qualified id and any Objective-C type to devolve to
  6232. // id. Currently localizing to here until clear this should be
  6233. // part of ObjCQualifiedIdTypesAreCompatible.
  6234. compositeType = Context.getObjCIdType();
  6235. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  6236. compositeType = Context.getObjCIdType();
  6237. } else {
  6238. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  6239. << LHSTy << RHSTy
  6240. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6241. QualType incompatTy = Context.getObjCIdType();
  6242. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  6243. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  6244. return incompatTy;
  6245. }
  6246. // The object pointer types are compatible.
  6247. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  6248. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  6249. return compositeType;
  6250. }
  6251. // Check Objective-C object pointer types and 'void *'
  6252. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  6253. if (getLangOpts().ObjCAutoRefCount) {
  6254. // ARC forbids the implicit conversion of object pointers to 'void *',
  6255. // so these types are not compatible.
  6256. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6257. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6258. LHS = RHS = true;
  6259. return QualType();
  6260. }
  6261. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  6262. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6263. QualType destPointee
  6264. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  6265. QualType destType = Context.getPointerType(destPointee);
  6266. // Add qualifiers if necessary.
  6267. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  6268. // Promote to void*.
  6269. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6270. return destType;
  6271. }
  6272. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  6273. if (getLangOpts().ObjCAutoRefCount) {
  6274. // ARC forbids the implicit conversion of object pointers to 'void *',
  6275. // so these types are not compatible.
  6276. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6277. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6278. LHS = RHS = true;
  6279. return QualType();
  6280. }
  6281. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6282. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  6283. QualType destPointee
  6284. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  6285. QualType destType = Context.getPointerType(destPointee);
  6286. // Add qualifiers if necessary.
  6287. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  6288. // Promote to void*.
  6289. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6290. return destType;
  6291. }
  6292. return QualType();
  6293. }
  6294. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  6295. /// ParenRange in parentheses.
  6296. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  6297. const PartialDiagnostic &Note,
  6298. SourceRange ParenRange) {
  6299. SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
  6300. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  6301. EndLoc.isValid()) {
  6302. Self.Diag(Loc, Note)
  6303. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  6304. << FixItHint::CreateInsertion(EndLoc, ")");
  6305. } else {
  6306. // We can't display the parentheses, so just show the bare note.
  6307. Self.Diag(Loc, Note) << ParenRange;
  6308. }
  6309. }
  6310. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  6311. return BinaryOperator::isAdditiveOp(Opc) ||
  6312. BinaryOperator::isMultiplicativeOp(Opc) ||
  6313. BinaryOperator::isShiftOp(Opc);
  6314. }
  6315. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  6316. /// expression, either using a built-in or overloaded operator,
  6317. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  6318. /// expression.
  6319. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  6320. Expr **RHSExprs) {
  6321. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  6322. E = E->IgnoreImpCasts();
  6323. E = E->IgnoreConversionOperator();
  6324. E = E->IgnoreImpCasts();
  6325. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
  6326. E = MTE->GetTemporaryExpr();
  6327. E = E->IgnoreImpCasts();
  6328. }
  6329. // Built-in binary operator.
  6330. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  6331. if (IsArithmeticOp(OP->getOpcode())) {
  6332. *Opcode = OP->getOpcode();
  6333. *RHSExprs = OP->getRHS();
  6334. return true;
  6335. }
  6336. }
  6337. // Overloaded operator.
  6338. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  6339. if (Call->getNumArgs() != 2)
  6340. return false;
  6341. // Make sure this is really a binary operator that is safe to pass into
  6342. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  6343. OverloadedOperatorKind OO = Call->getOperator();
  6344. if (OO < OO_Plus || OO > OO_Arrow ||
  6345. OO == OO_PlusPlus || OO == OO_MinusMinus)
  6346. return false;
  6347. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  6348. if (IsArithmeticOp(OpKind)) {
  6349. *Opcode = OpKind;
  6350. *RHSExprs = Call->getArg(1);
  6351. return true;
  6352. }
  6353. }
  6354. return false;
  6355. }
  6356. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  6357. /// or is a logical expression such as (x==y) which has int type, but is
  6358. /// commonly interpreted as boolean.
  6359. static bool ExprLooksBoolean(Expr *E) {
  6360. E = E->IgnoreParenImpCasts();
  6361. if (E->getType()->isBooleanType())
  6362. return true;
  6363. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  6364. return OP->isComparisonOp() || OP->isLogicalOp();
  6365. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  6366. return OP->getOpcode() == UO_LNot;
  6367. if (E->getType()->isPointerType())
  6368. return true;
  6369. // FIXME: What about overloaded operator calls returning "unspecified boolean
  6370. // type"s (commonly pointer-to-members)?
  6371. return false;
  6372. }
  6373. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  6374. /// and binary operator are mixed in a way that suggests the programmer assumed
  6375. /// the conditional operator has higher precedence, for example:
  6376. /// "int x = a + someBinaryCondition ? 1 : 2".
  6377. static void DiagnoseConditionalPrecedence(Sema &Self,
  6378. SourceLocation OpLoc,
  6379. Expr *Condition,
  6380. Expr *LHSExpr,
  6381. Expr *RHSExpr) {
  6382. BinaryOperatorKind CondOpcode;
  6383. Expr *CondRHS;
  6384. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  6385. return;
  6386. if (!ExprLooksBoolean(CondRHS))
  6387. return;
  6388. // The condition is an arithmetic binary expression, with a right-
  6389. // hand side that looks boolean, so warn.
  6390. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  6391. << Condition->getSourceRange()
  6392. << BinaryOperator::getOpcodeStr(CondOpcode);
  6393. SuggestParentheses(
  6394. Self, OpLoc,
  6395. Self.PDiag(diag::note_precedence_silence)
  6396. << BinaryOperator::getOpcodeStr(CondOpcode),
  6397. SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
  6398. SuggestParentheses(Self, OpLoc,
  6399. Self.PDiag(diag::note_precedence_conditional_first),
  6400. SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
  6401. }
  6402. /// Compute the nullability of a conditional expression.
  6403. static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
  6404. QualType LHSTy, QualType RHSTy,
  6405. ASTContext &Ctx) {
  6406. if (!ResTy->isAnyPointerType())
  6407. return ResTy;
  6408. auto GetNullability = [&Ctx](QualType Ty) {
  6409. Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
  6410. if (Kind)
  6411. return *Kind;
  6412. return NullabilityKind::Unspecified;
  6413. };
  6414. auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
  6415. NullabilityKind MergedKind;
  6416. // Compute nullability of a binary conditional expression.
  6417. if (IsBin) {
  6418. if (LHSKind == NullabilityKind::NonNull)
  6419. MergedKind = NullabilityKind::NonNull;
  6420. else
  6421. MergedKind = RHSKind;
  6422. // Compute nullability of a normal conditional expression.
  6423. } else {
  6424. if (LHSKind == NullabilityKind::Nullable ||
  6425. RHSKind == NullabilityKind::Nullable)
  6426. MergedKind = NullabilityKind::Nullable;
  6427. else if (LHSKind == NullabilityKind::NonNull)
  6428. MergedKind = RHSKind;
  6429. else if (RHSKind == NullabilityKind::NonNull)
  6430. MergedKind = LHSKind;
  6431. else
  6432. MergedKind = NullabilityKind::Unspecified;
  6433. }
  6434. // Return if ResTy already has the correct nullability.
  6435. if (GetNullability(ResTy) == MergedKind)
  6436. return ResTy;
  6437. // Strip all nullability from ResTy.
  6438. while (ResTy->getNullability(Ctx))
  6439. ResTy = ResTy.getSingleStepDesugaredType(Ctx);
  6440. // Create a new AttributedType with the new nullability kind.
  6441. auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
  6442. return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
  6443. }
  6444. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  6445. /// in the case of a the GNU conditional expr extension.
  6446. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  6447. SourceLocation ColonLoc,
  6448. Expr *CondExpr, Expr *LHSExpr,
  6449. Expr *RHSExpr) {
  6450. if (!getLangOpts().CPlusPlus) {
  6451. // C cannot handle TypoExpr nodes in the condition because it
  6452. // doesn't handle dependent types properly, so make sure any TypoExprs have
  6453. // been dealt with before checking the operands.
  6454. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  6455. ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
  6456. ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
  6457. if (!CondResult.isUsable())
  6458. return ExprError();
  6459. if (LHSExpr) {
  6460. if (!LHSResult.isUsable())
  6461. return ExprError();
  6462. }
  6463. if (!RHSResult.isUsable())
  6464. return ExprError();
  6465. CondExpr = CondResult.get();
  6466. LHSExpr = LHSResult.get();
  6467. RHSExpr = RHSResult.get();
  6468. }
  6469. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  6470. // was the condition.
  6471. OpaqueValueExpr *opaqueValue = nullptr;
  6472. Expr *commonExpr = nullptr;
  6473. if (!LHSExpr) {
  6474. commonExpr = CondExpr;
  6475. // Lower out placeholder types first. This is important so that we don't
  6476. // try to capture a placeholder. This happens in few cases in C++; such
  6477. // as Objective-C++'s dictionary subscripting syntax.
  6478. if (commonExpr->hasPlaceholderType()) {
  6479. ExprResult result = CheckPlaceholderExpr(commonExpr);
  6480. if (!result.isUsable()) return ExprError();
  6481. commonExpr = result.get();
  6482. }
  6483. // We usually want to apply unary conversions *before* saving, except
  6484. // in the special case of a C++ l-value conditional.
  6485. if (!(getLangOpts().CPlusPlus
  6486. && !commonExpr->isTypeDependent()
  6487. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  6488. && commonExpr->isGLValue()
  6489. && commonExpr->isOrdinaryOrBitFieldObject()
  6490. && RHSExpr->isOrdinaryOrBitFieldObject()
  6491. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  6492. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  6493. if (commonRes.isInvalid())
  6494. return ExprError();
  6495. commonExpr = commonRes.get();
  6496. }
  6497. // If the common expression is a class or array prvalue, materialize it
  6498. // so that we can safely refer to it multiple times.
  6499. if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
  6500. commonExpr->getType()->isArrayType())) {
  6501. ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
  6502. if (MatExpr.isInvalid())
  6503. return ExprError();
  6504. commonExpr = MatExpr.get();
  6505. }
  6506. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  6507. commonExpr->getType(),
  6508. commonExpr->getValueKind(),
  6509. commonExpr->getObjectKind(),
  6510. commonExpr);
  6511. LHSExpr = CondExpr = opaqueValue;
  6512. }
  6513. QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
  6514. ExprValueKind VK = VK_RValue;
  6515. ExprObjectKind OK = OK_Ordinary;
  6516. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  6517. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  6518. VK, OK, QuestionLoc);
  6519. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  6520. RHS.isInvalid())
  6521. return ExprError();
  6522. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  6523. RHS.get());
  6524. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  6525. result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
  6526. Context);
  6527. if (!commonExpr)
  6528. return new (Context)
  6529. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  6530. RHS.get(), result, VK, OK);
  6531. return new (Context) BinaryConditionalOperator(
  6532. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  6533. ColonLoc, result, VK, OK);
  6534. }
  6535. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  6536. // being closely modeled after the C99 spec:-). The odd characteristic of this
  6537. // routine is it effectively iqnores the qualifiers on the top level pointee.
  6538. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  6539. // FIXME: add a couple examples in this comment.
  6540. static Sema::AssignConvertType
  6541. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  6542. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6543. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6544. // get the "pointed to" type (ignoring qualifiers at the top level)
  6545. const Type *lhptee, *rhptee;
  6546. Qualifiers lhq, rhq;
  6547. std::tie(lhptee, lhq) =
  6548. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  6549. std::tie(rhptee, rhq) =
  6550. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  6551. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6552. // C99 6.5.16.1p1: This following citation is common to constraints
  6553. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  6554. // qualifiers of the type *pointed to* by the right;
  6555. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  6556. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  6557. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  6558. // Ignore lifetime for further calculation.
  6559. lhq.removeObjCLifetime();
  6560. rhq.removeObjCLifetime();
  6561. }
  6562. if (!lhq.compatiblyIncludes(rhq)) {
  6563. // Treat address-space mismatches as fatal. TODO: address subspaces
  6564. if (!lhq.isAddressSpaceSupersetOf(rhq))
  6565. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  6566. // It's okay to add or remove GC or lifetime qualifiers when converting to
  6567. // and from void*.
  6568. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  6569. .compatiblyIncludes(
  6570. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  6571. && (lhptee->isVoidType() || rhptee->isVoidType()))
  6572. ; // keep old
  6573. // Treat lifetime mismatches as fatal.
  6574. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  6575. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  6576. // For GCC/MS compatibility, other qualifier mismatches are treated
  6577. // as still compatible in C.
  6578. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6579. }
  6580. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  6581. // incomplete type and the other is a pointer to a qualified or unqualified
  6582. // version of void...
  6583. if (lhptee->isVoidType()) {
  6584. if (rhptee->isIncompleteOrObjectType())
  6585. return ConvTy;
  6586. // As an extension, we allow cast to/from void* to function pointer.
  6587. assert(rhptee->isFunctionType());
  6588. return Sema::FunctionVoidPointer;
  6589. }
  6590. if (rhptee->isVoidType()) {
  6591. if (lhptee->isIncompleteOrObjectType())
  6592. return ConvTy;
  6593. // As an extension, we allow cast to/from void* to function pointer.
  6594. assert(lhptee->isFunctionType());
  6595. return Sema::FunctionVoidPointer;
  6596. }
  6597. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  6598. // unqualified versions of compatible types, ...
  6599. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  6600. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  6601. // Check if the pointee types are compatible ignoring the sign.
  6602. // We explicitly check for char so that we catch "char" vs
  6603. // "unsigned char" on systems where "char" is unsigned.
  6604. if (lhptee->isCharType())
  6605. ltrans = S.Context.UnsignedCharTy;
  6606. else if (lhptee->hasSignedIntegerRepresentation())
  6607. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  6608. if (rhptee->isCharType())
  6609. rtrans = S.Context.UnsignedCharTy;
  6610. else if (rhptee->hasSignedIntegerRepresentation())
  6611. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  6612. if (ltrans == rtrans) {
  6613. // Types are compatible ignoring the sign. Qualifier incompatibility
  6614. // takes priority over sign incompatibility because the sign
  6615. // warning can be disabled.
  6616. if (ConvTy != Sema::Compatible)
  6617. return ConvTy;
  6618. return Sema::IncompatiblePointerSign;
  6619. }
  6620. // If we are a multi-level pointer, it's possible that our issue is simply
  6621. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  6622. // the eventual target type is the same and the pointers have the same
  6623. // level of indirection, this must be the issue.
  6624. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  6625. do {
  6626. lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
  6627. rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
  6628. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  6629. if (lhptee == rhptee)
  6630. return Sema::IncompatibleNestedPointerQualifiers;
  6631. }
  6632. // General pointer incompatibility takes priority over qualifiers.
  6633. return Sema::IncompatiblePointer;
  6634. }
  6635. if (!S.getLangOpts().CPlusPlus &&
  6636. S.IsFunctionConversion(ltrans, rtrans, ltrans))
  6637. return Sema::IncompatiblePointer;
  6638. return ConvTy;
  6639. }
  6640. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  6641. /// block pointer types are compatible or whether a block and normal pointer
  6642. /// are compatible. It is more restrict than comparing two function pointer
  6643. // types.
  6644. static Sema::AssignConvertType
  6645. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  6646. QualType RHSType) {
  6647. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6648. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6649. QualType lhptee, rhptee;
  6650. // get the "pointed to" type (ignoring qualifiers at the top level)
  6651. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  6652. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  6653. // In C++, the types have to match exactly.
  6654. if (S.getLangOpts().CPlusPlus)
  6655. return Sema::IncompatibleBlockPointer;
  6656. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6657. // For blocks we enforce that qualifiers are identical.
  6658. Qualifiers LQuals = lhptee.getLocalQualifiers();
  6659. Qualifiers RQuals = rhptee.getLocalQualifiers();
  6660. if (S.getLangOpts().OpenCL) {
  6661. LQuals.removeAddressSpace();
  6662. RQuals.removeAddressSpace();
  6663. }
  6664. if (LQuals != RQuals)
  6665. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6666. // FIXME: OpenCL doesn't define the exact compile time semantics for a block
  6667. // assignment.
  6668. // The current behavior is similar to C++ lambdas. A block might be
  6669. // assigned to a variable iff its return type and parameters are compatible
  6670. // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
  6671. // an assignment. Presumably it should behave in way that a function pointer
  6672. // assignment does in C, so for each parameter and return type:
  6673. // * CVR and address space of LHS should be a superset of CVR and address
  6674. // space of RHS.
  6675. // * unqualified types should be compatible.
  6676. if (S.getLangOpts().OpenCL) {
  6677. if (!S.Context.typesAreBlockPointerCompatible(
  6678. S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
  6679. S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
  6680. return Sema::IncompatibleBlockPointer;
  6681. } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  6682. return Sema::IncompatibleBlockPointer;
  6683. return ConvTy;
  6684. }
  6685. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  6686. /// for assignment compatibility.
  6687. static Sema::AssignConvertType
  6688. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  6689. QualType RHSType) {
  6690. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  6691. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  6692. if (LHSType->isObjCBuiltinType()) {
  6693. // Class is not compatible with ObjC object pointers.
  6694. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  6695. !RHSType->isObjCQualifiedClassType())
  6696. return Sema::IncompatiblePointer;
  6697. return Sema::Compatible;
  6698. }
  6699. if (RHSType->isObjCBuiltinType()) {
  6700. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  6701. !LHSType->isObjCQualifiedClassType())
  6702. return Sema::IncompatiblePointer;
  6703. return Sema::Compatible;
  6704. }
  6705. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6706. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6707. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  6708. // make an exception for id<P>
  6709. !LHSType->isObjCQualifiedIdType())
  6710. return Sema::CompatiblePointerDiscardsQualifiers;
  6711. if (S.Context.typesAreCompatible(LHSType, RHSType))
  6712. return Sema::Compatible;
  6713. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  6714. return Sema::IncompatibleObjCQualifiedId;
  6715. return Sema::IncompatiblePointer;
  6716. }
  6717. Sema::AssignConvertType
  6718. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  6719. QualType LHSType, QualType RHSType) {
  6720. // Fake up an opaque expression. We don't actually care about what
  6721. // cast operations are required, so if CheckAssignmentConstraints
  6722. // adds casts to this they'll be wasted, but fortunately that doesn't
  6723. // usually happen on valid code.
  6724. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  6725. ExprResult RHSPtr = &RHSExpr;
  6726. CastKind K;
  6727. return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
  6728. }
  6729. /// This helper function returns true if QT is a vector type that has element
  6730. /// type ElementType.
  6731. static bool isVector(QualType QT, QualType ElementType) {
  6732. if (const VectorType *VT = QT->getAs<VectorType>())
  6733. return VT->getElementType() == ElementType;
  6734. return false;
  6735. }
  6736. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  6737. /// has code to accommodate several GCC extensions when type checking
  6738. /// pointers. Here are some objectionable examples that GCC considers warnings:
  6739. ///
  6740. /// int a, *pint;
  6741. /// short *pshort;
  6742. /// struct foo *pfoo;
  6743. ///
  6744. /// pint = pshort; // warning: assignment from incompatible pointer type
  6745. /// a = pint; // warning: assignment makes integer from pointer without a cast
  6746. /// pint = a; // warning: assignment makes pointer from integer without a cast
  6747. /// pint = pfoo; // warning: assignment from incompatible pointer type
  6748. ///
  6749. /// As a result, the code for dealing with pointers is more complex than the
  6750. /// C99 spec dictates.
  6751. ///
  6752. /// Sets 'Kind' for any result kind except Incompatible.
  6753. Sema::AssignConvertType
  6754. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6755. CastKind &Kind, bool ConvertRHS) {
  6756. QualType RHSType = RHS.get()->getType();
  6757. QualType OrigLHSType = LHSType;
  6758. // Get canonical types. We're not formatting these types, just comparing
  6759. // them.
  6760. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  6761. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  6762. // Common case: no conversion required.
  6763. if (LHSType == RHSType) {
  6764. Kind = CK_NoOp;
  6765. return Compatible;
  6766. }
  6767. // If we have an atomic type, try a non-atomic assignment, then just add an
  6768. // atomic qualification step.
  6769. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  6770. Sema::AssignConvertType result =
  6771. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  6772. if (result != Compatible)
  6773. return result;
  6774. if (Kind != CK_NoOp && ConvertRHS)
  6775. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  6776. Kind = CK_NonAtomicToAtomic;
  6777. return Compatible;
  6778. }
  6779. // If the left-hand side is a reference type, then we are in a
  6780. // (rare!) case where we've allowed the use of references in C,
  6781. // e.g., as a parameter type in a built-in function. In this case,
  6782. // just make sure that the type referenced is compatible with the
  6783. // right-hand side type. The caller is responsible for adjusting
  6784. // LHSType so that the resulting expression does not have reference
  6785. // type.
  6786. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  6787. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  6788. Kind = CK_LValueBitCast;
  6789. return Compatible;
  6790. }
  6791. return Incompatible;
  6792. }
  6793. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  6794. // to the same ExtVector type.
  6795. if (LHSType->isExtVectorType()) {
  6796. if (RHSType->isExtVectorType())
  6797. return Incompatible;
  6798. if (RHSType->isArithmeticType()) {
  6799. // CK_VectorSplat does T -> vector T, so first cast to the element type.
  6800. if (ConvertRHS)
  6801. RHS = prepareVectorSplat(LHSType, RHS.get());
  6802. Kind = CK_VectorSplat;
  6803. return Compatible;
  6804. }
  6805. }
  6806. // Conversions to or from vector type.
  6807. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  6808. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  6809. // Allow assignments of an AltiVec vector type to an equivalent GCC
  6810. // vector type and vice versa
  6811. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6812. Kind = CK_BitCast;
  6813. return Compatible;
  6814. }
  6815. // If we are allowing lax vector conversions, and LHS and RHS are both
  6816. // vectors, the total size only needs to be the same. This is a bitcast;
  6817. // no bits are changed but the result type is different.
  6818. if (isLaxVectorConversion(RHSType, LHSType)) {
  6819. Kind = CK_BitCast;
  6820. return IncompatibleVectors;
  6821. }
  6822. }
  6823. // When the RHS comes from another lax conversion (e.g. binops between
  6824. // scalars and vectors) the result is canonicalized as a vector. When the
  6825. // LHS is also a vector, the lax is allowed by the condition above. Handle
  6826. // the case where LHS is a scalar.
  6827. if (LHSType->isScalarType()) {
  6828. const VectorType *VecType = RHSType->getAs<VectorType>();
  6829. if (VecType && VecType->getNumElements() == 1 &&
  6830. isLaxVectorConversion(RHSType, LHSType)) {
  6831. ExprResult *VecExpr = &RHS;
  6832. *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
  6833. Kind = CK_BitCast;
  6834. return Compatible;
  6835. }
  6836. }
  6837. return Incompatible;
  6838. }
  6839. // Diagnose attempts to convert between __float128 and long double where
  6840. // such conversions currently can't be handled.
  6841. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  6842. return Incompatible;
  6843. // Disallow assigning a _Complex to a real type in C++ mode since it simply
  6844. // discards the imaginary part.
  6845. if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
  6846. !LHSType->getAs<ComplexType>())
  6847. return Incompatible;
  6848. // Arithmetic conversions.
  6849. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  6850. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  6851. if (ConvertRHS)
  6852. Kind = PrepareScalarCast(RHS, LHSType);
  6853. return Compatible;
  6854. }
  6855. // Conversions to normal pointers.
  6856. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  6857. // U* -> T*
  6858. if (isa<PointerType>(RHSType)) {
  6859. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  6860. LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  6861. if (AddrSpaceL != AddrSpaceR)
  6862. Kind = CK_AddressSpaceConversion;
  6863. else if (Context.hasCvrSimilarType(RHSType, LHSType))
  6864. Kind = CK_NoOp;
  6865. else
  6866. Kind = CK_BitCast;
  6867. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  6868. }
  6869. // int -> T*
  6870. if (RHSType->isIntegerType()) {
  6871. Kind = CK_IntegralToPointer; // FIXME: null?
  6872. return IntToPointer;
  6873. }
  6874. // C pointers are not compatible with ObjC object pointers,
  6875. // with two exceptions:
  6876. if (isa<ObjCObjectPointerType>(RHSType)) {
  6877. // - conversions to void*
  6878. if (LHSPointer->getPointeeType()->isVoidType()) {
  6879. Kind = CK_BitCast;
  6880. return Compatible;
  6881. }
  6882. // - conversions from 'Class' to the redefinition type
  6883. if (RHSType->isObjCClassType() &&
  6884. Context.hasSameType(LHSType,
  6885. Context.getObjCClassRedefinitionType())) {
  6886. Kind = CK_BitCast;
  6887. return Compatible;
  6888. }
  6889. Kind = CK_BitCast;
  6890. return IncompatiblePointer;
  6891. }
  6892. // U^ -> void*
  6893. if (RHSType->getAs<BlockPointerType>()) {
  6894. if (LHSPointer->getPointeeType()->isVoidType()) {
  6895. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  6896. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  6897. ->getPointeeType()
  6898. .getAddressSpace();
  6899. Kind =
  6900. AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6901. return Compatible;
  6902. }
  6903. }
  6904. return Incompatible;
  6905. }
  6906. // Conversions to block pointers.
  6907. if (isa<BlockPointerType>(LHSType)) {
  6908. // U^ -> T^
  6909. if (RHSType->isBlockPointerType()) {
  6910. LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
  6911. ->getPointeeType()
  6912. .getAddressSpace();
  6913. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  6914. ->getPointeeType()
  6915. .getAddressSpace();
  6916. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6917. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  6918. }
  6919. // int or null -> T^
  6920. if (RHSType->isIntegerType()) {
  6921. Kind = CK_IntegralToPointer; // FIXME: null
  6922. return IntToBlockPointer;
  6923. }
  6924. // id -> T^
  6925. if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
  6926. Kind = CK_AnyPointerToBlockPointerCast;
  6927. return Compatible;
  6928. }
  6929. // void* -> T^
  6930. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  6931. if (RHSPT->getPointeeType()->isVoidType()) {
  6932. Kind = CK_AnyPointerToBlockPointerCast;
  6933. return Compatible;
  6934. }
  6935. return Incompatible;
  6936. }
  6937. // Conversions to Objective-C pointers.
  6938. if (isa<ObjCObjectPointerType>(LHSType)) {
  6939. // A* -> B*
  6940. if (RHSType->isObjCObjectPointerType()) {
  6941. Kind = CK_BitCast;
  6942. Sema::AssignConvertType result =
  6943. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  6944. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  6945. result == Compatible &&
  6946. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  6947. result = IncompatibleObjCWeakRef;
  6948. return result;
  6949. }
  6950. // int or null -> A*
  6951. if (RHSType->isIntegerType()) {
  6952. Kind = CK_IntegralToPointer; // FIXME: null
  6953. return IntToPointer;
  6954. }
  6955. // In general, C pointers are not compatible with ObjC object pointers,
  6956. // with two exceptions:
  6957. if (isa<PointerType>(RHSType)) {
  6958. Kind = CK_CPointerToObjCPointerCast;
  6959. // - conversions from 'void*'
  6960. if (RHSType->isVoidPointerType()) {
  6961. return Compatible;
  6962. }
  6963. // - conversions to 'Class' from its redefinition type
  6964. if (LHSType->isObjCClassType() &&
  6965. Context.hasSameType(RHSType,
  6966. Context.getObjCClassRedefinitionType())) {
  6967. return Compatible;
  6968. }
  6969. return IncompatiblePointer;
  6970. }
  6971. // Only under strict condition T^ is compatible with an Objective-C pointer.
  6972. if (RHSType->isBlockPointerType() &&
  6973. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  6974. if (ConvertRHS)
  6975. maybeExtendBlockObject(RHS);
  6976. Kind = CK_BlockPointerToObjCPointerCast;
  6977. return Compatible;
  6978. }
  6979. return Incompatible;
  6980. }
  6981. // Conversions from pointers that are not covered by the above.
  6982. if (isa<PointerType>(RHSType)) {
  6983. // T* -> _Bool
  6984. if (LHSType == Context.BoolTy) {
  6985. Kind = CK_PointerToBoolean;
  6986. return Compatible;
  6987. }
  6988. // T* -> int
  6989. if (LHSType->isIntegerType()) {
  6990. Kind = CK_PointerToIntegral;
  6991. return PointerToInt;
  6992. }
  6993. return Incompatible;
  6994. }
  6995. // Conversions from Objective-C pointers that are not covered by the above.
  6996. if (isa<ObjCObjectPointerType>(RHSType)) {
  6997. // T* -> _Bool
  6998. if (LHSType == Context.BoolTy) {
  6999. Kind = CK_PointerToBoolean;
  7000. return Compatible;
  7001. }
  7002. // T* -> int
  7003. if (LHSType->isIntegerType()) {
  7004. Kind = CK_PointerToIntegral;
  7005. return PointerToInt;
  7006. }
  7007. return Incompatible;
  7008. }
  7009. // struct A -> struct B
  7010. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  7011. if (Context.typesAreCompatible(LHSType, RHSType)) {
  7012. Kind = CK_NoOp;
  7013. return Compatible;
  7014. }
  7015. }
  7016. if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
  7017. Kind = CK_IntToOCLSampler;
  7018. return Compatible;
  7019. }
  7020. return Incompatible;
  7021. }
  7022. /// Constructs a transparent union from an expression that is
  7023. /// used to initialize the transparent union.
  7024. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  7025. ExprResult &EResult, QualType UnionType,
  7026. FieldDecl *Field) {
  7027. // Build an initializer list that designates the appropriate member
  7028. // of the transparent union.
  7029. Expr *E = EResult.get();
  7030. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  7031. E, SourceLocation());
  7032. Initializer->setType(UnionType);
  7033. Initializer->setInitializedFieldInUnion(Field);
  7034. // Build a compound literal constructing a value of the transparent
  7035. // union type from this initializer list.
  7036. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  7037. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  7038. VK_RValue, Initializer, false);
  7039. }
  7040. Sema::AssignConvertType
  7041. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  7042. ExprResult &RHS) {
  7043. QualType RHSType = RHS.get()->getType();
  7044. // If the ArgType is a Union type, we want to handle a potential
  7045. // transparent_union GCC extension.
  7046. const RecordType *UT = ArgType->getAsUnionType();
  7047. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  7048. return Incompatible;
  7049. // The field to initialize within the transparent union.
  7050. RecordDecl *UD = UT->getDecl();
  7051. FieldDecl *InitField = nullptr;
  7052. // It's compatible if the expression matches any of the fields.
  7053. for (auto *it : UD->fields()) {
  7054. if (it->getType()->isPointerType()) {
  7055. // If the transparent union contains a pointer type, we allow:
  7056. // 1) void pointer
  7057. // 2) null pointer constant
  7058. if (RHSType->isPointerType())
  7059. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  7060. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  7061. InitField = it;
  7062. break;
  7063. }
  7064. if (RHS.get()->isNullPointerConstant(Context,
  7065. Expr::NPC_ValueDependentIsNull)) {
  7066. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  7067. CK_NullToPointer);
  7068. InitField = it;
  7069. break;
  7070. }
  7071. }
  7072. CastKind Kind;
  7073. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  7074. == Compatible) {
  7075. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  7076. InitField = it;
  7077. break;
  7078. }
  7079. }
  7080. if (!InitField)
  7081. return Incompatible;
  7082. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  7083. return Compatible;
  7084. }
  7085. Sema::AssignConvertType
  7086. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
  7087. bool Diagnose,
  7088. bool DiagnoseCFAudited,
  7089. bool ConvertRHS) {
  7090. // We need to be able to tell the caller whether we diagnosed a problem, if
  7091. // they ask us to issue diagnostics.
  7092. assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
  7093. // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
  7094. // we can't avoid *all* modifications at the moment, so we need some somewhere
  7095. // to put the updated value.
  7096. ExprResult LocalRHS = CallerRHS;
  7097. ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
  7098. if (getLangOpts().CPlusPlus) {
  7099. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  7100. // C++ 5.17p3: If the left operand is not of class type, the
  7101. // expression is implicitly converted (C++ 4) to the
  7102. // cv-unqualified type of the left operand.
  7103. QualType RHSType = RHS.get()->getType();
  7104. if (Diagnose) {
  7105. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7106. AA_Assigning);
  7107. } else {
  7108. ImplicitConversionSequence ICS =
  7109. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7110. /*SuppressUserConversions=*/false,
  7111. /*AllowExplicit=*/false,
  7112. /*InOverloadResolution=*/false,
  7113. /*CStyle=*/false,
  7114. /*AllowObjCWritebackConversion=*/false);
  7115. if (ICS.isFailure())
  7116. return Incompatible;
  7117. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7118. ICS, AA_Assigning);
  7119. }
  7120. if (RHS.isInvalid())
  7121. return Incompatible;
  7122. Sema::AssignConvertType result = Compatible;
  7123. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7124. !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
  7125. result = IncompatibleObjCWeakRef;
  7126. return result;
  7127. }
  7128. // FIXME: Currently, we fall through and treat C++ classes like C
  7129. // structures.
  7130. // FIXME: We also fall through for atomics; not sure what should
  7131. // happen there, though.
  7132. } else if (RHS.get()->getType() == Context.OverloadTy) {
  7133. // As a set of extensions to C, we support overloading on functions. These
  7134. // functions need to be resolved here.
  7135. DeclAccessPair DAP;
  7136. if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
  7137. RHS.get(), LHSType, /*Complain=*/false, DAP))
  7138. RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
  7139. else
  7140. return Incompatible;
  7141. }
  7142. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  7143. // a null pointer constant.
  7144. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  7145. LHSType->isBlockPointerType()) &&
  7146. RHS.get()->isNullPointerConstant(Context,
  7147. Expr::NPC_ValueDependentIsNull)) {
  7148. if (Diagnose || ConvertRHS) {
  7149. CastKind Kind;
  7150. CXXCastPath Path;
  7151. CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
  7152. /*IgnoreBaseAccess=*/false, Diagnose);
  7153. if (ConvertRHS)
  7154. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  7155. }
  7156. return Compatible;
  7157. }
  7158. // OpenCL queue_t type assignment.
  7159. if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
  7160. Context, Expr::NPC_ValueDependentIsNull)) {
  7161. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7162. return Compatible;
  7163. }
  7164. // This check seems unnatural, however it is necessary to ensure the proper
  7165. // conversion of functions/arrays. If the conversion were done for all
  7166. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  7167. // expressions that suppress this implicit conversion (&, sizeof).
  7168. //
  7169. // Suppress this for references: C++ 8.5.3p5.
  7170. if (!LHSType->isReferenceType()) {
  7171. // FIXME: We potentially allocate here even if ConvertRHS is false.
  7172. RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
  7173. if (RHS.isInvalid())
  7174. return Incompatible;
  7175. }
  7176. CastKind Kind;
  7177. Sema::AssignConvertType result =
  7178. CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
  7179. // C99 6.5.16.1p2: The value of the right operand is converted to the
  7180. // type of the assignment expression.
  7181. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  7182. // so that we can use references in built-in functions even in C.
  7183. // The getNonReferenceType() call makes sure that the resulting expression
  7184. // does not have reference type.
  7185. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  7186. QualType Ty = LHSType.getNonLValueExprType(Context);
  7187. Expr *E = RHS.get();
  7188. // Check for various Objective-C errors. If we are not reporting
  7189. // diagnostics and just checking for errors, e.g., during overload
  7190. // resolution, return Incompatible to indicate the failure.
  7191. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7192. CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  7193. Diagnose, DiagnoseCFAudited) != ACR_okay) {
  7194. if (!Diagnose)
  7195. return Incompatible;
  7196. }
  7197. if (getLangOpts().ObjC &&
  7198. (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
  7199. E->getType(), E, Diagnose) ||
  7200. ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
  7201. if (!Diagnose)
  7202. return Incompatible;
  7203. // Replace the expression with a corrected version and continue so we
  7204. // can find further errors.
  7205. RHS = E;
  7206. return Compatible;
  7207. }
  7208. if (ConvertRHS)
  7209. RHS = ImpCastExprToType(E, Ty, Kind);
  7210. }
  7211. return result;
  7212. }
  7213. namespace {
  7214. /// The original operand to an operator, prior to the application of the usual
  7215. /// arithmetic conversions and converting the arguments of a builtin operator
  7216. /// candidate.
  7217. struct OriginalOperand {
  7218. explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
  7219. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
  7220. Op = MTE->GetTemporaryExpr();
  7221. if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
  7222. Op = BTE->getSubExpr();
  7223. if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
  7224. Orig = ICE->getSubExprAsWritten();
  7225. Conversion = ICE->getConversionFunction();
  7226. }
  7227. }
  7228. QualType getType() const { return Orig->getType(); }
  7229. Expr *Orig;
  7230. NamedDecl *Conversion;
  7231. };
  7232. }
  7233. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  7234. ExprResult &RHS) {
  7235. OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
  7236. Diag(Loc, diag::err_typecheck_invalid_operands)
  7237. << OrigLHS.getType() << OrigRHS.getType()
  7238. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7239. // If a user-defined conversion was applied to either of the operands prior
  7240. // to applying the built-in operator rules, tell the user about it.
  7241. if (OrigLHS.Conversion) {
  7242. Diag(OrigLHS.Conversion->getLocation(),
  7243. diag::note_typecheck_invalid_operands_converted)
  7244. << 0 << LHS.get()->getType();
  7245. }
  7246. if (OrigRHS.Conversion) {
  7247. Diag(OrigRHS.Conversion->getLocation(),
  7248. diag::note_typecheck_invalid_operands_converted)
  7249. << 1 << RHS.get()->getType();
  7250. }
  7251. return QualType();
  7252. }
  7253. // Diagnose cases where a scalar was implicitly converted to a vector and
  7254. // diagnose the underlying types. Otherwise, diagnose the error
  7255. // as invalid vector logical operands for non-C++ cases.
  7256. QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
  7257. ExprResult &RHS) {
  7258. QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
  7259. QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
  7260. bool LHSNatVec = LHSType->isVectorType();
  7261. bool RHSNatVec = RHSType->isVectorType();
  7262. if (!(LHSNatVec && RHSNatVec)) {
  7263. Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
  7264. Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
  7265. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7266. << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
  7267. << Vector->getSourceRange();
  7268. return QualType();
  7269. }
  7270. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7271. << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
  7272. << RHS.get()->getSourceRange();
  7273. return QualType();
  7274. }
  7275. /// Try to convert a value of non-vector type to a vector type by converting
  7276. /// the type to the element type of the vector and then performing a splat.
  7277. /// If the language is OpenCL, we only use conversions that promote scalar
  7278. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  7279. /// for float->int.
  7280. ///
  7281. /// OpenCL V2.0 6.2.6.p2:
  7282. /// An error shall occur if any scalar operand type has greater rank
  7283. /// than the type of the vector element.
  7284. ///
  7285. /// \param scalar - if non-null, actually perform the conversions
  7286. /// \return true if the operation fails (but without diagnosing the failure)
  7287. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  7288. QualType scalarTy,
  7289. QualType vectorEltTy,
  7290. QualType vectorTy,
  7291. unsigned &DiagID) {
  7292. // The conversion to apply to the scalar before splatting it,
  7293. // if necessary.
  7294. CastKind scalarCast = CK_NoOp;
  7295. if (vectorEltTy->isIntegralType(S.Context)) {
  7296. if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
  7297. (scalarTy->isIntegerType() &&
  7298. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
  7299. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7300. return true;
  7301. }
  7302. if (!scalarTy->isIntegralType(S.Context))
  7303. return true;
  7304. scalarCast = CK_IntegralCast;
  7305. } else if (vectorEltTy->isRealFloatingType()) {
  7306. if (scalarTy->isRealFloatingType()) {
  7307. if (S.getLangOpts().OpenCL &&
  7308. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
  7309. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7310. return true;
  7311. }
  7312. scalarCast = CK_FloatingCast;
  7313. }
  7314. else if (scalarTy->isIntegralType(S.Context))
  7315. scalarCast = CK_IntegralToFloating;
  7316. else
  7317. return true;
  7318. } else {
  7319. return true;
  7320. }
  7321. // Adjust scalar if desired.
  7322. if (scalar) {
  7323. if (scalarCast != CK_NoOp)
  7324. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  7325. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  7326. }
  7327. return false;
  7328. }
  7329. /// Convert vector E to a vector with the same number of elements but different
  7330. /// element type.
  7331. static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
  7332. const auto *VecTy = E->getType()->getAs<VectorType>();
  7333. assert(VecTy && "Expression E must be a vector");
  7334. QualType NewVecTy = S.Context.getVectorType(ElementType,
  7335. VecTy->getNumElements(),
  7336. VecTy->getVectorKind());
  7337. // Look through the implicit cast. Return the subexpression if its type is
  7338. // NewVecTy.
  7339. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  7340. if (ICE->getSubExpr()->getType() == NewVecTy)
  7341. return ICE->getSubExpr();
  7342. auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
  7343. return S.ImpCastExprToType(E, NewVecTy, Cast);
  7344. }
  7345. /// Test if a (constant) integer Int can be casted to another integer type
  7346. /// IntTy without losing precision.
  7347. static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
  7348. QualType OtherIntTy) {
  7349. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7350. // Reject cases where the value of the Int is unknown as that would
  7351. // possibly cause truncation, but accept cases where the scalar can be
  7352. // demoted without loss of precision.
  7353. llvm::APSInt Result;
  7354. bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
  7355. int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
  7356. bool IntSigned = IntTy->hasSignedIntegerRepresentation();
  7357. bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
  7358. if (CstInt) {
  7359. // If the scalar is constant and is of a higher order and has more active
  7360. // bits that the vector element type, reject it.
  7361. unsigned NumBits = IntSigned
  7362. ? (Result.isNegative() ? Result.getMinSignedBits()
  7363. : Result.getActiveBits())
  7364. : Result.getActiveBits();
  7365. if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
  7366. return true;
  7367. // If the signedness of the scalar type and the vector element type
  7368. // differs and the number of bits is greater than that of the vector
  7369. // element reject it.
  7370. return (IntSigned != OtherIntSigned &&
  7371. NumBits > S.Context.getIntWidth(OtherIntTy));
  7372. }
  7373. // Reject cases where the value of the scalar is not constant and it's
  7374. // order is greater than that of the vector element type.
  7375. return (Order < 0);
  7376. }
  7377. /// Test if a (constant) integer Int can be casted to floating point type
  7378. /// FloatTy without losing precision.
  7379. static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
  7380. QualType FloatTy) {
  7381. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7382. // Determine if the integer constant can be expressed as a floating point
  7383. // number of the appropriate type.
  7384. llvm::APSInt Result;
  7385. bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
  7386. uint64_t Bits = 0;
  7387. if (CstInt) {
  7388. // Reject constants that would be truncated if they were converted to
  7389. // the floating point type. Test by simple to/from conversion.
  7390. // FIXME: Ideally the conversion to an APFloat and from an APFloat
  7391. // could be avoided if there was a convertFromAPInt method
  7392. // which could signal back if implicit truncation occurred.
  7393. llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
  7394. Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
  7395. llvm::APFloat::rmTowardZero);
  7396. llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
  7397. !IntTy->hasSignedIntegerRepresentation());
  7398. bool Ignored = false;
  7399. Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
  7400. &Ignored);
  7401. if (Result != ConvertBack)
  7402. return true;
  7403. } else {
  7404. // Reject types that cannot be fully encoded into the mantissa of
  7405. // the float.
  7406. Bits = S.Context.getTypeSize(IntTy);
  7407. unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
  7408. S.Context.getFloatTypeSemantics(FloatTy));
  7409. if (Bits > FloatPrec)
  7410. return true;
  7411. }
  7412. return false;
  7413. }
  7414. /// Attempt to convert and splat Scalar into a vector whose types matches
  7415. /// Vector following GCC conversion rules. The rule is that implicit
  7416. /// conversion can occur when Scalar can be casted to match Vector's element
  7417. /// type without causing truncation of Scalar.
  7418. static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
  7419. ExprResult *Vector) {
  7420. QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
  7421. QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
  7422. const VectorType *VT = VectorTy->getAs<VectorType>();
  7423. assert(!isa<ExtVectorType>(VT) &&
  7424. "ExtVectorTypes should not be handled here!");
  7425. QualType VectorEltTy = VT->getElementType();
  7426. // Reject cases where the vector element type or the scalar element type are
  7427. // not integral or floating point types.
  7428. if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
  7429. return true;
  7430. // The conversion to apply to the scalar before splatting it,
  7431. // if necessary.
  7432. CastKind ScalarCast = CK_NoOp;
  7433. // Accept cases where the vector elements are integers and the scalar is
  7434. // an integer.
  7435. // FIXME: Notionally if the scalar was a floating point value with a precise
  7436. // integral representation, we could cast it to an appropriate integer
  7437. // type and then perform the rest of the checks here. GCC will perform
  7438. // this conversion in some cases as determined by the input language.
  7439. // We should accept it on a language independent basis.
  7440. if (VectorEltTy->isIntegralType(S.Context) &&
  7441. ScalarTy->isIntegralType(S.Context) &&
  7442. S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
  7443. if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
  7444. return true;
  7445. ScalarCast = CK_IntegralCast;
  7446. } else if (VectorEltTy->isRealFloatingType()) {
  7447. if (ScalarTy->isRealFloatingType()) {
  7448. // Reject cases where the scalar type is not a constant and has a higher
  7449. // Order than the vector element type.
  7450. llvm::APFloat Result(0.0);
  7451. bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
  7452. int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
  7453. if (!CstScalar && Order < 0)
  7454. return true;
  7455. // If the scalar cannot be safely casted to the vector element type,
  7456. // reject it.
  7457. if (CstScalar) {
  7458. bool Truncated = false;
  7459. Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
  7460. llvm::APFloat::rmNearestTiesToEven, &Truncated);
  7461. if (Truncated)
  7462. return true;
  7463. }
  7464. ScalarCast = CK_FloatingCast;
  7465. } else if (ScalarTy->isIntegralType(S.Context)) {
  7466. if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
  7467. return true;
  7468. ScalarCast = CK_IntegralToFloating;
  7469. } else
  7470. return true;
  7471. }
  7472. // Adjust scalar if desired.
  7473. if (Scalar) {
  7474. if (ScalarCast != CK_NoOp)
  7475. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
  7476. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
  7477. }
  7478. return false;
  7479. }
  7480. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  7481. SourceLocation Loc, bool IsCompAssign,
  7482. bool AllowBothBool,
  7483. bool AllowBoolConversions) {
  7484. if (!IsCompAssign) {
  7485. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  7486. if (LHS.isInvalid())
  7487. return QualType();
  7488. }
  7489. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  7490. if (RHS.isInvalid())
  7491. return QualType();
  7492. // For conversion purposes, we ignore any qualifiers.
  7493. // For example, "const float" and "float" are equivalent.
  7494. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  7495. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  7496. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  7497. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  7498. assert(LHSVecType || RHSVecType);
  7499. // AltiVec-style "vector bool op vector bool" combinations are allowed
  7500. // for some operators but not others.
  7501. if (!AllowBothBool &&
  7502. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7503. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7504. return InvalidOperands(Loc, LHS, RHS);
  7505. // If the vector types are identical, return.
  7506. if (Context.hasSameType(LHSType, RHSType))
  7507. return LHSType;
  7508. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  7509. if (LHSVecType && RHSVecType &&
  7510. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7511. if (isa<ExtVectorType>(LHSVecType)) {
  7512. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7513. return LHSType;
  7514. }
  7515. if (!IsCompAssign)
  7516. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7517. return RHSType;
  7518. }
  7519. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  7520. // can be mixed, with the result being the non-bool type. The non-bool
  7521. // operand must have integer element type.
  7522. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  7523. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  7524. (Context.getTypeSize(LHSVecType->getElementType()) ==
  7525. Context.getTypeSize(RHSVecType->getElementType()))) {
  7526. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7527. LHSVecType->getElementType()->isIntegerType() &&
  7528. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  7529. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7530. return LHSType;
  7531. }
  7532. if (!IsCompAssign &&
  7533. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7534. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7535. RHSVecType->getElementType()->isIntegerType()) {
  7536. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7537. return RHSType;
  7538. }
  7539. }
  7540. // If there's a vector type and a scalar, try to convert the scalar to
  7541. // the vector element type and splat.
  7542. unsigned DiagID = diag::err_typecheck_vector_not_convertable;
  7543. if (!RHSVecType) {
  7544. if (isa<ExtVectorType>(LHSVecType)) {
  7545. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  7546. LHSVecType->getElementType(), LHSType,
  7547. DiagID))
  7548. return LHSType;
  7549. } else {
  7550. if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
  7551. return LHSType;
  7552. }
  7553. }
  7554. if (!LHSVecType) {
  7555. if (isa<ExtVectorType>(RHSVecType)) {
  7556. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  7557. LHSType, RHSVecType->getElementType(),
  7558. RHSType, DiagID))
  7559. return RHSType;
  7560. } else {
  7561. if (LHS.get()->getValueKind() == VK_LValue ||
  7562. !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
  7563. return RHSType;
  7564. }
  7565. }
  7566. // FIXME: The code below also handles conversion between vectors and
  7567. // non-scalars, we should break this down into fine grained specific checks
  7568. // and emit proper diagnostics.
  7569. QualType VecType = LHSVecType ? LHSType : RHSType;
  7570. const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
  7571. QualType OtherType = LHSVecType ? RHSType : LHSType;
  7572. ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
  7573. if (isLaxVectorConversion(OtherType, VecType)) {
  7574. // If we're allowing lax vector conversions, only the total (data) size
  7575. // needs to be the same. For non compound assignment, if one of the types is
  7576. // scalar, the result is always the vector type.
  7577. if (!IsCompAssign) {
  7578. *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
  7579. return VecType;
  7580. // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
  7581. // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
  7582. // type. Note that this is already done by non-compound assignments in
  7583. // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
  7584. // <1 x T> -> T. The result is also a vector type.
  7585. } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
  7586. (OtherType->isScalarType() && VT->getNumElements() == 1)) {
  7587. ExprResult *RHSExpr = &RHS;
  7588. *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
  7589. return VecType;
  7590. }
  7591. }
  7592. // Okay, the expression is invalid.
  7593. // If there's a non-vector, non-real operand, diagnose that.
  7594. if ((!RHSVecType && !RHSType->isRealType()) ||
  7595. (!LHSVecType && !LHSType->isRealType())) {
  7596. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  7597. << LHSType << RHSType
  7598. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7599. return QualType();
  7600. }
  7601. // OpenCL V1.1 6.2.6.p1:
  7602. // If the operands are of more than one vector type, then an error shall
  7603. // occur. Implicit conversions between vector types are not permitted, per
  7604. // section 6.2.1.
  7605. if (getLangOpts().OpenCL &&
  7606. RHSVecType && isa<ExtVectorType>(RHSVecType) &&
  7607. LHSVecType && isa<ExtVectorType>(LHSVecType)) {
  7608. Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
  7609. << RHSType;
  7610. return QualType();
  7611. }
  7612. // If there is a vector type that is not a ExtVector and a scalar, we reach
  7613. // this point if scalar could not be converted to the vector's element type
  7614. // without truncation.
  7615. if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
  7616. (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
  7617. QualType Scalar = LHSVecType ? RHSType : LHSType;
  7618. QualType Vector = LHSVecType ? LHSType : RHSType;
  7619. unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
  7620. Diag(Loc,
  7621. diag::err_typecheck_vector_not_convertable_implict_truncation)
  7622. << ScalarOrVector << Scalar << Vector;
  7623. return QualType();
  7624. }
  7625. // Otherwise, use the generic diagnostic.
  7626. Diag(Loc, DiagID)
  7627. << LHSType << RHSType
  7628. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7629. return QualType();
  7630. }
  7631. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  7632. // expression. These are mainly cases where the null pointer is used as an
  7633. // integer instead of a pointer.
  7634. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  7635. SourceLocation Loc, bool IsCompare) {
  7636. // The canonical way to check for a GNU null is with isNullPointerConstant,
  7637. // but we use a bit of a hack here for speed; this is a relatively
  7638. // hot path, and isNullPointerConstant is slow.
  7639. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  7640. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  7641. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  7642. // Avoid analyzing cases where the result will either be invalid (and
  7643. // diagnosed as such) or entirely valid and not something to warn about.
  7644. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  7645. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  7646. return;
  7647. // Comparison operations would not make sense with a null pointer no matter
  7648. // what the other expression is.
  7649. if (!IsCompare) {
  7650. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  7651. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  7652. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  7653. return;
  7654. }
  7655. // The rest of the operations only make sense with a null pointer
  7656. // if the other expression is a pointer.
  7657. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  7658. NonNullType->canDecayToPointerType())
  7659. return;
  7660. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  7661. << LHSNull /* LHS is NULL */ << NonNullType
  7662. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7663. }
  7664. static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
  7665. SourceLocation Loc) {
  7666. const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
  7667. const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
  7668. if (!LUE || !RUE)
  7669. return;
  7670. if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
  7671. RUE->getKind() != UETT_SizeOf)
  7672. return;
  7673. QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
  7674. QualType RHSTy;
  7675. if (RUE->isArgumentType())
  7676. RHSTy = RUE->getArgumentType();
  7677. else
  7678. RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
  7679. if (!LHSTy->isPointerType() || RHSTy->isPointerType())
  7680. return;
  7681. if (LHSTy->getPointeeType() != RHSTy)
  7682. return;
  7683. S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
  7684. }
  7685. static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
  7686. ExprResult &RHS,
  7687. SourceLocation Loc, bool IsDiv) {
  7688. // Check for division/remainder by zero.
  7689. llvm::APSInt RHSValue;
  7690. if (!RHS.get()->isValueDependent() &&
  7691. RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
  7692. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7693. S.PDiag(diag::warn_remainder_division_by_zero)
  7694. << IsDiv << RHS.get()->getSourceRange());
  7695. }
  7696. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  7697. SourceLocation Loc,
  7698. bool IsCompAssign, bool IsDiv) {
  7699. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7700. if (LHS.get()->getType()->isVectorType() ||
  7701. RHS.get()->getType()->isVectorType())
  7702. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7703. /*AllowBothBool*/getLangOpts().AltiVec,
  7704. /*AllowBoolConversions*/false);
  7705. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  7706. if (LHS.isInvalid() || RHS.isInvalid())
  7707. return QualType();
  7708. if (compType.isNull() || !compType->isArithmeticType())
  7709. return InvalidOperands(Loc, LHS, RHS);
  7710. if (IsDiv) {
  7711. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
  7712. DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
  7713. }
  7714. return compType;
  7715. }
  7716. QualType Sema::CheckRemainderOperands(
  7717. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  7718. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7719. if (LHS.get()->getType()->isVectorType() ||
  7720. RHS.get()->getType()->isVectorType()) {
  7721. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  7722. RHS.get()->getType()->hasIntegerRepresentation())
  7723. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7724. /*AllowBothBool*/getLangOpts().AltiVec,
  7725. /*AllowBoolConversions*/false);
  7726. return InvalidOperands(Loc, LHS, RHS);
  7727. }
  7728. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  7729. if (LHS.isInvalid() || RHS.isInvalid())
  7730. return QualType();
  7731. if (compType.isNull() || !compType->isIntegerType())
  7732. return InvalidOperands(Loc, LHS, RHS);
  7733. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
  7734. return compType;
  7735. }
  7736. /// Diagnose invalid arithmetic on two void pointers.
  7737. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  7738. Expr *LHSExpr, Expr *RHSExpr) {
  7739. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7740. ? diag::err_typecheck_pointer_arith_void_type
  7741. : diag::ext_gnu_void_ptr)
  7742. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  7743. << RHSExpr->getSourceRange();
  7744. }
  7745. /// Diagnose invalid arithmetic on a void pointer.
  7746. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  7747. Expr *Pointer) {
  7748. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7749. ? diag::err_typecheck_pointer_arith_void_type
  7750. : diag::ext_gnu_void_ptr)
  7751. << 0 /* one pointer */ << Pointer->getSourceRange();
  7752. }
  7753. /// Diagnose invalid arithmetic on a null pointer.
  7754. ///
  7755. /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
  7756. /// idiom, which we recognize as a GNU extension.
  7757. ///
  7758. static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
  7759. Expr *Pointer, bool IsGNUIdiom) {
  7760. if (IsGNUIdiom)
  7761. S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
  7762. << Pointer->getSourceRange();
  7763. else
  7764. S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
  7765. << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
  7766. }
  7767. /// Diagnose invalid arithmetic on two function pointers.
  7768. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  7769. Expr *LHS, Expr *RHS) {
  7770. assert(LHS->getType()->isAnyPointerType());
  7771. assert(RHS->getType()->isAnyPointerType());
  7772. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7773. ? diag::err_typecheck_pointer_arith_function_type
  7774. : diag::ext_gnu_ptr_func_arith)
  7775. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  7776. // We only show the second type if it differs from the first.
  7777. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  7778. RHS->getType())
  7779. << RHS->getType()->getPointeeType()
  7780. << LHS->getSourceRange() << RHS->getSourceRange();
  7781. }
  7782. /// Diagnose invalid arithmetic on a function pointer.
  7783. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  7784. Expr *Pointer) {
  7785. assert(Pointer->getType()->isAnyPointerType());
  7786. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7787. ? diag::err_typecheck_pointer_arith_function_type
  7788. : diag::ext_gnu_ptr_func_arith)
  7789. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  7790. << 0 /* one pointer, so only one type */
  7791. << Pointer->getSourceRange();
  7792. }
  7793. /// Emit error if Operand is incomplete pointer type
  7794. ///
  7795. /// \returns True if pointer has incomplete type
  7796. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  7797. Expr *Operand) {
  7798. QualType ResType = Operand->getType();
  7799. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  7800. ResType = ResAtomicType->getValueType();
  7801. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  7802. QualType PointeeTy = ResType->getPointeeType();
  7803. return S.RequireCompleteType(Loc, PointeeTy,
  7804. diag::err_typecheck_arithmetic_incomplete_type,
  7805. PointeeTy, Operand->getSourceRange());
  7806. }
  7807. /// Check the validity of an arithmetic pointer operand.
  7808. ///
  7809. /// If the operand has pointer type, this code will check for pointer types
  7810. /// which are invalid in arithmetic operations. These will be diagnosed
  7811. /// appropriately, including whether or not the use is supported as an
  7812. /// extension.
  7813. ///
  7814. /// \returns True when the operand is valid to use (even if as an extension).
  7815. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  7816. Expr *Operand) {
  7817. QualType ResType = Operand->getType();
  7818. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  7819. ResType = ResAtomicType->getValueType();
  7820. if (!ResType->isAnyPointerType()) return true;
  7821. QualType PointeeTy = ResType->getPointeeType();
  7822. if (PointeeTy->isVoidType()) {
  7823. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  7824. return !S.getLangOpts().CPlusPlus;
  7825. }
  7826. if (PointeeTy->isFunctionType()) {
  7827. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  7828. return !S.getLangOpts().CPlusPlus;
  7829. }
  7830. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  7831. return true;
  7832. }
  7833. /// Check the validity of a binary arithmetic operation w.r.t. pointer
  7834. /// operands.
  7835. ///
  7836. /// This routine will diagnose any invalid arithmetic on pointer operands much
  7837. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  7838. /// for emitting a single diagnostic even for operations where both LHS and RHS
  7839. /// are (potentially problematic) pointers.
  7840. ///
  7841. /// \returns True when the operand is valid to use (even if as an extension).
  7842. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  7843. Expr *LHSExpr, Expr *RHSExpr) {
  7844. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  7845. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  7846. if (!isLHSPointer && !isRHSPointer) return true;
  7847. QualType LHSPointeeTy, RHSPointeeTy;
  7848. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  7849. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  7850. // if both are pointers check if operation is valid wrt address spaces
  7851. if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
  7852. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  7853. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  7854. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  7855. S.Diag(Loc,
  7856. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  7857. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  7858. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  7859. return false;
  7860. }
  7861. }
  7862. // Check for arithmetic on pointers to incomplete types.
  7863. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  7864. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  7865. if (isLHSVoidPtr || isRHSVoidPtr) {
  7866. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  7867. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  7868. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  7869. return !S.getLangOpts().CPlusPlus;
  7870. }
  7871. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  7872. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  7873. if (isLHSFuncPtr || isRHSFuncPtr) {
  7874. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  7875. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  7876. RHSExpr);
  7877. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  7878. return !S.getLangOpts().CPlusPlus;
  7879. }
  7880. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  7881. return false;
  7882. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  7883. return false;
  7884. return true;
  7885. }
  7886. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  7887. /// literal.
  7888. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  7889. Expr *LHSExpr, Expr *RHSExpr) {
  7890. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  7891. Expr* IndexExpr = RHSExpr;
  7892. if (!StrExpr) {
  7893. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  7894. IndexExpr = LHSExpr;
  7895. }
  7896. bool IsStringPlusInt = StrExpr &&
  7897. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  7898. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  7899. return;
  7900. llvm::APSInt index;
  7901. if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
  7902. unsigned StrLenWithNull = StrExpr->getLength() + 1;
  7903. if (index.isNonNegative() &&
  7904. index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
  7905. index.isUnsigned()))
  7906. return;
  7907. }
  7908. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  7909. Self.Diag(OpLoc, diag::warn_string_plus_int)
  7910. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  7911. // Only print a fixit for "str" + int, not for int + "str".
  7912. if (IndexExpr == RHSExpr) {
  7913. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  7914. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  7915. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  7916. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  7917. << FixItHint::CreateInsertion(EndLoc, "]");
  7918. } else
  7919. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  7920. }
  7921. /// Emit a warning when adding a char literal to a string.
  7922. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  7923. Expr *LHSExpr, Expr *RHSExpr) {
  7924. const Expr *StringRefExpr = LHSExpr;
  7925. const CharacterLiteral *CharExpr =
  7926. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  7927. if (!CharExpr) {
  7928. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  7929. StringRefExpr = RHSExpr;
  7930. }
  7931. if (!CharExpr || !StringRefExpr)
  7932. return;
  7933. const QualType StringType = StringRefExpr->getType();
  7934. // Return if not a PointerType.
  7935. if (!StringType->isAnyPointerType())
  7936. return;
  7937. // Return if not a CharacterType.
  7938. if (!StringType->getPointeeType()->isAnyCharacterType())
  7939. return;
  7940. ASTContext &Ctx = Self.getASTContext();
  7941. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  7942. const QualType CharType = CharExpr->getType();
  7943. if (!CharType->isAnyCharacterType() &&
  7944. CharType->isIntegerType() &&
  7945. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  7946. Self.Diag(OpLoc, diag::warn_string_plus_char)
  7947. << DiagRange << Ctx.CharTy;
  7948. } else {
  7949. Self.Diag(OpLoc, diag::warn_string_plus_char)
  7950. << DiagRange << CharExpr->getType();
  7951. }
  7952. // Only print a fixit for str + char, not for char + str.
  7953. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  7954. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  7955. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  7956. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  7957. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  7958. << FixItHint::CreateInsertion(EndLoc, "]");
  7959. } else {
  7960. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  7961. }
  7962. }
  7963. /// Emit error when two pointers are incompatible.
  7964. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  7965. Expr *LHSExpr, Expr *RHSExpr) {
  7966. assert(LHSExpr->getType()->isAnyPointerType());
  7967. assert(RHSExpr->getType()->isAnyPointerType());
  7968. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  7969. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  7970. << RHSExpr->getSourceRange();
  7971. }
  7972. // C99 6.5.6
  7973. QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
  7974. SourceLocation Loc, BinaryOperatorKind Opc,
  7975. QualType* CompLHSTy) {
  7976. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7977. if (LHS.get()->getType()->isVectorType() ||
  7978. RHS.get()->getType()->isVectorType()) {
  7979. QualType compType = CheckVectorOperands(
  7980. LHS, RHS, Loc, CompLHSTy,
  7981. /*AllowBothBool*/getLangOpts().AltiVec,
  7982. /*AllowBoolConversions*/getLangOpts().ZVector);
  7983. if (CompLHSTy) *CompLHSTy = compType;
  7984. return compType;
  7985. }
  7986. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  7987. if (LHS.isInvalid() || RHS.isInvalid())
  7988. return QualType();
  7989. // Diagnose "string literal" '+' int and string '+' "char literal".
  7990. if (Opc == BO_Add) {
  7991. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  7992. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  7993. }
  7994. // handle the common case first (both operands are arithmetic).
  7995. if (!compType.isNull() && compType->isArithmeticType()) {
  7996. if (CompLHSTy) *CompLHSTy = compType;
  7997. return compType;
  7998. }
  7999. // Type-checking. Ultimately the pointer's going to be in PExp;
  8000. // note that we bias towards the LHS being the pointer.
  8001. Expr *PExp = LHS.get(), *IExp = RHS.get();
  8002. bool isObjCPointer;
  8003. if (PExp->getType()->isPointerType()) {
  8004. isObjCPointer = false;
  8005. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8006. isObjCPointer = true;
  8007. } else {
  8008. std::swap(PExp, IExp);
  8009. if (PExp->getType()->isPointerType()) {
  8010. isObjCPointer = false;
  8011. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8012. isObjCPointer = true;
  8013. } else {
  8014. return InvalidOperands(Loc, LHS, RHS);
  8015. }
  8016. }
  8017. assert(PExp->getType()->isAnyPointerType());
  8018. if (!IExp->getType()->isIntegerType())
  8019. return InvalidOperands(Loc, LHS, RHS);
  8020. // Adding to a null pointer results in undefined behavior.
  8021. if (PExp->IgnoreParenCasts()->isNullPointerConstant(
  8022. Context, Expr::NPC_ValueDependentIsNotNull)) {
  8023. // In C++ adding zero to a null pointer is defined.
  8024. llvm::APSInt KnownVal;
  8025. if (!getLangOpts().CPlusPlus ||
  8026. (!IExp->isValueDependent() &&
  8027. (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
  8028. // Check the conditions to see if this is the 'p = nullptr + n' idiom.
  8029. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
  8030. Context, BO_Add, PExp, IExp);
  8031. diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
  8032. }
  8033. }
  8034. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  8035. return QualType();
  8036. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  8037. return QualType();
  8038. // Check array bounds for pointer arithemtic
  8039. CheckArrayAccess(PExp, IExp);
  8040. if (CompLHSTy) {
  8041. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  8042. if (LHSTy.isNull()) {
  8043. LHSTy = LHS.get()->getType();
  8044. if (LHSTy->isPromotableIntegerType())
  8045. LHSTy = Context.getPromotedIntegerType(LHSTy);
  8046. }
  8047. *CompLHSTy = LHSTy;
  8048. }
  8049. return PExp->getType();
  8050. }
  8051. // C99 6.5.6
  8052. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  8053. SourceLocation Loc,
  8054. QualType* CompLHSTy) {
  8055. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  8056. if (LHS.get()->getType()->isVectorType() ||
  8057. RHS.get()->getType()->isVectorType()) {
  8058. QualType compType = CheckVectorOperands(
  8059. LHS, RHS, Loc, CompLHSTy,
  8060. /*AllowBothBool*/getLangOpts().AltiVec,
  8061. /*AllowBoolConversions*/getLangOpts().ZVector);
  8062. if (CompLHSTy) *CompLHSTy = compType;
  8063. return compType;
  8064. }
  8065. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  8066. if (LHS.isInvalid() || RHS.isInvalid())
  8067. return QualType();
  8068. // Enforce type constraints: C99 6.5.6p3.
  8069. // Handle the common case first (both operands are arithmetic).
  8070. if (!compType.isNull() && compType->isArithmeticType()) {
  8071. if (CompLHSTy) *CompLHSTy = compType;
  8072. return compType;
  8073. }
  8074. // Either ptr - int or ptr - ptr.
  8075. if (LHS.get()->getType()->isAnyPointerType()) {
  8076. QualType lpointee = LHS.get()->getType()->getPointeeType();
  8077. // Diagnose bad cases where we step over interface counts.
  8078. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  8079. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  8080. return QualType();
  8081. // The result type of a pointer-int computation is the pointer type.
  8082. if (RHS.get()->getType()->isIntegerType()) {
  8083. // Subtracting from a null pointer should produce a warning.
  8084. // The last argument to the diagnose call says this doesn't match the
  8085. // GNU int-to-pointer idiom.
  8086. if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
  8087. Expr::NPC_ValueDependentIsNotNull)) {
  8088. // In C++ adding zero to a null pointer is defined.
  8089. llvm::APSInt KnownVal;
  8090. if (!getLangOpts().CPlusPlus ||
  8091. (!RHS.get()->isValueDependent() &&
  8092. (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
  8093. diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
  8094. }
  8095. }
  8096. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  8097. return QualType();
  8098. // Check array bounds for pointer arithemtic
  8099. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  8100. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  8101. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8102. return LHS.get()->getType();
  8103. }
  8104. // Handle pointer-pointer subtractions.
  8105. if (const PointerType *RHSPTy
  8106. = RHS.get()->getType()->getAs<PointerType>()) {
  8107. QualType rpointee = RHSPTy->getPointeeType();
  8108. if (getLangOpts().CPlusPlus) {
  8109. // Pointee types must be the same: C++ [expr.add]
  8110. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  8111. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8112. }
  8113. } else {
  8114. // Pointee types must be compatible C99 6.5.6p3
  8115. if (!Context.typesAreCompatible(
  8116. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  8117. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  8118. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8119. return QualType();
  8120. }
  8121. }
  8122. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  8123. LHS.get(), RHS.get()))
  8124. return QualType();
  8125. // FIXME: Add warnings for nullptr - ptr.
  8126. // The pointee type may have zero size. As an extension, a structure or
  8127. // union may have zero size or an array may have zero length. In this
  8128. // case subtraction does not make sense.
  8129. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  8130. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  8131. if (ElementSize.isZero()) {
  8132. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  8133. << rpointee.getUnqualifiedType()
  8134. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8135. }
  8136. }
  8137. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8138. return Context.getPointerDiffType();
  8139. }
  8140. }
  8141. return InvalidOperands(Loc, LHS, RHS);
  8142. }
  8143. static bool isScopedEnumerationType(QualType T) {
  8144. if (const EnumType *ET = T->getAs<EnumType>())
  8145. return ET->getDecl()->isScoped();
  8146. return false;
  8147. }
  8148. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  8149. SourceLocation Loc, BinaryOperatorKind Opc,
  8150. QualType LHSType) {
  8151. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  8152. // so skip remaining warnings as we don't want to modify values within Sema.
  8153. if (S.getLangOpts().OpenCL)
  8154. return;
  8155. llvm::APSInt Right;
  8156. // Check right/shifter operand
  8157. if (RHS.get()->isValueDependent() ||
  8158. !RHS.get()->EvaluateAsInt(Right, S.Context))
  8159. return;
  8160. if (Right.isNegative()) {
  8161. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8162. S.PDiag(diag::warn_shift_negative)
  8163. << RHS.get()->getSourceRange());
  8164. return;
  8165. }
  8166. llvm::APInt LeftBits(Right.getBitWidth(),
  8167. S.Context.getTypeSize(LHS.get()->getType()));
  8168. if (Right.uge(LeftBits)) {
  8169. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8170. S.PDiag(diag::warn_shift_gt_typewidth)
  8171. << RHS.get()->getSourceRange());
  8172. return;
  8173. }
  8174. if (Opc != BO_Shl)
  8175. return;
  8176. // When left shifting an ICE which is signed, we can check for overflow which
  8177. // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
  8178. // integers have defined behavior modulo one more than the maximum value
  8179. // representable in the result type, so never warn for those.
  8180. llvm::APSInt Left;
  8181. if (LHS.get()->isValueDependent() ||
  8182. LHSType->hasUnsignedIntegerRepresentation() ||
  8183. !LHS.get()->EvaluateAsInt(Left, S.Context))
  8184. return;
  8185. // If LHS does not have a signed type and non-negative value
  8186. // then, the behavior is undefined. Warn about it.
  8187. if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
  8188. S.DiagRuntimeBehavior(Loc, LHS.get(),
  8189. S.PDiag(diag::warn_shift_lhs_negative)
  8190. << LHS.get()->getSourceRange());
  8191. return;
  8192. }
  8193. llvm::APInt ResultBits =
  8194. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  8195. if (LeftBits.uge(ResultBits))
  8196. return;
  8197. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  8198. Result = Result.shl(Right);
  8199. // Print the bit representation of the signed integer as an unsigned
  8200. // hexadecimal number.
  8201. SmallString<40> HexResult;
  8202. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  8203. // If we are only missing a sign bit, this is less likely to result in actual
  8204. // bugs -- if the result is cast back to an unsigned type, it will have the
  8205. // expected value. Thus we place this behind a different warning that can be
  8206. // turned off separately if needed.
  8207. if (LeftBits == ResultBits - 1) {
  8208. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  8209. << HexResult << LHSType
  8210. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8211. return;
  8212. }
  8213. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  8214. << HexResult.str() << Result.getMinSignedBits() << LHSType
  8215. << Left.getBitWidth() << LHS.get()->getSourceRange()
  8216. << RHS.get()->getSourceRange();
  8217. }
  8218. /// Return the resulting type when a vector is shifted
  8219. /// by a scalar or vector shift amount.
  8220. static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8221. SourceLocation Loc, bool IsCompAssign) {
  8222. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  8223. if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
  8224. !LHS.get()->getType()->isVectorType()) {
  8225. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  8226. << RHS.get()->getType() << LHS.get()->getType()
  8227. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8228. return QualType();
  8229. }
  8230. if (!IsCompAssign) {
  8231. LHS = S.UsualUnaryConversions(LHS.get());
  8232. if (LHS.isInvalid()) return QualType();
  8233. }
  8234. RHS = S.UsualUnaryConversions(RHS.get());
  8235. if (RHS.isInvalid()) return QualType();
  8236. QualType LHSType = LHS.get()->getType();
  8237. // Note that LHS might be a scalar because the routine calls not only in
  8238. // OpenCL case.
  8239. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  8240. QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
  8241. // Note that RHS might not be a vector.
  8242. QualType RHSType = RHS.get()->getType();
  8243. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  8244. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  8245. // The operands need to be integers.
  8246. if (!LHSEleType->isIntegerType()) {
  8247. S.Diag(Loc, diag::err_typecheck_expect_int)
  8248. << LHS.get()->getType() << LHS.get()->getSourceRange();
  8249. return QualType();
  8250. }
  8251. if (!RHSEleType->isIntegerType()) {
  8252. S.Diag(Loc, diag::err_typecheck_expect_int)
  8253. << RHS.get()->getType() << RHS.get()->getSourceRange();
  8254. return QualType();
  8255. }
  8256. if (!LHSVecTy) {
  8257. assert(RHSVecTy);
  8258. if (IsCompAssign)
  8259. return RHSType;
  8260. if (LHSEleType != RHSEleType) {
  8261. LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
  8262. LHSEleType = RHSEleType;
  8263. }
  8264. QualType VecTy =
  8265. S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
  8266. LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
  8267. LHSType = VecTy;
  8268. } else if (RHSVecTy) {
  8269. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  8270. // are applied component-wise. So if RHS is a vector, then ensure
  8271. // that the number of elements is the same as LHS...
  8272. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  8273. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  8274. << LHS.get()->getType() << RHS.get()->getType()
  8275. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8276. return QualType();
  8277. }
  8278. if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
  8279. const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
  8280. const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
  8281. if (LHSBT != RHSBT &&
  8282. S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
  8283. S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
  8284. << LHS.get()->getType() << RHS.get()->getType()
  8285. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8286. }
  8287. }
  8288. } else {
  8289. // ...else expand RHS to match the number of elements in LHS.
  8290. QualType VecTy =
  8291. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  8292. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  8293. }
  8294. return LHSType;
  8295. }
  8296. // C99 6.5.7
  8297. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  8298. SourceLocation Loc, BinaryOperatorKind Opc,
  8299. bool IsCompAssign) {
  8300. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  8301. // Vector shifts promote their scalar inputs to vector type.
  8302. if (LHS.get()->getType()->isVectorType() ||
  8303. RHS.get()->getType()->isVectorType()) {
  8304. if (LangOpts.ZVector) {
  8305. // The shift operators for the z vector extensions work basically
  8306. // like general shifts, except that neither the LHS nor the RHS is
  8307. // allowed to be a "vector bool".
  8308. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  8309. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8310. return InvalidOperands(Loc, LHS, RHS);
  8311. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  8312. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8313. return InvalidOperands(Loc, LHS, RHS);
  8314. }
  8315. return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  8316. }
  8317. // Shifts don't perform usual arithmetic conversions, they just do integer
  8318. // promotions on each operand. C99 6.5.7p3
  8319. // For the LHS, do usual unary conversions, but then reset them away
  8320. // if this is a compound assignment.
  8321. ExprResult OldLHS = LHS;
  8322. LHS = UsualUnaryConversions(LHS.get());
  8323. if (LHS.isInvalid())
  8324. return QualType();
  8325. QualType LHSType = LHS.get()->getType();
  8326. if (IsCompAssign) LHS = OldLHS;
  8327. // The RHS is simpler.
  8328. RHS = UsualUnaryConversions(RHS.get());
  8329. if (RHS.isInvalid())
  8330. return QualType();
  8331. QualType RHSType = RHS.get()->getType();
  8332. // C99 6.5.7p2: Each of the operands shall have integer type.
  8333. if (!LHSType->hasIntegerRepresentation() ||
  8334. !RHSType->hasIntegerRepresentation())
  8335. return InvalidOperands(Loc, LHS, RHS);
  8336. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  8337. // hasIntegerRepresentation() above instead of this.
  8338. if (isScopedEnumerationType(LHSType) ||
  8339. isScopedEnumerationType(RHSType)) {
  8340. return InvalidOperands(Loc, LHS, RHS);
  8341. }
  8342. // Sanity-check shift operands
  8343. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  8344. // "The type of the result is that of the promoted left operand."
  8345. return LHSType;
  8346. }
  8347. /// If two different enums are compared, raise a warning.
  8348. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  8349. Expr *RHS) {
  8350. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  8351. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  8352. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  8353. if (!LHSEnumType)
  8354. return;
  8355. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  8356. if (!RHSEnumType)
  8357. return;
  8358. // Ignore anonymous enums.
  8359. if (!LHSEnumType->getDecl()->getIdentifier() &&
  8360. !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8361. return;
  8362. if (!RHSEnumType->getDecl()->getIdentifier() &&
  8363. !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8364. return;
  8365. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  8366. return;
  8367. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  8368. << LHSStrippedType << RHSStrippedType
  8369. << LHS->getSourceRange() << RHS->getSourceRange();
  8370. }
  8371. /// Diagnose bad pointer comparisons.
  8372. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  8373. ExprResult &LHS, ExprResult &RHS,
  8374. bool IsError) {
  8375. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  8376. : diag::ext_typecheck_comparison_of_distinct_pointers)
  8377. << LHS.get()->getType() << RHS.get()->getType()
  8378. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8379. }
  8380. /// Returns false if the pointers are converted to a composite type,
  8381. /// true otherwise.
  8382. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  8383. ExprResult &LHS, ExprResult &RHS) {
  8384. // C++ [expr.rel]p2:
  8385. // [...] Pointer conversions (4.10) and qualification
  8386. // conversions (4.4) are performed on pointer operands (or on
  8387. // a pointer operand and a null pointer constant) to bring
  8388. // them to their composite pointer type. [...]
  8389. //
  8390. // C++ [expr.eq]p1 uses the same notion for (in)equality
  8391. // comparisons of pointers.
  8392. QualType LHSType = LHS.get()->getType();
  8393. QualType RHSType = RHS.get()->getType();
  8394. assert(LHSType->isPointerType() || RHSType->isPointerType() ||
  8395. LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
  8396. QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
  8397. if (T.isNull()) {
  8398. if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
  8399. (RHSType->isPointerType() || RHSType->isMemberPointerType()))
  8400. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  8401. else
  8402. S.InvalidOperands(Loc, LHS, RHS);
  8403. return true;
  8404. }
  8405. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  8406. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  8407. return false;
  8408. }
  8409. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  8410. ExprResult &LHS,
  8411. ExprResult &RHS,
  8412. bool IsError) {
  8413. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  8414. : diag::ext_typecheck_comparison_of_fptr_to_void)
  8415. << LHS.get()->getType() << RHS.get()->getType()
  8416. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8417. }
  8418. static bool isObjCObjectLiteral(ExprResult &E) {
  8419. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  8420. case Stmt::ObjCArrayLiteralClass:
  8421. case Stmt::ObjCDictionaryLiteralClass:
  8422. case Stmt::ObjCStringLiteralClass:
  8423. case Stmt::ObjCBoxedExprClass:
  8424. return true;
  8425. default:
  8426. // Note that ObjCBoolLiteral is NOT an object literal!
  8427. return false;
  8428. }
  8429. }
  8430. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  8431. const ObjCObjectPointerType *Type =
  8432. LHS->getType()->getAs<ObjCObjectPointerType>();
  8433. // If this is not actually an Objective-C object, bail out.
  8434. if (!Type)
  8435. return false;
  8436. // Get the LHS object's interface type.
  8437. QualType InterfaceType = Type->getPointeeType();
  8438. // If the RHS isn't an Objective-C object, bail out.
  8439. if (!RHS->getType()->isObjCObjectPointerType())
  8440. return false;
  8441. // Try to find the -isEqual: method.
  8442. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  8443. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  8444. InterfaceType,
  8445. /*instance=*/true);
  8446. if (!Method) {
  8447. if (Type->isObjCIdType()) {
  8448. // For 'id', just check the global pool.
  8449. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  8450. /*receiverId=*/true);
  8451. } else {
  8452. // Check protocols.
  8453. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  8454. /*instance=*/true);
  8455. }
  8456. }
  8457. if (!Method)
  8458. return false;
  8459. QualType T = Method->parameters()[0]->getType();
  8460. if (!T->isObjCObjectPointerType())
  8461. return false;
  8462. QualType R = Method->getReturnType();
  8463. if (!R->isScalarType())
  8464. return false;
  8465. return true;
  8466. }
  8467. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  8468. FromE = FromE->IgnoreParenImpCasts();
  8469. switch (FromE->getStmtClass()) {
  8470. default:
  8471. break;
  8472. case Stmt::ObjCStringLiteralClass:
  8473. // "string literal"
  8474. return LK_String;
  8475. case Stmt::ObjCArrayLiteralClass:
  8476. // "array literal"
  8477. return LK_Array;
  8478. case Stmt::ObjCDictionaryLiteralClass:
  8479. // "dictionary literal"
  8480. return LK_Dictionary;
  8481. case Stmt::BlockExprClass:
  8482. return LK_Block;
  8483. case Stmt::ObjCBoxedExprClass: {
  8484. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  8485. switch (Inner->getStmtClass()) {
  8486. case Stmt::IntegerLiteralClass:
  8487. case Stmt::FloatingLiteralClass:
  8488. case Stmt::CharacterLiteralClass:
  8489. case Stmt::ObjCBoolLiteralExprClass:
  8490. case Stmt::CXXBoolLiteralExprClass:
  8491. // "numeric literal"
  8492. return LK_Numeric;
  8493. case Stmt::ImplicitCastExprClass: {
  8494. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  8495. // Boolean literals can be represented by implicit casts.
  8496. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  8497. return LK_Numeric;
  8498. break;
  8499. }
  8500. default:
  8501. break;
  8502. }
  8503. return LK_Boxed;
  8504. }
  8505. }
  8506. return LK_None;
  8507. }
  8508. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  8509. ExprResult &LHS, ExprResult &RHS,
  8510. BinaryOperator::Opcode Opc){
  8511. Expr *Literal;
  8512. Expr *Other;
  8513. if (isObjCObjectLiteral(LHS)) {
  8514. Literal = LHS.get();
  8515. Other = RHS.get();
  8516. } else {
  8517. Literal = RHS.get();
  8518. Other = LHS.get();
  8519. }
  8520. // Don't warn on comparisons against nil.
  8521. Other = Other->IgnoreParenCasts();
  8522. if (Other->isNullPointerConstant(S.getASTContext(),
  8523. Expr::NPC_ValueDependentIsNotNull))
  8524. return;
  8525. // This should be kept in sync with warn_objc_literal_comparison.
  8526. // LK_String should always be after the other literals, since it has its own
  8527. // warning flag.
  8528. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  8529. assert(LiteralKind != Sema::LK_Block);
  8530. if (LiteralKind == Sema::LK_None) {
  8531. llvm_unreachable("Unknown Objective-C object literal kind");
  8532. }
  8533. if (LiteralKind == Sema::LK_String)
  8534. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  8535. << Literal->getSourceRange();
  8536. else
  8537. S.Diag(Loc, diag::warn_objc_literal_comparison)
  8538. << LiteralKind << Literal->getSourceRange();
  8539. if (BinaryOperator::isEqualityOp(Opc) &&
  8540. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  8541. SourceLocation Start = LHS.get()->getBeginLoc();
  8542. SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
  8543. CharSourceRange OpRange =
  8544. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  8545. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  8546. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  8547. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  8548. << FixItHint::CreateInsertion(End, "]");
  8549. }
  8550. }
  8551. /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
  8552. static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
  8553. ExprResult &RHS, SourceLocation Loc,
  8554. BinaryOperatorKind Opc) {
  8555. // Check that left hand side is !something.
  8556. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  8557. if (!UO || UO->getOpcode() != UO_LNot) return;
  8558. // Only check if the right hand side is non-bool arithmetic type.
  8559. if (RHS.get()->isKnownToHaveBooleanValue()) return;
  8560. // Make sure that the something in !something is not bool.
  8561. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  8562. if (SubExpr->isKnownToHaveBooleanValue()) return;
  8563. // Emit warning.
  8564. bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
  8565. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
  8566. << Loc << IsBitwiseOp;
  8567. // First note suggest !(x < y)
  8568. SourceLocation FirstOpen = SubExpr->getBeginLoc();
  8569. SourceLocation FirstClose = RHS.get()->getEndLoc();
  8570. FirstClose = S.getLocForEndOfToken(FirstClose);
  8571. if (FirstClose.isInvalid())
  8572. FirstOpen = SourceLocation();
  8573. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  8574. << IsBitwiseOp
  8575. << FixItHint::CreateInsertion(FirstOpen, "(")
  8576. << FixItHint::CreateInsertion(FirstClose, ")");
  8577. // Second note suggests (!x) < y
  8578. SourceLocation SecondOpen = LHS.get()->getBeginLoc();
  8579. SourceLocation SecondClose = LHS.get()->getEndLoc();
  8580. SecondClose = S.getLocForEndOfToken(SecondClose);
  8581. if (SecondClose.isInvalid())
  8582. SecondOpen = SourceLocation();
  8583. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  8584. << FixItHint::CreateInsertion(SecondOpen, "(")
  8585. << FixItHint::CreateInsertion(SecondClose, ")");
  8586. }
  8587. // Get the decl for a simple expression: a reference to a variable,
  8588. // an implicit C++ field reference, or an implicit ObjC ivar reference.
  8589. static ValueDecl *getCompareDecl(Expr *E) {
  8590. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
  8591. return DR->getDecl();
  8592. if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
  8593. if (Ivar->isFreeIvar())
  8594. return Ivar->getDecl();
  8595. }
  8596. if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
  8597. if (Mem->isImplicitAccess())
  8598. return Mem->getMemberDecl();
  8599. }
  8600. return nullptr;
  8601. }
  8602. /// Diagnose some forms of syntactically-obvious tautological comparison.
  8603. static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
  8604. Expr *LHS, Expr *RHS,
  8605. BinaryOperatorKind Opc) {
  8606. Expr *LHSStripped = LHS->IgnoreParenImpCasts();
  8607. Expr *RHSStripped = RHS->IgnoreParenImpCasts();
  8608. QualType LHSType = LHS->getType();
  8609. QualType RHSType = RHS->getType();
  8610. if (LHSType->hasFloatingRepresentation() ||
  8611. (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
  8612. LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
  8613. S.inTemplateInstantiation())
  8614. return;
  8615. // Comparisons between two array types are ill-formed for operator<=>, so
  8616. // we shouldn't emit any additional warnings about it.
  8617. if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
  8618. return;
  8619. // For non-floating point types, check for self-comparisons of the form
  8620. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  8621. // often indicate logic errors in the program.
  8622. //
  8623. // NOTE: Don't warn about comparison expressions resulting from macro
  8624. // expansion. Also don't warn about comparisons which are only self
  8625. // comparisons within a template instantiation. The warnings should catch
  8626. // obvious cases in the definition of the template anyways. The idea is to
  8627. // warn when the typed comparison operator will always evaluate to the same
  8628. // result.
  8629. ValueDecl *DL = getCompareDecl(LHSStripped);
  8630. ValueDecl *DR = getCompareDecl(RHSStripped);
  8631. if (DL && DR && declaresSameEntity(DL, DR)) {
  8632. StringRef Result;
  8633. switch (Opc) {
  8634. case BO_EQ: case BO_LE: case BO_GE:
  8635. Result = "true";
  8636. break;
  8637. case BO_NE: case BO_LT: case BO_GT:
  8638. Result = "false";
  8639. break;
  8640. case BO_Cmp:
  8641. Result = "'std::strong_ordering::equal'";
  8642. break;
  8643. default:
  8644. break;
  8645. }
  8646. S.DiagRuntimeBehavior(Loc, nullptr,
  8647. S.PDiag(diag::warn_comparison_always)
  8648. << 0 /*self-comparison*/ << !Result.empty()
  8649. << Result);
  8650. } else if (DL && DR &&
  8651. DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
  8652. !DL->isWeak() && !DR->isWeak()) {
  8653. // What is it always going to evaluate to?
  8654. StringRef Result;
  8655. switch(Opc) {
  8656. case BO_EQ: // e.g. array1 == array2
  8657. Result = "false";
  8658. break;
  8659. case BO_NE: // e.g. array1 != array2
  8660. Result = "true";
  8661. break;
  8662. default: // e.g. array1 <= array2
  8663. // The best we can say is 'a constant'
  8664. break;
  8665. }
  8666. S.DiagRuntimeBehavior(Loc, nullptr,
  8667. S.PDiag(diag::warn_comparison_always)
  8668. << 1 /*array comparison*/
  8669. << !Result.empty() << Result);
  8670. }
  8671. if (isa<CastExpr>(LHSStripped))
  8672. LHSStripped = LHSStripped->IgnoreParenCasts();
  8673. if (isa<CastExpr>(RHSStripped))
  8674. RHSStripped = RHSStripped->IgnoreParenCasts();
  8675. // Warn about comparisons against a string constant (unless the other
  8676. // operand is null); the user probably wants strcmp.
  8677. Expr *LiteralString = nullptr;
  8678. Expr *LiteralStringStripped = nullptr;
  8679. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  8680. !RHSStripped->isNullPointerConstant(S.Context,
  8681. Expr::NPC_ValueDependentIsNull)) {
  8682. LiteralString = LHS;
  8683. LiteralStringStripped = LHSStripped;
  8684. } else if ((isa<StringLiteral>(RHSStripped) ||
  8685. isa<ObjCEncodeExpr>(RHSStripped)) &&
  8686. !LHSStripped->isNullPointerConstant(S.Context,
  8687. Expr::NPC_ValueDependentIsNull)) {
  8688. LiteralString = RHS;
  8689. LiteralStringStripped = RHSStripped;
  8690. }
  8691. if (LiteralString) {
  8692. S.DiagRuntimeBehavior(Loc, nullptr,
  8693. S.PDiag(diag::warn_stringcompare)
  8694. << isa<ObjCEncodeExpr>(LiteralStringStripped)
  8695. << LiteralString->getSourceRange());
  8696. }
  8697. }
  8698. static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
  8699. switch (CK) {
  8700. default: {
  8701. #ifndef NDEBUG
  8702. llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
  8703. << "\n";
  8704. #endif
  8705. llvm_unreachable("unhandled cast kind");
  8706. }
  8707. case CK_UserDefinedConversion:
  8708. return ICK_Identity;
  8709. case CK_LValueToRValue:
  8710. return ICK_Lvalue_To_Rvalue;
  8711. case CK_ArrayToPointerDecay:
  8712. return ICK_Array_To_Pointer;
  8713. case CK_FunctionToPointerDecay:
  8714. return ICK_Function_To_Pointer;
  8715. case CK_IntegralCast:
  8716. return ICK_Integral_Conversion;
  8717. case CK_FloatingCast:
  8718. return ICK_Floating_Conversion;
  8719. case CK_IntegralToFloating:
  8720. case CK_FloatingToIntegral:
  8721. return ICK_Floating_Integral;
  8722. case CK_IntegralComplexCast:
  8723. case CK_FloatingComplexCast:
  8724. case CK_FloatingComplexToIntegralComplex:
  8725. case CK_IntegralComplexToFloatingComplex:
  8726. return ICK_Complex_Conversion;
  8727. case CK_FloatingComplexToReal:
  8728. case CK_FloatingRealToComplex:
  8729. case CK_IntegralComplexToReal:
  8730. case CK_IntegralRealToComplex:
  8731. return ICK_Complex_Real;
  8732. }
  8733. }
  8734. static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
  8735. QualType FromType,
  8736. SourceLocation Loc) {
  8737. // Check for a narrowing implicit conversion.
  8738. StandardConversionSequence SCS;
  8739. SCS.setAsIdentityConversion();
  8740. SCS.setToType(0, FromType);
  8741. SCS.setToType(1, ToType);
  8742. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  8743. SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
  8744. APValue PreNarrowingValue;
  8745. QualType PreNarrowingType;
  8746. switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
  8747. PreNarrowingType,
  8748. /*IgnoreFloatToIntegralConversion*/ true)) {
  8749. case NK_Dependent_Narrowing:
  8750. // Implicit conversion to a narrower type, but the expression is
  8751. // value-dependent so we can't tell whether it's actually narrowing.
  8752. case NK_Not_Narrowing:
  8753. return false;
  8754. case NK_Constant_Narrowing:
  8755. // Implicit conversion to a narrower type, and the value is not a constant
  8756. // expression.
  8757. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  8758. << /*Constant*/ 1
  8759. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
  8760. return true;
  8761. case NK_Variable_Narrowing:
  8762. // Implicit conversion to a narrower type, and the value is not a constant
  8763. // expression.
  8764. case NK_Type_Narrowing:
  8765. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  8766. << /*Constant*/ 0 << FromType << ToType;
  8767. // TODO: It's not a constant expression, but what if the user intended it
  8768. // to be? Can we produce notes to help them figure out why it isn't?
  8769. return true;
  8770. }
  8771. llvm_unreachable("unhandled case in switch");
  8772. }
  8773. static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
  8774. ExprResult &LHS,
  8775. ExprResult &RHS,
  8776. SourceLocation Loc) {
  8777. using CCT = ComparisonCategoryType;
  8778. QualType LHSType = LHS.get()->getType();
  8779. QualType RHSType = RHS.get()->getType();
  8780. // Dig out the original argument type and expression before implicit casts
  8781. // were applied. These are the types/expressions we need to check the
  8782. // [expr.spaceship] requirements against.
  8783. ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
  8784. ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
  8785. QualType LHSStrippedType = LHSStripped.get()->getType();
  8786. QualType RHSStrippedType = RHSStripped.get()->getType();
  8787. // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
  8788. // other is not, the program is ill-formed.
  8789. if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
  8790. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  8791. return QualType();
  8792. }
  8793. int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
  8794. RHSStrippedType->isEnumeralType();
  8795. if (NumEnumArgs == 1) {
  8796. bool LHSIsEnum = LHSStrippedType->isEnumeralType();
  8797. QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
  8798. if (OtherTy->hasFloatingRepresentation()) {
  8799. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  8800. return QualType();
  8801. }
  8802. }
  8803. if (NumEnumArgs == 2) {
  8804. // C++2a [expr.spaceship]p5: If both operands have the same enumeration
  8805. // type E, the operator yields the result of converting the operands
  8806. // to the underlying type of E and applying <=> to the converted operands.
  8807. if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
  8808. S.InvalidOperands(Loc, LHS, RHS);
  8809. return QualType();
  8810. }
  8811. QualType IntType =
  8812. LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
  8813. assert(IntType->isArithmeticType());
  8814. // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
  8815. // promote the boolean type, and all other promotable integer types, to
  8816. // avoid this.
  8817. if (IntType->isPromotableIntegerType())
  8818. IntType = S.Context.getPromotedIntegerType(IntType);
  8819. LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
  8820. RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
  8821. LHSType = RHSType = IntType;
  8822. }
  8823. // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
  8824. // usual arithmetic conversions are applied to the operands.
  8825. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  8826. if (LHS.isInvalid() || RHS.isInvalid())
  8827. return QualType();
  8828. if (Type.isNull())
  8829. return S.InvalidOperands(Loc, LHS, RHS);
  8830. assert(Type->isArithmeticType() || Type->isEnumeralType());
  8831. bool HasNarrowing = checkThreeWayNarrowingConversion(
  8832. S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
  8833. HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
  8834. RHS.get()->getBeginLoc());
  8835. if (HasNarrowing)
  8836. return QualType();
  8837. assert(!Type.isNull() && "composite type for <=> has not been set");
  8838. auto TypeKind = [&]() {
  8839. if (const ComplexType *CT = Type->getAs<ComplexType>()) {
  8840. if (CT->getElementType()->hasFloatingRepresentation())
  8841. return CCT::WeakEquality;
  8842. return CCT::StrongEquality;
  8843. }
  8844. if (Type->isIntegralOrEnumerationType())
  8845. return CCT::StrongOrdering;
  8846. if (Type->hasFloatingRepresentation())
  8847. return CCT::PartialOrdering;
  8848. llvm_unreachable("other types are unimplemented");
  8849. }();
  8850. return S.CheckComparisonCategoryType(TypeKind, Loc);
  8851. }
  8852. static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
  8853. ExprResult &RHS,
  8854. SourceLocation Loc,
  8855. BinaryOperatorKind Opc) {
  8856. if (Opc == BO_Cmp)
  8857. return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
  8858. // C99 6.5.8p3 / C99 6.5.9p4
  8859. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  8860. if (LHS.isInvalid() || RHS.isInvalid())
  8861. return QualType();
  8862. if (Type.isNull())
  8863. return S.InvalidOperands(Loc, LHS, RHS);
  8864. assert(Type->isArithmeticType() || Type->isEnumeralType());
  8865. checkEnumComparison(S, Loc, LHS.get(), RHS.get());
  8866. if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
  8867. return S.InvalidOperands(Loc, LHS, RHS);
  8868. // Check for comparisons of floating point operands using != and ==.
  8869. if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
  8870. S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
  8871. // The result of comparisons is 'bool' in C++, 'int' in C.
  8872. return S.Context.getLogicalOperationType();
  8873. }
  8874. // C99 6.5.8, C++ [expr.rel]
  8875. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  8876. SourceLocation Loc,
  8877. BinaryOperatorKind Opc) {
  8878. bool IsRelational = BinaryOperator::isRelationalOp(Opc);
  8879. bool IsThreeWay = Opc == BO_Cmp;
  8880. auto IsAnyPointerType = [](ExprResult E) {
  8881. QualType Ty = E.get()->getType();
  8882. return Ty->isPointerType() || Ty->isMemberPointerType();
  8883. };
  8884. // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
  8885. // type, array-to-pointer, ..., conversions are performed on both operands to
  8886. // bring them to their composite type.
  8887. // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
  8888. // any type-related checks.
  8889. if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
  8890. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  8891. if (LHS.isInvalid())
  8892. return QualType();
  8893. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  8894. if (RHS.isInvalid())
  8895. return QualType();
  8896. } else {
  8897. LHS = DefaultLvalueConversion(LHS.get());
  8898. if (LHS.isInvalid())
  8899. return QualType();
  8900. RHS = DefaultLvalueConversion(RHS.get());
  8901. if (RHS.isInvalid())
  8902. return QualType();
  8903. }
  8904. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
  8905. // Handle vector comparisons separately.
  8906. if (LHS.get()->getType()->isVectorType() ||
  8907. RHS.get()->getType()->isVectorType())
  8908. return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
  8909. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  8910. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  8911. QualType LHSType = LHS.get()->getType();
  8912. QualType RHSType = RHS.get()->getType();
  8913. if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
  8914. (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
  8915. return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
  8916. const Expr::NullPointerConstantKind LHSNullKind =
  8917. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  8918. const Expr::NullPointerConstantKind RHSNullKind =
  8919. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  8920. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  8921. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  8922. auto computeResultTy = [&]() {
  8923. if (Opc != BO_Cmp)
  8924. return Context.getLogicalOperationType();
  8925. assert(getLangOpts().CPlusPlus);
  8926. assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
  8927. QualType CompositeTy = LHS.get()->getType();
  8928. assert(!CompositeTy->isReferenceType());
  8929. auto buildResultTy = [&](ComparisonCategoryType Kind) {
  8930. return CheckComparisonCategoryType(Kind, Loc);
  8931. };
  8932. // C++2a [expr.spaceship]p7: If the composite pointer type is a function
  8933. // pointer type, a pointer-to-member type, or std::nullptr_t, the
  8934. // result is of type std::strong_equality
  8935. if (CompositeTy->isFunctionPointerType() ||
  8936. CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
  8937. // FIXME: consider making the function pointer case produce
  8938. // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
  8939. // and direction polls
  8940. return buildResultTy(ComparisonCategoryType::StrongEquality);
  8941. // C++2a [expr.spaceship]p8: If the composite pointer type is an object
  8942. // pointer type, p <=> q is of type std::strong_ordering.
  8943. if (CompositeTy->isPointerType()) {
  8944. // P0946R0: Comparisons between a null pointer constant and an object
  8945. // pointer result in std::strong_equality
  8946. if (LHSIsNull != RHSIsNull)
  8947. return buildResultTy(ComparisonCategoryType::StrongEquality);
  8948. return buildResultTy(ComparisonCategoryType::StrongOrdering);
  8949. }
  8950. // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
  8951. // TODO: Extend support for operator<=> to ObjC types.
  8952. return InvalidOperands(Loc, LHS, RHS);
  8953. };
  8954. if (!IsRelational && LHSIsNull != RHSIsNull) {
  8955. bool IsEquality = Opc == BO_EQ;
  8956. if (RHSIsNull)
  8957. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  8958. RHS.get()->getSourceRange());
  8959. else
  8960. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  8961. LHS.get()->getSourceRange());
  8962. }
  8963. if ((LHSType->isIntegerType() && !LHSIsNull) ||
  8964. (RHSType->isIntegerType() && !RHSIsNull)) {
  8965. // Skip normal pointer conversion checks in this case; we have better
  8966. // diagnostics for this below.
  8967. } else if (getLangOpts().CPlusPlus) {
  8968. // Equality comparison of a function pointer to a void pointer is invalid,
  8969. // but we allow it as an extension.
  8970. // FIXME: If we really want to allow this, should it be part of composite
  8971. // pointer type computation so it works in conditionals too?
  8972. if (!IsRelational &&
  8973. ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
  8974. (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
  8975. // This is a gcc extension compatibility comparison.
  8976. // In a SFINAE context, we treat this as a hard error to maintain
  8977. // conformance with the C++ standard.
  8978. diagnoseFunctionPointerToVoidComparison(
  8979. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  8980. if (isSFINAEContext())
  8981. return QualType();
  8982. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  8983. return computeResultTy();
  8984. }
  8985. // C++ [expr.eq]p2:
  8986. // If at least one operand is a pointer [...] bring them to their
  8987. // composite pointer type.
  8988. // C++ [expr.spaceship]p6
  8989. // If at least one of the operands is of pointer type, [...] bring them
  8990. // to their composite pointer type.
  8991. // C++ [expr.rel]p2:
  8992. // If both operands are pointers, [...] bring them to their composite
  8993. // pointer type.
  8994. if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
  8995. (IsRelational ? 2 : 1) &&
  8996. (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
  8997. RHSType->isObjCObjectPointerType()))) {
  8998. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  8999. return QualType();
  9000. return computeResultTy();
  9001. }
  9002. } else if (LHSType->isPointerType() &&
  9003. RHSType->isPointerType()) { // C99 6.5.8p2
  9004. // All of the following pointer-related warnings are GCC extensions, except
  9005. // when handling null pointer constants.
  9006. QualType LCanPointeeTy =
  9007. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9008. QualType RCanPointeeTy =
  9009. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9010. // C99 6.5.9p2 and C99 6.5.8p2
  9011. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  9012. RCanPointeeTy.getUnqualifiedType())) {
  9013. // Valid unless a relational comparison of function pointers
  9014. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  9015. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  9016. << LHSType << RHSType << LHS.get()->getSourceRange()
  9017. << RHS.get()->getSourceRange();
  9018. }
  9019. } else if (!IsRelational &&
  9020. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  9021. // Valid unless comparison between non-null pointer and function pointer
  9022. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  9023. && !LHSIsNull && !RHSIsNull)
  9024. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  9025. /*isError*/false);
  9026. } else {
  9027. // Invalid
  9028. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  9029. }
  9030. if (LCanPointeeTy != RCanPointeeTy) {
  9031. // Treat NULL constant as a special case in OpenCL.
  9032. if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
  9033. const PointerType *LHSPtr = LHSType->getAs<PointerType>();
  9034. if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  9035. Diag(Loc,
  9036. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  9037. << LHSType << RHSType << 0 /* comparison */
  9038. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9039. }
  9040. }
  9041. LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
  9042. LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
  9043. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  9044. : CK_BitCast;
  9045. if (LHSIsNull && !RHSIsNull)
  9046. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  9047. else
  9048. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  9049. }
  9050. return computeResultTy();
  9051. }
  9052. if (getLangOpts().CPlusPlus) {
  9053. // C++ [expr.eq]p4:
  9054. // Two operands of type std::nullptr_t or one operand of type
  9055. // std::nullptr_t and the other a null pointer constant compare equal.
  9056. if (!IsRelational && LHSIsNull && RHSIsNull) {
  9057. if (LHSType->isNullPtrType()) {
  9058. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9059. return computeResultTy();
  9060. }
  9061. if (RHSType->isNullPtrType()) {
  9062. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9063. return computeResultTy();
  9064. }
  9065. }
  9066. // Comparison of Objective-C pointers and block pointers against nullptr_t.
  9067. // These aren't covered by the composite pointer type rules.
  9068. if (!IsRelational && RHSType->isNullPtrType() &&
  9069. (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
  9070. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9071. return computeResultTy();
  9072. }
  9073. if (!IsRelational && LHSType->isNullPtrType() &&
  9074. (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
  9075. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9076. return computeResultTy();
  9077. }
  9078. if (IsRelational &&
  9079. ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
  9080. (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
  9081. // HACK: Relational comparison of nullptr_t against a pointer type is
  9082. // invalid per DR583, but we allow it within std::less<> and friends,
  9083. // since otherwise common uses of it break.
  9084. // FIXME: Consider removing this hack once LWG fixes std::less<> and
  9085. // friends to have std::nullptr_t overload candidates.
  9086. DeclContext *DC = CurContext;
  9087. if (isa<FunctionDecl>(DC))
  9088. DC = DC->getParent();
  9089. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  9090. if (CTSD->isInStdNamespace() &&
  9091. llvm::StringSwitch<bool>(CTSD->getName())
  9092. .Cases("less", "less_equal", "greater", "greater_equal", true)
  9093. .Default(false)) {
  9094. if (RHSType->isNullPtrType())
  9095. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9096. else
  9097. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9098. return computeResultTy();
  9099. }
  9100. }
  9101. }
  9102. // C++ [expr.eq]p2:
  9103. // If at least one operand is a pointer to member, [...] bring them to
  9104. // their composite pointer type.
  9105. if (!IsRelational &&
  9106. (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
  9107. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  9108. return QualType();
  9109. else
  9110. return computeResultTy();
  9111. }
  9112. }
  9113. // Handle block pointer types.
  9114. if (!IsRelational && LHSType->isBlockPointerType() &&
  9115. RHSType->isBlockPointerType()) {
  9116. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  9117. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  9118. if (!LHSIsNull && !RHSIsNull &&
  9119. !Context.typesAreCompatible(lpointee, rpointee)) {
  9120. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9121. << LHSType << RHSType << LHS.get()->getSourceRange()
  9122. << RHS.get()->getSourceRange();
  9123. }
  9124. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9125. return computeResultTy();
  9126. }
  9127. // Allow block pointers to be compared with null pointer constants.
  9128. if (!IsRelational
  9129. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  9130. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  9131. if (!LHSIsNull && !RHSIsNull) {
  9132. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  9133. ->getPointeeType()->isVoidType())
  9134. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  9135. ->getPointeeType()->isVoidType())))
  9136. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9137. << LHSType << RHSType << LHS.get()->getSourceRange()
  9138. << RHS.get()->getSourceRange();
  9139. }
  9140. if (LHSIsNull && !RHSIsNull)
  9141. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9142. RHSType->isPointerType() ? CK_BitCast
  9143. : CK_AnyPointerToBlockPointerCast);
  9144. else
  9145. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9146. LHSType->isPointerType() ? CK_BitCast
  9147. : CK_AnyPointerToBlockPointerCast);
  9148. return computeResultTy();
  9149. }
  9150. if (LHSType->isObjCObjectPointerType() ||
  9151. RHSType->isObjCObjectPointerType()) {
  9152. const PointerType *LPT = LHSType->getAs<PointerType>();
  9153. const PointerType *RPT = RHSType->getAs<PointerType>();
  9154. if (LPT || RPT) {
  9155. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  9156. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  9157. if (!LPtrToVoid && !RPtrToVoid &&
  9158. !Context.typesAreCompatible(LHSType, RHSType)) {
  9159. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9160. /*isError*/false);
  9161. }
  9162. if (LHSIsNull && !RHSIsNull) {
  9163. Expr *E = LHS.get();
  9164. if (getLangOpts().ObjCAutoRefCount)
  9165. CheckObjCConversion(SourceRange(), RHSType, E,
  9166. CCK_ImplicitConversion);
  9167. LHS = ImpCastExprToType(E, RHSType,
  9168. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9169. }
  9170. else {
  9171. Expr *E = RHS.get();
  9172. if (getLangOpts().ObjCAutoRefCount)
  9173. CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
  9174. /*Diagnose=*/true,
  9175. /*DiagnoseCFAudited=*/false, Opc);
  9176. RHS = ImpCastExprToType(E, LHSType,
  9177. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9178. }
  9179. return computeResultTy();
  9180. }
  9181. if (LHSType->isObjCObjectPointerType() &&
  9182. RHSType->isObjCObjectPointerType()) {
  9183. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  9184. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9185. /*isError*/false);
  9186. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  9187. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  9188. if (LHSIsNull && !RHSIsNull)
  9189. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  9190. else
  9191. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9192. return computeResultTy();
  9193. }
  9194. if (!IsRelational && LHSType->isBlockPointerType() &&
  9195. RHSType->isBlockCompatibleObjCPointerType(Context)) {
  9196. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9197. CK_BlockPointerToObjCPointerCast);
  9198. return computeResultTy();
  9199. } else if (!IsRelational &&
  9200. LHSType->isBlockCompatibleObjCPointerType(Context) &&
  9201. RHSType->isBlockPointerType()) {
  9202. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9203. CK_BlockPointerToObjCPointerCast);
  9204. return computeResultTy();
  9205. }
  9206. }
  9207. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  9208. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  9209. unsigned DiagID = 0;
  9210. bool isError = false;
  9211. if (LangOpts.DebuggerSupport) {
  9212. // Under a debugger, allow the comparison of pointers to integers,
  9213. // since users tend to want to compare addresses.
  9214. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  9215. (RHSIsNull && RHSType->isIntegerType())) {
  9216. if (IsRelational) {
  9217. isError = getLangOpts().CPlusPlus;
  9218. DiagID =
  9219. isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
  9220. : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  9221. }
  9222. } else if (getLangOpts().CPlusPlus) {
  9223. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  9224. isError = true;
  9225. } else if (IsRelational)
  9226. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  9227. else
  9228. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  9229. if (DiagID) {
  9230. Diag(Loc, DiagID)
  9231. << LHSType << RHSType << LHS.get()->getSourceRange()
  9232. << RHS.get()->getSourceRange();
  9233. if (isError)
  9234. return QualType();
  9235. }
  9236. if (LHSType->isIntegerType())
  9237. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9238. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9239. else
  9240. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9241. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9242. return computeResultTy();
  9243. }
  9244. // Handle block pointers.
  9245. if (!IsRelational && RHSIsNull
  9246. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  9247. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9248. return computeResultTy();
  9249. }
  9250. if (!IsRelational && LHSIsNull
  9251. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  9252. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9253. return computeResultTy();
  9254. }
  9255. if (getLangOpts().OpenCLVersion >= 200) {
  9256. if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
  9257. return computeResultTy();
  9258. }
  9259. if (LHSType->isQueueT() && RHSType->isQueueT()) {
  9260. return computeResultTy();
  9261. }
  9262. if (LHSIsNull && RHSType->isQueueT()) {
  9263. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9264. return computeResultTy();
  9265. }
  9266. if (LHSType->isQueueT() && RHSIsNull) {
  9267. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9268. return computeResultTy();
  9269. }
  9270. }
  9271. return InvalidOperands(Loc, LHS, RHS);
  9272. }
  9273. // Return a signed ext_vector_type that is of identical size and number of
  9274. // elements. For floating point vectors, return an integer type of identical
  9275. // size and number of elements. In the non ext_vector_type case, search from
  9276. // the largest type to the smallest type to avoid cases where long long == long,
  9277. // where long gets picked over long long.
  9278. QualType Sema::GetSignedVectorType(QualType V) {
  9279. const VectorType *VTy = V->getAs<VectorType>();
  9280. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  9281. if (isa<ExtVectorType>(VTy)) {
  9282. if (TypeSize == Context.getTypeSize(Context.CharTy))
  9283. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  9284. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9285. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  9286. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9287. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  9288. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9289. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  9290. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  9291. "Unhandled vector element size in vector compare");
  9292. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  9293. }
  9294. if (TypeSize == Context.getTypeSize(Context.LongLongTy))
  9295. return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
  9296. VectorType::GenericVector);
  9297. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9298. return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
  9299. VectorType::GenericVector);
  9300. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9301. return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
  9302. VectorType::GenericVector);
  9303. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9304. return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
  9305. VectorType::GenericVector);
  9306. assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
  9307. "Unhandled vector element size in vector compare");
  9308. return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
  9309. VectorType::GenericVector);
  9310. }
  9311. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  9312. /// operates on extended vector types. Instead of producing an IntTy result,
  9313. /// like a scalar comparison, a vector comparison produces a vector of integer
  9314. /// types.
  9315. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9316. SourceLocation Loc,
  9317. BinaryOperatorKind Opc) {
  9318. // Check to make sure we're operating on vectors of the same type and width,
  9319. // Allowing one side to be a scalar of element type.
  9320. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  9321. /*AllowBothBool*/true,
  9322. /*AllowBoolConversions*/getLangOpts().ZVector);
  9323. if (vType.isNull())
  9324. return vType;
  9325. QualType LHSType = LHS.get()->getType();
  9326. // If AltiVec, the comparison results in a numeric type, i.e.
  9327. // bool for C++, int for C
  9328. if (getLangOpts().AltiVec &&
  9329. vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  9330. return Context.getLogicalOperationType();
  9331. // For non-floating point types, check for self-comparisons of the form
  9332. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  9333. // often indicate logic errors in the program.
  9334. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9335. // Check for comparisons of floating point operands using != and ==.
  9336. if (BinaryOperator::isEqualityOp(Opc) &&
  9337. LHSType->hasFloatingRepresentation()) {
  9338. assert(RHS.get()->getType()->hasFloatingRepresentation());
  9339. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9340. }
  9341. // Return a signed type for the vector.
  9342. return GetSignedVectorType(vType);
  9343. }
  9344. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9345. SourceLocation Loc) {
  9346. // Ensure that either both operands are of the same vector type, or
  9347. // one operand is of a vector type and the other is of its element type.
  9348. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  9349. /*AllowBothBool*/true,
  9350. /*AllowBoolConversions*/false);
  9351. if (vType.isNull())
  9352. return InvalidOperands(Loc, LHS, RHS);
  9353. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  9354. vType->hasFloatingRepresentation())
  9355. return InvalidOperands(Loc, LHS, RHS);
  9356. // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
  9357. // usage of the logical operators && and || with vectors in C. This
  9358. // check could be notionally dropped.
  9359. if (!getLangOpts().CPlusPlus &&
  9360. !(isa<ExtVectorType>(vType->getAs<VectorType>())))
  9361. return InvalidLogicalVectorOperands(Loc, LHS, RHS);
  9362. return GetSignedVectorType(LHS.get()->getType());
  9363. }
  9364. inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
  9365. SourceLocation Loc,
  9366. BinaryOperatorKind Opc) {
  9367. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  9368. bool IsCompAssign =
  9369. Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
  9370. if (LHS.get()->getType()->isVectorType() ||
  9371. RHS.get()->getType()->isVectorType()) {
  9372. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  9373. RHS.get()->getType()->hasIntegerRepresentation())
  9374. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9375. /*AllowBothBool*/true,
  9376. /*AllowBoolConversions*/getLangOpts().ZVector);
  9377. return InvalidOperands(Loc, LHS, RHS);
  9378. }
  9379. if (Opc == BO_And)
  9380. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9381. ExprResult LHSResult = LHS, RHSResult = RHS;
  9382. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  9383. IsCompAssign);
  9384. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  9385. return QualType();
  9386. LHS = LHSResult.get();
  9387. RHS = RHSResult.get();
  9388. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  9389. return compType;
  9390. return InvalidOperands(Loc, LHS, RHS);
  9391. }
  9392. // C99 6.5.[13,14]
  9393. inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9394. SourceLocation Loc,
  9395. BinaryOperatorKind Opc) {
  9396. // Check vector operands differently.
  9397. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  9398. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  9399. // Diagnose cases where the user write a logical and/or but probably meant a
  9400. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  9401. // is a constant.
  9402. if (LHS.get()->getType()->isIntegerType() &&
  9403. !LHS.get()->getType()->isBooleanType() &&
  9404. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  9405. // Don't warn in macros or template instantiations.
  9406. !Loc.isMacroID() && !inTemplateInstantiation()) {
  9407. // If the RHS can be constant folded, and if it constant folds to something
  9408. // that isn't 0 or 1 (which indicate a potential logical operation that
  9409. // happened to fold to true/false) then warn.
  9410. // Parens on the RHS are ignored.
  9411. llvm::APSInt Result;
  9412. if (RHS.get()->EvaluateAsInt(Result, Context))
  9413. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  9414. !RHS.get()->getExprLoc().isMacroID()) ||
  9415. (Result != 0 && Result != 1)) {
  9416. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  9417. << RHS.get()->getSourceRange()
  9418. << (Opc == BO_LAnd ? "&&" : "||");
  9419. // Suggest replacing the logical operator with the bitwise version
  9420. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  9421. << (Opc == BO_LAnd ? "&" : "|")
  9422. << FixItHint::CreateReplacement(SourceRange(
  9423. Loc, getLocForEndOfToken(Loc)),
  9424. Opc == BO_LAnd ? "&" : "|");
  9425. if (Opc == BO_LAnd)
  9426. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  9427. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  9428. << FixItHint::CreateRemoval(
  9429. SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
  9430. RHS.get()->getEndLoc()));
  9431. }
  9432. }
  9433. if (!Context.getLangOpts().CPlusPlus) {
  9434. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  9435. // not operate on the built-in scalar and vector float types.
  9436. if (Context.getLangOpts().OpenCL &&
  9437. Context.getLangOpts().OpenCLVersion < 120) {
  9438. if (LHS.get()->getType()->isFloatingType() ||
  9439. RHS.get()->getType()->isFloatingType())
  9440. return InvalidOperands(Loc, LHS, RHS);
  9441. }
  9442. LHS = UsualUnaryConversions(LHS.get());
  9443. if (LHS.isInvalid())
  9444. return QualType();
  9445. RHS = UsualUnaryConversions(RHS.get());
  9446. if (RHS.isInvalid())
  9447. return QualType();
  9448. if (!LHS.get()->getType()->isScalarType() ||
  9449. !RHS.get()->getType()->isScalarType())
  9450. return InvalidOperands(Loc, LHS, RHS);
  9451. return Context.IntTy;
  9452. }
  9453. // The following is safe because we only use this method for
  9454. // non-overloadable operands.
  9455. // C++ [expr.log.and]p1
  9456. // C++ [expr.log.or]p1
  9457. // The operands are both contextually converted to type bool.
  9458. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  9459. if (LHSRes.isInvalid())
  9460. return InvalidOperands(Loc, LHS, RHS);
  9461. LHS = LHSRes;
  9462. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  9463. if (RHSRes.isInvalid())
  9464. return InvalidOperands(Loc, LHS, RHS);
  9465. RHS = RHSRes;
  9466. // C++ [expr.log.and]p2
  9467. // C++ [expr.log.or]p2
  9468. // The result is a bool.
  9469. return Context.BoolTy;
  9470. }
  9471. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  9472. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  9473. if (!ME) return false;
  9474. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  9475. ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
  9476. ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
  9477. if (!Base) return false;
  9478. return Base->getMethodDecl() != nullptr;
  9479. }
  9480. /// Is the given expression (which must be 'const') a reference to a
  9481. /// variable which was originally non-const, but which has become
  9482. /// 'const' due to being captured within a block?
  9483. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  9484. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  9485. assert(E->isLValue() && E->getType().isConstQualified());
  9486. E = E->IgnoreParens();
  9487. // Must be a reference to a declaration from an enclosing scope.
  9488. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  9489. if (!DRE) return NCCK_None;
  9490. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  9491. // The declaration must be a variable which is not declared 'const'.
  9492. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  9493. if (!var) return NCCK_None;
  9494. if (var->getType().isConstQualified()) return NCCK_None;
  9495. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  9496. // Decide whether the first capture was for a block or a lambda.
  9497. DeclContext *DC = S.CurContext, *Prev = nullptr;
  9498. // Decide whether the first capture was for a block or a lambda.
  9499. while (DC) {
  9500. // For init-capture, it is possible that the variable belongs to the
  9501. // template pattern of the current context.
  9502. if (auto *FD = dyn_cast<FunctionDecl>(DC))
  9503. if (var->isInitCapture() &&
  9504. FD->getTemplateInstantiationPattern() == var->getDeclContext())
  9505. break;
  9506. if (DC == var->getDeclContext())
  9507. break;
  9508. Prev = DC;
  9509. DC = DC->getParent();
  9510. }
  9511. // Unless we have an init-capture, we've gone one step too far.
  9512. if (!var->isInitCapture())
  9513. DC = Prev;
  9514. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  9515. }
  9516. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  9517. Ty = Ty.getNonReferenceType();
  9518. if (IsDereference && Ty->isPointerType())
  9519. Ty = Ty->getPointeeType();
  9520. return !Ty.isConstQualified();
  9521. }
  9522. // Update err_typecheck_assign_const and note_typecheck_assign_const
  9523. // when this enum is changed.
  9524. enum {
  9525. ConstFunction,
  9526. ConstVariable,
  9527. ConstMember,
  9528. ConstMethod,
  9529. NestedConstMember,
  9530. ConstUnknown, // Keep as last element
  9531. };
  9532. /// Emit the "read-only variable not assignable" error and print notes to give
  9533. /// more information about why the variable is not assignable, such as pointing
  9534. /// to the declaration of a const variable, showing that a method is const, or
  9535. /// that the function is returning a const reference.
  9536. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  9537. SourceLocation Loc) {
  9538. SourceRange ExprRange = E->getSourceRange();
  9539. // Only emit one error on the first const found. All other consts will emit
  9540. // a note to the error.
  9541. bool DiagnosticEmitted = false;
  9542. // Track if the current expression is the result of a dereference, and if the
  9543. // next checked expression is the result of a dereference.
  9544. bool IsDereference = false;
  9545. bool NextIsDereference = false;
  9546. // Loop to process MemberExpr chains.
  9547. while (true) {
  9548. IsDereference = NextIsDereference;
  9549. E = E->IgnoreImplicit()->IgnoreParenImpCasts();
  9550. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  9551. NextIsDereference = ME->isArrow();
  9552. const ValueDecl *VD = ME->getMemberDecl();
  9553. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  9554. // Mutable fields can be modified even if the class is const.
  9555. if (Field->isMutable()) {
  9556. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  9557. break;
  9558. }
  9559. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  9560. if (!DiagnosticEmitted) {
  9561. S.Diag(Loc, diag::err_typecheck_assign_const)
  9562. << ExprRange << ConstMember << false /*static*/ << Field
  9563. << Field->getType();
  9564. DiagnosticEmitted = true;
  9565. }
  9566. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9567. << ConstMember << false /*static*/ << Field << Field->getType()
  9568. << Field->getSourceRange();
  9569. }
  9570. E = ME->getBase();
  9571. continue;
  9572. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  9573. if (VDecl->getType().isConstQualified()) {
  9574. if (!DiagnosticEmitted) {
  9575. S.Diag(Loc, diag::err_typecheck_assign_const)
  9576. << ExprRange << ConstMember << true /*static*/ << VDecl
  9577. << VDecl->getType();
  9578. DiagnosticEmitted = true;
  9579. }
  9580. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9581. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  9582. << VDecl->getSourceRange();
  9583. }
  9584. // Static fields do not inherit constness from parents.
  9585. break;
  9586. }
  9587. break; // End MemberExpr
  9588. } else if (const ArraySubscriptExpr *ASE =
  9589. dyn_cast<ArraySubscriptExpr>(E)) {
  9590. E = ASE->getBase()->IgnoreParenImpCasts();
  9591. continue;
  9592. } else if (const ExtVectorElementExpr *EVE =
  9593. dyn_cast<ExtVectorElementExpr>(E)) {
  9594. E = EVE->getBase()->IgnoreParenImpCasts();
  9595. continue;
  9596. }
  9597. break;
  9598. }
  9599. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  9600. // Function calls
  9601. const FunctionDecl *FD = CE->getDirectCallee();
  9602. if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  9603. if (!DiagnosticEmitted) {
  9604. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  9605. << ConstFunction << FD;
  9606. DiagnosticEmitted = true;
  9607. }
  9608. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  9609. diag::note_typecheck_assign_const)
  9610. << ConstFunction << FD << FD->getReturnType()
  9611. << FD->getReturnTypeSourceRange();
  9612. }
  9613. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9614. // Point to variable declaration.
  9615. if (const ValueDecl *VD = DRE->getDecl()) {
  9616. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  9617. if (!DiagnosticEmitted) {
  9618. S.Diag(Loc, diag::err_typecheck_assign_const)
  9619. << ExprRange << ConstVariable << VD << VD->getType();
  9620. DiagnosticEmitted = true;
  9621. }
  9622. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9623. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  9624. }
  9625. }
  9626. } else if (isa<CXXThisExpr>(E)) {
  9627. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  9628. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  9629. if (MD->isConst()) {
  9630. if (!DiagnosticEmitted) {
  9631. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  9632. << ConstMethod << MD;
  9633. DiagnosticEmitted = true;
  9634. }
  9635. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  9636. << ConstMethod << MD << MD->getSourceRange();
  9637. }
  9638. }
  9639. }
  9640. }
  9641. if (DiagnosticEmitted)
  9642. return;
  9643. // Can't determine a more specific message, so display the generic error.
  9644. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  9645. }
  9646. enum OriginalExprKind {
  9647. OEK_Variable,
  9648. OEK_Member,
  9649. OEK_LValue
  9650. };
  9651. static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
  9652. const RecordType *Ty,
  9653. SourceLocation Loc, SourceRange Range,
  9654. OriginalExprKind OEK,
  9655. bool &DiagnosticEmitted,
  9656. bool IsNested = false) {
  9657. // We walk the record hierarchy breadth-first to ensure that we print
  9658. // diagnostics in field nesting order.
  9659. // First, check every field for constness.
  9660. for (const FieldDecl *Field : Ty->getDecl()->fields()) {
  9661. if (Field->getType().isConstQualified()) {
  9662. if (!DiagnosticEmitted) {
  9663. S.Diag(Loc, diag::err_typecheck_assign_const)
  9664. << Range << NestedConstMember << OEK << VD
  9665. << IsNested << Field;
  9666. DiagnosticEmitted = true;
  9667. }
  9668. S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
  9669. << NestedConstMember << IsNested << Field
  9670. << Field->getType() << Field->getSourceRange();
  9671. }
  9672. }
  9673. // Then, recurse.
  9674. for (const FieldDecl *Field : Ty->getDecl()->fields()) {
  9675. QualType FTy = Field->getType();
  9676. if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
  9677. DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
  9678. OEK, DiagnosticEmitted, true);
  9679. }
  9680. }
  9681. /// Emit an error for the case where a record we are trying to assign to has a
  9682. /// const-qualified field somewhere in its hierarchy.
  9683. static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
  9684. SourceLocation Loc) {
  9685. QualType Ty = E->getType();
  9686. assert(Ty->isRecordType() && "lvalue was not record?");
  9687. SourceRange Range = E->getSourceRange();
  9688. const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
  9689. bool DiagEmitted = false;
  9690. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  9691. DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
  9692. Range, OEK_Member, DiagEmitted);
  9693. else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  9694. DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
  9695. Range, OEK_Variable, DiagEmitted);
  9696. else
  9697. DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
  9698. Range, OEK_LValue, DiagEmitted);
  9699. if (!DiagEmitted)
  9700. DiagnoseConstAssignment(S, E, Loc);
  9701. }
  9702. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  9703. /// emit an error and return true. If so, return false.
  9704. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  9705. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  9706. S.CheckShadowingDeclModification(E, Loc);
  9707. SourceLocation OrigLoc = Loc;
  9708. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  9709. &Loc);
  9710. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  9711. IsLV = Expr::MLV_InvalidMessageExpression;
  9712. if (IsLV == Expr::MLV_Valid)
  9713. return false;
  9714. unsigned DiagID = 0;
  9715. bool NeedType = false;
  9716. switch (IsLV) { // C99 6.5.16p2
  9717. case Expr::MLV_ConstQualified:
  9718. // Use a specialized diagnostic when we're assigning to an object
  9719. // from an enclosing function or block.
  9720. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  9721. if (NCCK == NCCK_Block)
  9722. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  9723. else
  9724. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  9725. break;
  9726. }
  9727. // In ARC, use some specialized diagnostics for occasions where we
  9728. // infer 'const'. These are always pseudo-strong variables.
  9729. if (S.getLangOpts().ObjCAutoRefCount) {
  9730. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  9731. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  9732. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  9733. // Use the normal diagnostic if it's pseudo-__strong but the
  9734. // user actually wrote 'const'.
  9735. if (var->isARCPseudoStrong() &&
  9736. (!var->getTypeSourceInfo() ||
  9737. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  9738. // There are two pseudo-strong cases:
  9739. // - self
  9740. ObjCMethodDecl *method = S.getCurMethodDecl();
  9741. if (method && var == method->getSelfDecl())
  9742. DiagID = method->isClassMethod()
  9743. ? diag::err_typecheck_arc_assign_self_class_method
  9744. : diag::err_typecheck_arc_assign_self;
  9745. // - fast enumeration variables
  9746. else
  9747. DiagID = diag::err_typecheck_arr_assign_enumeration;
  9748. SourceRange Assign;
  9749. if (Loc != OrigLoc)
  9750. Assign = SourceRange(OrigLoc, OrigLoc);
  9751. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  9752. // We need to preserve the AST regardless, so migration tool
  9753. // can do its job.
  9754. return false;
  9755. }
  9756. }
  9757. }
  9758. // If none of the special cases above are triggered, then this is a
  9759. // simple const assignment.
  9760. if (DiagID == 0) {
  9761. DiagnoseConstAssignment(S, E, Loc);
  9762. return true;
  9763. }
  9764. break;
  9765. case Expr::MLV_ConstAddrSpace:
  9766. DiagnoseConstAssignment(S, E, Loc);
  9767. return true;
  9768. case Expr::MLV_ConstQualifiedField:
  9769. DiagnoseRecursiveConstFields(S, E, Loc);
  9770. return true;
  9771. case Expr::MLV_ArrayType:
  9772. case Expr::MLV_ArrayTemporary:
  9773. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  9774. NeedType = true;
  9775. break;
  9776. case Expr::MLV_NotObjectType:
  9777. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  9778. NeedType = true;
  9779. break;
  9780. case Expr::MLV_LValueCast:
  9781. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  9782. break;
  9783. case Expr::MLV_Valid:
  9784. llvm_unreachable("did not take early return for MLV_Valid");
  9785. case Expr::MLV_InvalidExpression:
  9786. case Expr::MLV_MemberFunction:
  9787. case Expr::MLV_ClassTemporary:
  9788. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  9789. break;
  9790. case Expr::MLV_IncompleteType:
  9791. case Expr::MLV_IncompleteVoidType:
  9792. return S.RequireCompleteType(Loc, E->getType(),
  9793. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  9794. case Expr::MLV_DuplicateVectorComponents:
  9795. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  9796. break;
  9797. case Expr::MLV_NoSetterProperty:
  9798. llvm_unreachable("readonly properties should be processed differently");
  9799. case Expr::MLV_InvalidMessageExpression:
  9800. DiagID = diag::err_readonly_message_assignment;
  9801. break;
  9802. case Expr::MLV_SubObjCPropertySetting:
  9803. DiagID = diag::err_no_subobject_property_setting;
  9804. break;
  9805. }
  9806. SourceRange Assign;
  9807. if (Loc != OrigLoc)
  9808. Assign = SourceRange(OrigLoc, OrigLoc);
  9809. if (NeedType)
  9810. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  9811. else
  9812. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  9813. return true;
  9814. }
  9815. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  9816. SourceLocation Loc,
  9817. Sema &Sema) {
  9818. if (Sema.inTemplateInstantiation())
  9819. return;
  9820. if (Sema.isUnevaluatedContext())
  9821. return;
  9822. if (Loc.isInvalid() || Loc.isMacroID())
  9823. return;
  9824. if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
  9825. return;
  9826. // C / C++ fields
  9827. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  9828. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  9829. if (ML && MR) {
  9830. if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
  9831. return;
  9832. const ValueDecl *LHSDecl =
  9833. cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
  9834. const ValueDecl *RHSDecl =
  9835. cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
  9836. if (LHSDecl != RHSDecl)
  9837. return;
  9838. if (LHSDecl->getType().isVolatileQualified())
  9839. return;
  9840. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  9841. if (RefTy->getPointeeType().isVolatileQualified())
  9842. return;
  9843. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  9844. }
  9845. // Objective-C instance variables
  9846. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  9847. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  9848. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  9849. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  9850. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  9851. if (RL && RR && RL->getDecl() == RR->getDecl())
  9852. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  9853. }
  9854. }
  9855. // C99 6.5.16.1
  9856. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  9857. SourceLocation Loc,
  9858. QualType CompoundType) {
  9859. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  9860. // Verify that LHS is a modifiable lvalue, and emit error if not.
  9861. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  9862. return QualType();
  9863. QualType LHSType = LHSExpr->getType();
  9864. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  9865. CompoundType;
  9866. // OpenCL v1.2 s6.1.1.1 p2:
  9867. // The half data type can only be used to declare a pointer to a buffer that
  9868. // contains half values
  9869. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  9870. LHSType->isHalfType()) {
  9871. Diag(Loc, diag::err_opencl_half_load_store) << 1
  9872. << LHSType.getUnqualifiedType();
  9873. return QualType();
  9874. }
  9875. AssignConvertType ConvTy;
  9876. if (CompoundType.isNull()) {
  9877. Expr *RHSCheck = RHS.get();
  9878. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  9879. QualType LHSTy(LHSType);
  9880. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  9881. if (RHS.isInvalid())
  9882. return QualType();
  9883. // Special case of NSObject attributes on c-style pointer types.
  9884. if (ConvTy == IncompatiblePointer &&
  9885. ((Context.isObjCNSObjectType(LHSType) &&
  9886. RHSType->isObjCObjectPointerType()) ||
  9887. (Context.isObjCNSObjectType(RHSType) &&
  9888. LHSType->isObjCObjectPointerType())))
  9889. ConvTy = Compatible;
  9890. if (ConvTy == Compatible &&
  9891. LHSType->isObjCObjectType())
  9892. Diag(Loc, diag::err_objc_object_assignment)
  9893. << LHSType;
  9894. // If the RHS is a unary plus or minus, check to see if they = and + are
  9895. // right next to each other. If so, the user may have typo'd "x =+ 4"
  9896. // instead of "x += 4".
  9897. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  9898. RHSCheck = ICE->getSubExpr();
  9899. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  9900. if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
  9901. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  9902. // Only if the two operators are exactly adjacent.
  9903. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  9904. // And there is a space or other character before the subexpr of the
  9905. // unary +/-. We don't want to warn on "x=-1".
  9906. Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
  9907. UO->getSubExpr()->getBeginLoc().isFileID()) {
  9908. Diag(Loc, diag::warn_not_compound_assign)
  9909. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  9910. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  9911. }
  9912. }
  9913. if (ConvTy == Compatible) {
  9914. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  9915. // Warn about retain cycles where a block captures the LHS, but
  9916. // not if the LHS is a simple variable into which the block is
  9917. // being stored...unless that variable can be captured by reference!
  9918. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  9919. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  9920. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  9921. checkRetainCycles(LHSExpr, RHS.get());
  9922. }
  9923. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  9924. LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
  9925. // It is safe to assign a weak reference into a strong variable.
  9926. // Although this code can still have problems:
  9927. // id x = self.weakProp;
  9928. // id y = self.weakProp;
  9929. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  9930. // paths through the function. This should be revisited if
  9931. // -Wrepeated-use-of-weak is made flow-sensitive.
  9932. // For ObjCWeak only, we do not warn if the assign is to a non-weak
  9933. // variable, which will be valid for the current autorelease scope.
  9934. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  9935. RHS.get()->getBeginLoc()))
  9936. getCurFunction()->markSafeWeakUse(RHS.get());
  9937. } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
  9938. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  9939. }
  9940. }
  9941. } else {
  9942. // Compound assignment "x += y"
  9943. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  9944. }
  9945. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  9946. RHS.get(), AA_Assigning))
  9947. return QualType();
  9948. CheckForNullPointerDereference(*this, LHSExpr);
  9949. // C99 6.5.16p3: The type of an assignment expression is the type of the
  9950. // left operand unless the left operand has qualified type, in which case
  9951. // it is the unqualified version of the type of the left operand.
  9952. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  9953. // is converted to the type of the assignment expression (above).
  9954. // C++ 5.17p1: the type of the assignment expression is that of its left
  9955. // operand.
  9956. return (getLangOpts().CPlusPlus
  9957. ? LHSType : LHSType.getUnqualifiedType());
  9958. }
  9959. // Only ignore explicit casts to void.
  9960. static bool IgnoreCommaOperand(const Expr *E) {
  9961. E = E->IgnoreParens();
  9962. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  9963. if (CE->getCastKind() == CK_ToVoid) {
  9964. return true;
  9965. }
  9966. // static_cast<void> on a dependent type will not show up as CK_ToVoid.
  9967. if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
  9968. CE->getSubExpr()->getType()->isDependentType()) {
  9969. return true;
  9970. }
  9971. }
  9972. return false;
  9973. }
  9974. // Look for instances where it is likely the comma operator is confused with
  9975. // another operator. There is a whitelist of acceptable expressions for the
  9976. // left hand side of the comma operator, otherwise emit a warning.
  9977. void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
  9978. // No warnings in macros
  9979. if (Loc.isMacroID())
  9980. return;
  9981. // Don't warn in template instantiations.
  9982. if (inTemplateInstantiation())
  9983. return;
  9984. // Scope isn't fine-grained enough to whitelist the specific cases, so
  9985. // instead, skip more than needed, then call back into here with the
  9986. // CommaVisitor in SemaStmt.cpp.
  9987. // The whitelisted locations are the initialization and increment portions
  9988. // of a for loop. The additional checks are on the condition of
  9989. // if statements, do/while loops, and for loops.
  9990. // Differences in scope flags for C89 mode requires the extra logic.
  9991. const unsigned ForIncrementFlags =
  9992. getLangOpts().C99 || getLangOpts().CPlusPlus
  9993. ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
  9994. : Scope::ContinueScope | Scope::BreakScope;
  9995. const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
  9996. const unsigned ScopeFlags = getCurScope()->getFlags();
  9997. if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
  9998. (ScopeFlags & ForInitFlags) == ForInitFlags)
  9999. return;
  10000. // If there are multiple comma operators used together, get the RHS of the
  10001. // of the comma operator as the LHS.
  10002. while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
  10003. if (BO->getOpcode() != BO_Comma)
  10004. break;
  10005. LHS = BO->getRHS();
  10006. }
  10007. // Only allow some expressions on LHS to not warn.
  10008. if (IgnoreCommaOperand(LHS))
  10009. return;
  10010. Diag(Loc, diag::warn_comma_operator);
  10011. Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
  10012. << LHS->getSourceRange()
  10013. << FixItHint::CreateInsertion(LHS->getBeginLoc(),
  10014. LangOpts.CPlusPlus ? "static_cast<void>("
  10015. : "(void)(")
  10016. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
  10017. ")");
  10018. }
  10019. // C99 6.5.17
  10020. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  10021. SourceLocation Loc) {
  10022. LHS = S.CheckPlaceholderExpr(LHS.get());
  10023. RHS = S.CheckPlaceholderExpr(RHS.get());
  10024. if (LHS.isInvalid() || RHS.isInvalid())
  10025. return QualType();
  10026. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  10027. // operands, but not unary promotions.
  10028. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  10029. // So we treat the LHS as a ignored value, and in C++ we allow the
  10030. // containing site to determine what should be done with the RHS.
  10031. LHS = S.IgnoredValueConversions(LHS.get());
  10032. if (LHS.isInvalid())
  10033. return QualType();
  10034. S.DiagnoseUnusedExprResult(LHS.get());
  10035. if (!S.getLangOpts().CPlusPlus) {
  10036. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  10037. if (RHS.isInvalid())
  10038. return QualType();
  10039. if (!RHS.get()->getType()->isVoidType())
  10040. S.RequireCompleteType(Loc, RHS.get()->getType(),
  10041. diag::err_incomplete_type);
  10042. }
  10043. if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
  10044. S.DiagnoseCommaOperator(LHS.get(), Loc);
  10045. return RHS.get()->getType();
  10046. }
  10047. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  10048. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  10049. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  10050. ExprValueKind &VK,
  10051. ExprObjectKind &OK,
  10052. SourceLocation OpLoc,
  10053. bool IsInc, bool IsPrefix) {
  10054. if (Op->isTypeDependent())
  10055. return S.Context.DependentTy;
  10056. QualType ResType = Op->getType();
  10057. // Atomic types can be used for increment / decrement where the non-atomic
  10058. // versions can, so ignore the _Atomic() specifier for the purpose of
  10059. // checking.
  10060. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  10061. ResType = ResAtomicType->getValueType();
  10062. assert(!ResType.isNull() && "no type for increment/decrement expression");
  10063. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  10064. // Decrement of bool is not allowed.
  10065. if (!IsInc) {
  10066. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  10067. return QualType();
  10068. }
  10069. // Increment of bool sets it to true, but is deprecated.
  10070. S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
  10071. : diag::warn_increment_bool)
  10072. << Op->getSourceRange();
  10073. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  10074. // Error on enum increments and decrements in C++ mode
  10075. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  10076. return QualType();
  10077. } else if (ResType->isRealType()) {
  10078. // OK!
  10079. } else if (ResType->isPointerType()) {
  10080. // C99 6.5.2.4p2, 6.5.6p2
  10081. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  10082. return QualType();
  10083. } else if (ResType->isObjCObjectPointerType()) {
  10084. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  10085. // Otherwise, we just need a complete type.
  10086. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  10087. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  10088. return QualType();
  10089. } else if (ResType->isAnyComplexType()) {
  10090. // C99 does not support ++/-- on complex types, we allow as an extension.
  10091. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  10092. << ResType << Op->getSourceRange();
  10093. } else if (ResType->isPlaceholderType()) {
  10094. ExprResult PR = S.CheckPlaceholderExpr(Op);
  10095. if (PR.isInvalid()) return QualType();
  10096. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  10097. IsInc, IsPrefix);
  10098. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  10099. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  10100. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  10101. (ResType->getAs<VectorType>()->getVectorKind() !=
  10102. VectorType::AltiVecBool)) {
  10103. // The z vector extensions allow ++ and -- for non-bool vectors.
  10104. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  10105. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  10106. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  10107. } else {
  10108. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  10109. << ResType << int(IsInc) << Op->getSourceRange();
  10110. return QualType();
  10111. }
  10112. // At this point, we know we have a real, complex or pointer type.
  10113. // Now make sure the operand is a modifiable lvalue.
  10114. if (CheckForModifiableLvalue(Op, OpLoc, S))
  10115. return QualType();
  10116. // In C++, a prefix increment is the same type as the operand. Otherwise
  10117. // (in C or with postfix), the increment is the unqualified type of the
  10118. // operand.
  10119. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  10120. VK = VK_LValue;
  10121. OK = Op->getObjectKind();
  10122. return ResType;
  10123. } else {
  10124. VK = VK_RValue;
  10125. return ResType.getUnqualifiedType();
  10126. }
  10127. }
  10128. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  10129. /// This routine allows us to typecheck complex/recursive expressions
  10130. /// where the declaration is needed for type checking. We only need to
  10131. /// handle cases when the expression references a function designator
  10132. /// or is an lvalue. Here are some examples:
  10133. /// - &(x) => x
  10134. /// - &*****f => f for f a function designator.
  10135. /// - &s.xx => s
  10136. /// - &s.zz[1].yy -> s, if zz is an array
  10137. /// - *(x + 1) -> x, if x is an array
  10138. /// - &"123"[2] -> 0
  10139. /// - & __real__ x -> x
  10140. static ValueDecl *getPrimaryDecl(Expr *E) {
  10141. switch (E->getStmtClass()) {
  10142. case Stmt::DeclRefExprClass:
  10143. return cast<DeclRefExpr>(E)->getDecl();
  10144. case Stmt::MemberExprClass:
  10145. // If this is an arrow operator, the address is an offset from
  10146. // the base's value, so the object the base refers to is
  10147. // irrelevant.
  10148. if (cast<MemberExpr>(E)->isArrow())
  10149. return nullptr;
  10150. // Otherwise, the expression refers to a part of the base
  10151. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  10152. case Stmt::ArraySubscriptExprClass: {
  10153. // FIXME: This code shouldn't be necessary! We should catch the implicit
  10154. // promotion of register arrays earlier.
  10155. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  10156. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  10157. if (ICE->getSubExpr()->getType()->isArrayType())
  10158. return getPrimaryDecl(ICE->getSubExpr());
  10159. }
  10160. return nullptr;
  10161. }
  10162. case Stmt::UnaryOperatorClass: {
  10163. UnaryOperator *UO = cast<UnaryOperator>(E);
  10164. switch(UO->getOpcode()) {
  10165. case UO_Real:
  10166. case UO_Imag:
  10167. case UO_Extension:
  10168. return getPrimaryDecl(UO->getSubExpr());
  10169. default:
  10170. return nullptr;
  10171. }
  10172. }
  10173. case Stmt::ParenExprClass:
  10174. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  10175. case Stmt::ImplicitCastExprClass:
  10176. // If the result of an implicit cast is an l-value, we care about
  10177. // the sub-expression; otherwise, the result here doesn't matter.
  10178. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  10179. default:
  10180. return nullptr;
  10181. }
  10182. }
  10183. namespace {
  10184. enum {
  10185. AO_Bit_Field = 0,
  10186. AO_Vector_Element = 1,
  10187. AO_Property_Expansion = 2,
  10188. AO_Register_Variable = 3,
  10189. AO_No_Error = 4
  10190. };
  10191. }
  10192. /// Diagnose invalid operand for address of operations.
  10193. ///
  10194. /// \param Type The type of operand which cannot have its address taken.
  10195. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  10196. Expr *E, unsigned Type) {
  10197. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  10198. }
  10199. /// CheckAddressOfOperand - The operand of & must be either a function
  10200. /// designator or an lvalue designating an object. If it is an lvalue, the
  10201. /// object cannot be declared with storage class register or be a bit field.
  10202. /// Note: The usual conversions are *not* applied to the operand of the &
  10203. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  10204. /// In C++, the operand might be an overloaded function name, in which case
  10205. /// we allow the '&' but retain the overloaded-function type.
  10206. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  10207. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  10208. if (PTy->getKind() == BuiltinType::Overload) {
  10209. Expr *E = OrigOp.get()->IgnoreParens();
  10210. if (!isa<OverloadExpr>(E)) {
  10211. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  10212. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  10213. << OrigOp.get()->getSourceRange();
  10214. return QualType();
  10215. }
  10216. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  10217. if (isa<UnresolvedMemberExpr>(Ovl))
  10218. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  10219. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10220. << OrigOp.get()->getSourceRange();
  10221. return QualType();
  10222. }
  10223. return Context.OverloadTy;
  10224. }
  10225. if (PTy->getKind() == BuiltinType::UnknownAny)
  10226. return Context.UnknownAnyTy;
  10227. if (PTy->getKind() == BuiltinType::BoundMember) {
  10228. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10229. << OrigOp.get()->getSourceRange();
  10230. return QualType();
  10231. }
  10232. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  10233. if (OrigOp.isInvalid()) return QualType();
  10234. }
  10235. if (OrigOp.get()->isTypeDependent())
  10236. return Context.DependentTy;
  10237. assert(!OrigOp.get()->getType()->isPlaceholderType());
  10238. // Make sure to ignore parentheses in subsequent checks
  10239. Expr *op = OrigOp.get()->IgnoreParens();
  10240. // In OpenCL captures for blocks called as lambda functions
  10241. // are located in the private address space. Blocks used in
  10242. // enqueue_kernel can be located in a different address space
  10243. // depending on a vendor implementation. Thus preventing
  10244. // taking an address of the capture to avoid invalid AS casts.
  10245. if (LangOpts.OpenCL) {
  10246. auto* VarRef = dyn_cast<DeclRefExpr>(op);
  10247. if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
  10248. Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
  10249. return QualType();
  10250. }
  10251. }
  10252. if (getLangOpts().C99) {
  10253. // Implement C99-only parts of addressof rules.
  10254. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  10255. if (uOp->getOpcode() == UO_Deref)
  10256. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  10257. // (assuming the deref expression is valid).
  10258. return uOp->getSubExpr()->getType();
  10259. }
  10260. // Technically, there should be a check for array subscript
  10261. // expressions here, but the result of one is always an lvalue anyway.
  10262. }
  10263. ValueDecl *dcl = getPrimaryDecl(op);
  10264. if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
  10265. if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  10266. op->getBeginLoc()))
  10267. return QualType();
  10268. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  10269. unsigned AddressOfError = AO_No_Error;
  10270. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  10271. bool sfinae = (bool)isSFINAEContext();
  10272. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  10273. : diag::ext_typecheck_addrof_temporary)
  10274. << op->getType() << op->getSourceRange();
  10275. if (sfinae)
  10276. return QualType();
  10277. // Materialize the temporary as an lvalue so that we can take its address.
  10278. OrigOp = op =
  10279. CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  10280. } else if (isa<ObjCSelectorExpr>(op)) {
  10281. return Context.getPointerType(op->getType());
  10282. } else if (lval == Expr::LV_MemberFunction) {
  10283. // If it's an instance method, make a member pointer.
  10284. // The expression must have exactly the form &A::foo.
  10285. // If the underlying expression isn't a decl ref, give up.
  10286. if (!isa<DeclRefExpr>(op)) {
  10287. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10288. << OrigOp.get()->getSourceRange();
  10289. return QualType();
  10290. }
  10291. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  10292. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  10293. // The id-expression was parenthesized.
  10294. if (OrigOp.get() != DRE) {
  10295. Diag(OpLoc, diag::err_parens_pointer_member_function)
  10296. << OrigOp.get()->getSourceRange();
  10297. // The method was named without a qualifier.
  10298. } else if (!DRE->getQualifier()) {
  10299. if (MD->getParent()->getName().empty())
  10300. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10301. << op->getSourceRange();
  10302. else {
  10303. SmallString<32> Str;
  10304. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  10305. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10306. << op->getSourceRange()
  10307. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  10308. }
  10309. }
  10310. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  10311. if (isa<CXXDestructorDecl>(MD))
  10312. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  10313. QualType MPTy = Context.getMemberPointerType(
  10314. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  10315. // Under the MS ABI, lock down the inheritance model now.
  10316. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10317. (void)isCompleteType(OpLoc, MPTy);
  10318. return MPTy;
  10319. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  10320. // C99 6.5.3.2p1
  10321. // The operand must be either an l-value or a function designator
  10322. if (!op->getType()->isFunctionType()) {
  10323. // Use a special diagnostic for loads from property references.
  10324. if (isa<PseudoObjectExpr>(op)) {
  10325. AddressOfError = AO_Property_Expansion;
  10326. } else {
  10327. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  10328. << op->getType() << op->getSourceRange();
  10329. return QualType();
  10330. }
  10331. }
  10332. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  10333. // The operand cannot be a bit-field
  10334. AddressOfError = AO_Bit_Field;
  10335. } else if (op->getObjectKind() == OK_VectorComponent) {
  10336. // The operand cannot be an element of a vector
  10337. AddressOfError = AO_Vector_Element;
  10338. } else if (dcl) { // C99 6.5.3.2p1
  10339. // We have an lvalue with a decl. Make sure the decl is not declared
  10340. // with the register storage-class specifier.
  10341. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  10342. // in C++ it is not error to take address of a register
  10343. // variable (c++03 7.1.1P3)
  10344. if (vd->getStorageClass() == SC_Register &&
  10345. !getLangOpts().CPlusPlus) {
  10346. AddressOfError = AO_Register_Variable;
  10347. }
  10348. } else if (isa<MSPropertyDecl>(dcl)) {
  10349. AddressOfError = AO_Property_Expansion;
  10350. } else if (isa<FunctionTemplateDecl>(dcl)) {
  10351. return Context.OverloadTy;
  10352. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  10353. // Okay: we can take the address of a field.
  10354. // Could be a pointer to member, though, if there is an explicit
  10355. // scope qualifier for the class.
  10356. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  10357. DeclContext *Ctx = dcl->getDeclContext();
  10358. if (Ctx && Ctx->isRecord()) {
  10359. if (dcl->getType()->isReferenceType()) {
  10360. Diag(OpLoc,
  10361. diag::err_cannot_form_pointer_to_member_of_reference_type)
  10362. << dcl->getDeclName() << dcl->getType();
  10363. return QualType();
  10364. }
  10365. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  10366. Ctx = Ctx->getParent();
  10367. QualType MPTy = Context.getMemberPointerType(
  10368. op->getType(),
  10369. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  10370. // Under the MS ABI, lock down the inheritance model now.
  10371. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10372. (void)isCompleteType(OpLoc, MPTy);
  10373. return MPTy;
  10374. }
  10375. }
  10376. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
  10377. !isa<BindingDecl>(dcl))
  10378. llvm_unreachable("Unknown/unexpected decl type");
  10379. }
  10380. if (AddressOfError != AO_No_Error) {
  10381. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  10382. return QualType();
  10383. }
  10384. if (lval == Expr::LV_IncompleteVoidType) {
  10385. // Taking the address of a void variable is technically illegal, but we
  10386. // allow it in cases which are otherwise valid.
  10387. // Example: "extern void x; void* y = &x;".
  10388. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  10389. }
  10390. // If the operand has type "type", the result has type "pointer to type".
  10391. if (op->getType()->isObjCObjectType())
  10392. return Context.getObjCObjectPointerType(op->getType());
  10393. CheckAddressOfPackedMember(op);
  10394. return Context.getPointerType(op->getType());
  10395. }
  10396. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  10397. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  10398. if (!DRE)
  10399. return;
  10400. const Decl *D = DRE->getDecl();
  10401. if (!D)
  10402. return;
  10403. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  10404. if (!Param)
  10405. return;
  10406. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  10407. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  10408. return;
  10409. if (FunctionScopeInfo *FD = S.getCurFunction())
  10410. if (!FD->ModifiedNonNullParams.count(Param))
  10411. FD->ModifiedNonNullParams.insert(Param);
  10412. }
  10413. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  10414. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  10415. SourceLocation OpLoc) {
  10416. if (Op->isTypeDependent())
  10417. return S.Context.DependentTy;
  10418. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  10419. if (ConvResult.isInvalid())
  10420. return QualType();
  10421. Op = ConvResult.get();
  10422. QualType OpTy = Op->getType();
  10423. QualType Result;
  10424. if (isa<CXXReinterpretCastExpr>(Op)) {
  10425. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  10426. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  10427. Op->getSourceRange());
  10428. }
  10429. if (const PointerType *PT = OpTy->getAs<PointerType>())
  10430. {
  10431. Result = PT->getPointeeType();
  10432. }
  10433. else if (const ObjCObjectPointerType *OPT =
  10434. OpTy->getAs<ObjCObjectPointerType>())
  10435. Result = OPT->getPointeeType();
  10436. else {
  10437. ExprResult PR = S.CheckPlaceholderExpr(Op);
  10438. if (PR.isInvalid()) return QualType();
  10439. if (PR.get() != Op)
  10440. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  10441. }
  10442. if (Result.isNull()) {
  10443. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  10444. << OpTy << Op->getSourceRange();
  10445. return QualType();
  10446. }
  10447. // Note that per both C89 and C99, indirection is always legal, even if Result
  10448. // is an incomplete type or void. It would be possible to warn about
  10449. // dereferencing a void pointer, but it's completely well-defined, and such a
  10450. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  10451. // for pointers to 'void' but is fine for any other pointer type:
  10452. //
  10453. // C++ [expr.unary.op]p1:
  10454. // [...] the expression to which [the unary * operator] is applied shall
  10455. // be a pointer to an object type, or a pointer to a function type
  10456. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  10457. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  10458. << OpTy << Op->getSourceRange();
  10459. // Dereferences are usually l-values...
  10460. VK = VK_LValue;
  10461. // ...except that certain expressions are never l-values in C.
  10462. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  10463. VK = VK_RValue;
  10464. return Result;
  10465. }
  10466. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  10467. BinaryOperatorKind Opc;
  10468. switch (Kind) {
  10469. default: llvm_unreachable("Unknown binop!");
  10470. case tok::periodstar: Opc = BO_PtrMemD; break;
  10471. case tok::arrowstar: Opc = BO_PtrMemI; break;
  10472. case tok::star: Opc = BO_Mul; break;
  10473. case tok::slash: Opc = BO_Div; break;
  10474. case tok::percent: Opc = BO_Rem; break;
  10475. case tok::plus: Opc = BO_Add; break;
  10476. case tok::minus: Opc = BO_Sub; break;
  10477. case tok::lessless: Opc = BO_Shl; break;
  10478. case tok::greatergreater: Opc = BO_Shr; break;
  10479. case tok::lessequal: Opc = BO_LE; break;
  10480. case tok::less: Opc = BO_LT; break;
  10481. case tok::greaterequal: Opc = BO_GE; break;
  10482. case tok::greater: Opc = BO_GT; break;
  10483. case tok::exclaimequal: Opc = BO_NE; break;
  10484. case tok::equalequal: Opc = BO_EQ; break;
  10485. case tok::spaceship: Opc = BO_Cmp; break;
  10486. case tok::amp: Opc = BO_And; break;
  10487. case tok::caret: Opc = BO_Xor; break;
  10488. case tok::pipe: Opc = BO_Or; break;
  10489. case tok::ampamp: Opc = BO_LAnd; break;
  10490. case tok::pipepipe: Opc = BO_LOr; break;
  10491. case tok::equal: Opc = BO_Assign; break;
  10492. case tok::starequal: Opc = BO_MulAssign; break;
  10493. case tok::slashequal: Opc = BO_DivAssign; break;
  10494. case tok::percentequal: Opc = BO_RemAssign; break;
  10495. case tok::plusequal: Opc = BO_AddAssign; break;
  10496. case tok::minusequal: Opc = BO_SubAssign; break;
  10497. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  10498. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  10499. case tok::ampequal: Opc = BO_AndAssign; break;
  10500. case tok::caretequal: Opc = BO_XorAssign; break;
  10501. case tok::pipeequal: Opc = BO_OrAssign; break;
  10502. case tok::comma: Opc = BO_Comma; break;
  10503. }
  10504. return Opc;
  10505. }
  10506. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  10507. tok::TokenKind Kind) {
  10508. UnaryOperatorKind Opc;
  10509. switch (Kind) {
  10510. default: llvm_unreachable("Unknown unary op!");
  10511. case tok::plusplus: Opc = UO_PreInc; break;
  10512. case tok::minusminus: Opc = UO_PreDec; break;
  10513. case tok::amp: Opc = UO_AddrOf; break;
  10514. case tok::star: Opc = UO_Deref; break;
  10515. case tok::plus: Opc = UO_Plus; break;
  10516. case tok::minus: Opc = UO_Minus; break;
  10517. case tok::tilde: Opc = UO_Not; break;
  10518. case tok::exclaim: Opc = UO_LNot; break;
  10519. case tok::kw___real: Opc = UO_Real; break;
  10520. case tok::kw___imag: Opc = UO_Imag; break;
  10521. case tok::kw___extension__: Opc = UO_Extension; break;
  10522. }
  10523. return Opc;
  10524. }
  10525. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  10526. /// This warning suppressed in the event of macro expansions.
  10527. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  10528. SourceLocation OpLoc, bool IsBuiltin) {
  10529. if (S.inTemplateInstantiation())
  10530. return;
  10531. if (S.isUnevaluatedContext())
  10532. return;
  10533. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  10534. return;
  10535. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  10536. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  10537. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  10538. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  10539. if (!LHSDeclRef || !RHSDeclRef ||
  10540. LHSDeclRef->getLocation().isMacroID() ||
  10541. RHSDeclRef->getLocation().isMacroID())
  10542. return;
  10543. const ValueDecl *LHSDecl =
  10544. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  10545. const ValueDecl *RHSDecl =
  10546. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  10547. if (LHSDecl != RHSDecl)
  10548. return;
  10549. if (LHSDecl->getType().isVolatileQualified())
  10550. return;
  10551. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  10552. if (RefTy->getPointeeType().isVolatileQualified())
  10553. return;
  10554. S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
  10555. : diag::warn_self_assignment_overloaded)
  10556. << LHSDeclRef->getType() << LHSExpr->getSourceRange()
  10557. << RHSExpr->getSourceRange();
  10558. }
  10559. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  10560. /// is usually indicative of introspection within the Objective-C pointer.
  10561. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  10562. SourceLocation OpLoc) {
  10563. if (!S.getLangOpts().ObjC)
  10564. return;
  10565. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  10566. const Expr *LHS = L.get();
  10567. const Expr *RHS = R.get();
  10568. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  10569. ObjCPointerExpr = LHS;
  10570. OtherExpr = RHS;
  10571. }
  10572. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  10573. ObjCPointerExpr = RHS;
  10574. OtherExpr = LHS;
  10575. }
  10576. // This warning is deliberately made very specific to reduce false
  10577. // positives with logic that uses '&' for hashing. This logic mainly
  10578. // looks for code trying to introspect into tagged pointers, which
  10579. // code should generally never do.
  10580. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  10581. unsigned Diag = diag::warn_objc_pointer_masking;
  10582. // Determine if we are introspecting the result of performSelectorXXX.
  10583. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  10584. // Special case messages to -performSelector and friends, which
  10585. // can return non-pointer values boxed in a pointer value.
  10586. // Some clients may wish to silence warnings in this subcase.
  10587. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  10588. Selector S = ME->getSelector();
  10589. StringRef SelArg0 = S.getNameForSlot(0);
  10590. if (SelArg0.startswith("performSelector"))
  10591. Diag = diag::warn_objc_pointer_masking_performSelector;
  10592. }
  10593. S.Diag(OpLoc, Diag)
  10594. << ObjCPointerExpr->getSourceRange();
  10595. }
  10596. }
  10597. static NamedDecl *getDeclFromExpr(Expr *E) {
  10598. if (!E)
  10599. return nullptr;
  10600. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  10601. return DRE->getDecl();
  10602. if (auto *ME = dyn_cast<MemberExpr>(E))
  10603. return ME->getMemberDecl();
  10604. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  10605. return IRE->getDecl();
  10606. return nullptr;
  10607. }
  10608. // This helper function promotes a binary operator's operands (which are of a
  10609. // half vector type) to a vector of floats and then truncates the result to
  10610. // a vector of either half or short.
  10611. static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
  10612. BinaryOperatorKind Opc, QualType ResultTy,
  10613. ExprValueKind VK, ExprObjectKind OK,
  10614. bool IsCompAssign, SourceLocation OpLoc,
  10615. FPOptions FPFeatures) {
  10616. auto &Context = S.getASTContext();
  10617. assert((isVector(ResultTy, Context.HalfTy) ||
  10618. isVector(ResultTy, Context.ShortTy)) &&
  10619. "Result must be a vector of half or short");
  10620. assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
  10621. isVector(RHS.get()->getType(), Context.HalfTy) &&
  10622. "both operands expected to be a half vector");
  10623. RHS = convertVector(RHS.get(), Context.FloatTy, S);
  10624. QualType BinOpResTy = RHS.get()->getType();
  10625. // If Opc is a comparison, ResultType is a vector of shorts. In that case,
  10626. // change BinOpResTy to a vector of ints.
  10627. if (isVector(ResultTy, Context.ShortTy))
  10628. BinOpResTy = S.GetSignedVectorType(BinOpResTy);
  10629. if (IsCompAssign)
  10630. return new (Context) CompoundAssignOperator(
  10631. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
  10632. OpLoc, FPFeatures);
  10633. LHS = convertVector(LHS.get(), Context.FloatTy, S);
  10634. auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
  10635. VK, OK, OpLoc, FPFeatures);
  10636. return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
  10637. }
  10638. static std::pair<ExprResult, ExprResult>
  10639. CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
  10640. Expr *RHSExpr) {
  10641. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  10642. if (!S.getLangOpts().CPlusPlus) {
  10643. // C cannot handle TypoExpr nodes on either side of a binop because it
  10644. // doesn't handle dependent types properly, so make sure any TypoExprs have
  10645. // been dealt with before checking the operands.
  10646. LHS = S.CorrectDelayedTyposInExpr(LHS);
  10647. RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
  10648. if (Opc != BO_Assign)
  10649. return ExprResult(E);
  10650. // Avoid correcting the RHS to the same Expr as the LHS.
  10651. Decl *D = getDeclFromExpr(E);
  10652. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  10653. });
  10654. }
  10655. return std::make_pair(LHS, RHS);
  10656. }
  10657. /// Returns true if conversion between vectors of halfs and vectors of floats
  10658. /// is needed.
  10659. static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
  10660. QualType SrcType) {
  10661. return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
  10662. !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
  10663. isVector(SrcType, Ctx.HalfTy);
  10664. }
  10665. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  10666. /// operator @p Opc at location @c TokLoc. This routine only supports
  10667. /// built-in operations; ActOnBinOp handles overloaded operators.
  10668. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  10669. BinaryOperatorKind Opc,
  10670. Expr *LHSExpr, Expr *RHSExpr) {
  10671. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  10672. // The syntax only allows initializer lists on the RHS of assignment,
  10673. // so we don't need to worry about accepting invalid code for
  10674. // non-assignment operators.
  10675. // C++11 5.17p9:
  10676. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  10677. // of x = {} is x = T().
  10678. InitializationKind Kind = InitializationKind::CreateDirectList(
  10679. RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  10680. InitializedEntity Entity =
  10681. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  10682. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  10683. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  10684. if (Init.isInvalid())
  10685. return Init;
  10686. RHSExpr = Init.get();
  10687. }
  10688. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  10689. QualType ResultTy; // Result type of the binary operator.
  10690. // The following two variables are used for compound assignment operators
  10691. QualType CompLHSTy; // Type of LHS after promotions for computation
  10692. QualType CompResultTy; // Type of computation result
  10693. ExprValueKind VK = VK_RValue;
  10694. ExprObjectKind OK = OK_Ordinary;
  10695. bool ConvertHalfVec = false;
  10696. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  10697. if (!LHS.isUsable() || !RHS.isUsable())
  10698. return ExprError();
  10699. if (getLangOpts().OpenCL) {
  10700. QualType LHSTy = LHSExpr->getType();
  10701. QualType RHSTy = RHSExpr->getType();
  10702. // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
  10703. // the ATOMIC_VAR_INIT macro.
  10704. if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
  10705. SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  10706. if (BO_Assign == Opc)
  10707. Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
  10708. else
  10709. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  10710. return ExprError();
  10711. }
  10712. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  10713. // only with a builtin functions and therefore should be disallowed here.
  10714. if (LHSTy->isImageType() || RHSTy->isImageType() ||
  10715. LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
  10716. LHSTy->isPipeType() || RHSTy->isPipeType() ||
  10717. LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
  10718. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  10719. return ExprError();
  10720. }
  10721. }
  10722. switch (Opc) {
  10723. case BO_Assign:
  10724. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  10725. if (getLangOpts().CPlusPlus &&
  10726. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  10727. VK = LHS.get()->getValueKind();
  10728. OK = LHS.get()->getObjectKind();
  10729. }
  10730. if (!ResultTy.isNull()) {
  10731. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  10732. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  10733. }
  10734. RecordModifiableNonNullParam(*this, LHS.get());
  10735. break;
  10736. case BO_PtrMemD:
  10737. case BO_PtrMemI:
  10738. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  10739. Opc == BO_PtrMemI);
  10740. break;
  10741. case BO_Mul:
  10742. case BO_Div:
  10743. ConvertHalfVec = true;
  10744. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  10745. Opc == BO_Div);
  10746. break;
  10747. case BO_Rem:
  10748. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  10749. break;
  10750. case BO_Add:
  10751. ConvertHalfVec = true;
  10752. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  10753. break;
  10754. case BO_Sub:
  10755. ConvertHalfVec = true;
  10756. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  10757. break;
  10758. case BO_Shl:
  10759. case BO_Shr:
  10760. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  10761. break;
  10762. case BO_LE:
  10763. case BO_LT:
  10764. case BO_GE:
  10765. case BO_GT:
  10766. ConvertHalfVec = true;
  10767. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  10768. break;
  10769. case BO_EQ:
  10770. case BO_NE:
  10771. ConvertHalfVec = true;
  10772. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  10773. break;
  10774. case BO_Cmp:
  10775. ConvertHalfVec = true;
  10776. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  10777. assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
  10778. break;
  10779. case BO_And:
  10780. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  10781. LLVM_FALLTHROUGH;
  10782. case BO_Xor:
  10783. case BO_Or:
  10784. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  10785. break;
  10786. case BO_LAnd:
  10787. case BO_LOr:
  10788. ConvertHalfVec = true;
  10789. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  10790. break;
  10791. case BO_MulAssign:
  10792. case BO_DivAssign:
  10793. ConvertHalfVec = true;
  10794. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  10795. Opc == BO_DivAssign);
  10796. CompLHSTy = CompResultTy;
  10797. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10798. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10799. break;
  10800. case BO_RemAssign:
  10801. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  10802. CompLHSTy = CompResultTy;
  10803. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10804. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10805. break;
  10806. case BO_AddAssign:
  10807. ConvertHalfVec = true;
  10808. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  10809. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10810. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10811. break;
  10812. case BO_SubAssign:
  10813. ConvertHalfVec = true;
  10814. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  10815. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10816. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10817. break;
  10818. case BO_ShlAssign:
  10819. case BO_ShrAssign:
  10820. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  10821. CompLHSTy = CompResultTy;
  10822. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10823. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10824. break;
  10825. case BO_AndAssign:
  10826. case BO_OrAssign: // fallthrough
  10827. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  10828. LLVM_FALLTHROUGH;
  10829. case BO_XorAssign:
  10830. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  10831. CompLHSTy = CompResultTy;
  10832. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10833. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10834. break;
  10835. case BO_Comma:
  10836. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  10837. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  10838. VK = RHS.get()->getValueKind();
  10839. OK = RHS.get()->getObjectKind();
  10840. }
  10841. break;
  10842. }
  10843. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  10844. return ExprError();
  10845. // Some of the binary operations require promoting operands of half vector to
  10846. // float vectors and truncating the result back to half vector. For now, we do
  10847. // this only when HalfArgsAndReturn is set (that is, when the target is arm or
  10848. // arm64).
  10849. assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
  10850. isVector(LHS.get()->getType(), Context.HalfTy) &&
  10851. "both sides are half vectors or neither sides are");
  10852. ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
  10853. LHS.get()->getType());
  10854. // Check for array bounds violations for both sides of the BinaryOperator
  10855. CheckArrayAccess(LHS.get());
  10856. CheckArrayAccess(RHS.get());
  10857. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  10858. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  10859. &Context.Idents.get("object_setClass"),
  10860. SourceLocation(), LookupOrdinaryName);
  10861. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  10862. SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
  10863. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
  10864. << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
  10865. "object_setClass(")
  10866. << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
  10867. ",")
  10868. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  10869. }
  10870. else
  10871. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  10872. }
  10873. else if (const ObjCIvarRefExpr *OIRE =
  10874. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  10875. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  10876. // Opc is not a compound assignment if CompResultTy is null.
  10877. if (CompResultTy.isNull()) {
  10878. if (ConvertHalfVec)
  10879. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
  10880. OpLoc, FPFeatures);
  10881. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  10882. OK, OpLoc, FPFeatures);
  10883. }
  10884. // Handle compound assignments.
  10885. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  10886. OK_ObjCProperty) {
  10887. VK = VK_LValue;
  10888. OK = LHS.get()->getObjectKind();
  10889. }
  10890. if (ConvertHalfVec)
  10891. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
  10892. OpLoc, FPFeatures);
  10893. return new (Context) CompoundAssignOperator(
  10894. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  10895. OpLoc, FPFeatures);
  10896. }
  10897. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  10898. /// operators are mixed in a way that suggests that the programmer forgot that
  10899. /// comparison operators have higher precedence. The most typical example of
  10900. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  10901. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  10902. SourceLocation OpLoc, Expr *LHSExpr,
  10903. Expr *RHSExpr) {
  10904. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  10905. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  10906. // Check that one of the sides is a comparison operator and the other isn't.
  10907. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  10908. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  10909. if (isLeftComp == isRightComp)
  10910. return;
  10911. // Bitwise operations are sometimes used as eager logical ops.
  10912. // Don't diagnose this.
  10913. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  10914. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  10915. if (isLeftBitwise || isRightBitwise)
  10916. return;
  10917. SourceRange DiagRange = isLeftComp
  10918. ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
  10919. : SourceRange(OpLoc, RHSExpr->getEndLoc());
  10920. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  10921. SourceRange ParensRange =
  10922. isLeftComp
  10923. ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
  10924. : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
  10925. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  10926. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  10927. SuggestParentheses(Self, OpLoc,
  10928. Self.PDiag(diag::note_precedence_silence) << OpStr,
  10929. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  10930. SuggestParentheses(Self, OpLoc,
  10931. Self.PDiag(diag::note_precedence_bitwise_first)
  10932. << BinaryOperator::getOpcodeStr(Opc),
  10933. ParensRange);
  10934. }
  10935. /// It accepts a '&&' expr that is inside a '||' one.
  10936. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  10937. /// in parentheses.
  10938. static void
  10939. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  10940. BinaryOperator *Bop) {
  10941. assert(Bop->getOpcode() == BO_LAnd);
  10942. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  10943. << Bop->getSourceRange() << OpLoc;
  10944. SuggestParentheses(Self, Bop->getOperatorLoc(),
  10945. Self.PDiag(diag::note_precedence_silence)
  10946. << Bop->getOpcodeStr(),
  10947. Bop->getSourceRange());
  10948. }
  10949. /// Returns true if the given expression can be evaluated as a constant
  10950. /// 'true'.
  10951. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  10952. bool Res;
  10953. return !E->isValueDependent() &&
  10954. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  10955. }
  10956. /// Returns true if the given expression can be evaluated as a constant
  10957. /// 'false'.
  10958. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  10959. bool Res;
  10960. return !E->isValueDependent() &&
  10961. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  10962. }
  10963. /// Look for '&&' in the left hand of a '||' expr.
  10964. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  10965. Expr *LHSExpr, Expr *RHSExpr) {
  10966. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  10967. if (Bop->getOpcode() == BO_LAnd) {
  10968. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  10969. if (EvaluatesAsFalse(S, RHSExpr))
  10970. return;
  10971. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  10972. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  10973. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  10974. } else if (Bop->getOpcode() == BO_LOr) {
  10975. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  10976. // If it's "a || b && 1 || c" we didn't warn earlier for
  10977. // "a || b && 1", but warn now.
  10978. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  10979. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  10980. }
  10981. }
  10982. }
  10983. }
  10984. /// Look for '&&' in the right hand of a '||' expr.
  10985. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  10986. Expr *LHSExpr, Expr *RHSExpr) {
  10987. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  10988. if (Bop->getOpcode() == BO_LAnd) {
  10989. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  10990. if (EvaluatesAsFalse(S, LHSExpr))
  10991. return;
  10992. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  10993. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  10994. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  10995. }
  10996. }
  10997. }
  10998. /// Look for bitwise op in the left or right hand of a bitwise op with
  10999. /// lower precedence and emit a diagnostic together with a fixit hint that wraps
  11000. /// the '&' expression in parentheses.
  11001. static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
  11002. SourceLocation OpLoc, Expr *SubExpr) {
  11003. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11004. if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
  11005. S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
  11006. << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
  11007. << Bop->getSourceRange() << OpLoc;
  11008. SuggestParentheses(S, Bop->getOperatorLoc(),
  11009. S.PDiag(diag::note_precedence_silence)
  11010. << Bop->getOpcodeStr(),
  11011. Bop->getSourceRange());
  11012. }
  11013. }
  11014. }
  11015. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  11016. Expr *SubExpr, StringRef Shift) {
  11017. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11018. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  11019. StringRef Op = Bop->getOpcodeStr();
  11020. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  11021. << Bop->getSourceRange() << OpLoc << Shift << Op;
  11022. SuggestParentheses(S, Bop->getOperatorLoc(),
  11023. S.PDiag(diag::note_precedence_silence) << Op,
  11024. Bop->getSourceRange());
  11025. }
  11026. }
  11027. }
  11028. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  11029. Expr *LHSExpr, Expr *RHSExpr) {
  11030. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  11031. if (!OCE)
  11032. return;
  11033. FunctionDecl *FD = OCE->getDirectCallee();
  11034. if (!FD || !FD->isOverloadedOperator())
  11035. return;
  11036. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  11037. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  11038. return;
  11039. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  11040. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  11041. << (Kind == OO_LessLess);
  11042. SuggestParentheses(S, OCE->getOperatorLoc(),
  11043. S.PDiag(diag::note_precedence_silence)
  11044. << (Kind == OO_LessLess ? "<<" : ">>"),
  11045. OCE->getSourceRange());
  11046. SuggestParentheses(
  11047. S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
  11048. SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
  11049. }
  11050. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  11051. /// precedence.
  11052. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  11053. SourceLocation OpLoc, Expr *LHSExpr,
  11054. Expr *RHSExpr){
  11055. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  11056. if (BinaryOperator::isBitwiseOp(Opc))
  11057. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  11058. // Diagnose "arg1 & arg2 | arg3"
  11059. if ((Opc == BO_Or || Opc == BO_Xor) &&
  11060. !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11061. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
  11062. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
  11063. }
  11064. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  11065. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  11066. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11067. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  11068. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  11069. }
  11070. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  11071. || Opc == BO_Shr) {
  11072. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  11073. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  11074. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  11075. }
  11076. // Warn on overloaded shift operators and comparisons, such as:
  11077. // cout << 5 == 4;
  11078. if (BinaryOperator::isComparisonOp(Opc))
  11079. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  11080. }
  11081. // Binary Operators. 'Tok' is the token for the operator.
  11082. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  11083. tok::TokenKind Kind,
  11084. Expr *LHSExpr, Expr *RHSExpr) {
  11085. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  11086. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  11087. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  11088. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  11089. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  11090. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  11091. }
  11092. /// Build an overloaded binary operator expression in the given scope.
  11093. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  11094. BinaryOperatorKind Opc,
  11095. Expr *LHS, Expr *RHS) {
  11096. switch (Opc) {
  11097. case BO_Assign:
  11098. case BO_DivAssign:
  11099. case BO_RemAssign:
  11100. case BO_SubAssign:
  11101. case BO_AndAssign:
  11102. case BO_OrAssign:
  11103. case BO_XorAssign:
  11104. DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
  11105. CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
  11106. break;
  11107. default:
  11108. break;
  11109. }
  11110. // Find all of the overloaded operators visible from this
  11111. // point. We perform both an operator-name lookup from the local
  11112. // scope and an argument-dependent lookup based on the types of
  11113. // the arguments.
  11114. UnresolvedSet<16> Functions;
  11115. OverloadedOperatorKind OverOp
  11116. = BinaryOperator::getOverloadedOperator(Opc);
  11117. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  11118. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  11119. RHS->getType(), Functions);
  11120. // Build the (potentially-overloaded, potentially-dependent)
  11121. // binary operation.
  11122. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  11123. }
  11124. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  11125. BinaryOperatorKind Opc,
  11126. Expr *LHSExpr, Expr *RHSExpr) {
  11127. ExprResult LHS, RHS;
  11128. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  11129. if (!LHS.isUsable() || !RHS.isUsable())
  11130. return ExprError();
  11131. LHSExpr = LHS.get();
  11132. RHSExpr = RHS.get();
  11133. // We want to end up calling one of checkPseudoObjectAssignment
  11134. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  11135. // both expressions are overloadable or either is type-dependent),
  11136. // or CreateBuiltinBinOp (in any other case). We also want to get
  11137. // any placeholder types out of the way.
  11138. // Handle pseudo-objects in the LHS.
  11139. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  11140. // Assignments with a pseudo-object l-value need special analysis.
  11141. if (pty->getKind() == BuiltinType::PseudoObject &&
  11142. BinaryOperator::isAssignmentOp(Opc))
  11143. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  11144. // Don't resolve overloads if the other type is overloadable.
  11145. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
  11146. // We can't actually test that if we still have a placeholder,
  11147. // though. Fortunately, none of the exceptions we see in that
  11148. // code below are valid when the LHS is an overload set. Note
  11149. // that an overload set can be dependently-typed, but it never
  11150. // instantiates to having an overloadable type.
  11151. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11152. if (resolvedRHS.isInvalid()) return ExprError();
  11153. RHSExpr = resolvedRHS.get();
  11154. if (RHSExpr->isTypeDependent() ||
  11155. RHSExpr->getType()->isOverloadableType())
  11156. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11157. }
  11158. // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
  11159. // template, diagnose the missing 'template' keyword instead of diagnosing
  11160. // an invalid use of a bound member function.
  11161. //
  11162. // Note that "A::x < b" might be valid if 'b' has an overloadable type due
  11163. // to C++1z [over.over]/1.4, but we already checked for that case above.
  11164. if (Opc == BO_LT && inTemplateInstantiation() &&
  11165. (pty->getKind() == BuiltinType::BoundMember ||
  11166. pty->getKind() == BuiltinType::Overload)) {
  11167. auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
  11168. if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
  11169. std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
  11170. return isa<FunctionTemplateDecl>(ND);
  11171. })) {
  11172. Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
  11173. : OE->getNameLoc(),
  11174. diag::err_template_kw_missing)
  11175. << OE->getName().getAsString() << "";
  11176. return ExprError();
  11177. }
  11178. }
  11179. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  11180. if (LHS.isInvalid()) return ExprError();
  11181. LHSExpr = LHS.get();
  11182. }
  11183. // Handle pseudo-objects in the RHS.
  11184. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  11185. // An overload in the RHS can potentially be resolved by the type
  11186. // being assigned to.
  11187. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  11188. if (getLangOpts().CPlusPlus &&
  11189. (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
  11190. LHSExpr->getType()->isOverloadableType()))
  11191. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11192. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11193. }
  11194. // Don't resolve overloads if the other type is overloadable.
  11195. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
  11196. LHSExpr->getType()->isOverloadableType())
  11197. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11198. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11199. if (!resolvedRHS.isUsable()) return ExprError();
  11200. RHSExpr = resolvedRHS.get();
  11201. }
  11202. if (getLangOpts().CPlusPlus) {
  11203. // If either expression is type-dependent, always build an
  11204. // overloaded op.
  11205. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  11206. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11207. // Otherwise, build an overloaded op if either expression has an
  11208. // overloadable type.
  11209. if (LHSExpr->getType()->isOverloadableType() ||
  11210. RHSExpr->getType()->isOverloadableType())
  11211. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11212. }
  11213. // Build a built-in binary operation.
  11214. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11215. }
  11216. static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
  11217. if (T.isNull() || T->isDependentType())
  11218. return false;
  11219. if (!T->isPromotableIntegerType())
  11220. return true;
  11221. return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
  11222. }
  11223. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  11224. UnaryOperatorKind Opc,
  11225. Expr *InputExpr) {
  11226. ExprResult Input = InputExpr;
  11227. ExprValueKind VK = VK_RValue;
  11228. ExprObjectKind OK = OK_Ordinary;
  11229. QualType resultType;
  11230. bool CanOverflow = false;
  11231. bool ConvertHalfVec = false;
  11232. if (getLangOpts().OpenCL) {
  11233. QualType Ty = InputExpr->getType();
  11234. // The only legal unary operation for atomics is '&'.
  11235. if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
  11236. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  11237. // only with a builtin functions and therefore should be disallowed here.
  11238. (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
  11239. || Ty->isBlockPointerType())) {
  11240. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11241. << InputExpr->getType()
  11242. << Input.get()->getSourceRange());
  11243. }
  11244. }
  11245. switch (Opc) {
  11246. case UO_PreInc:
  11247. case UO_PreDec:
  11248. case UO_PostInc:
  11249. case UO_PostDec:
  11250. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  11251. OpLoc,
  11252. Opc == UO_PreInc ||
  11253. Opc == UO_PostInc,
  11254. Opc == UO_PreInc ||
  11255. Opc == UO_PreDec);
  11256. CanOverflow = isOverflowingIntegerType(Context, resultType);
  11257. break;
  11258. case UO_AddrOf:
  11259. resultType = CheckAddressOfOperand(Input, OpLoc);
  11260. RecordModifiableNonNullParam(*this, InputExpr);
  11261. break;
  11262. case UO_Deref: {
  11263. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11264. if (Input.isInvalid()) return ExprError();
  11265. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  11266. break;
  11267. }
  11268. case UO_Plus:
  11269. case UO_Minus:
  11270. CanOverflow = Opc == UO_Minus &&
  11271. isOverflowingIntegerType(Context, Input.get()->getType());
  11272. Input = UsualUnaryConversions(Input.get());
  11273. if (Input.isInvalid()) return ExprError();
  11274. // Unary plus and minus require promoting an operand of half vector to a
  11275. // float vector and truncating the result back to a half vector. For now, we
  11276. // do this only when HalfArgsAndReturns is set (that is, when the target is
  11277. // arm or arm64).
  11278. ConvertHalfVec =
  11279. needsConversionOfHalfVec(true, Context, Input.get()->getType());
  11280. // If the operand is a half vector, promote it to a float vector.
  11281. if (ConvertHalfVec)
  11282. Input = convertVector(Input.get(), Context.FloatTy, *this);
  11283. resultType = Input.get()->getType();
  11284. if (resultType->isDependentType())
  11285. break;
  11286. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  11287. break;
  11288. else if (resultType->isVectorType() &&
  11289. // The z vector extensions don't allow + or - with bool vectors.
  11290. (!Context.getLangOpts().ZVector ||
  11291. resultType->getAs<VectorType>()->getVectorKind() !=
  11292. VectorType::AltiVecBool))
  11293. break;
  11294. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  11295. Opc == UO_Plus &&
  11296. resultType->isPointerType())
  11297. break;
  11298. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11299. << resultType << Input.get()->getSourceRange());
  11300. case UO_Not: // bitwise complement
  11301. Input = UsualUnaryConversions(Input.get());
  11302. if (Input.isInvalid())
  11303. return ExprError();
  11304. resultType = Input.get()->getType();
  11305. if (resultType->isDependentType())
  11306. break;
  11307. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  11308. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  11309. // C99 does not support '~' for complex conjugation.
  11310. Diag(OpLoc, diag::ext_integer_complement_complex)
  11311. << resultType << Input.get()->getSourceRange();
  11312. else if (resultType->hasIntegerRepresentation())
  11313. break;
  11314. else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
  11315. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  11316. // on vector float types.
  11317. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  11318. if (!T->isIntegerType())
  11319. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11320. << resultType << Input.get()->getSourceRange());
  11321. } else {
  11322. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11323. << resultType << Input.get()->getSourceRange());
  11324. }
  11325. break;
  11326. case UO_LNot: // logical negation
  11327. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  11328. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11329. if (Input.isInvalid()) return ExprError();
  11330. resultType = Input.get()->getType();
  11331. // Though we still have to promote half FP to float...
  11332. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  11333. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  11334. resultType = Context.FloatTy;
  11335. }
  11336. if (resultType->isDependentType())
  11337. break;
  11338. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  11339. // C99 6.5.3.3p1: ok, fallthrough;
  11340. if (Context.getLangOpts().CPlusPlus) {
  11341. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  11342. // operand contextually converted to bool.
  11343. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  11344. ScalarTypeToBooleanCastKind(resultType));
  11345. } else if (Context.getLangOpts().OpenCL &&
  11346. Context.getLangOpts().OpenCLVersion < 120) {
  11347. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  11348. // operate on scalar float types.
  11349. if (!resultType->isIntegerType() && !resultType->isPointerType())
  11350. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11351. << resultType << Input.get()->getSourceRange());
  11352. }
  11353. } else if (resultType->isExtVectorType()) {
  11354. if (Context.getLangOpts().OpenCL &&
  11355. Context.getLangOpts().OpenCLVersion < 120) {
  11356. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  11357. // operate on vector float types.
  11358. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  11359. if (!T->isIntegerType())
  11360. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11361. << resultType << Input.get()->getSourceRange());
  11362. }
  11363. // Vector logical not returns the signed variant of the operand type.
  11364. resultType = GetSignedVectorType(resultType);
  11365. break;
  11366. } else {
  11367. // FIXME: GCC's vector extension permits the usage of '!' with a vector
  11368. // type in C++. We should allow that here too.
  11369. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11370. << resultType << Input.get()->getSourceRange());
  11371. }
  11372. // LNot always has type int. C99 6.5.3.3p5.
  11373. // In C++, it's bool. C++ 5.3.1p8
  11374. resultType = Context.getLogicalOperationType();
  11375. break;
  11376. case UO_Real:
  11377. case UO_Imag:
  11378. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  11379. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  11380. // complex l-values to ordinary l-values and all other values to r-values.
  11381. if (Input.isInvalid()) return ExprError();
  11382. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  11383. if (Input.get()->getValueKind() != VK_RValue &&
  11384. Input.get()->getObjectKind() == OK_Ordinary)
  11385. VK = Input.get()->getValueKind();
  11386. } else if (!getLangOpts().CPlusPlus) {
  11387. // In C, a volatile scalar is read by __imag. In C++, it is not.
  11388. Input = DefaultLvalueConversion(Input.get());
  11389. }
  11390. break;
  11391. case UO_Extension:
  11392. resultType = Input.get()->getType();
  11393. VK = Input.get()->getValueKind();
  11394. OK = Input.get()->getObjectKind();
  11395. break;
  11396. case UO_Coawait:
  11397. // It's unnecessary to represent the pass-through operator co_await in the
  11398. // AST; just return the input expression instead.
  11399. assert(!Input.get()->getType()->isDependentType() &&
  11400. "the co_await expression must be non-dependant before "
  11401. "building operator co_await");
  11402. return Input;
  11403. }
  11404. if (resultType.isNull() || Input.isInvalid())
  11405. return ExprError();
  11406. // Check for array bounds violations in the operand of the UnaryOperator,
  11407. // except for the '*' and '&' operators that have to be handled specially
  11408. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  11409. // that are explicitly defined as valid by the standard).
  11410. if (Opc != UO_AddrOf && Opc != UO_Deref)
  11411. CheckArrayAccess(Input.get());
  11412. auto *UO = new (Context)
  11413. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
  11414. // Convert the result back to a half vector.
  11415. if (ConvertHalfVec)
  11416. return convertVector(UO, Context.HalfTy, *this);
  11417. return UO;
  11418. }
  11419. /// Determine whether the given expression is a qualified member
  11420. /// access expression, of a form that could be turned into a pointer to member
  11421. /// with the address-of operator.
  11422. bool Sema::isQualifiedMemberAccess(Expr *E) {
  11423. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  11424. if (!DRE->getQualifier())
  11425. return false;
  11426. ValueDecl *VD = DRE->getDecl();
  11427. if (!VD->isCXXClassMember())
  11428. return false;
  11429. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  11430. return true;
  11431. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  11432. return Method->isInstance();
  11433. return false;
  11434. }
  11435. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  11436. if (!ULE->getQualifier())
  11437. return false;
  11438. for (NamedDecl *D : ULE->decls()) {
  11439. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  11440. if (Method->isInstance())
  11441. return true;
  11442. } else {
  11443. // Overload set does not contain methods.
  11444. break;
  11445. }
  11446. }
  11447. return false;
  11448. }
  11449. return false;
  11450. }
  11451. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  11452. UnaryOperatorKind Opc, Expr *Input) {
  11453. // First things first: handle placeholders so that the
  11454. // overloaded-operator check considers the right type.
  11455. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  11456. // Increment and decrement of pseudo-object references.
  11457. if (pty->getKind() == BuiltinType::PseudoObject &&
  11458. UnaryOperator::isIncrementDecrementOp(Opc))
  11459. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  11460. // extension is always a builtin operator.
  11461. if (Opc == UO_Extension)
  11462. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11463. // & gets special logic for several kinds of placeholder.
  11464. // The builtin code knows what to do.
  11465. if (Opc == UO_AddrOf &&
  11466. (pty->getKind() == BuiltinType::Overload ||
  11467. pty->getKind() == BuiltinType::UnknownAny ||
  11468. pty->getKind() == BuiltinType::BoundMember))
  11469. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11470. // Anything else needs to be handled now.
  11471. ExprResult Result = CheckPlaceholderExpr(Input);
  11472. if (Result.isInvalid()) return ExprError();
  11473. Input = Result.get();
  11474. }
  11475. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  11476. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  11477. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  11478. // Find all of the overloaded operators visible from this
  11479. // point. We perform both an operator-name lookup from the local
  11480. // scope and an argument-dependent lookup based on the types of
  11481. // the arguments.
  11482. UnresolvedSet<16> Functions;
  11483. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  11484. if (S && OverOp != OO_None)
  11485. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  11486. Functions);
  11487. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  11488. }
  11489. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  11490. }
  11491. // Unary Operators. 'Tok' is the token for the operator.
  11492. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  11493. tok::TokenKind Op, Expr *Input) {
  11494. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  11495. }
  11496. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  11497. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  11498. LabelDecl *TheDecl) {
  11499. TheDecl->markUsed(Context);
  11500. // Create the AST node. The address of a label always has type 'void*'.
  11501. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  11502. Context.getPointerType(Context.VoidTy));
  11503. }
  11504. /// Given the last statement in a statement-expression, check whether
  11505. /// the result is a producing expression (like a call to an
  11506. /// ns_returns_retained function) and, if so, rebuild it to hoist the
  11507. /// release out of the full-expression. Otherwise, return null.
  11508. /// Cannot fail.
  11509. static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
  11510. // Should always be wrapped with one of these.
  11511. ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
  11512. if (!cleanups) return nullptr;
  11513. ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
  11514. if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
  11515. return nullptr;
  11516. // Splice out the cast. This shouldn't modify any interesting
  11517. // features of the statement.
  11518. Expr *producer = cast->getSubExpr();
  11519. assert(producer->getType() == cast->getType());
  11520. assert(producer->getValueKind() == cast->getValueKind());
  11521. cleanups->setSubExpr(producer);
  11522. return cleanups;
  11523. }
  11524. void Sema::ActOnStartStmtExpr() {
  11525. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11526. }
  11527. void Sema::ActOnStmtExprError() {
  11528. // Note that function is also called by TreeTransform when leaving a
  11529. // StmtExpr scope without rebuilding anything.
  11530. DiscardCleanupsInEvaluationContext();
  11531. PopExpressionEvaluationContext();
  11532. }
  11533. ExprResult
  11534. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  11535. SourceLocation RPLoc) { // "({..})"
  11536. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  11537. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  11538. if (hasAnyUnrecoverableErrorsInThisFunction())
  11539. DiscardCleanupsInEvaluationContext();
  11540. assert(!Cleanup.exprNeedsCleanups() &&
  11541. "cleanups within StmtExpr not correctly bound!");
  11542. PopExpressionEvaluationContext();
  11543. // FIXME: there are a variety of strange constraints to enforce here, for
  11544. // example, it is not possible to goto into a stmt expression apparently.
  11545. // More semantic analysis is needed.
  11546. // If there are sub-stmts in the compound stmt, take the type of the last one
  11547. // as the type of the stmtexpr.
  11548. QualType Ty = Context.VoidTy;
  11549. bool StmtExprMayBindToTemp = false;
  11550. if (!Compound->body_empty()) {
  11551. Stmt *LastStmt = Compound->body_back();
  11552. LabelStmt *LastLabelStmt = nullptr;
  11553. // If LastStmt is a label, skip down through into the body.
  11554. while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
  11555. LastLabelStmt = Label;
  11556. LastStmt = Label->getSubStmt();
  11557. }
  11558. if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
  11559. // Do function/array conversion on the last expression, but not
  11560. // lvalue-to-rvalue. However, initialize an unqualified type.
  11561. ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
  11562. if (LastExpr.isInvalid())
  11563. return ExprError();
  11564. Ty = LastExpr.get()->getType().getUnqualifiedType();
  11565. if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
  11566. // In ARC, if the final expression ends in a consume, splice
  11567. // the consume out and bind it later. In the alternate case
  11568. // (when dealing with a retainable type), the result
  11569. // initialization will create a produce. In both cases the
  11570. // result will be +1, and we'll need to balance that out with
  11571. // a bind.
  11572. if (Expr *rebuiltLastStmt
  11573. = maybeRebuildARCConsumingStmt(LastExpr.get())) {
  11574. LastExpr = rebuiltLastStmt;
  11575. } else {
  11576. LastExpr = PerformCopyInitialization(
  11577. InitializedEntity::InitializeStmtExprResult(LPLoc, Ty),
  11578. SourceLocation(), LastExpr);
  11579. }
  11580. if (LastExpr.isInvalid())
  11581. return ExprError();
  11582. if (LastExpr.get() != nullptr) {
  11583. if (!LastLabelStmt)
  11584. Compound->setLastStmt(LastExpr.get());
  11585. else
  11586. LastLabelStmt->setSubStmt(LastExpr.get());
  11587. StmtExprMayBindToTemp = true;
  11588. }
  11589. }
  11590. }
  11591. }
  11592. // FIXME: Check that expression type is complete/non-abstract; statement
  11593. // expressions are not lvalues.
  11594. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  11595. if (StmtExprMayBindToTemp)
  11596. return MaybeBindToTemporary(ResStmtExpr);
  11597. return ResStmtExpr;
  11598. }
  11599. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  11600. TypeSourceInfo *TInfo,
  11601. ArrayRef<OffsetOfComponent> Components,
  11602. SourceLocation RParenLoc) {
  11603. QualType ArgTy = TInfo->getType();
  11604. bool Dependent = ArgTy->isDependentType();
  11605. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  11606. // We must have at least one component that refers to the type, and the first
  11607. // one is known to be a field designator. Verify that the ArgTy represents
  11608. // a struct/union/class.
  11609. if (!Dependent && !ArgTy->isRecordType())
  11610. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  11611. << ArgTy << TypeRange);
  11612. // Type must be complete per C99 7.17p3 because a declaring a variable
  11613. // with an incomplete type would be ill-formed.
  11614. if (!Dependent
  11615. && RequireCompleteType(BuiltinLoc, ArgTy,
  11616. diag::err_offsetof_incomplete_type, TypeRange))
  11617. return ExprError();
  11618. bool DidWarnAboutNonPOD = false;
  11619. QualType CurrentType = ArgTy;
  11620. SmallVector<OffsetOfNode, 4> Comps;
  11621. SmallVector<Expr*, 4> Exprs;
  11622. for (const OffsetOfComponent &OC : Components) {
  11623. if (OC.isBrackets) {
  11624. // Offset of an array sub-field. TODO: Should we allow vector elements?
  11625. if (!CurrentType->isDependentType()) {
  11626. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  11627. if(!AT)
  11628. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  11629. << CurrentType);
  11630. CurrentType = AT->getElementType();
  11631. } else
  11632. CurrentType = Context.DependentTy;
  11633. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  11634. if (IdxRval.isInvalid())
  11635. return ExprError();
  11636. Expr *Idx = IdxRval.get();
  11637. // The expression must be an integral expression.
  11638. // FIXME: An integral constant expression?
  11639. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  11640. !Idx->getType()->isIntegerType())
  11641. return ExprError(
  11642. Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
  11643. << Idx->getSourceRange());
  11644. // Record this array index.
  11645. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  11646. Exprs.push_back(Idx);
  11647. continue;
  11648. }
  11649. // Offset of a field.
  11650. if (CurrentType->isDependentType()) {
  11651. // We have the offset of a field, but we can't look into the dependent
  11652. // type. Just record the identifier of the field.
  11653. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  11654. CurrentType = Context.DependentTy;
  11655. continue;
  11656. }
  11657. // We need to have a complete type to look into.
  11658. if (RequireCompleteType(OC.LocStart, CurrentType,
  11659. diag::err_offsetof_incomplete_type))
  11660. return ExprError();
  11661. // Look for the designated field.
  11662. const RecordType *RC = CurrentType->getAs<RecordType>();
  11663. if (!RC)
  11664. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  11665. << CurrentType);
  11666. RecordDecl *RD = RC->getDecl();
  11667. // C++ [lib.support.types]p5:
  11668. // The macro offsetof accepts a restricted set of type arguments in this
  11669. // International Standard. type shall be a POD structure or a POD union
  11670. // (clause 9).
  11671. // C++11 [support.types]p4:
  11672. // If type is not a standard-layout class (Clause 9), the results are
  11673. // undefined.
  11674. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  11675. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  11676. unsigned DiagID =
  11677. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  11678. : diag::ext_offsetof_non_pod_type;
  11679. if (!IsSafe && !DidWarnAboutNonPOD &&
  11680. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  11681. PDiag(DiagID)
  11682. << SourceRange(Components[0].LocStart, OC.LocEnd)
  11683. << CurrentType))
  11684. DidWarnAboutNonPOD = true;
  11685. }
  11686. // Look for the field.
  11687. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  11688. LookupQualifiedName(R, RD);
  11689. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  11690. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  11691. if (!MemberDecl) {
  11692. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  11693. MemberDecl = IndirectMemberDecl->getAnonField();
  11694. }
  11695. if (!MemberDecl)
  11696. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  11697. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  11698. OC.LocEnd));
  11699. // C99 7.17p3:
  11700. // (If the specified member is a bit-field, the behavior is undefined.)
  11701. //
  11702. // We diagnose this as an error.
  11703. if (MemberDecl->isBitField()) {
  11704. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  11705. << MemberDecl->getDeclName()
  11706. << SourceRange(BuiltinLoc, RParenLoc);
  11707. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  11708. return ExprError();
  11709. }
  11710. RecordDecl *Parent = MemberDecl->getParent();
  11711. if (IndirectMemberDecl)
  11712. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  11713. // If the member was found in a base class, introduce OffsetOfNodes for
  11714. // the base class indirections.
  11715. CXXBasePaths Paths;
  11716. if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
  11717. Paths)) {
  11718. if (Paths.getDetectedVirtual()) {
  11719. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  11720. << MemberDecl->getDeclName()
  11721. << SourceRange(BuiltinLoc, RParenLoc);
  11722. return ExprError();
  11723. }
  11724. CXXBasePath &Path = Paths.front();
  11725. for (const CXXBasePathElement &B : Path)
  11726. Comps.push_back(OffsetOfNode(B.Base));
  11727. }
  11728. if (IndirectMemberDecl) {
  11729. for (auto *FI : IndirectMemberDecl->chain()) {
  11730. assert(isa<FieldDecl>(FI));
  11731. Comps.push_back(OffsetOfNode(OC.LocStart,
  11732. cast<FieldDecl>(FI), OC.LocEnd));
  11733. }
  11734. } else
  11735. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  11736. CurrentType = MemberDecl->getType().getNonReferenceType();
  11737. }
  11738. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  11739. Comps, Exprs, RParenLoc);
  11740. }
  11741. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  11742. SourceLocation BuiltinLoc,
  11743. SourceLocation TypeLoc,
  11744. ParsedType ParsedArgTy,
  11745. ArrayRef<OffsetOfComponent> Components,
  11746. SourceLocation RParenLoc) {
  11747. TypeSourceInfo *ArgTInfo;
  11748. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  11749. if (ArgTy.isNull())
  11750. return ExprError();
  11751. if (!ArgTInfo)
  11752. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  11753. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
  11754. }
  11755. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  11756. Expr *CondExpr,
  11757. Expr *LHSExpr, Expr *RHSExpr,
  11758. SourceLocation RPLoc) {
  11759. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  11760. ExprValueKind VK = VK_RValue;
  11761. ExprObjectKind OK = OK_Ordinary;
  11762. QualType resType;
  11763. bool ValueDependent = false;
  11764. bool CondIsTrue = false;
  11765. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  11766. resType = Context.DependentTy;
  11767. ValueDependent = true;
  11768. } else {
  11769. // The conditional expression is required to be a constant expression.
  11770. llvm::APSInt condEval(32);
  11771. ExprResult CondICE
  11772. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  11773. diag::err_typecheck_choose_expr_requires_constant, false);
  11774. if (CondICE.isInvalid())
  11775. return ExprError();
  11776. CondExpr = CondICE.get();
  11777. CondIsTrue = condEval.getZExtValue();
  11778. // If the condition is > zero, then the AST type is the same as the LHSExpr.
  11779. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  11780. resType = ActiveExpr->getType();
  11781. ValueDependent = ActiveExpr->isValueDependent();
  11782. VK = ActiveExpr->getValueKind();
  11783. OK = ActiveExpr->getObjectKind();
  11784. }
  11785. return new (Context)
  11786. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  11787. CondIsTrue, resType->isDependentType(), ValueDependent);
  11788. }
  11789. //===----------------------------------------------------------------------===//
  11790. // Clang Extensions.
  11791. //===----------------------------------------------------------------------===//
  11792. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  11793. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  11794. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  11795. if (LangOpts.CPlusPlus) {
  11796. Decl *ManglingContextDecl;
  11797. if (MangleNumberingContext *MCtx =
  11798. getCurrentMangleNumberContext(Block->getDeclContext(),
  11799. ManglingContextDecl)) {
  11800. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  11801. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  11802. }
  11803. }
  11804. PushBlockScope(CurScope, Block);
  11805. CurContext->addDecl(Block);
  11806. if (CurScope)
  11807. PushDeclContext(CurScope, Block);
  11808. else
  11809. CurContext = Block;
  11810. getCurBlock()->HasImplicitReturnType = true;
  11811. // Enter a new evaluation context to insulate the block from any
  11812. // cleanups from the enclosing full-expression.
  11813. PushExpressionEvaluationContext(
  11814. ExpressionEvaluationContext::PotentiallyEvaluated);
  11815. }
  11816. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  11817. Scope *CurScope) {
  11818. assert(ParamInfo.getIdentifier() == nullptr &&
  11819. "block-id should have no identifier!");
  11820. assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
  11821. BlockScopeInfo *CurBlock = getCurBlock();
  11822. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  11823. QualType T = Sig->getType();
  11824. // FIXME: We should allow unexpanded parameter packs here, but that would,
  11825. // in turn, make the block expression contain unexpanded parameter packs.
  11826. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  11827. // Drop the parameters.
  11828. FunctionProtoType::ExtProtoInfo EPI;
  11829. EPI.HasTrailingReturn = false;
  11830. EPI.TypeQuals |= DeclSpec::TQ_const;
  11831. T = Context.getFunctionType(Context.DependentTy, None, EPI);
  11832. Sig = Context.getTrivialTypeSourceInfo(T);
  11833. }
  11834. // GetTypeForDeclarator always produces a function type for a block
  11835. // literal signature. Furthermore, it is always a FunctionProtoType
  11836. // unless the function was written with a typedef.
  11837. assert(T->isFunctionType() &&
  11838. "GetTypeForDeclarator made a non-function block signature");
  11839. // Look for an explicit signature in that function type.
  11840. FunctionProtoTypeLoc ExplicitSignature;
  11841. if ((ExplicitSignature =
  11842. Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
  11843. // Check whether that explicit signature was synthesized by
  11844. // GetTypeForDeclarator. If so, don't save that as part of the
  11845. // written signature.
  11846. if (ExplicitSignature.getLocalRangeBegin() ==
  11847. ExplicitSignature.getLocalRangeEnd()) {
  11848. // This would be much cheaper if we stored TypeLocs instead of
  11849. // TypeSourceInfos.
  11850. TypeLoc Result = ExplicitSignature.getReturnLoc();
  11851. unsigned Size = Result.getFullDataSize();
  11852. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  11853. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  11854. ExplicitSignature = FunctionProtoTypeLoc();
  11855. }
  11856. }
  11857. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  11858. CurBlock->FunctionType = T;
  11859. const FunctionType *Fn = T->getAs<FunctionType>();
  11860. QualType RetTy = Fn->getReturnType();
  11861. bool isVariadic =
  11862. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  11863. CurBlock->TheDecl->setIsVariadic(isVariadic);
  11864. // Context.DependentTy is used as a placeholder for a missing block
  11865. // return type. TODO: what should we do with declarators like:
  11866. // ^ * { ... }
  11867. // If the answer is "apply template argument deduction"....
  11868. if (RetTy != Context.DependentTy) {
  11869. CurBlock->ReturnType = RetTy;
  11870. CurBlock->TheDecl->setBlockMissingReturnType(false);
  11871. CurBlock->HasImplicitReturnType = false;
  11872. }
  11873. // Push block parameters from the declarator if we had them.
  11874. SmallVector<ParmVarDecl*, 8> Params;
  11875. if (ExplicitSignature) {
  11876. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  11877. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  11878. if (Param->getIdentifier() == nullptr &&
  11879. !Param->isImplicit() &&
  11880. !Param->isInvalidDecl() &&
  11881. !getLangOpts().CPlusPlus)
  11882. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  11883. Params.push_back(Param);
  11884. }
  11885. // Fake up parameter variables if we have a typedef, like
  11886. // ^ fntype { ... }
  11887. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  11888. for (const auto &I : Fn->param_types()) {
  11889. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  11890. CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
  11891. Params.push_back(Param);
  11892. }
  11893. }
  11894. // Set the parameters on the block decl.
  11895. if (!Params.empty()) {
  11896. CurBlock->TheDecl->setParams(Params);
  11897. CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
  11898. /*CheckParameterNames=*/false);
  11899. }
  11900. // Finally we can process decl attributes.
  11901. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  11902. // Put the parameter variables in scope.
  11903. for (auto AI : CurBlock->TheDecl->parameters()) {
  11904. AI->setOwningFunction(CurBlock->TheDecl);
  11905. // If this has an identifier, add it to the scope stack.
  11906. if (AI->getIdentifier()) {
  11907. CheckShadow(CurBlock->TheScope, AI);
  11908. PushOnScopeChains(AI, CurBlock->TheScope);
  11909. }
  11910. }
  11911. }
  11912. /// ActOnBlockError - If there is an error parsing a block, this callback
  11913. /// is invoked to pop the information about the block from the action impl.
  11914. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  11915. // Leave the expression-evaluation context.
  11916. DiscardCleanupsInEvaluationContext();
  11917. PopExpressionEvaluationContext();
  11918. // Pop off CurBlock, handle nested blocks.
  11919. PopDeclContext();
  11920. PopFunctionScopeInfo();
  11921. }
  11922. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  11923. /// literal was successfully completed. ^(int x){...}
  11924. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  11925. Stmt *Body, Scope *CurScope) {
  11926. // If blocks are disabled, emit an error.
  11927. if (!LangOpts.Blocks)
  11928. Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
  11929. // Leave the expression-evaluation context.
  11930. if (hasAnyUnrecoverableErrorsInThisFunction())
  11931. DiscardCleanupsInEvaluationContext();
  11932. assert(!Cleanup.exprNeedsCleanups() &&
  11933. "cleanups within block not correctly bound!");
  11934. PopExpressionEvaluationContext();
  11935. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  11936. BlockDecl *BD = BSI->TheDecl;
  11937. if (BSI->HasImplicitReturnType)
  11938. deduceClosureReturnType(*BSI);
  11939. PopDeclContext();
  11940. QualType RetTy = Context.VoidTy;
  11941. if (!BSI->ReturnType.isNull())
  11942. RetTy = BSI->ReturnType;
  11943. bool NoReturn = BD->hasAttr<NoReturnAttr>();
  11944. QualType BlockTy;
  11945. // Set the captured variables on the block.
  11946. // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
  11947. SmallVector<BlockDecl::Capture, 4> Captures;
  11948. for (Capture &Cap : BSI->Captures) {
  11949. if (Cap.isThisCapture())
  11950. continue;
  11951. BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
  11952. Cap.isNested(), Cap.getInitExpr());
  11953. Captures.push_back(NewCap);
  11954. }
  11955. BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
  11956. // If the user wrote a function type in some form, try to use that.
  11957. if (!BSI->FunctionType.isNull()) {
  11958. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  11959. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  11960. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  11961. // Turn protoless block types into nullary block types.
  11962. if (isa<FunctionNoProtoType>(FTy)) {
  11963. FunctionProtoType::ExtProtoInfo EPI;
  11964. EPI.ExtInfo = Ext;
  11965. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  11966. // Otherwise, if we don't need to change anything about the function type,
  11967. // preserve its sugar structure.
  11968. } else if (FTy->getReturnType() == RetTy &&
  11969. (!NoReturn || FTy->getNoReturnAttr())) {
  11970. BlockTy = BSI->FunctionType;
  11971. // Otherwise, make the minimal modifications to the function type.
  11972. } else {
  11973. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  11974. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  11975. EPI.TypeQuals = 0; // FIXME: silently?
  11976. EPI.ExtInfo = Ext;
  11977. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  11978. }
  11979. // If we don't have a function type, just build one from nothing.
  11980. } else {
  11981. FunctionProtoType::ExtProtoInfo EPI;
  11982. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  11983. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  11984. }
  11985. DiagnoseUnusedParameters(BD->parameters());
  11986. BlockTy = Context.getBlockPointerType(BlockTy);
  11987. // If needed, diagnose invalid gotos and switches in the block.
  11988. if (getCurFunction()->NeedsScopeChecking() &&
  11989. !PP.isCodeCompletionEnabled())
  11990. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  11991. BD->setBody(cast<CompoundStmt>(Body));
  11992. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  11993. DiagnoseUnguardedAvailabilityViolations(BD);
  11994. // Try to apply the named return value optimization. We have to check again
  11995. // if we can do this, though, because blocks keep return statements around
  11996. // to deduce an implicit return type.
  11997. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  11998. !BD->isDependentContext())
  11999. computeNRVO(Body, BSI);
  12000. BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
  12001. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  12002. PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
  12003. // If the block isn't obviously global, i.e. it captures anything at
  12004. // all, then we need to do a few things in the surrounding context:
  12005. if (Result->getBlockDecl()->hasCaptures()) {
  12006. // First, this expression has a new cleanup object.
  12007. ExprCleanupObjects.push_back(Result->getBlockDecl());
  12008. Cleanup.setExprNeedsCleanups(true);
  12009. // It also gets a branch-protected scope if any of the captured
  12010. // variables needs destruction.
  12011. for (const auto &CI : Result->getBlockDecl()->captures()) {
  12012. const VarDecl *var = CI.getVariable();
  12013. if (var->getType().isDestructedType() != QualType::DK_none) {
  12014. setFunctionHasBranchProtectedScope();
  12015. break;
  12016. }
  12017. }
  12018. }
  12019. if (getCurFunction())
  12020. getCurFunction()->addBlock(BD);
  12021. return Result;
  12022. }
  12023. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
  12024. SourceLocation RPLoc) {
  12025. TypeSourceInfo *TInfo;
  12026. GetTypeFromParser(Ty, &TInfo);
  12027. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  12028. }
  12029. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  12030. Expr *E, TypeSourceInfo *TInfo,
  12031. SourceLocation RPLoc) {
  12032. Expr *OrigExpr = E;
  12033. bool IsMS = false;
  12034. // CUDA device code does not support varargs.
  12035. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  12036. if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
  12037. CUDAFunctionTarget T = IdentifyCUDATarget(F);
  12038. if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
  12039. return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
  12040. }
  12041. }
  12042. // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
  12043. // as Microsoft ABI on an actual Microsoft platform, where
  12044. // __builtin_ms_va_list and __builtin_va_list are the same.)
  12045. if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
  12046. Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
  12047. QualType MSVaListType = Context.getBuiltinMSVaListType();
  12048. if (Context.hasSameType(MSVaListType, E->getType())) {
  12049. if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12050. return ExprError();
  12051. IsMS = true;
  12052. }
  12053. }
  12054. // Get the va_list type
  12055. QualType VaListType = Context.getBuiltinVaListType();
  12056. if (!IsMS) {
  12057. if (VaListType->isArrayType()) {
  12058. // Deal with implicit array decay; for example, on x86-64,
  12059. // va_list is an array, but it's supposed to decay to
  12060. // a pointer for va_arg.
  12061. VaListType = Context.getArrayDecayedType(VaListType);
  12062. // Make sure the input expression also decays appropriately.
  12063. ExprResult Result = UsualUnaryConversions(E);
  12064. if (Result.isInvalid())
  12065. return ExprError();
  12066. E = Result.get();
  12067. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  12068. // If va_list is a record type and we are compiling in C++ mode,
  12069. // check the argument using reference binding.
  12070. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  12071. Context, Context.getLValueReferenceType(VaListType), false);
  12072. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  12073. if (Init.isInvalid())
  12074. return ExprError();
  12075. E = Init.getAs<Expr>();
  12076. } else {
  12077. // Otherwise, the va_list argument must be an l-value because
  12078. // it is modified by va_arg.
  12079. if (!E->isTypeDependent() &&
  12080. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12081. return ExprError();
  12082. }
  12083. }
  12084. if (!IsMS && !E->isTypeDependent() &&
  12085. !Context.hasSameType(VaListType, E->getType()))
  12086. return ExprError(
  12087. Diag(E->getBeginLoc(),
  12088. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  12089. << OrigExpr->getType() << E->getSourceRange());
  12090. if (!TInfo->getType()->isDependentType()) {
  12091. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  12092. diag::err_second_parameter_to_va_arg_incomplete,
  12093. TInfo->getTypeLoc()))
  12094. return ExprError();
  12095. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  12096. TInfo->getType(),
  12097. diag::err_second_parameter_to_va_arg_abstract,
  12098. TInfo->getTypeLoc()))
  12099. return ExprError();
  12100. if (!TInfo->getType().isPODType(Context)) {
  12101. Diag(TInfo->getTypeLoc().getBeginLoc(),
  12102. TInfo->getType()->isObjCLifetimeType()
  12103. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  12104. : diag::warn_second_parameter_to_va_arg_not_pod)
  12105. << TInfo->getType()
  12106. << TInfo->getTypeLoc().getSourceRange();
  12107. }
  12108. // Check for va_arg where arguments of the given type will be promoted
  12109. // (i.e. this va_arg is guaranteed to have undefined behavior).
  12110. QualType PromoteType;
  12111. if (TInfo->getType()->isPromotableIntegerType()) {
  12112. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  12113. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  12114. PromoteType = QualType();
  12115. }
  12116. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  12117. PromoteType = Context.DoubleTy;
  12118. if (!PromoteType.isNull())
  12119. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  12120. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  12121. << TInfo->getType()
  12122. << PromoteType
  12123. << TInfo->getTypeLoc().getSourceRange());
  12124. }
  12125. QualType T = TInfo->getType().getNonLValueExprType(Context);
  12126. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
  12127. }
  12128. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  12129. // The type of __null will be int or long, depending on the size of
  12130. // pointers on the target.
  12131. QualType Ty;
  12132. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  12133. if (pw == Context.getTargetInfo().getIntWidth())
  12134. Ty = Context.IntTy;
  12135. else if (pw == Context.getTargetInfo().getLongWidth())
  12136. Ty = Context.LongTy;
  12137. else if (pw == Context.getTargetInfo().getLongLongWidth())
  12138. Ty = Context.LongLongTy;
  12139. else {
  12140. llvm_unreachable("I don't know size of pointer!");
  12141. }
  12142. return new (Context) GNUNullExpr(Ty, TokenLoc);
  12143. }
  12144. bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
  12145. bool Diagnose) {
  12146. if (!getLangOpts().ObjC)
  12147. return false;
  12148. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  12149. if (!PT)
  12150. return false;
  12151. if (!PT->isObjCIdType()) {
  12152. // Check if the destination is the 'NSString' interface.
  12153. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  12154. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  12155. return false;
  12156. }
  12157. // Ignore any parens, implicit casts (should only be
  12158. // array-to-pointer decays), and not-so-opaque values. The last is
  12159. // important for making this trigger for property assignments.
  12160. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  12161. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  12162. if (OV->getSourceExpr())
  12163. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  12164. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  12165. if (!SL || !SL->isAscii())
  12166. return false;
  12167. if (Diagnose) {
  12168. Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
  12169. << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
  12170. Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
  12171. }
  12172. return true;
  12173. }
  12174. static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
  12175. const Expr *SrcExpr) {
  12176. if (!DstType->isFunctionPointerType() ||
  12177. !SrcExpr->getType()->isFunctionType())
  12178. return false;
  12179. auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
  12180. if (!DRE)
  12181. return false;
  12182. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  12183. if (!FD)
  12184. return false;
  12185. return !S.checkAddressOfFunctionIsAvailable(FD,
  12186. /*Complain=*/true,
  12187. SrcExpr->getBeginLoc());
  12188. }
  12189. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  12190. SourceLocation Loc,
  12191. QualType DstType, QualType SrcType,
  12192. Expr *SrcExpr, AssignmentAction Action,
  12193. bool *Complained) {
  12194. if (Complained)
  12195. *Complained = false;
  12196. // Decode the result (notice that AST's are still created for extensions).
  12197. bool CheckInferredResultType = false;
  12198. bool isInvalid = false;
  12199. unsigned DiagKind = 0;
  12200. FixItHint Hint;
  12201. ConversionFixItGenerator ConvHints;
  12202. bool MayHaveConvFixit = false;
  12203. bool MayHaveFunctionDiff = false;
  12204. const ObjCInterfaceDecl *IFace = nullptr;
  12205. const ObjCProtocolDecl *PDecl = nullptr;
  12206. switch (ConvTy) {
  12207. case Compatible:
  12208. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  12209. return false;
  12210. case PointerToInt:
  12211. DiagKind = diag::ext_typecheck_convert_pointer_int;
  12212. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12213. MayHaveConvFixit = true;
  12214. break;
  12215. case IntToPointer:
  12216. DiagKind = diag::ext_typecheck_convert_int_pointer;
  12217. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12218. MayHaveConvFixit = true;
  12219. break;
  12220. case IncompatiblePointer:
  12221. if (Action == AA_Passing_CFAudited)
  12222. DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
  12223. else if (SrcType->isFunctionPointerType() &&
  12224. DstType->isFunctionPointerType())
  12225. DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
  12226. else
  12227. DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
  12228. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  12229. SrcType->isObjCObjectPointerType();
  12230. if (Hint.isNull() && !CheckInferredResultType) {
  12231. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12232. }
  12233. else if (CheckInferredResultType) {
  12234. SrcType = SrcType.getUnqualifiedType();
  12235. DstType = DstType.getUnqualifiedType();
  12236. }
  12237. MayHaveConvFixit = true;
  12238. break;
  12239. case IncompatiblePointerSign:
  12240. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  12241. break;
  12242. case FunctionVoidPointer:
  12243. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  12244. break;
  12245. case IncompatiblePointerDiscardsQualifiers: {
  12246. // Perform array-to-pointer decay if necessary.
  12247. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  12248. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  12249. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  12250. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  12251. DiagKind = diag::err_typecheck_incompatible_address_space;
  12252. break;
  12253. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  12254. DiagKind = diag::err_typecheck_incompatible_ownership;
  12255. break;
  12256. }
  12257. llvm_unreachable("unknown error case for discarding qualifiers!");
  12258. // fallthrough
  12259. }
  12260. case CompatiblePointerDiscardsQualifiers:
  12261. // If the qualifiers lost were because we were applying the
  12262. // (deprecated) C++ conversion from a string literal to a char*
  12263. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  12264. // Ideally, this check would be performed in
  12265. // checkPointerTypesForAssignment. However, that would require a
  12266. // bit of refactoring (so that the second argument is an
  12267. // expression, rather than a type), which should be done as part
  12268. // of a larger effort to fix checkPointerTypesForAssignment for
  12269. // C++ semantics.
  12270. if (getLangOpts().CPlusPlus &&
  12271. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  12272. return false;
  12273. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  12274. break;
  12275. case IncompatibleNestedPointerQualifiers:
  12276. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  12277. break;
  12278. case IntToBlockPointer:
  12279. DiagKind = diag::err_int_to_block_pointer;
  12280. break;
  12281. case IncompatibleBlockPointer:
  12282. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  12283. break;
  12284. case IncompatibleObjCQualifiedId: {
  12285. if (SrcType->isObjCQualifiedIdType()) {
  12286. const ObjCObjectPointerType *srcOPT =
  12287. SrcType->getAs<ObjCObjectPointerType>();
  12288. for (auto *srcProto : srcOPT->quals()) {
  12289. PDecl = srcProto;
  12290. break;
  12291. }
  12292. if (const ObjCInterfaceType *IFaceT =
  12293. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  12294. IFace = IFaceT->getDecl();
  12295. }
  12296. else if (DstType->isObjCQualifiedIdType()) {
  12297. const ObjCObjectPointerType *dstOPT =
  12298. DstType->getAs<ObjCObjectPointerType>();
  12299. for (auto *dstProto : dstOPT->quals()) {
  12300. PDecl = dstProto;
  12301. break;
  12302. }
  12303. if (const ObjCInterfaceType *IFaceT =
  12304. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  12305. IFace = IFaceT->getDecl();
  12306. }
  12307. DiagKind = diag::warn_incompatible_qualified_id;
  12308. break;
  12309. }
  12310. case IncompatibleVectors:
  12311. DiagKind = diag::warn_incompatible_vectors;
  12312. break;
  12313. case IncompatibleObjCWeakRef:
  12314. DiagKind = diag::err_arc_weak_unavailable_assign;
  12315. break;
  12316. case Incompatible:
  12317. if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
  12318. if (Complained)
  12319. *Complained = true;
  12320. return true;
  12321. }
  12322. DiagKind = diag::err_typecheck_convert_incompatible;
  12323. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12324. MayHaveConvFixit = true;
  12325. isInvalid = true;
  12326. MayHaveFunctionDiff = true;
  12327. break;
  12328. }
  12329. QualType FirstType, SecondType;
  12330. switch (Action) {
  12331. case AA_Assigning:
  12332. case AA_Initializing:
  12333. // The destination type comes first.
  12334. FirstType = DstType;
  12335. SecondType = SrcType;
  12336. break;
  12337. case AA_Returning:
  12338. case AA_Passing:
  12339. case AA_Passing_CFAudited:
  12340. case AA_Converting:
  12341. case AA_Sending:
  12342. case AA_Casting:
  12343. // The source type comes first.
  12344. FirstType = SrcType;
  12345. SecondType = DstType;
  12346. break;
  12347. }
  12348. PartialDiagnostic FDiag = PDiag(DiagKind);
  12349. if (Action == AA_Passing_CFAudited)
  12350. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  12351. else
  12352. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  12353. // If we can fix the conversion, suggest the FixIts.
  12354. assert(ConvHints.isNull() || Hint.isNull());
  12355. if (!ConvHints.isNull()) {
  12356. for (FixItHint &H : ConvHints.Hints)
  12357. FDiag << H;
  12358. } else {
  12359. FDiag << Hint;
  12360. }
  12361. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  12362. if (MayHaveFunctionDiff)
  12363. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  12364. Diag(Loc, FDiag);
  12365. if (DiagKind == diag::warn_incompatible_qualified_id &&
  12366. PDecl && IFace && !IFace->hasDefinition())
  12367. Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
  12368. << IFace << PDecl;
  12369. if (SecondType == Context.OverloadTy)
  12370. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  12371. FirstType, /*TakingAddress=*/true);
  12372. if (CheckInferredResultType)
  12373. EmitRelatedResultTypeNote(SrcExpr);
  12374. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  12375. EmitRelatedResultTypeNoteForReturn(DstType);
  12376. if (Complained)
  12377. *Complained = true;
  12378. return isInvalid;
  12379. }
  12380. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  12381. llvm::APSInt *Result) {
  12382. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  12383. public:
  12384. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  12385. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  12386. }
  12387. } Diagnoser;
  12388. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  12389. }
  12390. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  12391. llvm::APSInt *Result,
  12392. unsigned DiagID,
  12393. bool AllowFold) {
  12394. class IDDiagnoser : public VerifyICEDiagnoser {
  12395. unsigned DiagID;
  12396. public:
  12397. IDDiagnoser(unsigned DiagID)
  12398. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  12399. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  12400. S.Diag(Loc, DiagID) << SR;
  12401. }
  12402. } Diagnoser(DiagID);
  12403. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  12404. }
  12405. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  12406. SourceRange SR) {
  12407. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  12408. }
  12409. ExprResult
  12410. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  12411. VerifyICEDiagnoser &Diagnoser,
  12412. bool AllowFold) {
  12413. SourceLocation DiagLoc = E->getBeginLoc();
  12414. if (getLangOpts().CPlusPlus11) {
  12415. // C++11 [expr.const]p5:
  12416. // If an expression of literal class type is used in a context where an
  12417. // integral constant expression is required, then that class type shall
  12418. // have a single non-explicit conversion function to an integral or
  12419. // unscoped enumeration type
  12420. ExprResult Converted;
  12421. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  12422. public:
  12423. CXX11ConvertDiagnoser(bool Silent)
  12424. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  12425. Silent, true) {}
  12426. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  12427. QualType T) override {
  12428. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  12429. }
  12430. SemaDiagnosticBuilder diagnoseIncomplete(
  12431. Sema &S, SourceLocation Loc, QualType T) override {
  12432. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  12433. }
  12434. SemaDiagnosticBuilder diagnoseExplicitConv(
  12435. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  12436. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  12437. }
  12438. SemaDiagnosticBuilder noteExplicitConv(
  12439. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  12440. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  12441. << ConvTy->isEnumeralType() << ConvTy;
  12442. }
  12443. SemaDiagnosticBuilder diagnoseAmbiguous(
  12444. Sema &S, SourceLocation Loc, QualType T) override {
  12445. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  12446. }
  12447. SemaDiagnosticBuilder noteAmbiguous(
  12448. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  12449. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  12450. << ConvTy->isEnumeralType() << ConvTy;
  12451. }
  12452. SemaDiagnosticBuilder diagnoseConversion(
  12453. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  12454. llvm_unreachable("conversion functions are permitted");
  12455. }
  12456. } ConvertDiagnoser(Diagnoser.Suppress);
  12457. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  12458. ConvertDiagnoser);
  12459. if (Converted.isInvalid())
  12460. return Converted;
  12461. E = Converted.get();
  12462. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  12463. return ExprError();
  12464. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  12465. // An ICE must be of integral or unscoped enumeration type.
  12466. if (!Diagnoser.Suppress)
  12467. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  12468. return ExprError();
  12469. }
  12470. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  12471. // in the non-ICE case.
  12472. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  12473. if (Result)
  12474. *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
  12475. return E;
  12476. }
  12477. Expr::EvalResult EvalResult;
  12478. SmallVector<PartialDiagnosticAt, 8> Notes;
  12479. EvalResult.Diag = &Notes;
  12480. // Try to evaluate the expression, and produce diagnostics explaining why it's
  12481. // not a constant expression as a side-effect.
  12482. bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
  12483. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  12484. // In C++11, we can rely on diagnostics being produced for any expression
  12485. // which is not a constant expression. If no diagnostics were produced, then
  12486. // this is a constant expression.
  12487. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  12488. if (Result)
  12489. *Result = EvalResult.Val.getInt();
  12490. return E;
  12491. }
  12492. // If our only note is the usual "invalid subexpression" note, just point
  12493. // the caret at its location rather than producing an essentially
  12494. // redundant note.
  12495. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  12496. diag::note_invalid_subexpr_in_const_expr) {
  12497. DiagLoc = Notes[0].first;
  12498. Notes.clear();
  12499. }
  12500. if (!Folded || !AllowFold) {
  12501. if (!Diagnoser.Suppress) {
  12502. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  12503. for (const PartialDiagnosticAt &Note : Notes)
  12504. Diag(Note.first, Note.second);
  12505. }
  12506. return ExprError();
  12507. }
  12508. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  12509. for (const PartialDiagnosticAt &Note : Notes)
  12510. Diag(Note.first, Note.second);
  12511. if (Result)
  12512. *Result = EvalResult.Val.getInt();
  12513. return E;
  12514. }
  12515. namespace {
  12516. // Handle the case where we conclude a expression which we speculatively
  12517. // considered to be unevaluated is actually evaluated.
  12518. class TransformToPE : public TreeTransform<TransformToPE> {
  12519. typedef TreeTransform<TransformToPE> BaseTransform;
  12520. public:
  12521. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  12522. // Make sure we redo semantic analysis
  12523. bool AlwaysRebuild() { return true; }
  12524. // Make sure we handle LabelStmts correctly.
  12525. // FIXME: This does the right thing, but maybe we need a more general
  12526. // fix to TreeTransform?
  12527. StmtResult TransformLabelStmt(LabelStmt *S) {
  12528. S->getDecl()->setStmt(nullptr);
  12529. return BaseTransform::TransformLabelStmt(S);
  12530. }
  12531. // We need to special-case DeclRefExprs referring to FieldDecls which
  12532. // are not part of a member pointer formation; normal TreeTransforming
  12533. // doesn't catch this case because of the way we represent them in the AST.
  12534. // FIXME: This is a bit ugly; is it really the best way to handle this
  12535. // case?
  12536. //
  12537. // Error on DeclRefExprs referring to FieldDecls.
  12538. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  12539. if (isa<FieldDecl>(E->getDecl()) &&
  12540. !SemaRef.isUnevaluatedContext())
  12541. return SemaRef.Diag(E->getLocation(),
  12542. diag::err_invalid_non_static_member_use)
  12543. << E->getDecl() << E->getSourceRange();
  12544. return BaseTransform::TransformDeclRefExpr(E);
  12545. }
  12546. // Exception: filter out member pointer formation
  12547. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  12548. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  12549. return E;
  12550. return BaseTransform::TransformUnaryOperator(E);
  12551. }
  12552. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  12553. // Lambdas never need to be transformed.
  12554. return E;
  12555. }
  12556. };
  12557. }
  12558. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  12559. assert(isUnevaluatedContext() &&
  12560. "Should only transform unevaluated expressions");
  12561. ExprEvalContexts.back().Context =
  12562. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  12563. if (isUnevaluatedContext())
  12564. return E;
  12565. return TransformToPE(*this).TransformExpr(E);
  12566. }
  12567. void
  12568. Sema::PushExpressionEvaluationContext(
  12569. ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
  12570. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  12571. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
  12572. LambdaContextDecl, ExprContext);
  12573. Cleanup.reset();
  12574. if (!MaybeODRUseExprs.empty())
  12575. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  12576. }
  12577. void
  12578. Sema::PushExpressionEvaluationContext(
  12579. ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
  12580. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  12581. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  12582. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
  12583. }
  12584. void Sema::PopExpressionEvaluationContext() {
  12585. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  12586. unsigned NumTypos = Rec.NumTypos;
  12587. if (!Rec.Lambdas.empty()) {
  12588. using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
  12589. if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
  12590. (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
  12591. unsigned D;
  12592. if (Rec.isUnevaluated()) {
  12593. // C++11 [expr.prim.lambda]p2:
  12594. // A lambda-expression shall not appear in an unevaluated operand
  12595. // (Clause 5).
  12596. D = diag::err_lambda_unevaluated_operand;
  12597. } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
  12598. // C++1y [expr.const]p2:
  12599. // A conditional-expression e is a core constant expression unless the
  12600. // evaluation of e, following the rules of the abstract machine, would
  12601. // evaluate [...] a lambda-expression.
  12602. D = diag::err_lambda_in_constant_expression;
  12603. } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
  12604. // C++17 [expr.prim.lamda]p2:
  12605. // A lambda-expression shall not appear [...] in a template-argument.
  12606. D = diag::err_lambda_in_invalid_context;
  12607. } else
  12608. llvm_unreachable("Couldn't infer lambda error message.");
  12609. for (const auto *L : Rec.Lambdas)
  12610. Diag(L->getBeginLoc(), D);
  12611. } else {
  12612. // Mark the capture expressions odr-used. This was deferred
  12613. // during lambda expression creation.
  12614. for (auto *Lambda : Rec.Lambdas) {
  12615. for (auto *C : Lambda->capture_inits())
  12616. MarkDeclarationsReferencedInExpr(C);
  12617. }
  12618. }
  12619. }
  12620. // When are coming out of an unevaluated context, clear out any
  12621. // temporaries that we may have created as part of the evaluation of
  12622. // the expression in that context: they aren't relevant because they
  12623. // will never be constructed.
  12624. if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
  12625. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  12626. ExprCleanupObjects.end());
  12627. Cleanup = Rec.ParentCleanup;
  12628. CleanupVarDeclMarking();
  12629. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  12630. // Otherwise, merge the contexts together.
  12631. } else {
  12632. Cleanup.mergeFrom(Rec.ParentCleanup);
  12633. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  12634. Rec.SavedMaybeODRUseExprs.end());
  12635. }
  12636. // Pop the current expression evaluation context off the stack.
  12637. ExprEvalContexts.pop_back();
  12638. if (!ExprEvalContexts.empty())
  12639. ExprEvalContexts.back().NumTypos += NumTypos;
  12640. else
  12641. assert(NumTypos == 0 && "There are outstanding typos after popping the "
  12642. "last ExpressionEvaluationContextRecord");
  12643. }
  12644. void Sema::DiscardCleanupsInEvaluationContext() {
  12645. ExprCleanupObjects.erase(
  12646. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  12647. ExprCleanupObjects.end());
  12648. Cleanup.reset();
  12649. MaybeODRUseExprs.clear();
  12650. }
  12651. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  12652. if (!E->getType()->isVariablyModifiedType())
  12653. return E;
  12654. return TransformToPotentiallyEvaluated(E);
  12655. }
  12656. /// Are we within a context in which some evaluation could be performed (be it
  12657. /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
  12658. /// captured by C++'s idea of an "unevaluated context".
  12659. static bool isEvaluatableContext(Sema &SemaRef) {
  12660. switch (SemaRef.ExprEvalContexts.back().Context) {
  12661. case Sema::ExpressionEvaluationContext::Unevaluated:
  12662. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  12663. // Expressions in this context are never evaluated.
  12664. return false;
  12665. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  12666. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  12667. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  12668. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  12669. // Expressions in this context could be evaluated.
  12670. return true;
  12671. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  12672. // Referenced declarations will only be used if the construct in the
  12673. // containing expression is used, at which point we'll be given another
  12674. // turn to mark them.
  12675. return false;
  12676. }
  12677. llvm_unreachable("Invalid context");
  12678. }
  12679. /// Are we within a context in which references to resolved functions or to
  12680. /// variables result in odr-use?
  12681. static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
  12682. // An expression in a template is not really an expression until it's been
  12683. // instantiated, so it doesn't trigger odr-use.
  12684. if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
  12685. return false;
  12686. switch (SemaRef.ExprEvalContexts.back().Context) {
  12687. case Sema::ExpressionEvaluationContext::Unevaluated:
  12688. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  12689. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  12690. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  12691. return false;
  12692. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  12693. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  12694. return true;
  12695. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  12696. return false;
  12697. }
  12698. llvm_unreachable("Invalid context");
  12699. }
  12700. static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
  12701. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  12702. return Func->isConstexpr() &&
  12703. (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
  12704. }
  12705. /// Mark a function referenced, and check whether it is odr-used
  12706. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  12707. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  12708. bool MightBeOdrUse) {
  12709. assert(Func && "No function?");
  12710. Func->setReferenced();
  12711. // C++11 [basic.def.odr]p3:
  12712. // A function whose name appears as a potentially-evaluated expression is
  12713. // odr-used if it is the unique lookup result or the selected member of a
  12714. // set of overloaded functions [...].
  12715. //
  12716. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  12717. // can just check that here.
  12718. bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
  12719. // Determine whether we require a function definition to exist, per
  12720. // C++11 [temp.inst]p3:
  12721. // Unless a function template specialization has been explicitly
  12722. // instantiated or explicitly specialized, the function template
  12723. // specialization is implicitly instantiated when the specialization is
  12724. // referenced in a context that requires a function definition to exist.
  12725. //
  12726. // That is either when this is an odr-use, or when a usage of a constexpr
  12727. // function occurs within an evaluatable context.
  12728. bool NeedDefinition =
  12729. OdrUse || (isEvaluatableContext(*this) &&
  12730. isImplicitlyDefinableConstexprFunction(Func));
  12731. // C++14 [temp.expl.spec]p6:
  12732. // If a template [...] is explicitly specialized then that specialization
  12733. // shall be declared before the first use of that specialization that would
  12734. // cause an implicit instantiation to take place, in every translation unit
  12735. // in which such a use occurs
  12736. if (NeedDefinition &&
  12737. (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
  12738. Func->getMemberSpecializationInfo()))
  12739. checkSpecializationVisibility(Loc, Func);
  12740. // C++14 [except.spec]p17:
  12741. // An exception-specification is considered to be needed when:
  12742. // - the function is odr-used or, if it appears in an unevaluated operand,
  12743. // would be odr-used if the expression were potentially-evaluated;
  12744. //
  12745. // Note, we do this even if MightBeOdrUse is false. That indicates that the
  12746. // function is a pure virtual function we're calling, and in that case the
  12747. // function was selected by overload resolution and we need to resolve its
  12748. // exception specification for a different reason.
  12749. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  12750. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  12751. ResolveExceptionSpec(Loc, FPT);
  12752. // If we don't need to mark the function as used, and we don't need to
  12753. // try to provide a definition, there's nothing more to do.
  12754. if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
  12755. (!NeedDefinition || Func->getBody()))
  12756. return;
  12757. // Note that this declaration has been used.
  12758. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  12759. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  12760. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  12761. if (Constructor->isDefaultConstructor()) {
  12762. if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
  12763. return;
  12764. DefineImplicitDefaultConstructor(Loc, Constructor);
  12765. } else if (Constructor->isCopyConstructor()) {
  12766. DefineImplicitCopyConstructor(Loc, Constructor);
  12767. } else if (Constructor->isMoveConstructor()) {
  12768. DefineImplicitMoveConstructor(Loc, Constructor);
  12769. }
  12770. } else if (Constructor->getInheritedConstructor()) {
  12771. DefineInheritingConstructor(Loc, Constructor);
  12772. }
  12773. } else if (CXXDestructorDecl *Destructor =
  12774. dyn_cast<CXXDestructorDecl>(Func)) {
  12775. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  12776. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  12777. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  12778. return;
  12779. DefineImplicitDestructor(Loc, Destructor);
  12780. }
  12781. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  12782. MarkVTableUsed(Loc, Destructor->getParent());
  12783. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  12784. if (MethodDecl->isOverloadedOperator() &&
  12785. MethodDecl->getOverloadedOperator() == OO_Equal) {
  12786. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  12787. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  12788. if (MethodDecl->isCopyAssignmentOperator())
  12789. DefineImplicitCopyAssignment(Loc, MethodDecl);
  12790. else if (MethodDecl->isMoveAssignmentOperator())
  12791. DefineImplicitMoveAssignment(Loc, MethodDecl);
  12792. }
  12793. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  12794. MethodDecl->getParent()->isLambda()) {
  12795. CXXConversionDecl *Conversion =
  12796. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  12797. if (Conversion->isLambdaToBlockPointerConversion())
  12798. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  12799. else
  12800. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  12801. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  12802. MarkVTableUsed(Loc, MethodDecl->getParent());
  12803. }
  12804. // Recursive functions should be marked when used from another function.
  12805. // FIXME: Is this really right?
  12806. if (CurContext == Func) return;
  12807. // Implicit instantiation of function templates and member functions of
  12808. // class templates.
  12809. if (Func->isImplicitlyInstantiable()) {
  12810. TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
  12811. SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
  12812. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  12813. if (FirstInstantiation) {
  12814. PointOfInstantiation = Loc;
  12815. Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  12816. } else if (TSK != TSK_ImplicitInstantiation) {
  12817. // Use the point of use as the point of instantiation, instead of the
  12818. // point of explicit instantiation (which we track as the actual point of
  12819. // instantiation). This gives better backtraces in diagnostics.
  12820. PointOfInstantiation = Loc;
  12821. }
  12822. if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
  12823. Func->isConstexpr()) {
  12824. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  12825. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  12826. CodeSynthesisContexts.size())
  12827. PendingLocalImplicitInstantiations.push_back(
  12828. std::make_pair(Func, PointOfInstantiation));
  12829. else if (Func->isConstexpr())
  12830. // Do not defer instantiations of constexpr functions, to avoid the
  12831. // expression evaluator needing to call back into Sema if it sees a
  12832. // call to such a function.
  12833. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  12834. else {
  12835. Func->setInstantiationIsPending(true);
  12836. PendingInstantiations.push_back(std::make_pair(Func,
  12837. PointOfInstantiation));
  12838. // Notify the consumer that a function was implicitly instantiated.
  12839. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  12840. }
  12841. }
  12842. } else {
  12843. // Walk redefinitions, as some of them may be instantiable.
  12844. for (auto i : Func->redecls()) {
  12845. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  12846. MarkFunctionReferenced(Loc, i, OdrUse);
  12847. }
  12848. }
  12849. if (!OdrUse) return;
  12850. // Keep track of used but undefined functions.
  12851. if (!Func->isDefined()) {
  12852. if (mightHaveNonExternalLinkage(Func))
  12853. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  12854. else if (Func->getMostRecentDecl()->isInlined() &&
  12855. !LangOpts.GNUInline &&
  12856. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  12857. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  12858. else if (isExternalWithNoLinkageType(Func))
  12859. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  12860. }
  12861. Func->markUsed(Context);
  12862. }
  12863. static void
  12864. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  12865. ValueDecl *var, DeclContext *DC) {
  12866. DeclContext *VarDC = var->getDeclContext();
  12867. // If the parameter still belongs to the translation unit, then
  12868. // we're actually just using one parameter in the declaration of
  12869. // the next.
  12870. if (isa<ParmVarDecl>(var) &&
  12871. isa<TranslationUnitDecl>(VarDC))
  12872. return;
  12873. // For C code, don't diagnose about capture if we're not actually in code
  12874. // right now; it's impossible to write a non-constant expression outside of
  12875. // function context, so we'll get other (more useful) diagnostics later.
  12876. //
  12877. // For C++, things get a bit more nasty... it would be nice to suppress this
  12878. // diagnostic for certain cases like using a local variable in an array bound
  12879. // for a member of a local class, but the correct predicate is not obvious.
  12880. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  12881. return;
  12882. unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
  12883. unsigned ContextKind = 3; // unknown
  12884. if (isa<CXXMethodDecl>(VarDC) &&
  12885. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  12886. ContextKind = 2;
  12887. } else if (isa<FunctionDecl>(VarDC)) {
  12888. ContextKind = 0;
  12889. } else if (isa<BlockDecl>(VarDC)) {
  12890. ContextKind = 1;
  12891. }
  12892. S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
  12893. << var << ValueKind << ContextKind << VarDC;
  12894. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  12895. << var;
  12896. // FIXME: Add additional diagnostic info about class etc. which prevents
  12897. // capture.
  12898. }
  12899. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  12900. bool &SubCapturesAreNested,
  12901. QualType &CaptureType,
  12902. QualType &DeclRefType) {
  12903. // Check whether we've already captured it.
  12904. if (CSI->CaptureMap.count(Var)) {
  12905. // If we found a capture, any subcaptures are nested.
  12906. SubCapturesAreNested = true;
  12907. // Retrieve the capture type for this variable.
  12908. CaptureType = CSI->getCapture(Var).getCaptureType();
  12909. // Compute the type of an expression that refers to this variable.
  12910. DeclRefType = CaptureType.getNonReferenceType();
  12911. // Similarly to mutable captures in lambda, all the OpenMP captures by copy
  12912. // are mutable in the sense that user can change their value - they are
  12913. // private instances of the captured declarations.
  12914. const Capture &Cap = CSI->getCapture(Var);
  12915. if (Cap.isCopyCapture() &&
  12916. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
  12917. !(isa<CapturedRegionScopeInfo>(CSI) &&
  12918. cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
  12919. DeclRefType.addConst();
  12920. return true;
  12921. }
  12922. return false;
  12923. }
  12924. // Only block literals, captured statements, and lambda expressions can
  12925. // capture; other scopes don't work.
  12926. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  12927. SourceLocation Loc,
  12928. const bool Diagnose, Sema &S) {
  12929. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  12930. return getLambdaAwareParentOfDeclContext(DC);
  12931. else if (Var->hasLocalStorage()) {
  12932. if (Diagnose)
  12933. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  12934. }
  12935. return nullptr;
  12936. }
  12937. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  12938. // certain types of variables (unnamed, variably modified types etc.)
  12939. // so check for eligibility.
  12940. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  12941. SourceLocation Loc,
  12942. const bool Diagnose, Sema &S) {
  12943. bool IsBlock = isa<BlockScopeInfo>(CSI);
  12944. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  12945. // Lambdas are not allowed to capture unnamed variables
  12946. // (e.g. anonymous unions).
  12947. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  12948. // assuming that's the intent.
  12949. if (IsLambda && !Var->getDeclName()) {
  12950. if (Diagnose) {
  12951. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  12952. S.Diag(Var->getLocation(), diag::note_declared_at);
  12953. }
  12954. return false;
  12955. }
  12956. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  12957. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  12958. if (Diagnose) {
  12959. S.Diag(Loc, diag::err_ref_vm_type);
  12960. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12961. << Var->getDeclName();
  12962. }
  12963. return false;
  12964. }
  12965. // Prohibit structs with flexible array members too.
  12966. // We cannot capture what is in the tail end of the struct.
  12967. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  12968. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  12969. if (Diagnose) {
  12970. if (IsBlock)
  12971. S.Diag(Loc, diag::err_ref_flexarray_type);
  12972. else
  12973. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  12974. << Var->getDeclName();
  12975. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12976. << Var->getDeclName();
  12977. }
  12978. return false;
  12979. }
  12980. }
  12981. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  12982. // Lambdas and captured statements are not allowed to capture __block
  12983. // variables; they don't support the expected semantics.
  12984. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  12985. if (Diagnose) {
  12986. S.Diag(Loc, diag::err_capture_block_variable)
  12987. << Var->getDeclName() << !IsLambda;
  12988. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12989. << Var->getDeclName();
  12990. }
  12991. return false;
  12992. }
  12993. // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
  12994. if (S.getLangOpts().OpenCL && IsBlock &&
  12995. Var->getType()->isBlockPointerType()) {
  12996. if (Diagnose)
  12997. S.Diag(Loc, diag::err_opencl_block_ref_block);
  12998. return false;
  12999. }
  13000. return true;
  13001. }
  13002. // Returns true if the capture by block was successful.
  13003. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  13004. SourceLocation Loc,
  13005. const bool BuildAndDiagnose,
  13006. QualType &CaptureType,
  13007. QualType &DeclRefType,
  13008. const bool Nested,
  13009. Sema &S) {
  13010. Expr *CopyExpr = nullptr;
  13011. bool ByRef = false;
  13012. // Blocks are not allowed to capture arrays, excepting OpenCL.
  13013. // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
  13014. // (decayed to pointers).
  13015. if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
  13016. if (BuildAndDiagnose) {
  13017. S.Diag(Loc, diag::err_ref_array_type);
  13018. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13019. << Var->getDeclName();
  13020. }
  13021. return false;
  13022. }
  13023. // Forbid the block-capture of autoreleasing variables.
  13024. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  13025. if (BuildAndDiagnose) {
  13026. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  13027. << /*block*/ 0;
  13028. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13029. << Var->getDeclName();
  13030. }
  13031. return false;
  13032. }
  13033. // Warn about implicitly autoreleasing indirect parameters captured by blocks.
  13034. if (const auto *PT = CaptureType->getAs<PointerType>()) {
  13035. // This function finds out whether there is an AttributedType of kind
  13036. // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
  13037. // attr::ObjCOwnership implies __autoreleasing was explicitly specified
  13038. // rather than being added implicitly by the compiler.
  13039. auto IsObjCOwnershipAttributedType = [](QualType Ty) {
  13040. while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
  13041. if (AttrTy->getAttrKind() == attr::ObjCOwnership)
  13042. return true;
  13043. // Peel off AttributedTypes that are not of kind ObjCOwnership.
  13044. Ty = AttrTy->getModifiedType();
  13045. }
  13046. return false;
  13047. };
  13048. QualType PointeeTy = PT->getPointeeType();
  13049. if (PointeeTy->getAs<ObjCObjectPointerType>() &&
  13050. PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
  13051. !IsObjCOwnershipAttributedType(PointeeTy)) {
  13052. if (BuildAndDiagnose) {
  13053. SourceLocation VarLoc = Var->getLocation();
  13054. S.Diag(Loc, diag::warn_block_capture_autoreleasing);
  13055. S.Diag(VarLoc, diag::note_declare_parameter_strong);
  13056. }
  13057. }
  13058. }
  13059. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  13060. if (HasBlocksAttr || CaptureType->isReferenceType() ||
  13061. (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
  13062. // Block capture by reference does not change the capture or
  13063. // declaration reference types.
  13064. ByRef = true;
  13065. } else {
  13066. // Block capture by copy introduces 'const'.
  13067. CaptureType = CaptureType.getNonReferenceType().withConst();
  13068. DeclRefType = CaptureType;
  13069. if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
  13070. if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
  13071. // The capture logic needs the destructor, so make sure we mark it.
  13072. // Usually this is unnecessary because most local variables have
  13073. // their destructors marked at declaration time, but parameters are
  13074. // an exception because it's technically only the call site that
  13075. // actually requires the destructor.
  13076. if (isa<ParmVarDecl>(Var))
  13077. S.FinalizeVarWithDestructor(Var, Record);
  13078. // Enter a new evaluation context to insulate the copy
  13079. // full-expression.
  13080. EnterExpressionEvaluationContext scope(
  13081. S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  13082. // According to the blocks spec, the capture of a variable from
  13083. // the stack requires a const copy constructor. This is not true
  13084. // of the copy/move done to move a __block variable to the heap.
  13085. Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
  13086. DeclRefType.withConst(),
  13087. VK_LValue, Loc);
  13088. ExprResult Result
  13089. = S.PerformCopyInitialization(
  13090. InitializedEntity::InitializeBlock(Var->getLocation(),
  13091. CaptureType, false),
  13092. Loc, DeclRef);
  13093. // Build a full-expression copy expression if initialization
  13094. // succeeded and used a non-trivial constructor. Recover from
  13095. // errors by pretending that the copy isn't necessary.
  13096. if (!Result.isInvalid() &&
  13097. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  13098. ->isTrivial()) {
  13099. Result = S.MaybeCreateExprWithCleanups(Result);
  13100. CopyExpr = Result.get();
  13101. }
  13102. }
  13103. }
  13104. }
  13105. // Actually capture the variable.
  13106. if (BuildAndDiagnose)
  13107. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
  13108. SourceLocation(), CaptureType, CopyExpr);
  13109. return true;
  13110. }
  13111. /// Capture the given variable in the captured region.
  13112. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  13113. VarDecl *Var,
  13114. SourceLocation Loc,
  13115. const bool BuildAndDiagnose,
  13116. QualType &CaptureType,
  13117. QualType &DeclRefType,
  13118. const bool RefersToCapturedVariable,
  13119. Sema &S) {
  13120. // By default, capture variables by reference.
  13121. bool ByRef = true;
  13122. // Using an LValue reference type is consistent with Lambdas (see below).
  13123. if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
  13124. if (S.isOpenMPCapturedDecl(Var)) {
  13125. bool HasConst = DeclRefType.isConstQualified();
  13126. DeclRefType = DeclRefType.getUnqualifiedType();
  13127. // Don't lose diagnostics about assignments to const.
  13128. if (HasConst)
  13129. DeclRefType.addConst();
  13130. }
  13131. ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
  13132. }
  13133. if (ByRef)
  13134. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  13135. else
  13136. CaptureType = DeclRefType;
  13137. Expr *CopyExpr = nullptr;
  13138. if (BuildAndDiagnose) {
  13139. // The current implementation assumes that all variables are captured
  13140. // by references. Since there is no capture by copy, no expression
  13141. // evaluation will be needed.
  13142. RecordDecl *RD = RSI->TheRecordDecl;
  13143. FieldDecl *Field
  13144. = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
  13145. S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
  13146. nullptr, false, ICIS_NoInit);
  13147. Field->setImplicit(true);
  13148. Field->setAccess(AS_private);
  13149. RD->addDecl(Field);
  13150. if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
  13151. S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
  13152. CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
  13153. DeclRefType, VK_LValue, Loc);
  13154. Var->setReferenced(true);
  13155. Var->markUsed(S.Context);
  13156. }
  13157. // Actually capture the variable.
  13158. if (BuildAndDiagnose)
  13159. RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
  13160. SourceLocation(), CaptureType, CopyExpr);
  13161. return true;
  13162. }
  13163. /// Create a field within the lambda class for the variable
  13164. /// being captured.
  13165. static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
  13166. QualType FieldType, QualType DeclRefType,
  13167. SourceLocation Loc,
  13168. bool RefersToCapturedVariable) {
  13169. CXXRecordDecl *Lambda = LSI->Lambda;
  13170. // Build the non-static data member.
  13171. FieldDecl *Field
  13172. = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
  13173. S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
  13174. nullptr, false, ICIS_NoInit);
  13175. Field->setImplicit(true);
  13176. Field->setAccess(AS_private);
  13177. Lambda->addDecl(Field);
  13178. }
  13179. /// Capture the given variable in the lambda.
  13180. static bool captureInLambda(LambdaScopeInfo *LSI,
  13181. VarDecl *Var,
  13182. SourceLocation Loc,
  13183. const bool BuildAndDiagnose,
  13184. QualType &CaptureType,
  13185. QualType &DeclRefType,
  13186. const bool RefersToCapturedVariable,
  13187. const Sema::TryCaptureKind Kind,
  13188. SourceLocation EllipsisLoc,
  13189. const bool IsTopScope,
  13190. Sema &S) {
  13191. // Determine whether we are capturing by reference or by value.
  13192. bool ByRef = false;
  13193. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  13194. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  13195. } else {
  13196. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  13197. }
  13198. // Compute the type of the field that will capture this variable.
  13199. if (ByRef) {
  13200. // C++11 [expr.prim.lambda]p15:
  13201. // An entity is captured by reference if it is implicitly or
  13202. // explicitly captured but not captured by copy. It is
  13203. // unspecified whether additional unnamed non-static data
  13204. // members are declared in the closure type for entities
  13205. // captured by reference.
  13206. //
  13207. // FIXME: It is not clear whether we want to build an lvalue reference
  13208. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  13209. // to do the former, while EDG does the latter. Core issue 1249 will
  13210. // clarify, but for now we follow GCC because it's a more permissive and
  13211. // easily defensible position.
  13212. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  13213. } else {
  13214. // C++11 [expr.prim.lambda]p14:
  13215. // For each entity captured by copy, an unnamed non-static
  13216. // data member is declared in the closure type. The
  13217. // declaration order of these members is unspecified. The type
  13218. // of such a data member is the type of the corresponding
  13219. // captured entity if the entity is not a reference to an
  13220. // object, or the referenced type otherwise. [Note: If the
  13221. // captured entity is a reference to a function, the
  13222. // corresponding data member is also a reference to a
  13223. // function. - end note ]
  13224. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  13225. if (!RefType->getPointeeType()->isFunctionType())
  13226. CaptureType = RefType->getPointeeType();
  13227. }
  13228. // Forbid the lambda copy-capture of autoreleasing variables.
  13229. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  13230. if (BuildAndDiagnose) {
  13231. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  13232. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13233. << Var->getDeclName();
  13234. }
  13235. return false;
  13236. }
  13237. // Make sure that by-copy captures are of a complete and non-abstract type.
  13238. if (BuildAndDiagnose) {
  13239. if (!CaptureType->isDependentType() &&
  13240. S.RequireCompleteType(Loc, CaptureType,
  13241. diag::err_capture_of_incomplete_type,
  13242. Var->getDeclName()))
  13243. return false;
  13244. if (S.RequireNonAbstractType(Loc, CaptureType,
  13245. diag::err_capture_of_abstract_type))
  13246. return false;
  13247. }
  13248. }
  13249. // Capture this variable in the lambda.
  13250. if (BuildAndDiagnose)
  13251. addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
  13252. RefersToCapturedVariable);
  13253. // Compute the type of a reference to this captured variable.
  13254. if (ByRef)
  13255. DeclRefType = CaptureType.getNonReferenceType();
  13256. else {
  13257. // C++ [expr.prim.lambda]p5:
  13258. // The closure type for a lambda-expression has a public inline
  13259. // function call operator [...]. This function call operator is
  13260. // declared const (9.3.1) if and only if the lambda-expression's
  13261. // parameter-declaration-clause is not followed by mutable.
  13262. DeclRefType = CaptureType.getNonReferenceType();
  13263. if (!LSI->Mutable && !CaptureType->isReferenceType())
  13264. DeclRefType.addConst();
  13265. }
  13266. // Add the capture.
  13267. if (BuildAndDiagnose)
  13268. LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
  13269. Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
  13270. return true;
  13271. }
  13272. bool Sema::tryCaptureVariable(
  13273. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  13274. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  13275. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  13276. // An init-capture is notionally from the context surrounding its
  13277. // declaration, but its parent DC is the lambda class.
  13278. DeclContext *VarDC = Var->getDeclContext();
  13279. if (Var->isInitCapture())
  13280. VarDC = VarDC->getParent();
  13281. DeclContext *DC = CurContext;
  13282. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  13283. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  13284. // We need to sync up the Declaration Context with the
  13285. // FunctionScopeIndexToStopAt
  13286. if (FunctionScopeIndexToStopAt) {
  13287. unsigned FSIndex = FunctionScopes.size() - 1;
  13288. while (FSIndex != MaxFunctionScopesIndex) {
  13289. DC = getLambdaAwareParentOfDeclContext(DC);
  13290. --FSIndex;
  13291. }
  13292. }
  13293. // If the variable is declared in the current context, there is no need to
  13294. // capture it.
  13295. if (VarDC == DC) return true;
  13296. // Capture global variables if it is required to use private copy of this
  13297. // variable.
  13298. bool IsGlobal = !Var->hasLocalStorage();
  13299. if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
  13300. return true;
  13301. Var = Var->getCanonicalDecl();
  13302. // Walk up the stack to determine whether we can capture the variable,
  13303. // performing the "simple" checks that don't depend on type. We stop when
  13304. // we've either hit the declared scope of the variable or find an existing
  13305. // capture of that variable. We start from the innermost capturing-entity
  13306. // (the DC) and ensure that all intervening capturing-entities
  13307. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  13308. // declcontext can either capture the variable or have already captured
  13309. // the variable.
  13310. CaptureType = Var->getType();
  13311. DeclRefType = CaptureType.getNonReferenceType();
  13312. bool Nested = false;
  13313. bool Explicit = (Kind != TryCapture_Implicit);
  13314. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  13315. do {
  13316. // Only block literals, captured statements, and lambda expressions can
  13317. // capture; other scopes don't work.
  13318. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  13319. ExprLoc,
  13320. BuildAndDiagnose,
  13321. *this);
  13322. // We need to check for the parent *first* because, if we *have*
  13323. // private-captured a global variable, we need to recursively capture it in
  13324. // intermediate blocks, lambdas, etc.
  13325. if (!ParentDC) {
  13326. if (IsGlobal) {
  13327. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  13328. break;
  13329. }
  13330. return true;
  13331. }
  13332. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  13333. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  13334. // Check whether we've already captured it.
  13335. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  13336. DeclRefType)) {
  13337. CSI->getCapture(Var).markUsed(BuildAndDiagnose);
  13338. break;
  13339. }
  13340. // If we are instantiating a generic lambda call operator body,
  13341. // we do not want to capture new variables. What was captured
  13342. // during either a lambdas transformation or initial parsing
  13343. // should be used.
  13344. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  13345. if (BuildAndDiagnose) {
  13346. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  13347. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  13348. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  13349. Diag(Var->getLocation(), diag::note_previous_decl)
  13350. << Var->getDeclName();
  13351. Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
  13352. } else
  13353. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  13354. }
  13355. return true;
  13356. }
  13357. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  13358. // certain types of variables (unnamed, variably modified types etc.)
  13359. // so check for eligibility.
  13360. if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
  13361. return true;
  13362. // Try to capture variable-length arrays types.
  13363. if (Var->getType()->isVariablyModifiedType()) {
  13364. // We're going to walk down into the type and look for VLA
  13365. // expressions.
  13366. QualType QTy = Var->getType();
  13367. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  13368. QTy = PVD->getOriginalType();
  13369. captureVariablyModifiedType(Context, QTy, CSI);
  13370. }
  13371. if (getLangOpts().OpenMP) {
  13372. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  13373. // OpenMP private variables should not be captured in outer scope, so
  13374. // just break here. Similarly, global variables that are captured in a
  13375. // target region should not be captured outside the scope of the region.
  13376. if (RSI->CapRegionKind == CR_OpenMP) {
  13377. bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
  13378. auto IsTargetCap = !IsOpenMPPrivateDecl &&
  13379. isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
  13380. // When we detect target captures we are looking from inside the
  13381. // target region, therefore we need to propagate the capture from the
  13382. // enclosing region. Therefore, the capture is not initially nested.
  13383. if (IsTargetCap)
  13384. adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
  13385. if (IsTargetCap || IsOpenMPPrivateDecl) {
  13386. Nested = !IsTargetCap;
  13387. DeclRefType = DeclRefType.getUnqualifiedType();
  13388. CaptureType = Context.getLValueReferenceType(DeclRefType);
  13389. break;
  13390. }
  13391. }
  13392. }
  13393. }
  13394. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  13395. // No capture-default, and this is not an explicit capture
  13396. // so cannot capture this variable.
  13397. if (BuildAndDiagnose) {
  13398. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  13399. Diag(Var->getLocation(), diag::note_previous_decl)
  13400. << Var->getDeclName();
  13401. if (cast<LambdaScopeInfo>(CSI)->Lambda)
  13402. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
  13403. diag::note_lambda_decl);
  13404. // FIXME: If we error out because an outer lambda can not implicitly
  13405. // capture a variable that an inner lambda explicitly captures, we
  13406. // should have the inner lambda do the explicit capture - because
  13407. // it makes for cleaner diagnostics later. This would purely be done
  13408. // so that the diagnostic does not misleadingly claim that a variable
  13409. // can not be captured by a lambda implicitly even though it is captured
  13410. // explicitly. Suggestion:
  13411. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  13412. // at the function head
  13413. // - cache the StartingDeclContext - this must be a lambda
  13414. // - captureInLambda in the innermost lambda the variable.
  13415. }
  13416. return true;
  13417. }
  13418. FunctionScopesIndex--;
  13419. DC = ParentDC;
  13420. Explicit = false;
  13421. } while (!VarDC->Equals(DC));
  13422. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  13423. // computing the type of the capture at each step, checking type-specific
  13424. // requirements, and adding captures if requested.
  13425. // If the variable had already been captured previously, we start capturing
  13426. // at the lambda nested within that one.
  13427. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  13428. ++I) {
  13429. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  13430. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  13431. if (!captureInBlock(BSI, Var, ExprLoc,
  13432. BuildAndDiagnose, CaptureType,
  13433. DeclRefType, Nested, *this))
  13434. return true;
  13435. Nested = true;
  13436. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  13437. if (!captureInCapturedRegion(RSI, Var, ExprLoc,
  13438. BuildAndDiagnose, CaptureType,
  13439. DeclRefType, Nested, *this))
  13440. return true;
  13441. Nested = true;
  13442. } else {
  13443. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  13444. if (!captureInLambda(LSI, Var, ExprLoc,
  13445. BuildAndDiagnose, CaptureType,
  13446. DeclRefType, Nested, Kind, EllipsisLoc,
  13447. /*IsTopScope*/I == N - 1, *this))
  13448. return true;
  13449. Nested = true;
  13450. }
  13451. }
  13452. return false;
  13453. }
  13454. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  13455. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  13456. QualType CaptureType;
  13457. QualType DeclRefType;
  13458. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  13459. /*BuildAndDiagnose=*/true, CaptureType,
  13460. DeclRefType, nullptr);
  13461. }
  13462. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  13463. QualType CaptureType;
  13464. QualType DeclRefType;
  13465. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  13466. /*BuildAndDiagnose=*/false, CaptureType,
  13467. DeclRefType, nullptr);
  13468. }
  13469. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  13470. QualType CaptureType;
  13471. QualType DeclRefType;
  13472. // Determine whether we can capture this variable.
  13473. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  13474. /*BuildAndDiagnose=*/false, CaptureType,
  13475. DeclRefType, nullptr))
  13476. return QualType();
  13477. return DeclRefType;
  13478. }
  13479. // If either the type of the variable or the initializer is dependent,
  13480. // return false. Otherwise, determine whether the variable is a constant
  13481. // expression. Use this if you need to know if a variable that might or
  13482. // might not be dependent is truly a constant expression.
  13483. static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
  13484. ASTContext &Context) {
  13485. if (Var->getType()->isDependentType())
  13486. return false;
  13487. const VarDecl *DefVD = nullptr;
  13488. Var->getAnyInitializer(DefVD);
  13489. if (!DefVD)
  13490. return false;
  13491. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  13492. Expr *Init = cast<Expr>(Eval->Value);
  13493. if (Init->isValueDependent())
  13494. return false;
  13495. return IsVariableAConstantExpression(Var, Context);
  13496. }
  13497. void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
  13498. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  13499. // an object that satisfies the requirements for appearing in a
  13500. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  13501. // is immediately applied." This function handles the lvalue-to-rvalue
  13502. // conversion part.
  13503. MaybeODRUseExprs.erase(E->IgnoreParens());
  13504. // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
  13505. // to a variable that is a constant expression, and if so, identify it as
  13506. // a reference to a variable that does not involve an odr-use of that
  13507. // variable.
  13508. if (LambdaScopeInfo *LSI = getCurLambda()) {
  13509. Expr *SansParensExpr = E->IgnoreParens();
  13510. VarDecl *Var = nullptr;
  13511. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
  13512. Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
  13513. else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
  13514. Var = dyn_cast<VarDecl>(ME->getMemberDecl());
  13515. if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
  13516. LSI->markVariableExprAsNonODRUsed(SansParensExpr);
  13517. }
  13518. }
  13519. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  13520. Res = CorrectDelayedTyposInExpr(Res);
  13521. if (!Res.isUsable())
  13522. return Res;
  13523. // If a constant-expression is a reference to a variable where we delay
  13524. // deciding whether it is an odr-use, just assume we will apply the
  13525. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  13526. // (a non-type template argument), we have special handling anyway.
  13527. UpdateMarkingForLValueToRValue(Res.get());
  13528. return Res;
  13529. }
  13530. void Sema::CleanupVarDeclMarking() {
  13531. for (Expr *E : MaybeODRUseExprs) {
  13532. VarDecl *Var;
  13533. SourceLocation Loc;
  13534. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  13535. Var = cast<VarDecl>(DRE->getDecl());
  13536. Loc = DRE->getLocation();
  13537. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  13538. Var = cast<VarDecl>(ME->getMemberDecl());
  13539. Loc = ME->getMemberLoc();
  13540. } else {
  13541. llvm_unreachable("Unexpected expression");
  13542. }
  13543. MarkVarDeclODRUsed(Var, Loc, *this,
  13544. /*MaxFunctionScopeIndex Pointer*/ nullptr);
  13545. }
  13546. MaybeODRUseExprs.clear();
  13547. }
  13548. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  13549. VarDecl *Var, Expr *E) {
  13550. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
  13551. "Invalid Expr argument to DoMarkVarDeclReferenced");
  13552. Var->setReferenced();
  13553. TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
  13554. bool OdrUseContext = isOdrUseContext(SemaRef);
  13555. bool UsableInConstantExpr =
  13556. Var->isUsableInConstantExpressions(SemaRef.Context);
  13557. bool NeedDefinition =
  13558. OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
  13559. VarTemplateSpecializationDecl *VarSpec =
  13560. dyn_cast<VarTemplateSpecializationDecl>(Var);
  13561. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  13562. "Can't instantiate a partial template specialization.");
  13563. // If this might be a member specialization of a static data member, check
  13564. // the specialization is visible. We already did the checks for variable
  13565. // template specializations when we created them.
  13566. if (NeedDefinition && TSK != TSK_Undeclared &&
  13567. !isa<VarTemplateSpecializationDecl>(Var))
  13568. SemaRef.checkSpecializationVisibility(Loc, Var);
  13569. // Perform implicit instantiation of static data members, static data member
  13570. // templates of class templates, and variable template specializations. Delay
  13571. // instantiations of variable templates, except for those that could be used
  13572. // in a constant expression.
  13573. if (NeedDefinition && isTemplateInstantiation(TSK)) {
  13574. // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
  13575. // instantiation declaration if a variable is usable in a constant
  13576. // expression (among other cases).
  13577. bool TryInstantiating =
  13578. TSK == TSK_ImplicitInstantiation ||
  13579. (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
  13580. if (TryInstantiating) {
  13581. SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
  13582. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  13583. if (FirstInstantiation) {
  13584. PointOfInstantiation = Loc;
  13585. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  13586. }
  13587. bool InstantiationDependent = false;
  13588. bool IsNonDependent =
  13589. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  13590. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  13591. : true;
  13592. // Do not instantiate specializations that are still type-dependent.
  13593. if (IsNonDependent) {
  13594. if (UsableInConstantExpr) {
  13595. // Do not defer instantiations of variables that could be used in a
  13596. // constant expression.
  13597. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  13598. } else if (FirstInstantiation ||
  13599. isa<VarTemplateSpecializationDecl>(Var)) {
  13600. // FIXME: For a specialization of a variable template, we don't
  13601. // distinguish between "declaration and type implicitly instantiated"
  13602. // and "implicit instantiation of definition requested", so we have
  13603. // no direct way to avoid enqueueing the pending instantiation
  13604. // multiple times.
  13605. SemaRef.PendingInstantiations
  13606. .push_back(std::make_pair(Var, PointOfInstantiation));
  13607. }
  13608. }
  13609. }
  13610. }
  13611. // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
  13612. // the requirements for appearing in a constant expression (5.19) and, if
  13613. // it is an object, the lvalue-to-rvalue conversion (4.1)
  13614. // is immediately applied." We check the first part here, and
  13615. // Sema::UpdateMarkingForLValueToRValue deals with the second part.
  13616. // Note that we use the C++11 definition everywhere because nothing in
  13617. // C++03 depends on whether we get the C++03 version correct. The second
  13618. // part does not apply to references, since they are not objects.
  13619. if (OdrUseContext && E &&
  13620. IsVariableAConstantExpression(Var, SemaRef.Context)) {
  13621. // A reference initialized by a constant expression can never be
  13622. // odr-used, so simply ignore it.
  13623. if (!Var->getType()->isReferenceType() ||
  13624. (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
  13625. SemaRef.MaybeODRUseExprs.insert(E);
  13626. } else if (OdrUseContext) {
  13627. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  13628. /*MaxFunctionScopeIndex ptr*/ nullptr);
  13629. } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
  13630. // If this is a dependent context, we don't need to mark variables as
  13631. // odr-used, but we may still need to track them for lambda capture.
  13632. // FIXME: Do we also need to do this inside dependent typeid expressions
  13633. // (which are modeled as unevaluated at this point)?
  13634. const bool RefersToEnclosingScope =
  13635. (SemaRef.CurContext != Var->getDeclContext() &&
  13636. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  13637. if (RefersToEnclosingScope) {
  13638. LambdaScopeInfo *const LSI =
  13639. SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
  13640. if (LSI && (!LSI->CallOperator ||
  13641. !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
  13642. // If a variable could potentially be odr-used, defer marking it so
  13643. // until we finish analyzing the full expression for any
  13644. // lvalue-to-rvalue
  13645. // or discarded value conversions that would obviate odr-use.
  13646. // Add it to the list of potential captures that will be analyzed
  13647. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  13648. // unless the variable is a reference that was initialized by a constant
  13649. // expression (this will never need to be captured or odr-used).
  13650. assert(E && "Capture variable should be used in an expression.");
  13651. if (!Var->getType()->isReferenceType() ||
  13652. !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
  13653. LSI->addPotentialCapture(E->IgnoreParens());
  13654. }
  13655. }
  13656. }
  13657. }
  13658. /// Mark a variable referenced, and check whether it is odr-used
  13659. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  13660. /// used directly for normal expressions referring to VarDecl.
  13661. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  13662. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  13663. }
  13664. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  13665. Decl *D, Expr *E, bool MightBeOdrUse) {
  13666. if (SemaRef.isInOpenMPDeclareTargetContext())
  13667. SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
  13668. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  13669. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  13670. return;
  13671. }
  13672. SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
  13673. // If this is a call to a method via a cast, also mark the method in the
  13674. // derived class used in case codegen can devirtualize the call.
  13675. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  13676. if (!ME)
  13677. return;
  13678. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  13679. if (!MD)
  13680. return;
  13681. // Only attempt to devirtualize if this is truly a virtual call.
  13682. bool IsVirtualCall = MD->isVirtual() &&
  13683. ME->performsVirtualDispatch(SemaRef.getLangOpts());
  13684. if (!IsVirtualCall)
  13685. return;
  13686. // If it's possible to devirtualize the call, mark the called function
  13687. // referenced.
  13688. CXXMethodDecl *DM = MD->getDevirtualizedMethod(
  13689. ME->getBase(), SemaRef.getLangOpts().AppleKext);
  13690. if (DM)
  13691. SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
  13692. }
  13693. /// Perform reference-marking and odr-use handling for a DeclRefExpr.
  13694. void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
  13695. // TODO: update this with DR# once a defect report is filed.
  13696. // C++11 defect. The address of a pure member should not be an ODR use, even
  13697. // if it's a qualified reference.
  13698. bool OdrUse = true;
  13699. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  13700. if (Method->isVirtual() &&
  13701. !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
  13702. OdrUse = false;
  13703. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  13704. }
  13705. /// Perform reference-marking and odr-use handling for a MemberExpr.
  13706. void Sema::MarkMemberReferenced(MemberExpr *E) {
  13707. // C++11 [basic.def.odr]p2:
  13708. // A non-overloaded function whose name appears as a potentially-evaluated
  13709. // expression or a member of a set of candidate functions, if selected by
  13710. // overload resolution when referred to from a potentially-evaluated
  13711. // expression, is odr-used, unless it is a pure virtual function and its
  13712. // name is not explicitly qualified.
  13713. bool MightBeOdrUse = true;
  13714. if (E->performsVirtualDispatch(getLangOpts())) {
  13715. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  13716. if (Method->isPure())
  13717. MightBeOdrUse = false;
  13718. }
  13719. SourceLocation Loc =
  13720. E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
  13721. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
  13722. }
  13723. /// Perform marking for a reference to an arbitrary declaration. It
  13724. /// marks the declaration referenced, and performs odr-use checking for
  13725. /// functions and variables. This method should not be used when building a
  13726. /// normal expression which refers to a variable.
  13727. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
  13728. bool MightBeOdrUse) {
  13729. if (MightBeOdrUse) {
  13730. if (auto *VD = dyn_cast<VarDecl>(D)) {
  13731. MarkVariableReferenced(Loc, VD);
  13732. return;
  13733. }
  13734. }
  13735. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  13736. MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
  13737. return;
  13738. }
  13739. D->setReferenced();
  13740. }
  13741. namespace {
  13742. // Mark all of the declarations used by a type as referenced.
  13743. // FIXME: Not fully implemented yet! We need to have a better understanding
  13744. // of when we're entering a context we should not recurse into.
  13745. // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
  13746. // TreeTransforms rebuilding the type in a new context. Rather than
  13747. // duplicating the TreeTransform logic, we should consider reusing it here.
  13748. // Currently that causes problems when rebuilding LambdaExprs.
  13749. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  13750. Sema &S;
  13751. SourceLocation Loc;
  13752. public:
  13753. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  13754. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  13755. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  13756. };
  13757. }
  13758. bool MarkReferencedDecls::TraverseTemplateArgument(
  13759. const TemplateArgument &Arg) {
  13760. {
  13761. // A non-type template argument is a constant-evaluated context.
  13762. EnterExpressionEvaluationContext Evaluated(
  13763. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  13764. if (Arg.getKind() == TemplateArgument::Declaration) {
  13765. if (Decl *D = Arg.getAsDecl())
  13766. S.MarkAnyDeclReferenced(Loc, D, true);
  13767. } else if (Arg.getKind() == TemplateArgument::Expression) {
  13768. S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
  13769. }
  13770. }
  13771. return Inherited::TraverseTemplateArgument(Arg);
  13772. }
  13773. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  13774. MarkReferencedDecls Marker(*this, Loc);
  13775. Marker.TraverseType(T);
  13776. }
  13777. namespace {
  13778. /// Helper class that marks all of the declarations referenced by
  13779. /// potentially-evaluated subexpressions as "referenced".
  13780. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  13781. Sema &S;
  13782. bool SkipLocalVariables;
  13783. public:
  13784. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  13785. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  13786. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  13787. void VisitDeclRefExpr(DeclRefExpr *E) {
  13788. // If we were asked not to visit local variables, don't.
  13789. if (SkipLocalVariables) {
  13790. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  13791. if (VD->hasLocalStorage())
  13792. return;
  13793. }
  13794. S.MarkDeclRefReferenced(E);
  13795. }
  13796. void VisitMemberExpr(MemberExpr *E) {
  13797. S.MarkMemberReferenced(E);
  13798. Inherited::VisitMemberExpr(E);
  13799. }
  13800. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  13801. S.MarkFunctionReferenced(
  13802. E->getBeginLoc(),
  13803. const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
  13804. Visit(E->getSubExpr());
  13805. }
  13806. void VisitCXXNewExpr(CXXNewExpr *E) {
  13807. if (E->getOperatorNew())
  13808. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
  13809. if (E->getOperatorDelete())
  13810. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  13811. Inherited::VisitCXXNewExpr(E);
  13812. }
  13813. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  13814. if (E->getOperatorDelete())
  13815. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  13816. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  13817. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  13818. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  13819. S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
  13820. }
  13821. Inherited::VisitCXXDeleteExpr(E);
  13822. }
  13823. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  13824. S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
  13825. Inherited::VisitCXXConstructExpr(E);
  13826. }
  13827. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  13828. Visit(E->getExpr());
  13829. }
  13830. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  13831. Inherited::VisitImplicitCastExpr(E);
  13832. if (E->getCastKind() == CK_LValueToRValue)
  13833. S.UpdateMarkingForLValueToRValue(E->getSubExpr());
  13834. }
  13835. };
  13836. }
  13837. /// Mark any declarations that appear within this expression or any
  13838. /// potentially-evaluated subexpressions as "referenced".
  13839. ///
  13840. /// \param SkipLocalVariables If true, don't mark local variables as
  13841. /// 'referenced'.
  13842. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  13843. bool SkipLocalVariables) {
  13844. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  13845. }
  13846. /// Emit a diagnostic that describes an effect on the run-time behavior
  13847. /// of the program being compiled.
  13848. ///
  13849. /// This routine emits the given diagnostic when the code currently being
  13850. /// type-checked is "potentially evaluated", meaning that there is a
  13851. /// possibility that the code will actually be executable. Code in sizeof()
  13852. /// expressions, code used only during overload resolution, etc., are not
  13853. /// potentially evaluated. This routine will suppress such diagnostics or,
  13854. /// in the absolutely nutty case of potentially potentially evaluated
  13855. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  13856. /// later.
  13857. ///
  13858. /// This routine should be used for all diagnostics that describe the run-time
  13859. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  13860. /// Failure to do so will likely result in spurious diagnostics or failures
  13861. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  13862. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  13863. const PartialDiagnostic &PD) {
  13864. switch (ExprEvalContexts.back().Context) {
  13865. case ExpressionEvaluationContext::Unevaluated:
  13866. case ExpressionEvaluationContext::UnevaluatedList:
  13867. case ExpressionEvaluationContext::UnevaluatedAbstract:
  13868. case ExpressionEvaluationContext::DiscardedStatement:
  13869. // The argument will never be evaluated, so don't complain.
  13870. break;
  13871. case ExpressionEvaluationContext::ConstantEvaluated:
  13872. // Relevant diagnostics should be produced by constant evaluation.
  13873. break;
  13874. case ExpressionEvaluationContext::PotentiallyEvaluated:
  13875. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13876. if (Statement && getCurFunctionOrMethodDecl()) {
  13877. FunctionScopes.back()->PossiblyUnreachableDiags.
  13878. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
  13879. return true;
  13880. }
  13881. // The initializer of a constexpr variable or of the first declaration of a
  13882. // static data member is not syntactically a constant evaluated constant,
  13883. // but nonetheless is always required to be a constant expression, so we
  13884. // can skip diagnosing.
  13885. // FIXME: Using the mangling context here is a hack.
  13886. if (auto *VD = dyn_cast_or_null<VarDecl>(
  13887. ExprEvalContexts.back().ManglingContextDecl)) {
  13888. if (VD->isConstexpr() ||
  13889. (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
  13890. break;
  13891. // FIXME: For any other kind of variable, we should build a CFG for its
  13892. // initializer and check whether the context in question is reachable.
  13893. }
  13894. Diag(Loc, PD);
  13895. return true;
  13896. }
  13897. return false;
  13898. }
  13899. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  13900. CallExpr *CE, FunctionDecl *FD) {
  13901. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  13902. return false;
  13903. // If we're inside a decltype's expression, don't check for a valid return
  13904. // type or construct temporaries until we know whether this is the last call.
  13905. if (ExprEvalContexts.back().ExprContext ==
  13906. ExpressionEvaluationContextRecord::EK_Decltype) {
  13907. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  13908. return false;
  13909. }
  13910. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  13911. FunctionDecl *FD;
  13912. CallExpr *CE;
  13913. public:
  13914. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  13915. : FD(FD), CE(CE) { }
  13916. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  13917. if (!FD) {
  13918. S.Diag(Loc, diag::err_call_incomplete_return)
  13919. << T << CE->getSourceRange();
  13920. return;
  13921. }
  13922. S.Diag(Loc, diag::err_call_function_incomplete_return)
  13923. << CE->getSourceRange() << FD->getDeclName() << T;
  13924. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  13925. << FD->getDeclName();
  13926. }
  13927. } Diagnoser(FD, CE);
  13928. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  13929. return true;
  13930. return false;
  13931. }
  13932. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  13933. // will prevent this condition from triggering, which is what we want.
  13934. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  13935. SourceLocation Loc;
  13936. unsigned diagnostic = diag::warn_condition_is_assignment;
  13937. bool IsOrAssign = false;
  13938. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  13939. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  13940. return;
  13941. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  13942. // Greylist some idioms by putting them into a warning subcategory.
  13943. if (ObjCMessageExpr *ME
  13944. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  13945. Selector Sel = ME->getSelector();
  13946. // self = [<foo> init...]
  13947. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  13948. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  13949. // <foo> = [<bar> nextObject]
  13950. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  13951. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  13952. }
  13953. Loc = Op->getOperatorLoc();
  13954. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  13955. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  13956. return;
  13957. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  13958. Loc = Op->getOperatorLoc();
  13959. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  13960. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  13961. else {
  13962. // Not an assignment.
  13963. return;
  13964. }
  13965. Diag(Loc, diagnostic) << E->getSourceRange();
  13966. SourceLocation Open = E->getBeginLoc();
  13967. SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
  13968. Diag(Loc, diag::note_condition_assign_silence)
  13969. << FixItHint::CreateInsertion(Open, "(")
  13970. << FixItHint::CreateInsertion(Close, ")");
  13971. if (IsOrAssign)
  13972. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  13973. << FixItHint::CreateReplacement(Loc, "!=");
  13974. else
  13975. Diag(Loc, diag::note_condition_assign_to_comparison)
  13976. << FixItHint::CreateReplacement(Loc, "==");
  13977. }
  13978. /// Redundant parentheses over an equality comparison can indicate
  13979. /// that the user intended an assignment used as condition.
  13980. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  13981. // Don't warn if the parens came from a macro.
  13982. SourceLocation parenLoc = ParenE->getBeginLoc();
  13983. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  13984. return;
  13985. // Don't warn for dependent expressions.
  13986. if (ParenE->isTypeDependent())
  13987. return;
  13988. Expr *E = ParenE->IgnoreParens();
  13989. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  13990. if (opE->getOpcode() == BO_EQ &&
  13991. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  13992. == Expr::MLV_Valid) {
  13993. SourceLocation Loc = opE->getOperatorLoc();
  13994. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  13995. SourceRange ParenERange = ParenE->getSourceRange();
  13996. Diag(Loc, diag::note_equality_comparison_silence)
  13997. << FixItHint::CreateRemoval(ParenERange.getBegin())
  13998. << FixItHint::CreateRemoval(ParenERange.getEnd());
  13999. Diag(Loc, diag::note_equality_comparison_to_assign)
  14000. << FixItHint::CreateReplacement(Loc, "=");
  14001. }
  14002. }
  14003. ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
  14004. bool IsConstexpr) {
  14005. DiagnoseAssignmentAsCondition(E);
  14006. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  14007. DiagnoseEqualityWithExtraParens(parenE);
  14008. ExprResult result = CheckPlaceholderExpr(E);
  14009. if (result.isInvalid()) return ExprError();
  14010. E = result.get();
  14011. if (!E->isTypeDependent()) {
  14012. if (getLangOpts().CPlusPlus)
  14013. return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
  14014. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  14015. if (ERes.isInvalid())
  14016. return ExprError();
  14017. E = ERes.get();
  14018. QualType T = E->getType();
  14019. if (!T->isScalarType()) { // C99 6.8.4.1p1
  14020. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  14021. << T << E->getSourceRange();
  14022. return ExprError();
  14023. }
  14024. CheckBoolLikeConversion(E, Loc);
  14025. }
  14026. return E;
  14027. }
  14028. Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
  14029. Expr *SubExpr, ConditionKind CK) {
  14030. // Empty conditions are valid in for-statements.
  14031. if (!SubExpr)
  14032. return ConditionResult();
  14033. ExprResult Cond;
  14034. switch (CK) {
  14035. case ConditionKind::Boolean:
  14036. Cond = CheckBooleanCondition(Loc, SubExpr);
  14037. break;
  14038. case ConditionKind::ConstexprIf:
  14039. Cond = CheckBooleanCondition(Loc, SubExpr, true);
  14040. break;
  14041. case ConditionKind::Switch:
  14042. Cond = CheckSwitchCondition(Loc, SubExpr);
  14043. break;
  14044. }
  14045. if (Cond.isInvalid())
  14046. return ConditionError();
  14047. // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
  14048. FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
  14049. if (!FullExpr.get())
  14050. return ConditionError();
  14051. return ConditionResult(*this, nullptr, FullExpr,
  14052. CK == ConditionKind::ConstexprIf);
  14053. }
  14054. namespace {
  14055. /// A visitor for rebuilding a call to an __unknown_any expression
  14056. /// to have an appropriate type.
  14057. struct RebuildUnknownAnyFunction
  14058. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  14059. Sema &S;
  14060. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  14061. ExprResult VisitStmt(Stmt *S) {
  14062. llvm_unreachable("unexpected statement!");
  14063. }
  14064. ExprResult VisitExpr(Expr *E) {
  14065. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  14066. << E->getSourceRange();
  14067. return ExprError();
  14068. }
  14069. /// Rebuild an expression which simply semantically wraps another
  14070. /// expression which it shares the type and value kind of.
  14071. template <class T> ExprResult rebuildSugarExpr(T *E) {
  14072. ExprResult SubResult = Visit(E->getSubExpr());
  14073. if (SubResult.isInvalid()) return ExprError();
  14074. Expr *SubExpr = SubResult.get();
  14075. E->setSubExpr(SubExpr);
  14076. E->setType(SubExpr->getType());
  14077. E->setValueKind(SubExpr->getValueKind());
  14078. assert(E->getObjectKind() == OK_Ordinary);
  14079. return E;
  14080. }
  14081. ExprResult VisitParenExpr(ParenExpr *E) {
  14082. return rebuildSugarExpr(E);
  14083. }
  14084. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  14085. return rebuildSugarExpr(E);
  14086. }
  14087. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  14088. ExprResult SubResult = Visit(E->getSubExpr());
  14089. if (SubResult.isInvalid()) return ExprError();
  14090. Expr *SubExpr = SubResult.get();
  14091. E->setSubExpr(SubExpr);
  14092. E->setType(S.Context.getPointerType(SubExpr->getType()));
  14093. assert(E->getValueKind() == VK_RValue);
  14094. assert(E->getObjectKind() == OK_Ordinary);
  14095. return E;
  14096. }
  14097. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  14098. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  14099. E->setType(VD->getType());
  14100. assert(E->getValueKind() == VK_RValue);
  14101. if (S.getLangOpts().CPlusPlus &&
  14102. !(isa<CXXMethodDecl>(VD) &&
  14103. cast<CXXMethodDecl>(VD)->isInstance()))
  14104. E->setValueKind(VK_LValue);
  14105. return E;
  14106. }
  14107. ExprResult VisitMemberExpr(MemberExpr *E) {
  14108. return resolveDecl(E, E->getMemberDecl());
  14109. }
  14110. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  14111. return resolveDecl(E, E->getDecl());
  14112. }
  14113. };
  14114. }
  14115. /// Given a function expression of unknown-any type, try to rebuild it
  14116. /// to have a function type.
  14117. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  14118. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  14119. if (Result.isInvalid()) return ExprError();
  14120. return S.DefaultFunctionArrayConversion(Result.get());
  14121. }
  14122. namespace {
  14123. /// A visitor for rebuilding an expression of type __unknown_anytype
  14124. /// into one which resolves the type directly on the referring
  14125. /// expression. Strict preservation of the original source
  14126. /// structure is not a goal.
  14127. struct RebuildUnknownAnyExpr
  14128. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  14129. Sema &S;
  14130. /// The current destination type.
  14131. QualType DestType;
  14132. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  14133. : S(S), DestType(CastType) {}
  14134. ExprResult VisitStmt(Stmt *S) {
  14135. llvm_unreachable("unexpected statement!");
  14136. }
  14137. ExprResult VisitExpr(Expr *E) {
  14138. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  14139. << E->getSourceRange();
  14140. return ExprError();
  14141. }
  14142. ExprResult VisitCallExpr(CallExpr *E);
  14143. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  14144. /// Rebuild an expression which simply semantically wraps another
  14145. /// expression which it shares the type and value kind of.
  14146. template <class T> ExprResult rebuildSugarExpr(T *E) {
  14147. ExprResult SubResult = Visit(E->getSubExpr());
  14148. if (SubResult.isInvalid()) return ExprError();
  14149. Expr *SubExpr = SubResult.get();
  14150. E->setSubExpr(SubExpr);
  14151. E->setType(SubExpr->getType());
  14152. E->setValueKind(SubExpr->getValueKind());
  14153. assert(E->getObjectKind() == OK_Ordinary);
  14154. return E;
  14155. }
  14156. ExprResult VisitParenExpr(ParenExpr *E) {
  14157. return rebuildSugarExpr(E);
  14158. }
  14159. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  14160. return rebuildSugarExpr(E);
  14161. }
  14162. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  14163. const PointerType *Ptr = DestType->getAs<PointerType>();
  14164. if (!Ptr) {
  14165. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  14166. << E->getSourceRange();
  14167. return ExprError();
  14168. }
  14169. if (isa<CallExpr>(E->getSubExpr())) {
  14170. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
  14171. << E->getSourceRange();
  14172. return ExprError();
  14173. }
  14174. assert(E->getValueKind() == VK_RValue);
  14175. assert(E->getObjectKind() == OK_Ordinary);
  14176. E->setType(DestType);
  14177. // Build the sub-expression as if it were an object of the pointee type.
  14178. DestType = Ptr->getPointeeType();
  14179. ExprResult SubResult = Visit(E->getSubExpr());
  14180. if (SubResult.isInvalid()) return ExprError();
  14181. E->setSubExpr(SubResult.get());
  14182. return E;
  14183. }
  14184. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  14185. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  14186. ExprResult VisitMemberExpr(MemberExpr *E) {
  14187. return resolveDecl(E, E->getMemberDecl());
  14188. }
  14189. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  14190. return resolveDecl(E, E->getDecl());
  14191. }
  14192. };
  14193. }
  14194. /// Rebuilds a call expression which yielded __unknown_anytype.
  14195. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  14196. Expr *CalleeExpr = E->getCallee();
  14197. enum FnKind {
  14198. FK_MemberFunction,
  14199. FK_FunctionPointer,
  14200. FK_BlockPointer
  14201. };
  14202. FnKind Kind;
  14203. QualType CalleeType = CalleeExpr->getType();
  14204. if (CalleeType == S.Context.BoundMemberTy) {
  14205. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  14206. Kind = FK_MemberFunction;
  14207. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  14208. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  14209. CalleeType = Ptr->getPointeeType();
  14210. Kind = FK_FunctionPointer;
  14211. } else {
  14212. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  14213. Kind = FK_BlockPointer;
  14214. }
  14215. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  14216. // Verify that this is a legal result type of a function.
  14217. if (DestType->isArrayType() || DestType->isFunctionType()) {
  14218. unsigned diagID = diag::err_func_returning_array_function;
  14219. if (Kind == FK_BlockPointer)
  14220. diagID = diag::err_block_returning_array_function;
  14221. S.Diag(E->getExprLoc(), diagID)
  14222. << DestType->isFunctionType() << DestType;
  14223. return ExprError();
  14224. }
  14225. // Otherwise, go ahead and set DestType as the call's result.
  14226. E->setType(DestType.getNonLValueExprType(S.Context));
  14227. E->setValueKind(Expr::getValueKindForType(DestType));
  14228. assert(E->getObjectKind() == OK_Ordinary);
  14229. // Rebuild the function type, replacing the result type with DestType.
  14230. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  14231. if (Proto) {
  14232. // __unknown_anytype(...) is a special case used by the debugger when
  14233. // it has no idea what a function's signature is.
  14234. //
  14235. // We want to build this call essentially under the K&R
  14236. // unprototyped rules, but making a FunctionNoProtoType in C++
  14237. // would foul up all sorts of assumptions. However, we cannot
  14238. // simply pass all arguments as variadic arguments, nor can we
  14239. // portably just call the function under a non-variadic type; see
  14240. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  14241. // However, it turns out that in practice it is generally safe to
  14242. // call a function declared as "A foo(B,C,D);" under the prototype
  14243. // "A foo(B,C,D,...);". The only known exception is with the
  14244. // Windows ABI, where any variadic function is implicitly cdecl
  14245. // regardless of its normal CC. Therefore we change the parameter
  14246. // types to match the types of the arguments.
  14247. //
  14248. // This is a hack, but it is far superior to moving the
  14249. // corresponding target-specific code from IR-gen to Sema/AST.
  14250. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  14251. SmallVector<QualType, 8> ArgTypes;
  14252. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  14253. ArgTypes.reserve(E->getNumArgs());
  14254. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  14255. Expr *Arg = E->getArg(i);
  14256. QualType ArgType = Arg->getType();
  14257. if (E->isLValue()) {
  14258. ArgType = S.Context.getLValueReferenceType(ArgType);
  14259. } else if (E->isXValue()) {
  14260. ArgType = S.Context.getRValueReferenceType(ArgType);
  14261. }
  14262. ArgTypes.push_back(ArgType);
  14263. }
  14264. ParamTypes = ArgTypes;
  14265. }
  14266. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  14267. Proto->getExtProtoInfo());
  14268. } else {
  14269. DestType = S.Context.getFunctionNoProtoType(DestType,
  14270. FnType->getExtInfo());
  14271. }
  14272. // Rebuild the appropriate pointer-to-function type.
  14273. switch (Kind) {
  14274. case FK_MemberFunction:
  14275. // Nothing to do.
  14276. break;
  14277. case FK_FunctionPointer:
  14278. DestType = S.Context.getPointerType(DestType);
  14279. break;
  14280. case FK_BlockPointer:
  14281. DestType = S.Context.getBlockPointerType(DestType);
  14282. break;
  14283. }
  14284. // Finally, we can recurse.
  14285. ExprResult CalleeResult = Visit(CalleeExpr);
  14286. if (!CalleeResult.isUsable()) return ExprError();
  14287. E->setCallee(CalleeResult.get());
  14288. // Bind a temporary if necessary.
  14289. return S.MaybeBindToTemporary(E);
  14290. }
  14291. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  14292. // Verify that this is a legal result type of a call.
  14293. if (DestType->isArrayType() || DestType->isFunctionType()) {
  14294. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  14295. << DestType->isFunctionType() << DestType;
  14296. return ExprError();
  14297. }
  14298. // Rewrite the method result type if available.
  14299. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  14300. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  14301. Method->setReturnType(DestType);
  14302. }
  14303. // Change the type of the message.
  14304. E->setType(DestType.getNonReferenceType());
  14305. E->setValueKind(Expr::getValueKindForType(DestType));
  14306. return S.MaybeBindToTemporary(E);
  14307. }
  14308. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  14309. // The only case we should ever see here is a function-to-pointer decay.
  14310. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  14311. assert(E->getValueKind() == VK_RValue);
  14312. assert(E->getObjectKind() == OK_Ordinary);
  14313. E->setType(DestType);
  14314. // Rebuild the sub-expression as the pointee (function) type.
  14315. DestType = DestType->castAs<PointerType>()->getPointeeType();
  14316. ExprResult Result = Visit(E->getSubExpr());
  14317. if (!Result.isUsable()) return ExprError();
  14318. E->setSubExpr(Result.get());
  14319. return E;
  14320. } else if (E->getCastKind() == CK_LValueToRValue) {
  14321. assert(E->getValueKind() == VK_RValue);
  14322. assert(E->getObjectKind() == OK_Ordinary);
  14323. assert(isa<BlockPointerType>(E->getType()));
  14324. E->setType(DestType);
  14325. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  14326. DestType = S.Context.getLValueReferenceType(DestType);
  14327. ExprResult Result = Visit(E->getSubExpr());
  14328. if (!Result.isUsable()) return ExprError();
  14329. E->setSubExpr(Result.get());
  14330. return E;
  14331. } else {
  14332. llvm_unreachable("Unhandled cast type!");
  14333. }
  14334. }
  14335. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  14336. ExprValueKind ValueKind = VK_LValue;
  14337. QualType Type = DestType;
  14338. // We know how to make this work for certain kinds of decls:
  14339. // - functions
  14340. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  14341. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  14342. DestType = Ptr->getPointeeType();
  14343. ExprResult Result = resolveDecl(E, VD);
  14344. if (Result.isInvalid()) return ExprError();
  14345. return S.ImpCastExprToType(Result.get(), Type,
  14346. CK_FunctionToPointerDecay, VK_RValue);
  14347. }
  14348. if (!Type->isFunctionType()) {
  14349. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  14350. << VD << E->getSourceRange();
  14351. return ExprError();
  14352. }
  14353. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  14354. // We must match the FunctionDecl's type to the hack introduced in
  14355. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  14356. // type. See the lengthy commentary in that routine.
  14357. QualType FDT = FD->getType();
  14358. const FunctionType *FnType = FDT->castAs<FunctionType>();
  14359. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  14360. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  14361. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  14362. SourceLocation Loc = FD->getLocation();
  14363. FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
  14364. FD->getDeclContext(),
  14365. Loc, Loc, FD->getNameInfo().getName(),
  14366. DestType, FD->getTypeSourceInfo(),
  14367. SC_None, false/*isInlineSpecified*/,
  14368. FD->hasPrototype(),
  14369. false/*isConstexprSpecified*/);
  14370. if (FD->getQualifier())
  14371. NewFD->setQualifierInfo(FD->getQualifierLoc());
  14372. SmallVector<ParmVarDecl*, 16> Params;
  14373. for (const auto &AI : FT->param_types()) {
  14374. ParmVarDecl *Param =
  14375. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  14376. Param->setScopeInfo(0, Params.size());
  14377. Params.push_back(Param);
  14378. }
  14379. NewFD->setParams(Params);
  14380. DRE->setDecl(NewFD);
  14381. VD = DRE->getDecl();
  14382. }
  14383. }
  14384. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  14385. if (MD->isInstance()) {
  14386. ValueKind = VK_RValue;
  14387. Type = S.Context.BoundMemberTy;
  14388. }
  14389. // Function references aren't l-values in C.
  14390. if (!S.getLangOpts().CPlusPlus)
  14391. ValueKind = VK_RValue;
  14392. // - variables
  14393. } else if (isa<VarDecl>(VD)) {
  14394. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  14395. Type = RefTy->getPointeeType();
  14396. } else if (Type->isFunctionType()) {
  14397. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  14398. << VD << E->getSourceRange();
  14399. return ExprError();
  14400. }
  14401. // - nothing else
  14402. } else {
  14403. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  14404. << VD << E->getSourceRange();
  14405. return ExprError();
  14406. }
  14407. // Modifying the declaration like this is friendly to IR-gen but
  14408. // also really dangerous.
  14409. VD->setType(DestType);
  14410. E->setType(Type);
  14411. E->setValueKind(ValueKind);
  14412. return E;
  14413. }
  14414. /// Check a cast of an unknown-any type. We intentionally only
  14415. /// trigger this for C-style casts.
  14416. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  14417. Expr *CastExpr, CastKind &CastKind,
  14418. ExprValueKind &VK, CXXCastPath &Path) {
  14419. // The type we're casting to must be either void or complete.
  14420. if (!CastType->isVoidType() &&
  14421. RequireCompleteType(TypeRange.getBegin(), CastType,
  14422. diag::err_typecheck_cast_to_incomplete))
  14423. return ExprError();
  14424. // Rewrite the casted expression from scratch.
  14425. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  14426. if (!result.isUsable()) return ExprError();
  14427. CastExpr = result.get();
  14428. VK = CastExpr->getValueKind();
  14429. CastKind = CK_NoOp;
  14430. return CastExpr;
  14431. }
  14432. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  14433. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  14434. }
  14435. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  14436. Expr *arg, QualType &paramType) {
  14437. // If the syntactic form of the argument is not an explicit cast of
  14438. // any sort, just do default argument promotion.
  14439. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  14440. if (!castArg) {
  14441. ExprResult result = DefaultArgumentPromotion(arg);
  14442. if (result.isInvalid()) return ExprError();
  14443. paramType = result.get()->getType();
  14444. return result;
  14445. }
  14446. // Otherwise, use the type that was written in the explicit cast.
  14447. assert(!arg->hasPlaceholderType());
  14448. paramType = castArg->getTypeAsWritten();
  14449. // Copy-initialize a parameter of that type.
  14450. InitializedEntity entity =
  14451. InitializedEntity::InitializeParameter(Context, paramType,
  14452. /*consumed*/ false);
  14453. return PerformCopyInitialization(entity, callLoc, arg);
  14454. }
  14455. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  14456. Expr *orig = E;
  14457. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  14458. while (true) {
  14459. E = E->IgnoreParenImpCasts();
  14460. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  14461. E = call->getCallee();
  14462. diagID = diag::err_uncasted_call_of_unknown_any;
  14463. } else {
  14464. break;
  14465. }
  14466. }
  14467. SourceLocation loc;
  14468. NamedDecl *d;
  14469. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  14470. loc = ref->getLocation();
  14471. d = ref->getDecl();
  14472. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  14473. loc = mem->getMemberLoc();
  14474. d = mem->getMemberDecl();
  14475. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  14476. diagID = diag::err_uncasted_call_of_unknown_any;
  14477. loc = msg->getSelectorStartLoc();
  14478. d = msg->getMethodDecl();
  14479. if (!d) {
  14480. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  14481. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  14482. << orig->getSourceRange();
  14483. return ExprError();
  14484. }
  14485. } else {
  14486. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  14487. << E->getSourceRange();
  14488. return ExprError();
  14489. }
  14490. S.Diag(loc, diagID) << d << orig->getSourceRange();
  14491. // Never recoverable.
  14492. return ExprError();
  14493. }
  14494. /// Check for operands with placeholder types and complain if found.
  14495. /// Returns ExprError() if there was an error and no recovery was possible.
  14496. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  14497. if (!getLangOpts().CPlusPlus) {
  14498. // C cannot handle TypoExpr nodes on either side of a binop because it
  14499. // doesn't handle dependent types properly, so make sure any TypoExprs have
  14500. // been dealt with before checking the operands.
  14501. ExprResult Result = CorrectDelayedTyposInExpr(E);
  14502. if (!Result.isUsable()) return ExprError();
  14503. E = Result.get();
  14504. }
  14505. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  14506. if (!placeholderType) return E;
  14507. switch (placeholderType->getKind()) {
  14508. // Overloaded expressions.
  14509. case BuiltinType::Overload: {
  14510. // Try to resolve a single function template specialization.
  14511. // This is obligatory.
  14512. ExprResult Result = E;
  14513. if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
  14514. return Result;
  14515. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  14516. // leaves Result unchanged on failure.
  14517. Result = E;
  14518. if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
  14519. return Result;
  14520. // If that failed, try to recover with a call.
  14521. tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
  14522. /*complain*/ true);
  14523. return Result;
  14524. }
  14525. // Bound member functions.
  14526. case BuiltinType::BoundMember: {
  14527. ExprResult result = E;
  14528. const Expr *BME = E->IgnoreParens();
  14529. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  14530. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  14531. if (isa<CXXPseudoDestructorExpr>(BME)) {
  14532. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  14533. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  14534. if (ME->getMemberNameInfo().getName().getNameKind() ==
  14535. DeclarationName::CXXDestructorName)
  14536. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  14537. }
  14538. tryToRecoverWithCall(result, PD,
  14539. /*complain*/ true);
  14540. return result;
  14541. }
  14542. // ARC unbridged casts.
  14543. case BuiltinType::ARCUnbridgedCast: {
  14544. Expr *realCast = stripARCUnbridgedCast(E);
  14545. diagnoseARCUnbridgedCast(realCast);
  14546. return realCast;
  14547. }
  14548. // Expressions of unknown type.
  14549. case BuiltinType::UnknownAny:
  14550. return diagnoseUnknownAnyExpr(*this, E);
  14551. // Pseudo-objects.
  14552. case BuiltinType::PseudoObject:
  14553. return checkPseudoObjectRValue(E);
  14554. case BuiltinType::BuiltinFn: {
  14555. // Accept __noop without parens by implicitly converting it to a call expr.
  14556. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  14557. if (DRE) {
  14558. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  14559. if (FD->getBuiltinID() == Builtin::BI__noop) {
  14560. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  14561. CK_BuiltinFnToFnPtr).get();
  14562. return new (Context) CallExpr(Context, E, None, Context.IntTy,
  14563. VK_RValue, SourceLocation());
  14564. }
  14565. }
  14566. Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
  14567. return ExprError();
  14568. }
  14569. // Expressions of unknown type.
  14570. case BuiltinType::OMPArraySection:
  14571. Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
  14572. return ExprError();
  14573. // Everything else should be impossible.
  14574. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  14575. case BuiltinType::Id:
  14576. #include "clang/Basic/OpenCLImageTypes.def"
  14577. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  14578. case BuiltinType::Id:
  14579. #include "clang/Basic/OpenCLExtensionTypes.def"
  14580. #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
  14581. #define PLACEHOLDER_TYPE(Id, SingletonId)
  14582. #include "clang/AST/BuiltinTypes.def"
  14583. break;
  14584. }
  14585. llvm_unreachable("invalid placeholder type!");
  14586. }
  14587. bool Sema::CheckCaseExpression(Expr *E) {
  14588. if (E->isTypeDependent())
  14589. return true;
  14590. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  14591. return E->getType()->isIntegralOrEnumerationType();
  14592. return false;
  14593. }
  14594. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  14595. ExprResult
  14596. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  14597. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  14598. "Unknown Objective-C Boolean value!");
  14599. QualType BoolT = Context.ObjCBuiltinBoolTy;
  14600. if (!Context.getBOOLDecl()) {
  14601. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  14602. Sema::LookupOrdinaryName);
  14603. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  14604. NamedDecl *ND = Result.getFoundDecl();
  14605. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  14606. Context.setBOOLDecl(TD);
  14607. }
  14608. }
  14609. if (Context.getBOOLDecl())
  14610. BoolT = Context.getBOOLType();
  14611. return new (Context)
  14612. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  14613. }
  14614. ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
  14615. llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
  14616. SourceLocation RParen) {
  14617. StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
  14618. auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
  14619. [&](const AvailabilitySpec &Spec) {
  14620. return Spec.getPlatform() == Platform;
  14621. });
  14622. VersionTuple Version;
  14623. if (Spec != AvailSpecs.end())
  14624. Version = Spec->getVersion();
  14625. // The use of `@available` in the enclosing function should be analyzed to
  14626. // warn when it's used inappropriately (i.e. not if(@available)).
  14627. if (getCurFunctionOrMethodDecl())
  14628. getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
  14629. else if (getCurBlock() || getCurLambda())
  14630. getCurFunction()->HasPotentialAvailabilityViolations = true;
  14631. return new (Context)
  14632. ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
  14633. }