SemaChecking.cpp 457 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485
  1. //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
  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 extra semantic analysis beyond what is enforced
  11. // by the C type system.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/AST/APValue.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/Attr.h"
  17. #include "clang/AST/AttrIterator.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclBase.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/DeclarationName.h"
  24. #include "clang/AST/EvaluatedExprVisitor.h"
  25. #include "clang/AST/Expr.h"
  26. #include "clang/AST/ExprCXX.h"
  27. #include "clang/AST/ExprObjC.h"
  28. #include "clang/AST/ExprOpenMP.h"
  29. #include "clang/AST/NSAPI.h"
  30. #include "clang/AST/OperationKinds.h"
  31. #include "clang/AST/Stmt.h"
  32. #include "clang/AST/TemplateBase.h"
  33. #include "clang/AST/Type.h"
  34. #include "clang/AST/TypeLoc.h"
  35. #include "clang/AST/UnresolvedSet.h"
  36. #include "clang/Analysis/Analyses/FormatString.h"
  37. #include "clang/Basic/AddressSpaces.h"
  38. #include "clang/Basic/CharInfo.h"
  39. #include "clang/Basic/Diagnostic.h"
  40. #include "clang/Basic/IdentifierTable.h"
  41. #include "clang/Basic/LLVM.h"
  42. #include "clang/Basic/LangOptions.h"
  43. #include "clang/Basic/OpenCLOptions.h"
  44. #include "clang/Basic/OperatorKinds.h"
  45. #include "clang/Basic/PartialDiagnostic.h"
  46. #include "clang/Basic/SourceLocation.h"
  47. #include "clang/Basic/SourceManager.h"
  48. #include "clang/Basic/Specifiers.h"
  49. #include "clang/Basic/SyncScope.h"
  50. #include "clang/Basic/TargetBuiltins.h"
  51. #include "clang/Basic/TargetCXXABI.h"
  52. #include "clang/Basic/TargetInfo.h"
  53. #include "clang/Basic/TypeTraits.h"
  54. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  55. #include "clang/Sema/Initialization.h"
  56. #include "clang/Sema/Lookup.h"
  57. #include "clang/Sema/Ownership.h"
  58. #include "clang/Sema/Scope.h"
  59. #include "clang/Sema/ScopeInfo.h"
  60. #include "clang/Sema/Sema.h"
  61. #include "clang/Sema/SemaInternal.h"
  62. #include "llvm/ADT/APFloat.h"
  63. #include "llvm/ADT/APInt.h"
  64. #include "llvm/ADT/APSInt.h"
  65. #include "llvm/ADT/ArrayRef.h"
  66. #include "llvm/ADT/DenseMap.h"
  67. #include "llvm/ADT/FoldingSet.h"
  68. #include "llvm/ADT/None.h"
  69. #include "llvm/ADT/Optional.h"
  70. #include "llvm/ADT/STLExtras.h"
  71. #include "llvm/ADT/SmallBitVector.h"
  72. #include "llvm/ADT/SmallPtrSet.h"
  73. #include "llvm/ADT/SmallString.h"
  74. #include "llvm/ADT/SmallVector.h"
  75. #include "llvm/ADT/StringRef.h"
  76. #include "llvm/ADT/StringSwitch.h"
  77. #include "llvm/ADT/Triple.h"
  78. #include "llvm/Support/AtomicOrdering.h"
  79. #include "llvm/Support/Casting.h"
  80. #include "llvm/Support/Compiler.h"
  81. #include "llvm/Support/ConvertUTF.h"
  82. #include "llvm/Support/ErrorHandling.h"
  83. #include "llvm/Support/Format.h"
  84. #include "llvm/Support/Locale.h"
  85. #include "llvm/Support/MathExtras.h"
  86. #include "llvm/Support/raw_ostream.h"
  87. #include <algorithm>
  88. #include <cassert>
  89. #include <cstddef>
  90. #include <cstdint>
  91. #include <functional>
  92. #include <limits>
  93. #include <string>
  94. #include <tuple>
  95. #include <utility>
  96. using namespace clang;
  97. using namespace sema;
  98. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  99. unsigned ByteNo) const {
  100. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  101. Context.getTargetInfo());
  102. }
  103. /// Checks that a call expression's argument count is the desired number.
  104. /// This is useful when doing custom type-checking. Returns true on error.
  105. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  106. unsigned argCount = call->getNumArgs();
  107. if (argCount == desiredArgCount) return false;
  108. if (argCount < desiredArgCount)
  109. return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
  110. << 0 /*function call*/ << desiredArgCount << argCount
  111. << call->getSourceRange();
  112. // Highlight all the excess arguments.
  113. SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
  114. call->getArg(argCount - 1)->getLocEnd());
  115. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  116. << 0 /*function call*/ << desiredArgCount << argCount
  117. << call->getArg(1)->getSourceRange();
  118. }
  119. /// Check that the first argument to __builtin_annotation is an integer
  120. /// and the second argument is a non-wide string literal.
  121. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  122. if (checkArgCount(S, TheCall, 2))
  123. return true;
  124. // First argument should be an integer.
  125. Expr *ValArg = TheCall->getArg(0);
  126. QualType Ty = ValArg->getType();
  127. if (!Ty->isIntegerType()) {
  128. S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
  129. << ValArg->getSourceRange();
  130. return true;
  131. }
  132. // Second argument should be a constant string.
  133. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  134. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  135. if (!Literal || !Literal->isAscii()) {
  136. S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
  137. << StrArg->getSourceRange();
  138. return true;
  139. }
  140. TheCall->setType(Ty);
  141. return false;
  142. }
  143. static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
  144. // We need at least one argument.
  145. if (TheCall->getNumArgs() < 1) {
  146. S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  147. << 0 << 1 << TheCall->getNumArgs()
  148. << TheCall->getCallee()->getSourceRange();
  149. return true;
  150. }
  151. // All arguments should be wide string literals.
  152. for (Expr *Arg : TheCall->arguments()) {
  153. auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
  154. if (!Literal || !Literal->isWide()) {
  155. S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
  156. << Arg->getSourceRange();
  157. return true;
  158. }
  159. }
  160. return false;
  161. }
  162. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  163. /// result type to the corresponding pointer type.
  164. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  165. if (checkArgCount(S, TheCall, 1))
  166. return true;
  167. ExprResult Arg(TheCall->getArg(0));
  168. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
  169. if (ResultType.isNull())
  170. return true;
  171. TheCall->setArg(0, Arg.get());
  172. TheCall->setType(ResultType);
  173. return false;
  174. }
  175. static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
  176. if (checkArgCount(S, TheCall, 3))
  177. return true;
  178. // First two arguments should be integers.
  179. for (unsigned I = 0; I < 2; ++I) {
  180. Expr *Arg = TheCall->getArg(I);
  181. QualType Ty = Arg->getType();
  182. if (!Ty->isIntegerType()) {
  183. S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
  184. << Ty << Arg->getSourceRange();
  185. return true;
  186. }
  187. }
  188. // Third argument should be a pointer to a non-const integer.
  189. // IRGen correctly handles volatile, restrict, and address spaces, and
  190. // the other qualifiers aren't possible.
  191. {
  192. Expr *Arg = TheCall->getArg(2);
  193. QualType Ty = Arg->getType();
  194. const auto *PtrTy = Ty->getAs<PointerType>();
  195. if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
  196. !PtrTy->getPointeeType().isConstQualified())) {
  197. S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
  198. << Ty << Arg->getSourceRange();
  199. return true;
  200. }
  201. }
  202. return false;
  203. }
  204. static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
  205. CallExpr *TheCall, unsigned SizeIdx,
  206. unsigned DstSizeIdx) {
  207. if (TheCall->getNumArgs() <= SizeIdx ||
  208. TheCall->getNumArgs() <= DstSizeIdx)
  209. return;
  210. const Expr *SizeArg = TheCall->getArg(SizeIdx);
  211. const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
  212. llvm::APSInt Size, DstSize;
  213. // find out if both sizes are known at compile time
  214. if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
  215. !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
  216. return;
  217. if (Size.ule(DstSize))
  218. return;
  219. // confirmed overflow so generate the diagnostic.
  220. IdentifierInfo *FnName = FDecl->getIdentifier();
  221. SourceLocation SL = TheCall->getLocStart();
  222. SourceRange SR = TheCall->getSourceRange();
  223. S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
  224. }
  225. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  226. if (checkArgCount(S, BuiltinCall, 2))
  227. return true;
  228. SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
  229. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  230. Expr *Call = BuiltinCall->getArg(0);
  231. Expr *Chain = BuiltinCall->getArg(1);
  232. if (Call->getStmtClass() != Stmt::CallExprClass) {
  233. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  234. << Call->getSourceRange();
  235. return true;
  236. }
  237. auto CE = cast<CallExpr>(Call);
  238. if (CE->getCallee()->getType()->isBlockPointerType()) {
  239. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  240. << Call->getSourceRange();
  241. return true;
  242. }
  243. const Decl *TargetDecl = CE->getCalleeDecl();
  244. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  245. if (FD->getBuiltinID()) {
  246. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  247. << Call->getSourceRange();
  248. return true;
  249. }
  250. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  251. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  252. << Call->getSourceRange();
  253. return true;
  254. }
  255. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  256. if (ChainResult.isInvalid())
  257. return true;
  258. if (!ChainResult.get()->getType()->isPointerType()) {
  259. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  260. << Chain->getSourceRange();
  261. return true;
  262. }
  263. QualType ReturnTy = CE->getCallReturnType(S.Context);
  264. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  265. QualType BuiltinTy = S.Context.getFunctionType(
  266. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
  267. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  268. Builtin =
  269. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  270. BuiltinCall->setType(CE->getType());
  271. BuiltinCall->setValueKind(CE->getValueKind());
  272. BuiltinCall->setObjectKind(CE->getObjectKind());
  273. BuiltinCall->setCallee(Builtin);
  274. BuiltinCall->setArg(1, ChainResult.get());
  275. return false;
  276. }
  277. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  278. Scope::ScopeFlags NeededScopeFlags,
  279. unsigned DiagID) {
  280. // Scopes aren't available during instantiation. Fortunately, builtin
  281. // functions cannot be template args so they cannot be formed through template
  282. // instantiation. Therefore checking once during the parse is sufficient.
  283. if (SemaRef.inTemplateInstantiation())
  284. return false;
  285. Scope *S = SemaRef.getCurScope();
  286. while (S && !S->isSEHExceptScope())
  287. S = S->getParent();
  288. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  289. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  290. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  291. << DRE->getDecl()->getIdentifier();
  292. return true;
  293. }
  294. return false;
  295. }
  296. static inline bool isBlockPointer(Expr *Arg) {
  297. return Arg->getType()->isBlockPointerType();
  298. }
  299. /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
  300. /// void*, which is a requirement of device side enqueue.
  301. static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
  302. const BlockPointerType *BPT =
  303. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  304. ArrayRef<QualType> Params =
  305. BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
  306. unsigned ArgCounter = 0;
  307. bool IllegalParams = false;
  308. // Iterate through the block parameters until either one is found that is not
  309. // a local void*, or the block is valid.
  310. for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
  311. I != E; ++I, ++ArgCounter) {
  312. if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
  313. (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
  314. LangAS::opencl_local) {
  315. // Get the location of the error. If a block literal has been passed
  316. // (BlockExpr) then we can point straight to the offending argument,
  317. // else we just point to the variable reference.
  318. SourceLocation ErrorLoc;
  319. if (isa<BlockExpr>(BlockArg)) {
  320. BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
  321. ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
  322. } else if (isa<DeclRefExpr>(BlockArg)) {
  323. ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
  324. }
  325. S.Diag(ErrorLoc,
  326. diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
  327. IllegalParams = true;
  328. }
  329. }
  330. return IllegalParams;
  331. }
  332. static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
  333. if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
  334. S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
  335. << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
  336. return true;
  337. }
  338. return false;
  339. }
  340. static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
  341. if (checkArgCount(S, TheCall, 2))
  342. return true;
  343. if (checkOpenCLSubgroupExt(S, TheCall))
  344. return true;
  345. // First argument is an ndrange_t type.
  346. Expr *NDRangeArg = TheCall->getArg(0);
  347. if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  348. S.Diag(NDRangeArg->getLocStart(),
  349. diag::err_opencl_builtin_expected_type)
  350. << TheCall->getDirectCallee() << "'ndrange_t'";
  351. return true;
  352. }
  353. Expr *BlockArg = TheCall->getArg(1);
  354. if (!isBlockPointer(BlockArg)) {
  355. S.Diag(BlockArg->getLocStart(),
  356. diag::err_opencl_builtin_expected_type)
  357. << TheCall->getDirectCallee() << "block";
  358. return true;
  359. }
  360. return checkOpenCLBlockArgs(S, BlockArg);
  361. }
  362. /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
  363. /// get_kernel_work_group_size
  364. /// and get_kernel_preferred_work_group_size_multiple builtin functions.
  365. static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
  366. if (checkArgCount(S, TheCall, 1))
  367. return true;
  368. Expr *BlockArg = TheCall->getArg(0);
  369. if (!isBlockPointer(BlockArg)) {
  370. S.Diag(BlockArg->getLocStart(),
  371. diag::err_opencl_builtin_expected_type)
  372. << TheCall->getDirectCallee() << "block";
  373. return true;
  374. }
  375. return checkOpenCLBlockArgs(S, BlockArg);
  376. }
  377. /// Diagnose integer type and any valid implicit conversion to it.
  378. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
  379. const QualType &IntType);
  380. static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
  381. unsigned Start, unsigned End) {
  382. bool IllegalParams = false;
  383. for (unsigned I = Start; I <= End; ++I)
  384. IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
  385. S.Context.getSizeType());
  386. return IllegalParams;
  387. }
  388. /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
  389. /// 'local void*' parameter of passed block.
  390. static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
  391. Expr *BlockArg,
  392. unsigned NumNonVarArgs) {
  393. const BlockPointerType *BPT =
  394. cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
  395. unsigned NumBlockParams =
  396. BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
  397. unsigned TotalNumArgs = TheCall->getNumArgs();
  398. // For each argument passed to the block, a corresponding uint needs to
  399. // be passed to describe the size of the local memory.
  400. if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
  401. S.Diag(TheCall->getLocStart(),
  402. diag::err_opencl_enqueue_kernel_local_size_args);
  403. return true;
  404. }
  405. // Check that the sizes of the local memory are specified by integers.
  406. return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
  407. TotalNumArgs - 1);
  408. }
  409. /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
  410. /// overload formats specified in Table 6.13.17.1.
  411. /// int enqueue_kernel(queue_t queue,
  412. /// kernel_enqueue_flags_t flags,
  413. /// const ndrange_t ndrange,
  414. /// void (^block)(void))
  415. /// int enqueue_kernel(queue_t queue,
  416. /// kernel_enqueue_flags_t flags,
  417. /// const ndrange_t ndrange,
  418. /// uint num_events_in_wait_list,
  419. /// clk_event_t *event_wait_list,
  420. /// clk_event_t *event_ret,
  421. /// void (^block)(void))
  422. /// int enqueue_kernel(queue_t queue,
  423. /// kernel_enqueue_flags_t flags,
  424. /// const ndrange_t ndrange,
  425. /// void (^block)(local void*, ...),
  426. /// uint size0, ...)
  427. /// int enqueue_kernel(queue_t queue,
  428. /// kernel_enqueue_flags_t flags,
  429. /// const ndrange_t ndrange,
  430. /// uint num_events_in_wait_list,
  431. /// clk_event_t *event_wait_list,
  432. /// clk_event_t *event_ret,
  433. /// void (^block)(local void*, ...),
  434. /// uint size0, ...)
  435. static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
  436. unsigned NumArgs = TheCall->getNumArgs();
  437. if (NumArgs < 4) {
  438. S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
  439. return true;
  440. }
  441. Expr *Arg0 = TheCall->getArg(0);
  442. Expr *Arg1 = TheCall->getArg(1);
  443. Expr *Arg2 = TheCall->getArg(2);
  444. Expr *Arg3 = TheCall->getArg(3);
  445. // First argument always needs to be a queue_t type.
  446. if (!Arg0->getType()->isQueueT()) {
  447. S.Diag(TheCall->getArg(0)->getLocStart(),
  448. diag::err_opencl_builtin_expected_type)
  449. << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
  450. return true;
  451. }
  452. // Second argument always needs to be a kernel_enqueue_flags_t enum value.
  453. if (!Arg1->getType()->isIntegerType()) {
  454. S.Diag(TheCall->getArg(1)->getLocStart(),
  455. diag::err_opencl_builtin_expected_type)
  456. << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
  457. return true;
  458. }
  459. // Third argument is always an ndrange_t type.
  460. if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
  461. S.Diag(TheCall->getArg(2)->getLocStart(),
  462. diag::err_opencl_builtin_expected_type)
  463. << TheCall->getDirectCallee() << "'ndrange_t'";
  464. return true;
  465. }
  466. // With four arguments, there is only one form that the function could be
  467. // called in: no events and no variable arguments.
  468. if (NumArgs == 4) {
  469. // check that the last argument is the right block type.
  470. if (!isBlockPointer(Arg3)) {
  471. S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
  472. << TheCall->getDirectCallee() << "block";
  473. return true;
  474. }
  475. // we have a block type, check the prototype
  476. const BlockPointerType *BPT =
  477. cast<BlockPointerType>(Arg3->getType().getCanonicalType());
  478. if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
  479. S.Diag(Arg3->getLocStart(),
  480. diag::err_opencl_enqueue_kernel_blocks_no_args);
  481. return true;
  482. }
  483. return false;
  484. }
  485. // we can have block + varargs.
  486. if (isBlockPointer(Arg3))
  487. return (checkOpenCLBlockArgs(S, Arg3) ||
  488. checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
  489. // last two cases with either exactly 7 args or 7 args and varargs.
  490. if (NumArgs >= 7) {
  491. // check common block argument.
  492. Expr *Arg6 = TheCall->getArg(6);
  493. if (!isBlockPointer(Arg6)) {
  494. S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
  495. << TheCall->getDirectCallee() << "block";
  496. return true;
  497. }
  498. if (checkOpenCLBlockArgs(S, Arg6))
  499. return true;
  500. // Forth argument has to be any integer type.
  501. if (!Arg3->getType()->isIntegerType()) {
  502. S.Diag(TheCall->getArg(3)->getLocStart(),
  503. diag::err_opencl_builtin_expected_type)
  504. << TheCall->getDirectCallee() << "integer";
  505. return true;
  506. }
  507. // check remaining common arguments.
  508. Expr *Arg4 = TheCall->getArg(4);
  509. Expr *Arg5 = TheCall->getArg(5);
  510. // Fifth argument is always passed as a pointer to clk_event_t.
  511. if (!Arg4->isNullPointerConstant(S.Context,
  512. Expr::NPC_ValueDependentIsNotNull) &&
  513. !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
  514. S.Diag(TheCall->getArg(4)->getLocStart(),
  515. diag::err_opencl_builtin_expected_type)
  516. << TheCall->getDirectCallee()
  517. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  518. return true;
  519. }
  520. // Sixth argument is always passed as a pointer to clk_event_t.
  521. if (!Arg5->isNullPointerConstant(S.Context,
  522. Expr::NPC_ValueDependentIsNotNull) &&
  523. !(Arg5->getType()->isPointerType() &&
  524. Arg5->getType()->getPointeeType()->isClkEventT())) {
  525. S.Diag(TheCall->getArg(5)->getLocStart(),
  526. diag::err_opencl_builtin_expected_type)
  527. << TheCall->getDirectCallee()
  528. << S.Context.getPointerType(S.Context.OCLClkEventTy);
  529. return true;
  530. }
  531. if (NumArgs == 7)
  532. return false;
  533. return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
  534. }
  535. // None of the specific case has been detected, give generic error
  536. S.Diag(TheCall->getLocStart(),
  537. diag::err_opencl_enqueue_kernel_incorrect_args);
  538. return true;
  539. }
  540. /// Returns OpenCL access qual.
  541. static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
  542. return D->getAttr<OpenCLAccessAttr>();
  543. }
  544. /// Returns true if pipe element type is different from the pointer.
  545. static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
  546. const Expr *Arg0 = Call->getArg(0);
  547. // First argument type should always be pipe.
  548. if (!Arg0->getType()->isPipeType()) {
  549. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
  550. << Call->getDirectCallee() << Arg0->getSourceRange();
  551. return true;
  552. }
  553. OpenCLAccessAttr *AccessQual =
  554. getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
  555. // Validates the access qualifier is compatible with the call.
  556. // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
  557. // read_only and write_only, and assumed to be read_only if no qualifier is
  558. // specified.
  559. switch (Call->getDirectCallee()->getBuiltinID()) {
  560. case Builtin::BIread_pipe:
  561. case Builtin::BIreserve_read_pipe:
  562. case Builtin::BIcommit_read_pipe:
  563. case Builtin::BIwork_group_reserve_read_pipe:
  564. case Builtin::BIsub_group_reserve_read_pipe:
  565. case Builtin::BIwork_group_commit_read_pipe:
  566. case Builtin::BIsub_group_commit_read_pipe:
  567. if (!(!AccessQual || AccessQual->isReadOnly())) {
  568. S.Diag(Arg0->getLocStart(),
  569. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  570. << "read_only" << Arg0->getSourceRange();
  571. return true;
  572. }
  573. break;
  574. case Builtin::BIwrite_pipe:
  575. case Builtin::BIreserve_write_pipe:
  576. case Builtin::BIcommit_write_pipe:
  577. case Builtin::BIwork_group_reserve_write_pipe:
  578. case Builtin::BIsub_group_reserve_write_pipe:
  579. case Builtin::BIwork_group_commit_write_pipe:
  580. case Builtin::BIsub_group_commit_write_pipe:
  581. if (!(AccessQual && AccessQual->isWriteOnly())) {
  582. S.Diag(Arg0->getLocStart(),
  583. diag::err_opencl_builtin_pipe_invalid_access_modifier)
  584. << "write_only" << Arg0->getSourceRange();
  585. return true;
  586. }
  587. break;
  588. default:
  589. break;
  590. }
  591. return false;
  592. }
  593. /// Returns true if pipe element type is different from the pointer.
  594. static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
  595. const Expr *Arg0 = Call->getArg(0);
  596. const Expr *ArgIdx = Call->getArg(Idx);
  597. const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
  598. const QualType EltTy = PipeTy->getElementType();
  599. const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
  600. // The Idx argument should be a pointer and the type of the pointer and
  601. // the type of pipe element should also be the same.
  602. if (!ArgTy ||
  603. !S.Context.hasSameType(
  604. EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
  605. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  606. << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
  607. << ArgIdx->getType() << ArgIdx->getSourceRange();
  608. return true;
  609. }
  610. return false;
  611. }
  612. // \brief Performs semantic analysis for the read/write_pipe call.
  613. // \param S Reference to the semantic analyzer.
  614. // \param Call A pointer to the builtin call.
  615. // \return True if a semantic error has been found, false otherwise.
  616. static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
  617. // OpenCL v2.0 s6.13.16.2 - The built-in read/write
  618. // functions have two forms.
  619. switch (Call->getNumArgs()) {
  620. case 2:
  621. if (checkOpenCLPipeArg(S, Call))
  622. return true;
  623. // The call with 2 arguments should be
  624. // read/write_pipe(pipe T, T*).
  625. // Check packet type T.
  626. if (checkOpenCLPipePacketType(S, Call, 1))
  627. return true;
  628. break;
  629. case 4: {
  630. if (checkOpenCLPipeArg(S, Call))
  631. return true;
  632. // The call with 4 arguments should be
  633. // read/write_pipe(pipe T, reserve_id_t, uint, T*).
  634. // Check reserve_id_t.
  635. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  636. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  637. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  638. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  639. return true;
  640. }
  641. // Check the index.
  642. const Expr *Arg2 = Call->getArg(2);
  643. if (!Arg2->getType()->isIntegerType() &&
  644. !Arg2->getType()->isUnsignedIntegerType()) {
  645. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  646. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  647. << Arg2->getType() << Arg2->getSourceRange();
  648. return true;
  649. }
  650. // Check packet type T.
  651. if (checkOpenCLPipePacketType(S, Call, 3))
  652. return true;
  653. } break;
  654. default:
  655. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
  656. << Call->getDirectCallee() << Call->getSourceRange();
  657. return true;
  658. }
  659. return false;
  660. }
  661. // \brief Performs a semantic analysis on the {work_group_/sub_group_
  662. // /_}reserve_{read/write}_pipe
  663. // \param S Reference to the semantic analyzer.
  664. // \param Call The call to the builtin function to be analyzed.
  665. // \return True if a semantic error was found, false otherwise.
  666. static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
  667. if (checkArgCount(S, Call, 2))
  668. return true;
  669. if (checkOpenCLPipeArg(S, Call))
  670. return true;
  671. // Check the reserve size.
  672. if (!Call->getArg(1)->getType()->isIntegerType() &&
  673. !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
  674. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  675. << Call->getDirectCallee() << S.Context.UnsignedIntTy
  676. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  677. return true;
  678. }
  679. // Since return type of reserve_read/write_pipe built-in function is
  680. // reserve_id_t, which is not defined in the builtin def file , we used int
  681. // as return type and need to override the return type of these functions.
  682. Call->setType(S.Context.OCLReserveIDTy);
  683. return false;
  684. }
  685. // \brief Performs a semantic analysis on {work_group_/sub_group_
  686. // /_}commit_{read/write}_pipe
  687. // \param S Reference to the semantic analyzer.
  688. // \param Call The call to the builtin function to be analyzed.
  689. // \return True if a semantic error was found, false otherwise.
  690. static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
  691. if (checkArgCount(S, Call, 2))
  692. return true;
  693. if (checkOpenCLPipeArg(S, Call))
  694. return true;
  695. // Check reserve_id_t.
  696. if (!Call->getArg(1)->getType()->isReserveIDT()) {
  697. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
  698. << Call->getDirectCallee() << S.Context.OCLReserveIDTy
  699. << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
  700. return true;
  701. }
  702. return false;
  703. }
  704. // \brief Performs a semantic analysis on the call to built-in Pipe
  705. // Query Functions.
  706. // \param S Reference to the semantic analyzer.
  707. // \param Call The call to the builtin function to be analyzed.
  708. // \return True if a semantic error was found, false otherwise.
  709. static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
  710. if (checkArgCount(S, Call, 1))
  711. return true;
  712. if (!Call->getArg(0)->getType()->isPipeType()) {
  713. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
  714. << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
  715. return true;
  716. }
  717. return false;
  718. }
  719. // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
  720. // \brief Performs semantic analysis for the to_global/local/private call.
  721. // \param S Reference to the semantic analyzer.
  722. // \param BuiltinID ID of the builtin function.
  723. // \param Call A pointer to the builtin call.
  724. // \return True if a semantic error has been found, false otherwise.
  725. static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
  726. CallExpr *Call) {
  727. if (Call->getNumArgs() != 1) {
  728. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
  729. << Call->getDirectCallee() << Call->getSourceRange();
  730. return true;
  731. }
  732. auto RT = Call->getArg(0)->getType();
  733. if (!RT->isPointerType() || RT->getPointeeType()
  734. .getAddressSpace() == LangAS::opencl_constant) {
  735. S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
  736. << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
  737. return true;
  738. }
  739. RT = RT->getPointeeType();
  740. auto Qual = RT.getQualifiers();
  741. switch (BuiltinID) {
  742. case Builtin::BIto_global:
  743. Qual.setAddressSpace(LangAS::opencl_global);
  744. break;
  745. case Builtin::BIto_local:
  746. Qual.setAddressSpace(LangAS::opencl_local);
  747. break;
  748. case Builtin::BIto_private:
  749. Qual.setAddressSpace(LangAS::opencl_private);
  750. break;
  751. default:
  752. llvm_unreachable("Invalid builtin function");
  753. }
  754. Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
  755. RT.getUnqualifiedType(), Qual)));
  756. return false;
  757. }
  758. ExprResult
  759. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  760. CallExpr *TheCall) {
  761. ExprResult TheCallResult(TheCall);
  762. // Find out if any arguments are required to be integer constant expressions.
  763. unsigned ICEArguments = 0;
  764. ASTContext::GetBuiltinTypeError Error;
  765. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  766. if (Error != ASTContext::GE_None)
  767. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  768. // If any arguments are required to be ICE's, check and diagnose.
  769. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  770. // Skip arguments not required to be ICE's.
  771. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  772. llvm::APSInt Result;
  773. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  774. return true;
  775. ICEArguments &= ~(1 << ArgNo);
  776. }
  777. switch (BuiltinID) {
  778. case Builtin::BI__builtin___CFStringMakeConstantString:
  779. assert(TheCall->getNumArgs() == 1 &&
  780. "Wrong # arguments to builtin CFStringMakeConstantString");
  781. if (CheckObjCString(TheCall->getArg(0)))
  782. return ExprError();
  783. break;
  784. case Builtin::BI__builtin_ms_va_start:
  785. case Builtin::BI__builtin_stdarg_start:
  786. case Builtin::BI__builtin_va_start:
  787. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  788. return ExprError();
  789. break;
  790. case Builtin::BI__va_start: {
  791. switch (Context.getTargetInfo().getTriple().getArch()) {
  792. case llvm::Triple::arm:
  793. case llvm::Triple::thumb:
  794. if (SemaBuiltinVAStartARMMicrosoft(TheCall))
  795. return ExprError();
  796. break;
  797. default:
  798. if (SemaBuiltinVAStart(BuiltinID, TheCall))
  799. return ExprError();
  800. break;
  801. }
  802. break;
  803. }
  804. case Builtin::BI__builtin_isgreater:
  805. case Builtin::BI__builtin_isgreaterequal:
  806. case Builtin::BI__builtin_isless:
  807. case Builtin::BI__builtin_islessequal:
  808. case Builtin::BI__builtin_islessgreater:
  809. case Builtin::BI__builtin_isunordered:
  810. if (SemaBuiltinUnorderedCompare(TheCall))
  811. return ExprError();
  812. break;
  813. case Builtin::BI__builtin_fpclassify:
  814. if (SemaBuiltinFPClassification(TheCall, 6))
  815. return ExprError();
  816. break;
  817. case Builtin::BI__builtin_isfinite:
  818. case Builtin::BI__builtin_isinf:
  819. case Builtin::BI__builtin_isinf_sign:
  820. case Builtin::BI__builtin_isnan:
  821. case Builtin::BI__builtin_isnormal:
  822. if (SemaBuiltinFPClassification(TheCall, 1))
  823. return ExprError();
  824. break;
  825. case Builtin::BI__builtin_shufflevector:
  826. return SemaBuiltinShuffleVector(TheCall);
  827. // TheCall will be freed by the smart pointer here, but that's fine, since
  828. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  829. case Builtin::BI__builtin_prefetch:
  830. if (SemaBuiltinPrefetch(TheCall))
  831. return ExprError();
  832. break;
  833. case Builtin::BI__builtin_alloca_with_align:
  834. if (SemaBuiltinAllocaWithAlign(TheCall))
  835. return ExprError();
  836. break;
  837. case Builtin::BI__assume:
  838. case Builtin::BI__builtin_assume:
  839. if (SemaBuiltinAssume(TheCall))
  840. return ExprError();
  841. break;
  842. case Builtin::BI__builtin_assume_aligned:
  843. if (SemaBuiltinAssumeAligned(TheCall))
  844. return ExprError();
  845. break;
  846. case Builtin::BI__builtin_object_size:
  847. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  848. return ExprError();
  849. break;
  850. case Builtin::BI__builtin_longjmp:
  851. if (SemaBuiltinLongjmp(TheCall))
  852. return ExprError();
  853. break;
  854. case Builtin::BI__builtin_setjmp:
  855. if (SemaBuiltinSetjmp(TheCall))
  856. return ExprError();
  857. break;
  858. case Builtin::BI_setjmp:
  859. case Builtin::BI_setjmpex:
  860. if (checkArgCount(*this, TheCall, 1))
  861. return true;
  862. break;
  863. case Builtin::BI__builtin_classify_type:
  864. if (checkArgCount(*this, TheCall, 1)) return true;
  865. TheCall->setType(Context.IntTy);
  866. break;
  867. case Builtin::BI__builtin_constant_p:
  868. if (checkArgCount(*this, TheCall, 1)) return true;
  869. TheCall->setType(Context.IntTy);
  870. break;
  871. case Builtin::BI__sync_fetch_and_add:
  872. case Builtin::BI__sync_fetch_and_add_1:
  873. case Builtin::BI__sync_fetch_and_add_2:
  874. case Builtin::BI__sync_fetch_and_add_4:
  875. case Builtin::BI__sync_fetch_and_add_8:
  876. case Builtin::BI__sync_fetch_and_add_16:
  877. case Builtin::BI__sync_fetch_and_sub:
  878. case Builtin::BI__sync_fetch_and_sub_1:
  879. case Builtin::BI__sync_fetch_and_sub_2:
  880. case Builtin::BI__sync_fetch_and_sub_4:
  881. case Builtin::BI__sync_fetch_and_sub_8:
  882. case Builtin::BI__sync_fetch_and_sub_16:
  883. case Builtin::BI__sync_fetch_and_or:
  884. case Builtin::BI__sync_fetch_and_or_1:
  885. case Builtin::BI__sync_fetch_and_or_2:
  886. case Builtin::BI__sync_fetch_and_or_4:
  887. case Builtin::BI__sync_fetch_and_or_8:
  888. case Builtin::BI__sync_fetch_and_or_16:
  889. case Builtin::BI__sync_fetch_and_and:
  890. case Builtin::BI__sync_fetch_and_and_1:
  891. case Builtin::BI__sync_fetch_and_and_2:
  892. case Builtin::BI__sync_fetch_and_and_4:
  893. case Builtin::BI__sync_fetch_and_and_8:
  894. case Builtin::BI__sync_fetch_and_and_16:
  895. case Builtin::BI__sync_fetch_and_xor:
  896. case Builtin::BI__sync_fetch_and_xor_1:
  897. case Builtin::BI__sync_fetch_and_xor_2:
  898. case Builtin::BI__sync_fetch_and_xor_4:
  899. case Builtin::BI__sync_fetch_and_xor_8:
  900. case Builtin::BI__sync_fetch_and_xor_16:
  901. case Builtin::BI__sync_fetch_and_nand:
  902. case Builtin::BI__sync_fetch_and_nand_1:
  903. case Builtin::BI__sync_fetch_and_nand_2:
  904. case Builtin::BI__sync_fetch_and_nand_4:
  905. case Builtin::BI__sync_fetch_and_nand_8:
  906. case Builtin::BI__sync_fetch_and_nand_16:
  907. case Builtin::BI__sync_add_and_fetch:
  908. case Builtin::BI__sync_add_and_fetch_1:
  909. case Builtin::BI__sync_add_and_fetch_2:
  910. case Builtin::BI__sync_add_and_fetch_4:
  911. case Builtin::BI__sync_add_and_fetch_8:
  912. case Builtin::BI__sync_add_and_fetch_16:
  913. case Builtin::BI__sync_sub_and_fetch:
  914. case Builtin::BI__sync_sub_and_fetch_1:
  915. case Builtin::BI__sync_sub_and_fetch_2:
  916. case Builtin::BI__sync_sub_and_fetch_4:
  917. case Builtin::BI__sync_sub_and_fetch_8:
  918. case Builtin::BI__sync_sub_and_fetch_16:
  919. case Builtin::BI__sync_and_and_fetch:
  920. case Builtin::BI__sync_and_and_fetch_1:
  921. case Builtin::BI__sync_and_and_fetch_2:
  922. case Builtin::BI__sync_and_and_fetch_4:
  923. case Builtin::BI__sync_and_and_fetch_8:
  924. case Builtin::BI__sync_and_and_fetch_16:
  925. case Builtin::BI__sync_or_and_fetch:
  926. case Builtin::BI__sync_or_and_fetch_1:
  927. case Builtin::BI__sync_or_and_fetch_2:
  928. case Builtin::BI__sync_or_and_fetch_4:
  929. case Builtin::BI__sync_or_and_fetch_8:
  930. case Builtin::BI__sync_or_and_fetch_16:
  931. case Builtin::BI__sync_xor_and_fetch:
  932. case Builtin::BI__sync_xor_and_fetch_1:
  933. case Builtin::BI__sync_xor_and_fetch_2:
  934. case Builtin::BI__sync_xor_and_fetch_4:
  935. case Builtin::BI__sync_xor_and_fetch_8:
  936. case Builtin::BI__sync_xor_and_fetch_16:
  937. case Builtin::BI__sync_nand_and_fetch:
  938. case Builtin::BI__sync_nand_and_fetch_1:
  939. case Builtin::BI__sync_nand_and_fetch_2:
  940. case Builtin::BI__sync_nand_and_fetch_4:
  941. case Builtin::BI__sync_nand_and_fetch_8:
  942. case Builtin::BI__sync_nand_and_fetch_16:
  943. case Builtin::BI__sync_val_compare_and_swap:
  944. case Builtin::BI__sync_val_compare_and_swap_1:
  945. case Builtin::BI__sync_val_compare_and_swap_2:
  946. case Builtin::BI__sync_val_compare_and_swap_4:
  947. case Builtin::BI__sync_val_compare_and_swap_8:
  948. case Builtin::BI__sync_val_compare_and_swap_16:
  949. case Builtin::BI__sync_bool_compare_and_swap:
  950. case Builtin::BI__sync_bool_compare_and_swap_1:
  951. case Builtin::BI__sync_bool_compare_and_swap_2:
  952. case Builtin::BI__sync_bool_compare_and_swap_4:
  953. case Builtin::BI__sync_bool_compare_and_swap_8:
  954. case Builtin::BI__sync_bool_compare_and_swap_16:
  955. case Builtin::BI__sync_lock_test_and_set:
  956. case Builtin::BI__sync_lock_test_and_set_1:
  957. case Builtin::BI__sync_lock_test_and_set_2:
  958. case Builtin::BI__sync_lock_test_and_set_4:
  959. case Builtin::BI__sync_lock_test_and_set_8:
  960. case Builtin::BI__sync_lock_test_and_set_16:
  961. case Builtin::BI__sync_lock_release:
  962. case Builtin::BI__sync_lock_release_1:
  963. case Builtin::BI__sync_lock_release_2:
  964. case Builtin::BI__sync_lock_release_4:
  965. case Builtin::BI__sync_lock_release_8:
  966. case Builtin::BI__sync_lock_release_16:
  967. case Builtin::BI__sync_swap:
  968. case Builtin::BI__sync_swap_1:
  969. case Builtin::BI__sync_swap_2:
  970. case Builtin::BI__sync_swap_4:
  971. case Builtin::BI__sync_swap_8:
  972. case Builtin::BI__sync_swap_16:
  973. return SemaBuiltinAtomicOverloaded(TheCallResult);
  974. case Builtin::BI__builtin_nontemporal_load:
  975. case Builtin::BI__builtin_nontemporal_store:
  976. return SemaBuiltinNontemporalOverloaded(TheCallResult);
  977. #define BUILTIN(ID, TYPE, ATTRS)
  978. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  979. case Builtin::BI##ID: \
  980. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  981. #include "clang/Basic/Builtins.def"
  982. case Builtin::BI__annotation:
  983. if (SemaBuiltinMSVCAnnotation(*this, TheCall))
  984. return ExprError();
  985. break;
  986. case Builtin::BI__builtin_annotation:
  987. if (SemaBuiltinAnnotation(*this, TheCall))
  988. return ExprError();
  989. break;
  990. case Builtin::BI__builtin_addressof:
  991. if (SemaBuiltinAddressof(*this, TheCall))
  992. return ExprError();
  993. break;
  994. case Builtin::BI__builtin_add_overflow:
  995. case Builtin::BI__builtin_sub_overflow:
  996. case Builtin::BI__builtin_mul_overflow:
  997. if (SemaBuiltinOverflow(*this, TheCall))
  998. return ExprError();
  999. break;
  1000. case Builtin::BI__builtin_operator_new:
  1001. case Builtin::BI__builtin_operator_delete:
  1002. if (!getLangOpts().CPlusPlus) {
  1003. Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
  1004. << (BuiltinID == Builtin::BI__builtin_operator_new
  1005. ? "__builtin_operator_new"
  1006. : "__builtin_operator_delete")
  1007. << "C++";
  1008. return ExprError();
  1009. }
  1010. // CodeGen assumes it can find the global new and delete to call,
  1011. // so ensure that they are declared.
  1012. DeclareGlobalNewDelete();
  1013. break;
  1014. // check secure string manipulation functions where overflows
  1015. // are detectable at compile time
  1016. case Builtin::BI__builtin___memcpy_chk:
  1017. case Builtin::BI__builtin___memmove_chk:
  1018. case Builtin::BI__builtin___memset_chk:
  1019. case Builtin::BI__builtin___strlcat_chk:
  1020. case Builtin::BI__builtin___strlcpy_chk:
  1021. case Builtin::BI__builtin___strncat_chk:
  1022. case Builtin::BI__builtin___strncpy_chk:
  1023. case Builtin::BI__builtin___stpncpy_chk:
  1024. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
  1025. break;
  1026. case Builtin::BI__builtin___memccpy_chk:
  1027. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
  1028. break;
  1029. case Builtin::BI__builtin___snprintf_chk:
  1030. case Builtin::BI__builtin___vsnprintf_chk:
  1031. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
  1032. break;
  1033. case Builtin::BI__builtin_call_with_static_chain:
  1034. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  1035. return ExprError();
  1036. break;
  1037. case Builtin::BI__exception_code:
  1038. case Builtin::BI_exception_code:
  1039. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  1040. diag::err_seh___except_block))
  1041. return ExprError();
  1042. break;
  1043. case Builtin::BI__exception_info:
  1044. case Builtin::BI_exception_info:
  1045. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  1046. diag::err_seh___except_filter))
  1047. return ExprError();
  1048. break;
  1049. case Builtin::BI__GetExceptionInfo:
  1050. if (checkArgCount(*this, TheCall, 1))
  1051. return ExprError();
  1052. if (CheckCXXThrowOperand(
  1053. TheCall->getLocStart(),
  1054. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  1055. TheCall))
  1056. return ExprError();
  1057. TheCall->setType(Context.VoidPtrTy);
  1058. break;
  1059. // OpenCL v2.0, s6.13.16 - Pipe functions
  1060. case Builtin::BIread_pipe:
  1061. case Builtin::BIwrite_pipe:
  1062. // Since those two functions are declared with var args, we need a semantic
  1063. // check for the argument.
  1064. if (SemaBuiltinRWPipe(*this, TheCall))
  1065. return ExprError();
  1066. TheCall->setType(Context.IntTy);
  1067. break;
  1068. case Builtin::BIreserve_read_pipe:
  1069. case Builtin::BIreserve_write_pipe:
  1070. case Builtin::BIwork_group_reserve_read_pipe:
  1071. case Builtin::BIwork_group_reserve_write_pipe:
  1072. if (SemaBuiltinReserveRWPipe(*this, TheCall))
  1073. return ExprError();
  1074. break;
  1075. case Builtin::BIsub_group_reserve_read_pipe:
  1076. case Builtin::BIsub_group_reserve_write_pipe:
  1077. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1078. SemaBuiltinReserveRWPipe(*this, TheCall))
  1079. return ExprError();
  1080. break;
  1081. case Builtin::BIcommit_read_pipe:
  1082. case Builtin::BIcommit_write_pipe:
  1083. case Builtin::BIwork_group_commit_read_pipe:
  1084. case Builtin::BIwork_group_commit_write_pipe:
  1085. if (SemaBuiltinCommitRWPipe(*this, TheCall))
  1086. return ExprError();
  1087. break;
  1088. case Builtin::BIsub_group_commit_read_pipe:
  1089. case Builtin::BIsub_group_commit_write_pipe:
  1090. if (checkOpenCLSubgroupExt(*this, TheCall) ||
  1091. SemaBuiltinCommitRWPipe(*this, TheCall))
  1092. return ExprError();
  1093. break;
  1094. case Builtin::BIget_pipe_num_packets:
  1095. case Builtin::BIget_pipe_max_packets:
  1096. if (SemaBuiltinPipePackets(*this, TheCall))
  1097. return ExprError();
  1098. TheCall->setType(Context.UnsignedIntTy);
  1099. break;
  1100. case Builtin::BIto_global:
  1101. case Builtin::BIto_local:
  1102. case Builtin::BIto_private:
  1103. if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
  1104. return ExprError();
  1105. break;
  1106. // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
  1107. case Builtin::BIenqueue_kernel:
  1108. if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
  1109. return ExprError();
  1110. break;
  1111. case Builtin::BIget_kernel_work_group_size:
  1112. case Builtin::BIget_kernel_preferred_work_group_size_multiple:
  1113. if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
  1114. return ExprError();
  1115. break;
  1116. break;
  1117. case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
  1118. case Builtin::BIget_kernel_sub_group_count_for_ndrange:
  1119. if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
  1120. return ExprError();
  1121. break;
  1122. case Builtin::BI__builtin_os_log_format:
  1123. case Builtin::BI__builtin_os_log_format_buffer_size:
  1124. if (SemaBuiltinOSLogFormat(TheCall))
  1125. return ExprError();
  1126. break;
  1127. }
  1128. // Since the target specific builtins for each arch overlap, only check those
  1129. // of the arch we are compiling for.
  1130. if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
  1131. switch (Context.getTargetInfo().getTriple().getArch()) {
  1132. case llvm::Triple::arm:
  1133. case llvm::Triple::armeb:
  1134. case llvm::Triple::thumb:
  1135. case llvm::Triple::thumbeb:
  1136. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  1137. return ExprError();
  1138. break;
  1139. case llvm::Triple::aarch64:
  1140. case llvm::Triple::aarch64_be:
  1141. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  1142. return ExprError();
  1143. break;
  1144. case llvm::Triple::mips:
  1145. case llvm::Triple::mipsel:
  1146. case llvm::Triple::mips64:
  1147. case llvm::Triple::mips64el:
  1148. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  1149. return ExprError();
  1150. break;
  1151. case llvm::Triple::systemz:
  1152. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  1153. return ExprError();
  1154. break;
  1155. case llvm::Triple::x86:
  1156. case llvm::Triple::x86_64:
  1157. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  1158. return ExprError();
  1159. break;
  1160. case llvm::Triple::ppc:
  1161. case llvm::Triple::ppc64:
  1162. case llvm::Triple::ppc64le:
  1163. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  1164. return ExprError();
  1165. break;
  1166. default:
  1167. break;
  1168. }
  1169. }
  1170. return TheCallResult;
  1171. }
  1172. // Get the valid immediate range for the specified NEON type code.
  1173. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  1174. NeonTypeFlags Type(t);
  1175. int IsQuad = ForceQuad ? true : Type.isQuad();
  1176. switch (Type.getEltType()) {
  1177. case NeonTypeFlags::Int8:
  1178. case NeonTypeFlags::Poly8:
  1179. return shift ? 7 : (8 << IsQuad) - 1;
  1180. case NeonTypeFlags::Int16:
  1181. case NeonTypeFlags::Poly16:
  1182. return shift ? 15 : (4 << IsQuad) - 1;
  1183. case NeonTypeFlags::Int32:
  1184. return shift ? 31 : (2 << IsQuad) - 1;
  1185. case NeonTypeFlags::Int64:
  1186. case NeonTypeFlags::Poly64:
  1187. return shift ? 63 : (1 << IsQuad) - 1;
  1188. case NeonTypeFlags::Poly128:
  1189. return shift ? 127 : (1 << IsQuad) - 1;
  1190. case NeonTypeFlags::Float16:
  1191. assert(!shift && "cannot shift float types!");
  1192. return (4 << IsQuad) - 1;
  1193. case NeonTypeFlags::Float32:
  1194. assert(!shift && "cannot shift float types!");
  1195. return (2 << IsQuad) - 1;
  1196. case NeonTypeFlags::Float64:
  1197. assert(!shift && "cannot shift float types!");
  1198. return (1 << IsQuad) - 1;
  1199. }
  1200. llvm_unreachable("Invalid NeonTypeFlag!");
  1201. }
  1202. /// getNeonEltType - Return the QualType corresponding to the elements of
  1203. /// the vector type specified by the NeonTypeFlags. This is used to check
  1204. /// the pointer arguments for Neon load/store intrinsics.
  1205. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  1206. bool IsPolyUnsigned, bool IsInt64Long) {
  1207. switch (Flags.getEltType()) {
  1208. case NeonTypeFlags::Int8:
  1209. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  1210. case NeonTypeFlags::Int16:
  1211. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  1212. case NeonTypeFlags::Int32:
  1213. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  1214. case NeonTypeFlags::Int64:
  1215. if (IsInt64Long)
  1216. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  1217. else
  1218. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  1219. : Context.LongLongTy;
  1220. case NeonTypeFlags::Poly8:
  1221. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  1222. case NeonTypeFlags::Poly16:
  1223. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  1224. case NeonTypeFlags::Poly64:
  1225. if (IsInt64Long)
  1226. return Context.UnsignedLongTy;
  1227. else
  1228. return Context.UnsignedLongLongTy;
  1229. case NeonTypeFlags::Poly128:
  1230. break;
  1231. case NeonTypeFlags::Float16:
  1232. return Context.HalfTy;
  1233. case NeonTypeFlags::Float32:
  1234. return Context.FloatTy;
  1235. case NeonTypeFlags::Float64:
  1236. return Context.DoubleTy;
  1237. }
  1238. llvm_unreachable("Invalid NeonTypeFlag!");
  1239. }
  1240. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1241. llvm::APSInt Result;
  1242. uint64_t mask = 0;
  1243. unsigned TV = 0;
  1244. int PtrArgNum = -1;
  1245. bool HasConstPtr = false;
  1246. switch (BuiltinID) {
  1247. #define GET_NEON_OVERLOAD_CHECK
  1248. #include "clang/Basic/arm_neon.inc"
  1249. #include "clang/Basic/arm_fp16.inc"
  1250. #undef GET_NEON_OVERLOAD_CHECK
  1251. }
  1252. // For NEON intrinsics which are overloaded on vector element type, validate
  1253. // the immediate which specifies which variant to emit.
  1254. unsigned ImmArg = TheCall->getNumArgs()-1;
  1255. if (mask) {
  1256. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  1257. return true;
  1258. TV = Result.getLimitedValue(64);
  1259. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  1260. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  1261. << TheCall->getArg(ImmArg)->getSourceRange();
  1262. }
  1263. if (PtrArgNum >= 0) {
  1264. // Check that pointer arguments have the specified type.
  1265. Expr *Arg = TheCall->getArg(PtrArgNum);
  1266. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  1267. Arg = ICE->getSubExpr();
  1268. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  1269. QualType RHSTy = RHS.get()->getType();
  1270. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  1271. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
  1272. Arch == llvm::Triple::aarch64_be;
  1273. bool IsInt64Long =
  1274. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  1275. QualType EltTy =
  1276. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  1277. if (HasConstPtr)
  1278. EltTy = EltTy.withConst();
  1279. QualType LHSTy = Context.getPointerType(EltTy);
  1280. AssignConvertType ConvTy;
  1281. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  1282. if (RHS.isInvalid())
  1283. return true;
  1284. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  1285. RHS.get(), AA_Assigning))
  1286. return true;
  1287. }
  1288. // For NEON intrinsics which take an immediate value as part of the
  1289. // instruction, range check them here.
  1290. unsigned i = 0, l = 0, u = 0;
  1291. switch (BuiltinID) {
  1292. default:
  1293. return false;
  1294. #define GET_NEON_IMMEDIATE_CHECK
  1295. #include "clang/Basic/arm_neon.inc"
  1296. #include "clang/Basic/arm_fp16.inc"
  1297. #undef GET_NEON_IMMEDIATE_CHECK
  1298. }
  1299. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1300. }
  1301. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  1302. unsigned MaxWidth) {
  1303. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1304. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1305. BuiltinID == ARM::BI__builtin_arm_strex ||
  1306. BuiltinID == ARM::BI__builtin_arm_stlex ||
  1307. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1308. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1309. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1310. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  1311. "unexpected ARM builtin");
  1312. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1313. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1314. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1315. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  1316. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1317. // Ensure that we have the proper number of arguments.
  1318. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  1319. return true;
  1320. // Inspect the pointer argument of the atomic builtin. This should always be
  1321. // a pointer type, whose element is an integral scalar or pointer type.
  1322. // Because it is a pointer type, we don't have to worry about any implicit
  1323. // casts here.
  1324. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  1325. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  1326. if (PointerArgRes.isInvalid())
  1327. return true;
  1328. PointerArg = PointerArgRes.get();
  1329. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  1330. if (!pointerType) {
  1331. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  1332. << PointerArg->getType() << PointerArg->getSourceRange();
  1333. return true;
  1334. }
  1335. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  1336. // task is to insert the appropriate casts into the AST. First work out just
  1337. // what the appropriate type is.
  1338. QualType ValType = pointerType->getPointeeType();
  1339. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  1340. if (IsLdrex)
  1341. AddrType.addConst();
  1342. // Issue a warning if the cast is dodgy.
  1343. CastKind CastNeeded = CK_NoOp;
  1344. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  1345. CastNeeded = CK_BitCast;
  1346. Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
  1347. << PointerArg->getType()
  1348. << Context.getPointerType(AddrType)
  1349. << AA_Passing << PointerArg->getSourceRange();
  1350. }
  1351. // Finally, do the cast and replace the argument with the corrected version.
  1352. AddrType = Context.getPointerType(AddrType);
  1353. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  1354. if (PointerArgRes.isInvalid())
  1355. return true;
  1356. PointerArg = PointerArgRes.get();
  1357. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  1358. // In general, we allow ints, floats and pointers to be loaded and stored.
  1359. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1360. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  1361. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  1362. << PointerArg->getType() << PointerArg->getSourceRange();
  1363. return true;
  1364. }
  1365. // But ARM doesn't have instructions to deal with 128-bit versions.
  1366. if (Context.getTypeSize(ValType) > MaxWidth) {
  1367. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  1368. Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
  1369. << PointerArg->getType() << PointerArg->getSourceRange();
  1370. return true;
  1371. }
  1372. switch (ValType.getObjCLifetime()) {
  1373. case Qualifiers::OCL_None:
  1374. case Qualifiers::OCL_ExplicitNone:
  1375. // okay
  1376. break;
  1377. case Qualifiers::OCL_Weak:
  1378. case Qualifiers::OCL_Strong:
  1379. case Qualifiers::OCL_Autoreleasing:
  1380. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  1381. << ValType << PointerArg->getSourceRange();
  1382. return true;
  1383. }
  1384. if (IsLdrex) {
  1385. TheCall->setType(ValType);
  1386. return false;
  1387. }
  1388. // Initialize the argument to be stored.
  1389. ExprResult ValArg = TheCall->getArg(0);
  1390. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  1391. Context, ValType, /*consume*/ false);
  1392. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  1393. if (ValArg.isInvalid())
  1394. return true;
  1395. TheCall->setArg(0, ValArg.get());
  1396. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  1397. // but the custom checker bypasses all default analysis.
  1398. TheCall->setType(Context.IntTy);
  1399. return false;
  1400. }
  1401. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1402. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  1403. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  1404. BuiltinID == ARM::BI__builtin_arm_strex ||
  1405. BuiltinID == ARM::BI__builtin_arm_stlex) {
  1406. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  1407. }
  1408. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  1409. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1410. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  1411. }
  1412. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  1413. BuiltinID == ARM::BI__builtin_arm_wsr64)
  1414. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  1415. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  1416. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  1417. BuiltinID == ARM::BI__builtin_arm_wsr ||
  1418. BuiltinID == ARM::BI__builtin_arm_wsrp)
  1419. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1420. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1421. return true;
  1422. // For intrinsics which take an immediate value as part of the instruction,
  1423. // range check them here.
  1424. // FIXME: VFP Intrinsics should error if VFP not present.
  1425. switch (BuiltinID) {
  1426. default: return false;
  1427. case ARM::BI__builtin_arm_ssat:
  1428. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
  1429. case ARM::BI__builtin_arm_usat:
  1430. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
  1431. case ARM::BI__builtin_arm_ssat16:
  1432. return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
  1433. case ARM::BI__builtin_arm_usat16:
  1434. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  1435. case ARM::BI__builtin_arm_vcvtr_f:
  1436. case ARM::BI__builtin_arm_vcvtr_d:
  1437. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
  1438. case ARM::BI__builtin_arm_dmb:
  1439. case ARM::BI__builtin_arm_dsb:
  1440. case ARM::BI__builtin_arm_isb:
  1441. case ARM::BI__builtin_arm_dbg:
  1442. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
  1443. }
  1444. }
  1445. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  1446. CallExpr *TheCall) {
  1447. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  1448. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  1449. BuiltinID == AArch64::BI__builtin_arm_strex ||
  1450. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  1451. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  1452. }
  1453. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  1454. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1455. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  1456. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  1457. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  1458. }
  1459. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  1460. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  1461. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1462. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  1463. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  1464. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  1465. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  1466. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  1467. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  1468. return true;
  1469. // For intrinsics which take an immediate value as part of the instruction,
  1470. // range check them here.
  1471. unsigned i = 0, l = 0, u = 0;
  1472. switch (BuiltinID) {
  1473. default: return false;
  1474. case AArch64::BI__builtin_arm_dmb:
  1475. case AArch64::BI__builtin_arm_dsb:
  1476. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  1477. }
  1478. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  1479. }
  1480. // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
  1481. // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
  1482. // ordering for DSP is unspecified. MSA is ordered by the data format used
  1483. // by the underlying instruction i.e., df/m, df/n and then by size.
  1484. //
  1485. // FIXME: The size tests here should instead be tablegen'd along with the
  1486. // definitions from include/clang/Basic/BuiltinsMips.def.
  1487. // FIXME: GCC is strict on signedness for some of these intrinsics, we should
  1488. // be too.
  1489. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1490. unsigned i = 0, l = 0, u = 0, m = 0;
  1491. switch (BuiltinID) {
  1492. default: return false;
  1493. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  1494. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  1495. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  1496. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  1497. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  1498. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  1499. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  1500. // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
  1501. // df/m field.
  1502. // These intrinsics take an unsigned 3 bit immediate.
  1503. case Mips::BI__builtin_msa_bclri_b:
  1504. case Mips::BI__builtin_msa_bnegi_b:
  1505. case Mips::BI__builtin_msa_bseti_b:
  1506. case Mips::BI__builtin_msa_sat_s_b:
  1507. case Mips::BI__builtin_msa_sat_u_b:
  1508. case Mips::BI__builtin_msa_slli_b:
  1509. case Mips::BI__builtin_msa_srai_b:
  1510. case Mips::BI__builtin_msa_srari_b:
  1511. case Mips::BI__builtin_msa_srli_b:
  1512. case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
  1513. case Mips::BI__builtin_msa_binsli_b:
  1514. case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
  1515. // These intrinsics take an unsigned 4 bit immediate.
  1516. case Mips::BI__builtin_msa_bclri_h:
  1517. case Mips::BI__builtin_msa_bnegi_h:
  1518. case Mips::BI__builtin_msa_bseti_h:
  1519. case Mips::BI__builtin_msa_sat_s_h:
  1520. case Mips::BI__builtin_msa_sat_u_h:
  1521. case Mips::BI__builtin_msa_slli_h:
  1522. case Mips::BI__builtin_msa_srai_h:
  1523. case Mips::BI__builtin_msa_srari_h:
  1524. case Mips::BI__builtin_msa_srli_h:
  1525. case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
  1526. case Mips::BI__builtin_msa_binsli_h:
  1527. case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
  1528. // These intrinsics take an unsigned 5 bit immedate.
  1529. // The first block of intrinsics actually have an unsigned 5 bit field,
  1530. // not a df/n field.
  1531. case Mips::BI__builtin_msa_clei_u_b:
  1532. case Mips::BI__builtin_msa_clei_u_h:
  1533. case Mips::BI__builtin_msa_clei_u_w:
  1534. case Mips::BI__builtin_msa_clei_u_d:
  1535. case Mips::BI__builtin_msa_clti_u_b:
  1536. case Mips::BI__builtin_msa_clti_u_h:
  1537. case Mips::BI__builtin_msa_clti_u_w:
  1538. case Mips::BI__builtin_msa_clti_u_d:
  1539. case Mips::BI__builtin_msa_maxi_u_b:
  1540. case Mips::BI__builtin_msa_maxi_u_h:
  1541. case Mips::BI__builtin_msa_maxi_u_w:
  1542. case Mips::BI__builtin_msa_maxi_u_d:
  1543. case Mips::BI__builtin_msa_mini_u_b:
  1544. case Mips::BI__builtin_msa_mini_u_h:
  1545. case Mips::BI__builtin_msa_mini_u_w:
  1546. case Mips::BI__builtin_msa_mini_u_d:
  1547. case Mips::BI__builtin_msa_addvi_b:
  1548. case Mips::BI__builtin_msa_addvi_h:
  1549. case Mips::BI__builtin_msa_addvi_w:
  1550. case Mips::BI__builtin_msa_addvi_d:
  1551. case Mips::BI__builtin_msa_bclri_w:
  1552. case Mips::BI__builtin_msa_bnegi_w:
  1553. case Mips::BI__builtin_msa_bseti_w:
  1554. case Mips::BI__builtin_msa_sat_s_w:
  1555. case Mips::BI__builtin_msa_sat_u_w:
  1556. case Mips::BI__builtin_msa_slli_w:
  1557. case Mips::BI__builtin_msa_srai_w:
  1558. case Mips::BI__builtin_msa_srari_w:
  1559. case Mips::BI__builtin_msa_srli_w:
  1560. case Mips::BI__builtin_msa_srlri_w:
  1561. case Mips::BI__builtin_msa_subvi_b:
  1562. case Mips::BI__builtin_msa_subvi_h:
  1563. case Mips::BI__builtin_msa_subvi_w:
  1564. case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
  1565. case Mips::BI__builtin_msa_binsli_w:
  1566. case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
  1567. // These intrinsics take an unsigned 6 bit immediate.
  1568. case Mips::BI__builtin_msa_bclri_d:
  1569. case Mips::BI__builtin_msa_bnegi_d:
  1570. case Mips::BI__builtin_msa_bseti_d:
  1571. case Mips::BI__builtin_msa_sat_s_d:
  1572. case Mips::BI__builtin_msa_sat_u_d:
  1573. case Mips::BI__builtin_msa_slli_d:
  1574. case Mips::BI__builtin_msa_srai_d:
  1575. case Mips::BI__builtin_msa_srari_d:
  1576. case Mips::BI__builtin_msa_srli_d:
  1577. case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
  1578. case Mips::BI__builtin_msa_binsli_d:
  1579. case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
  1580. // These intrinsics take a signed 5 bit immediate.
  1581. case Mips::BI__builtin_msa_ceqi_b:
  1582. case Mips::BI__builtin_msa_ceqi_h:
  1583. case Mips::BI__builtin_msa_ceqi_w:
  1584. case Mips::BI__builtin_msa_ceqi_d:
  1585. case Mips::BI__builtin_msa_clti_s_b:
  1586. case Mips::BI__builtin_msa_clti_s_h:
  1587. case Mips::BI__builtin_msa_clti_s_w:
  1588. case Mips::BI__builtin_msa_clti_s_d:
  1589. case Mips::BI__builtin_msa_clei_s_b:
  1590. case Mips::BI__builtin_msa_clei_s_h:
  1591. case Mips::BI__builtin_msa_clei_s_w:
  1592. case Mips::BI__builtin_msa_clei_s_d:
  1593. case Mips::BI__builtin_msa_maxi_s_b:
  1594. case Mips::BI__builtin_msa_maxi_s_h:
  1595. case Mips::BI__builtin_msa_maxi_s_w:
  1596. case Mips::BI__builtin_msa_maxi_s_d:
  1597. case Mips::BI__builtin_msa_mini_s_b:
  1598. case Mips::BI__builtin_msa_mini_s_h:
  1599. case Mips::BI__builtin_msa_mini_s_w:
  1600. case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
  1601. // These intrinsics take an unsigned 8 bit immediate.
  1602. case Mips::BI__builtin_msa_andi_b:
  1603. case Mips::BI__builtin_msa_nori_b:
  1604. case Mips::BI__builtin_msa_ori_b:
  1605. case Mips::BI__builtin_msa_shf_b:
  1606. case Mips::BI__builtin_msa_shf_h:
  1607. case Mips::BI__builtin_msa_shf_w:
  1608. case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
  1609. case Mips::BI__builtin_msa_bseli_b:
  1610. case Mips::BI__builtin_msa_bmnzi_b:
  1611. case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
  1612. // df/n format
  1613. // These intrinsics take an unsigned 4 bit immediate.
  1614. case Mips::BI__builtin_msa_copy_s_b:
  1615. case Mips::BI__builtin_msa_copy_u_b:
  1616. case Mips::BI__builtin_msa_insve_b:
  1617. case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
  1618. case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
  1619. // These intrinsics take an unsigned 3 bit immediate.
  1620. case Mips::BI__builtin_msa_copy_s_h:
  1621. case Mips::BI__builtin_msa_copy_u_h:
  1622. case Mips::BI__builtin_msa_insve_h:
  1623. case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
  1624. case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
  1625. // These intrinsics take an unsigned 2 bit immediate.
  1626. case Mips::BI__builtin_msa_copy_s_w:
  1627. case Mips::BI__builtin_msa_copy_u_w:
  1628. case Mips::BI__builtin_msa_insve_w:
  1629. case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
  1630. case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
  1631. // These intrinsics take an unsigned 1 bit immediate.
  1632. case Mips::BI__builtin_msa_copy_s_d:
  1633. case Mips::BI__builtin_msa_copy_u_d:
  1634. case Mips::BI__builtin_msa_insve_d:
  1635. case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
  1636. case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
  1637. // Memory offsets and immediate loads.
  1638. // These intrinsics take a signed 10 bit immediate.
  1639. case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
  1640. case Mips::BI__builtin_msa_ldi_h:
  1641. case Mips::BI__builtin_msa_ldi_w:
  1642. case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
  1643. case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
  1644. case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
  1645. case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
  1646. case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
  1647. case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
  1648. case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
  1649. case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
  1650. case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
  1651. }
  1652. if (!m)
  1653. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  1654. return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
  1655. SemaBuiltinConstantArgMultiple(TheCall, i, m);
  1656. }
  1657. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  1658. unsigned i = 0, l = 0, u = 0;
  1659. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  1660. BuiltinID == PPC::BI__builtin_divdeu ||
  1661. BuiltinID == PPC::BI__builtin_bpermd;
  1662. bool IsTarget64Bit = Context.getTargetInfo()
  1663. .getTypeWidth(Context
  1664. .getTargetInfo()
  1665. .getIntPtrType()) == 64;
  1666. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  1667. BuiltinID == PPC::BI__builtin_divweu ||
  1668. BuiltinID == PPC::BI__builtin_divde ||
  1669. BuiltinID == PPC::BI__builtin_divdeu;
  1670. if (Is64BitBltin && !IsTarget64Bit)
  1671. return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
  1672. << TheCall->getSourceRange();
  1673. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  1674. (BuiltinID == PPC::BI__builtin_bpermd &&
  1675. !Context.getTargetInfo().hasFeature("bpermd")))
  1676. return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
  1677. << TheCall->getSourceRange();
  1678. switch (BuiltinID) {
  1679. default: return false;
  1680. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  1681. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  1682. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  1683. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  1684. case PPC::BI__builtin_tbegin:
  1685. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  1686. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  1687. case PPC::BI__builtin_tabortwc:
  1688. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  1689. case PPC::BI__builtin_tabortwci:
  1690. case PPC::BI__builtin_tabortdci:
  1691. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  1692. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  1693. case PPC::BI__builtin_vsx_xxpermdi:
  1694. case PPC::BI__builtin_vsx_xxsldwi:
  1695. return SemaBuiltinVSX(TheCall);
  1696. }
  1697. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  1698. }
  1699. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  1700. CallExpr *TheCall) {
  1701. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  1702. Expr *Arg = TheCall->getArg(0);
  1703. llvm::APSInt AbortCode(32);
  1704. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  1705. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  1706. return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
  1707. << Arg->getSourceRange();
  1708. }
  1709. // For intrinsics which take an immediate value as part of the instruction,
  1710. // range check them here.
  1711. unsigned i = 0, l = 0, u = 0;
  1712. switch (BuiltinID) {
  1713. default: return false;
  1714. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  1715. case SystemZ::BI__builtin_s390_verimb:
  1716. case SystemZ::BI__builtin_s390_verimh:
  1717. case SystemZ::BI__builtin_s390_verimf:
  1718. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  1719. case SystemZ::BI__builtin_s390_vfaeb:
  1720. case SystemZ::BI__builtin_s390_vfaeh:
  1721. case SystemZ::BI__builtin_s390_vfaef:
  1722. case SystemZ::BI__builtin_s390_vfaebs:
  1723. case SystemZ::BI__builtin_s390_vfaehs:
  1724. case SystemZ::BI__builtin_s390_vfaefs:
  1725. case SystemZ::BI__builtin_s390_vfaezb:
  1726. case SystemZ::BI__builtin_s390_vfaezh:
  1727. case SystemZ::BI__builtin_s390_vfaezf:
  1728. case SystemZ::BI__builtin_s390_vfaezbs:
  1729. case SystemZ::BI__builtin_s390_vfaezhs:
  1730. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  1731. case SystemZ::BI__builtin_s390_vfisb:
  1732. case SystemZ::BI__builtin_s390_vfidb:
  1733. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  1734. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  1735. case SystemZ::BI__builtin_s390_vftcisb:
  1736. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  1737. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  1738. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  1739. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  1740. case SystemZ::BI__builtin_s390_vstrcb:
  1741. case SystemZ::BI__builtin_s390_vstrch:
  1742. case SystemZ::BI__builtin_s390_vstrcf:
  1743. case SystemZ::BI__builtin_s390_vstrczb:
  1744. case SystemZ::BI__builtin_s390_vstrczh:
  1745. case SystemZ::BI__builtin_s390_vstrczf:
  1746. case SystemZ::BI__builtin_s390_vstrcbs:
  1747. case SystemZ::BI__builtin_s390_vstrchs:
  1748. case SystemZ::BI__builtin_s390_vstrcfs:
  1749. case SystemZ::BI__builtin_s390_vstrczbs:
  1750. case SystemZ::BI__builtin_s390_vstrczhs:
  1751. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  1752. case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
  1753. case SystemZ::BI__builtin_s390_vfminsb:
  1754. case SystemZ::BI__builtin_s390_vfmaxsb:
  1755. case SystemZ::BI__builtin_s390_vfmindb:
  1756. case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
  1757. }
  1758. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  1759. }
  1760. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  1761. /// This checks that the target supports __builtin_cpu_supports and
  1762. /// that the string argument is constant and valid.
  1763. static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
  1764. Expr *Arg = TheCall->getArg(0);
  1765. // Check if the argument is a string literal.
  1766. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  1767. return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  1768. << Arg->getSourceRange();
  1769. // Check the contents of the string.
  1770. StringRef Feature =
  1771. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  1772. if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
  1773. return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
  1774. << Arg->getSourceRange();
  1775. return false;
  1776. }
  1777. /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
  1778. /// This checks that the target supports __builtin_cpu_is and
  1779. /// that the string argument is constant and valid.
  1780. static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
  1781. Expr *Arg = TheCall->getArg(0);
  1782. // Check if the argument is a string literal.
  1783. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  1784. return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  1785. << Arg->getSourceRange();
  1786. // Check the contents of the string.
  1787. StringRef Feature =
  1788. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  1789. if (!S.Context.getTargetInfo().validateCpuIs(Feature))
  1790. return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
  1791. << Arg->getSourceRange();
  1792. return false;
  1793. }
  1794. // Check if the rounding mode is legal.
  1795. bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
  1796. // Indicates if this instruction has rounding control or just SAE.
  1797. bool HasRC = false;
  1798. unsigned ArgNum = 0;
  1799. switch (BuiltinID) {
  1800. default:
  1801. return false;
  1802. case X86::BI__builtin_ia32_vcvttsd2si32:
  1803. case X86::BI__builtin_ia32_vcvttsd2si64:
  1804. case X86::BI__builtin_ia32_vcvttsd2usi32:
  1805. case X86::BI__builtin_ia32_vcvttsd2usi64:
  1806. case X86::BI__builtin_ia32_vcvttss2si32:
  1807. case X86::BI__builtin_ia32_vcvttss2si64:
  1808. case X86::BI__builtin_ia32_vcvttss2usi32:
  1809. case X86::BI__builtin_ia32_vcvttss2usi64:
  1810. ArgNum = 1;
  1811. break;
  1812. case X86::BI__builtin_ia32_cvtps2pd512_mask:
  1813. case X86::BI__builtin_ia32_cvttpd2dq512_mask:
  1814. case X86::BI__builtin_ia32_cvttpd2qq512_mask:
  1815. case X86::BI__builtin_ia32_cvttpd2udq512_mask:
  1816. case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
  1817. case X86::BI__builtin_ia32_cvttps2dq512_mask:
  1818. case X86::BI__builtin_ia32_cvttps2qq512_mask:
  1819. case X86::BI__builtin_ia32_cvttps2udq512_mask:
  1820. case X86::BI__builtin_ia32_cvttps2uqq512_mask:
  1821. case X86::BI__builtin_ia32_exp2pd_mask:
  1822. case X86::BI__builtin_ia32_exp2ps_mask:
  1823. case X86::BI__builtin_ia32_getexppd512_mask:
  1824. case X86::BI__builtin_ia32_getexpps512_mask:
  1825. case X86::BI__builtin_ia32_rcp28pd_mask:
  1826. case X86::BI__builtin_ia32_rcp28ps_mask:
  1827. case X86::BI__builtin_ia32_rsqrt28pd_mask:
  1828. case X86::BI__builtin_ia32_rsqrt28ps_mask:
  1829. case X86::BI__builtin_ia32_vcomisd:
  1830. case X86::BI__builtin_ia32_vcomiss:
  1831. case X86::BI__builtin_ia32_vcvtph2ps512_mask:
  1832. ArgNum = 3;
  1833. break;
  1834. case X86::BI__builtin_ia32_cmppd512_mask:
  1835. case X86::BI__builtin_ia32_cmpps512_mask:
  1836. case X86::BI__builtin_ia32_cmpsd_mask:
  1837. case X86::BI__builtin_ia32_cmpss_mask:
  1838. case X86::BI__builtin_ia32_cvtss2sd_round_mask:
  1839. case X86::BI__builtin_ia32_getexpsd128_round_mask:
  1840. case X86::BI__builtin_ia32_getexpss128_round_mask:
  1841. case X86::BI__builtin_ia32_maxpd512_mask:
  1842. case X86::BI__builtin_ia32_maxps512_mask:
  1843. case X86::BI__builtin_ia32_maxsd_round_mask:
  1844. case X86::BI__builtin_ia32_maxss_round_mask:
  1845. case X86::BI__builtin_ia32_minpd512_mask:
  1846. case X86::BI__builtin_ia32_minps512_mask:
  1847. case X86::BI__builtin_ia32_minsd_round_mask:
  1848. case X86::BI__builtin_ia32_minss_round_mask:
  1849. case X86::BI__builtin_ia32_rcp28sd_round_mask:
  1850. case X86::BI__builtin_ia32_rcp28ss_round_mask:
  1851. case X86::BI__builtin_ia32_reducepd512_mask:
  1852. case X86::BI__builtin_ia32_reduceps512_mask:
  1853. case X86::BI__builtin_ia32_rndscalepd_mask:
  1854. case X86::BI__builtin_ia32_rndscaleps_mask:
  1855. case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
  1856. case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
  1857. ArgNum = 4;
  1858. break;
  1859. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  1860. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  1861. case X86::BI__builtin_ia32_fixupimmps512_mask:
  1862. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  1863. case X86::BI__builtin_ia32_fixupimmsd_mask:
  1864. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  1865. case X86::BI__builtin_ia32_fixupimmss_mask:
  1866. case X86::BI__builtin_ia32_fixupimmss_maskz:
  1867. case X86::BI__builtin_ia32_rangepd512_mask:
  1868. case X86::BI__builtin_ia32_rangeps512_mask:
  1869. case X86::BI__builtin_ia32_rangesd128_round_mask:
  1870. case X86::BI__builtin_ia32_rangess128_round_mask:
  1871. case X86::BI__builtin_ia32_reducesd_mask:
  1872. case X86::BI__builtin_ia32_reducess_mask:
  1873. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  1874. case X86::BI__builtin_ia32_rndscaless_round_mask:
  1875. ArgNum = 5;
  1876. break;
  1877. case X86::BI__builtin_ia32_vcvtsd2si64:
  1878. case X86::BI__builtin_ia32_vcvtsd2si32:
  1879. case X86::BI__builtin_ia32_vcvtsd2usi32:
  1880. case X86::BI__builtin_ia32_vcvtsd2usi64:
  1881. case X86::BI__builtin_ia32_vcvtss2si32:
  1882. case X86::BI__builtin_ia32_vcvtss2si64:
  1883. case X86::BI__builtin_ia32_vcvtss2usi32:
  1884. case X86::BI__builtin_ia32_vcvtss2usi64:
  1885. ArgNum = 1;
  1886. HasRC = true;
  1887. break;
  1888. case X86::BI__builtin_ia32_cvtsi2sd64:
  1889. case X86::BI__builtin_ia32_cvtsi2ss32:
  1890. case X86::BI__builtin_ia32_cvtsi2ss64:
  1891. case X86::BI__builtin_ia32_cvtusi2sd64:
  1892. case X86::BI__builtin_ia32_cvtusi2ss32:
  1893. case X86::BI__builtin_ia32_cvtusi2ss64:
  1894. ArgNum = 2;
  1895. HasRC = true;
  1896. break;
  1897. case X86::BI__builtin_ia32_cvtdq2ps512_mask:
  1898. case X86::BI__builtin_ia32_cvtudq2ps512_mask:
  1899. case X86::BI__builtin_ia32_cvtpd2ps512_mask:
  1900. case X86::BI__builtin_ia32_cvtpd2qq512_mask:
  1901. case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
  1902. case X86::BI__builtin_ia32_cvtps2qq512_mask:
  1903. case X86::BI__builtin_ia32_cvtps2uqq512_mask:
  1904. case X86::BI__builtin_ia32_cvtqq2pd512_mask:
  1905. case X86::BI__builtin_ia32_cvtqq2ps512_mask:
  1906. case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
  1907. case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
  1908. case X86::BI__builtin_ia32_sqrtpd512_mask:
  1909. case X86::BI__builtin_ia32_sqrtps512_mask:
  1910. ArgNum = 3;
  1911. HasRC = true;
  1912. break;
  1913. case X86::BI__builtin_ia32_addpd512_mask:
  1914. case X86::BI__builtin_ia32_addps512_mask:
  1915. case X86::BI__builtin_ia32_divpd512_mask:
  1916. case X86::BI__builtin_ia32_divps512_mask:
  1917. case X86::BI__builtin_ia32_mulpd512_mask:
  1918. case X86::BI__builtin_ia32_mulps512_mask:
  1919. case X86::BI__builtin_ia32_subpd512_mask:
  1920. case X86::BI__builtin_ia32_subps512_mask:
  1921. case X86::BI__builtin_ia32_addss_round_mask:
  1922. case X86::BI__builtin_ia32_addsd_round_mask:
  1923. case X86::BI__builtin_ia32_divss_round_mask:
  1924. case X86::BI__builtin_ia32_divsd_round_mask:
  1925. case X86::BI__builtin_ia32_mulss_round_mask:
  1926. case X86::BI__builtin_ia32_mulsd_round_mask:
  1927. case X86::BI__builtin_ia32_subss_round_mask:
  1928. case X86::BI__builtin_ia32_subsd_round_mask:
  1929. case X86::BI__builtin_ia32_scalefpd512_mask:
  1930. case X86::BI__builtin_ia32_scalefps512_mask:
  1931. case X86::BI__builtin_ia32_scalefsd_round_mask:
  1932. case X86::BI__builtin_ia32_scalefss_round_mask:
  1933. case X86::BI__builtin_ia32_getmantpd512_mask:
  1934. case X86::BI__builtin_ia32_getmantps512_mask:
  1935. case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
  1936. case X86::BI__builtin_ia32_sqrtsd_round_mask:
  1937. case X86::BI__builtin_ia32_sqrtss_round_mask:
  1938. case X86::BI__builtin_ia32_vfmaddpd512_mask:
  1939. case X86::BI__builtin_ia32_vfmaddpd512_mask3:
  1940. case X86::BI__builtin_ia32_vfmaddpd512_maskz:
  1941. case X86::BI__builtin_ia32_vfmaddps512_mask:
  1942. case X86::BI__builtin_ia32_vfmaddps512_mask3:
  1943. case X86::BI__builtin_ia32_vfmaddps512_maskz:
  1944. case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
  1945. case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
  1946. case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
  1947. case X86::BI__builtin_ia32_vfmaddsubps512_mask:
  1948. case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
  1949. case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
  1950. case X86::BI__builtin_ia32_vfmsubpd512_mask3:
  1951. case X86::BI__builtin_ia32_vfmsubps512_mask3:
  1952. case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
  1953. case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
  1954. case X86::BI__builtin_ia32_vfnmaddpd512_mask:
  1955. case X86::BI__builtin_ia32_vfnmaddps512_mask:
  1956. case X86::BI__builtin_ia32_vfnmsubpd512_mask:
  1957. case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
  1958. case X86::BI__builtin_ia32_vfnmsubps512_mask:
  1959. case X86::BI__builtin_ia32_vfnmsubps512_mask3:
  1960. case X86::BI__builtin_ia32_vfmaddsd3_mask:
  1961. case X86::BI__builtin_ia32_vfmaddsd3_maskz:
  1962. case X86::BI__builtin_ia32_vfmaddsd3_mask3:
  1963. case X86::BI__builtin_ia32_vfmaddss3_mask:
  1964. case X86::BI__builtin_ia32_vfmaddss3_maskz:
  1965. case X86::BI__builtin_ia32_vfmaddss3_mask3:
  1966. ArgNum = 4;
  1967. HasRC = true;
  1968. break;
  1969. case X86::BI__builtin_ia32_getmantsd_round_mask:
  1970. case X86::BI__builtin_ia32_getmantss_round_mask:
  1971. ArgNum = 5;
  1972. HasRC = true;
  1973. break;
  1974. }
  1975. llvm::APSInt Result;
  1976. // We can't check the value of a dependent argument.
  1977. Expr *Arg = TheCall->getArg(ArgNum);
  1978. if (Arg->isTypeDependent() || Arg->isValueDependent())
  1979. return false;
  1980. // Check constant-ness first.
  1981. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  1982. return true;
  1983. // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
  1984. // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
  1985. // combined with ROUND_NO_EXC.
  1986. if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
  1987. Result == 8/*ROUND_NO_EXC*/ ||
  1988. (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
  1989. return false;
  1990. return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
  1991. << Arg->getSourceRange();
  1992. }
  1993. // Check if the gather/scatter scale is legal.
  1994. bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
  1995. CallExpr *TheCall) {
  1996. unsigned ArgNum = 0;
  1997. switch (BuiltinID) {
  1998. default:
  1999. return false;
  2000. case X86::BI__builtin_ia32_gatherpfdpd:
  2001. case X86::BI__builtin_ia32_gatherpfdps:
  2002. case X86::BI__builtin_ia32_gatherpfqpd:
  2003. case X86::BI__builtin_ia32_gatherpfqps:
  2004. case X86::BI__builtin_ia32_scatterpfdpd:
  2005. case X86::BI__builtin_ia32_scatterpfdps:
  2006. case X86::BI__builtin_ia32_scatterpfqpd:
  2007. case X86::BI__builtin_ia32_scatterpfqps:
  2008. ArgNum = 3;
  2009. break;
  2010. case X86::BI__builtin_ia32_gatherd_pd:
  2011. case X86::BI__builtin_ia32_gatherd_pd256:
  2012. case X86::BI__builtin_ia32_gatherq_pd:
  2013. case X86::BI__builtin_ia32_gatherq_pd256:
  2014. case X86::BI__builtin_ia32_gatherd_ps:
  2015. case X86::BI__builtin_ia32_gatherd_ps256:
  2016. case X86::BI__builtin_ia32_gatherq_ps:
  2017. case X86::BI__builtin_ia32_gatherq_ps256:
  2018. case X86::BI__builtin_ia32_gatherd_q:
  2019. case X86::BI__builtin_ia32_gatherd_q256:
  2020. case X86::BI__builtin_ia32_gatherq_q:
  2021. case X86::BI__builtin_ia32_gatherq_q256:
  2022. case X86::BI__builtin_ia32_gatherd_d:
  2023. case X86::BI__builtin_ia32_gatherd_d256:
  2024. case X86::BI__builtin_ia32_gatherq_d:
  2025. case X86::BI__builtin_ia32_gatherq_d256:
  2026. case X86::BI__builtin_ia32_gather3div2df:
  2027. case X86::BI__builtin_ia32_gather3div2di:
  2028. case X86::BI__builtin_ia32_gather3div4df:
  2029. case X86::BI__builtin_ia32_gather3div4di:
  2030. case X86::BI__builtin_ia32_gather3div4sf:
  2031. case X86::BI__builtin_ia32_gather3div4si:
  2032. case X86::BI__builtin_ia32_gather3div8sf:
  2033. case X86::BI__builtin_ia32_gather3div8si:
  2034. case X86::BI__builtin_ia32_gather3siv2df:
  2035. case X86::BI__builtin_ia32_gather3siv2di:
  2036. case X86::BI__builtin_ia32_gather3siv4df:
  2037. case X86::BI__builtin_ia32_gather3siv4di:
  2038. case X86::BI__builtin_ia32_gather3siv4sf:
  2039. case X86::BI__builtin_ia32_gather3siv4si:
  2040. case X86::BI__builtin_ia32_gather3siv8sf:
  2041. case X86::BI__builtin_ia32_gather3siv8si:
  2042. case X86::BI__builtin_ia32_gathersiv8df:
  2043. case X86::BI__builtin_ia32_gathersiv16sf:
  2044. case X86::BI__builtin_ia32_gatherdiv8df:
  2045. case X86::BI__builtin_ia32_gatherdiv16sf:
  2046. case X86::BI__builtin_ia32_gathersiv8di:
  2047. case X86::BI__builtin_ia32_gathersiv16si:
  2048. case X86::BI__builtin_ia32_gatherdiv8di:
  2049. case X86::BI__builtin_ia32_gatherdiv16si:
  2050. case X86::BI__builtin_ia32_scatterdiv2df:
  2051. case X86::BI__builtin_ia32_scatterdiv2di:
  2052. case X86::BI__builtin_ia32_scatterdiv4df:
  2053. case X86::BI__builtin_ia32_scatterdiv4di:
  2054. case X86::BI__builtin_ia32_scatterdiv4sf:
  2055. case X86::BI__builtin_ia32_scatterdiv4si:
  2056. case X86::BI__builtin_ia32_scatterdiv8sf:
  2057. case X86::BI__builtin_ia32_scatterdiv8si:
  2058. case X86::BI__builtin_ia32_scattersiv2df:
  2059. case X86::BI__builtin_ia32_scattersiv2di:
  2060. case X86::BI__builtin_ia32_scattersiv4df:
  2061. case X86::BI__builtin_ia32_scattersiv4di:
  2062. case X86::BI__builtin_ia32_scattersiv4sf:
  2063. case X86::BI__builtin_ia32_scattersiv4si:
  2064. case X86::BI__builtin_ia32_scattersiv8sf:
  2065. case X86::BI__builtin_ia32_scattersiv8si:
  2066. case X86::BI__builtin_ia32_scattersiv8df:
  2067. case X86::BI__builtin_ia32_scattersiv16sf:
  2068. case X86::BI__builtin_ia32_scatterdiv8df:
  2069. case X86::BI__builtin_ia32_scatterdiv16sf:
  2070. case X86::BI__builtin_ia32_scattersiv8di:
  2071. case X86::BI__builtin_ia32_scattersiv16si:
  2072. case X86::BI__builtin_ia32_scatterdiv8di:
  2073. case X86::BI__builtin_ia32_scatterdiv16si:
  2074. ArgNum = 4;
  2075. break;
  2076. }
  2077. llvm::APSInt Result;
  2078. // We can't check the value of a dependent argument.
  2079. Expr *Arg = TheCall->getArg(ArgNum);
  2080. if (Arg->isTypeDependent() || Arg->isValueDependent())
  2081. return false;
  2082. // Check constant-ness first.
  2083. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  2084. return true;
  2085. if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
  2086. return false;
  2087. return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
  2088. << Arg->getSourceRange();
  2089. }
  2090. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  2091. if (BuiltinID == X86::BI__builtin_cpu_supports)
  2092. return SemaBuiltinCpuSupports(*this, TheCall);
  2093. if (BuiltinID == X86::BI__builtin_cpu_is)
  2094. return SemaBuiltinCpuIs(*this, TheCall);
  2095. // If the intrinsic has rounding or SAE make sure its valid.
  2096. if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
  2097. return true;
  2098. // If the intrinsic has a gather/scatter scale immediate make sure its valid.
  2099. if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
  2100. return true;
  2101. // For intrinsics which take an immediate value as part of the instruction,
  2102. // range check them here.
  2103. int i = 0, l = 0, u = 0;
  2104. switch (BuiltinID) {
  2105. default:
  2106. return false;
  2107. case X86::BI_mm_prefetch:
  2108. i = 1; l = 0; u = 7;
  2109. break;
  2110. case X86::BI__builtin_ia32_sha1rnds4:
  2111. case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
  2112. case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
  2113. case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
  2114. case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
  2115. i = 2; l = 0; u = 3;
  2116. break;
  2117. case X86::BI__builtin_ia32_vpermil2pd:
  2118. case X86::BI__builtin_ia32_vpermil2pd256:
  2119. case X86::BI__builtin_ia32_vpermil2ps:
  2120. case X86::BI__builtin_ia32_vpermil2ps256:
  2121. i = 3; l = 0; u = 3;
  2122. break;
  2123. case X86::BI__builtin_ia32_cmpb128_mask:
  2124. case X86::BI__builtin_ia32_cmpw128_mask:
  2125. case X86::BI__builtin_ia32_cmpd128_mask:
  2126. case X86::BI__builtin_ia32_cmpq128_mask:
  2127. case X86::BI__builtin_ia32_cmpb256_mask:
  2128. case X86::BI__builtin_ia32_cmpw256_mask:
  2129. case X86::BI__builtin_ia32_cmpd256_mask:
  2130. case X86::BI__builtin_ia32_cmpq256_mask:
  2131. case X86::BI__builtin_ia32_cmpb512_mask:
  2132. case X86::BI__builtin_ia32_cmpw512_mask:
  2133. case X86::BI__builtin_ia32_cmpd512_mask:
  2134. case X86::BI__builtin_ia32_cmpq512_mask:
  2135. case X86::BI__builtin_ia32_ucmpb128_mask:
  2136. case X86::BI__builtin_ia32_ucmpw128_mask:
  2137. case X86::BI__builtin_ia32_ucmpd128_mask:
  2138. case X86::BI__builtin_ia32_ucmpq128_mask:
  2139. case X86::BI__builtin_ia32_ucmpb256_mask:
  2140. case X86::BI__builtin_ia32_ucmpw256_mask:
  2141. case X86::BI__builtin_ia32_ucmpd256_mask:
  2142. case X86::BI__builtin_ia32_ucmpq256_mask:
  2143. case X86::BI__builtin_ia32_ucmpb512_mask:
  2144. case X86::BI__builtin_ia32_ucmpw512_mask:
  2145. case X86::BI__builtin_ia32_ucmpd512_mask:
  2146. case X86::BI__builtin_ia32_ucmpq512_mask:
  2147. case X86::BI__builtin_ia32_vpcomub:
  2148. case X86::BI__builtin_ia32_vpcomuw:
  2149. case X86::BI__builtin_ia32_vpcomud:
  2150. case X86::BI__builtin_ia32_vpcomuq:
  2151. case X86::BI__builtin_ia32_vpcomb:
  2152. case X86::BI__builtin_ia32_vpcomw:
  2153. case X86::BI__builtin_ia32_vpcomd:
  2154. case X86::BI__builtin_ia32_vpcomq:
  2155. i = 2; l = 0; u = 7;
  2156. break;
  2157. case X86::BI__builtin_ia32_roundps:
  2158. case X86::BI__builtin_ia32_roundpd:
  2159. case X86::BI__builtin_ia32_roundps256:
  2160. case X86::BI__builtin_ia32_roundpd256:
  2161. i = 1; l = 0; u = 15;
  2162. break;
  2163. case X86::BI__builtin_ia32_roundss:
  2164. case X86::BI__builtin_ia32_roundsd:
  2165. case X86::BI__builtin_ia32_rangepd128_mask:
  2166. case X86::BI__builtin_ia32_rangepd256_mask:
  2167. case X86::BI__builtin_ia32_rangepd512_mask:
  2168. case X86::BI__builtin_ia32_rangeps128_mask:
  2169. case X86::BI__builtin_ia32_rangeps256_mask:
  2170. case X86::BI__builtin_ia32_rangeps512_mask:
  2171. case X86::BI__builtin_ia32_getmantsd_round_mask:
  2172. case X86::BI__builtin_ia32_getmantss_round_mask:
  2173. i = 2; l = 0; u = 15;
  2174. break;
  2175. case X86::BI__builtin_ia32_cmpps:
  2176. case X86::BI__builtin_ia32_cmpss:
  2177. case X86::BI__builtin_ia32_cmppd:
  2178. case X86::BI__builtin_ia32_cmpsd:
  2179. case X86::BI__builtin_ia32_cmpps256:
  2180. case X86::BI__builtin_ia32_cmppd256:
  2181. case X86::BI__builtin_ia32_cmpps128_mask:
  2182. case X86::BI__builtin_ia32_cmppd128_mask:
  2183. case X86::BI__builtin_ia32_cmpps256_mask:
  2184. case X86::BI__builtin_ia32_cmppd256_mask:
  2185. case X86::BI__builtin_ia32_cmpps512_mask:
  2186. case X86::BI__builtin_ia32_cmppd512_mask:
  2187. case X86::BI__builtin_ia32_cmpsd_mask:
  2188. case X86::BI__builtin_ia32_cmpss_mask:
  2189. i = 2; l = 0; u = 31;
  2190. break;
  2191. case X86::BI__builtin_ia32_vcvtps2ph:
  2192. case X86::BI__builtin_ia32_vcvtps2ph_mask:
  2193. case X86::BI__builtin_ia32_vcvtps2ph256:
  2194. case X86::BI__builtin_ia32_vcvtps2ph256_mask:
  2195. case X86::BI__builtin_ia32_vcvtps2ph512_mask:
  2196. case X86::BI__builtin_ia32_rndscaleps_128_mask:
  2197. case X86::BI__builtin_ia32_rndscalepd_128_mask:
  2198. case X86::BI__builtin_ia32_rndscaleps_256_mask:
  2199. case X86::BI__builtin_ia32_rndscalepd_256_mask:
  2200. case X86::BI__builtin_ia32_rndscaleps_mask:
  2201. case X86::BI__builtin_ia32_rndscalepd_mask:
  2202. case X86::BI__builtin_ia32_reducepd128_mask:
  2203. case X86::BI__builtin_ia32_reducepd256_mask:
  2204. case X86::BI__builtin_ia32_reducepd512_mask:
  2205. case X86::BI__builtin_ia32_reduceps128_mask:
  2206. case X86::BI__builtin_ia32_reduceps256_mask:
  2207. case X86::BI__builtin_ia32_reduceps512_mask:
  2208. case X86::BI__builtin_ia32_prold512_mask:
  2209. case X86::BI__builtin_ia32_prolq512_mask:
  2210. case X86::BI__builtin_ia32_prold128_mask:
  2211. case X86::BI__builtin_ia32_prold256_mask:
  2212. case X86::BI__builtin_ia32_prolq128_mask:
  2213. case X86::BI__builtin_ia32_prolq256_mask:
  2214. case X86::BI__builtin_ia32_prord128_mask:
  2215. case X86::BI__builtin_ia32_prord256_mask:
  2216. case X86::BI__builtin_ia32_prorq128_mask:
  2217. case X86::BI__builtin_ia32_prorq256_mask:
  2218. case X86::BI__builtin_ia32_fpclasspd128_mask:
  2219. case X86::BI__builtin_ia32_fpclasspd256_mask:
  2220. case X86::BI__builtin_ia32_fpclassps128_mask:
  2221. case X86::BI__builtin_ia32_fpclassps256_mask:
  2222. case X86::BI__builtin_ia32_fpclassps512_mask:
  2223. case X86::BI__builtin_ia32_fpclasspd512_mask:
  2224. case X86::BI__builtin_ia32_fpclasssd_mask:
  2225. case X86::BI__builtin_ia32_fpclassss_mask:
  2226. i = 1; l = 0; u = 255;
  2227. break;
  2228. case X86::BI__builtin_ia32_palignr128:
  2229. case X86::BI__builtin_ia32_palignr256:
  2230. case X86::BI__builtin_ia32_palignr512_mask:
  2231. case X86::BI__builtin_ia32_vcomisd:
  2232. case X86::BI__builtin_ia32_vcomiss:
  2233. case X86::BI__builtin_ia32_shuf_f32x4_mask:
  2234. case X86::BI__builtin_ia32_shuf_f64x2_mask:
  2235. case X86::BI__builtin_ia32_shuf_i32x4_mask:
  2236. case X86::BI__builtin_ia32_shuf_i64x2_mask:
  2237. case X86::BI__builtin_ia32_dbpsadbw128_mask:
  2238. case X86::BI__builtin_ia32_dbpsadbw256_mask:
  2239. case X86::BI__builtin_ia32_dbpsadbw512_mask:
  2240. case X86::BI__builtin_ia32_vpshldd128_mask:
  2241. case X86::BI__builtin_ia32_vpshldd256_mask:
  2242. case X86::BI__builtin_ia32_vpshldd512_mask:
  2243. case X86::BI__builtin_ia32_vpshldq128_mask:
  2244. case X86::BI__builtin_ia32_vpshldq256_mask:
  2245. case X86::BI__builtin_ia32_vpshldq512_mask:
  2246. case X86::BI__builtin_ia32_vpshldw128_mask:
  2247. case X86::BI__builtin_ia32_vpshldw256_mask:
  2248. case X86::BI__builtin_ia32_vpshldw512_mask:
  2249. case X86::BI__builtin_ia32_vpshrdd128_mask:
  2250. case X86::BI__builtin_ia32_vpshrdd256_mask:
  2251. case X86::BI__builtin_ia32_vpshrdd512_mask:
  2252. case X86::BI__builtin_ia32_vpshrdq128_mask:
  2253. case X86::BI__builtin_ia32_vpshrdq256_mask:
  2254. case X86::BI__builtin_ia32_vpshrdq512_mask:
  2255. case X86::BI__builtin_ia32_vpshrdw128_mask:
  2256. case X86::BI__builtin_ia32_vpshrdw256_mask:
  2257. case X86::BI__builtin_ia32_vpshrdw512_mask:
  2258. i = 2; l = 0; u = 255;
  2259. break;
  2260. case X86::BI__builtin_ia32_fixupimmpd512_mask:
  2261. case X86::BI__builtin_ia32_fixupimmpd512_maskz:
  2262. case X86::BI__builtin_ia32_fixupimmps512_mask:
  2263. case X86::BI__builtin_ia32_fixupimmps512_maskz:
  2264. case X86::BI__builtin_ia32_fixupimmsd_mask:
  2265. case X86::BI__builtin_ia32_fixupimmsd_maskz:
  2266. case X86::BI__builtin_ia32_fixupimmss_mask:
  2267. case X86::BI__builtin_ia32_fixupimmss_maskz:
  2268. case X86::BI__builtin_ia32_fixupimmpd128_mask:
  2269. case X86::BI__builtin_ia32_fixupimmpd128_maskz:
  2270. case X86::BI__builtin_ia32_fixupimmpd256_mask:
  2271. case X86::BI__builtin_ia32_fixupimmpd256_maskz:
  2272. case X86::BI__builtin_ia32_fixupimmps128_mask:
  2273. case X86::BI__builtin_ia32_fixupimmps128_maskz:
  2274. case X86::BI__builtin_ia32_fixupimmps256_mask:
  2275. case X86::BI__builtin_ia32_fixupimmps256_maskz:
  2276. case X86::BI__builtin_ia32_pternlogd512_mask:
  2277. case X86::BI__builtin_ia32_pternlogd512_maskz:
  2278. case X86::BI__builtin_ia32_pternlogq512_mask:
  2279. case X86::BI__builtin_ia32_pternlogq512_maskz:
  2280. case X86::BI__builtin_ia32_pternlogd128_mask:
  2281. case X86::BI__builtin_ia32_pternlogd128_maskz:
  2282. case X86::BI__builtin_ia32_pternlogd256_mask:
  2283. case X86::BI__builtin_ia32_pternlogd256_maskz:
  2284. case X86::BI__builtin_ia32_pternlogq128_mask:
  2285. case X86::BI__builtin_ia32_pternlogq128_maskz:
  2286. case X86::BI__builtin_ia32_pternlogq256_mask:
  2287. case X86::BI__builtin_ia32_pternlogq256_maskz:
  2288. i = 3; l = 0; u = 255;
  2289. break;
  2290. case X86::BI__builtin_ia32_gatherpfdpd:
  2291. case X86::BI__builtin_ia32_gatherpfdps:
  2292. case X86::BI__builtin_ia32_gatherpfqpd:
  2293. case X86::BI__builtin_ia32_gatherpfqps:
  2294. case X86::BI__builtin_ia32_scatterpfdpd:
  2295. case X86::BI__builtin_ia32_scatterpfdps:
  2296. case X86::BI__builtin_ia32_scatterpfqpd:
  2297. case X86::BI__builtin_ia32_scatterpfqps:
  2298. i = 4; l = 2; u = 3;
  2299. break;
  2300. case X86::BI__builtin_ia32_rndscalesd_round_mask:
  2301. case X86::BI__builtin_ia32_rndscaless_round_mask:
  2302. i = 4; l = 0; u = 255;
  2303. break;
  2304. }
  2305. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  2306. }
  2307. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  2308. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  2309. /// Returns true when the format fits the function and the FormatStringInfo has
  2310. /// been populated.
  2311. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  2312. FormatStringInfo *FSI) {
  2313. FSI->HasVAListArg = Format->getFirstArg() == 0;
  2314. FSI->FormatIdx = Format->getFormatIdx() - 1;
  2315. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  2316. // The way the format attribute works in GCC, the implicit this argument
  2317. // of member functions is counted. However, it doesn't appear in our own
  2318. // lists, so decrement format_idx in that case.
  2319. if (IsCXXMember) {
  2320. if(FSI->FormatIdx == 0)
  2321. return false;
  2322. --FSI->FormatIdx;
  2323. if (FSI->FirstDataArg != 0)
  2324. --FSI->FirstDataArg;
  2325. }
  2326. return true;
  2327. }
  2328. /// Checks if a the given expression evaluates to null.
  2329. ///
  2330. /// \brief Returns true if the value evaluates to null.
  2331. static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
  2332. // If the expression has non-null type, it doesn't evaluate to null.
  2333. if (auto nullability
  2334. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  2335. if (*nullability == NullabilityKind::NonNull)
  2336. return false;
  2337. }
  2338. // As a special case, transparent unions initialized with zero are
  2339. // considered null for the purposes of the nonnull attribute.
  2340. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  2341. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  2342. if (const CompoundLiteralExpr *CLE =
  2343. dyn_cast<CompoundLiteralExpr>(Expr))
  2344. if (const InitListExpr *ILE =
  2345. dyn_cast<InitListExpr>(CLE->getInitializer()))
  2346. Expr = ILE->getInit(0);
  2347. }
  2348. bool Result;
  2349. return (!Expr->isValueDependent() &&
  2350. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  2351. !Result);
  2352. }
  2353. static void CheckNonNullArgument(Sema &S,
  2354. const Expr *ArgExpr,
  2355. SourceLocation CallSiteLoc) {
  2356. if (CheckNonNullExpr(S, ArgExpr))
  2357. S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
  2358. S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
  2359. }
  2360. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  2361. FormatStringInfo FSI;
  2362. if ((GetFormatStringType(Format) == FST_NSString) &&
  2363. getFormatStringInfo(Format, false, &FSI)) {
  2364. Idx = FSI.FormatIdx;
  2365. return true;
  2366. }
  2367. return false;
  2368. }
  2369. /// \brief Diagnose use of %s directive in an NSString which is being passed
  2370. /// as formatting string to formatting method.
  2371. static void
  2372. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  2373. const NamedDecl *FDecl,
  2374. Expr **Args,
  2375. unsigned NumArgs) {
  2376. unsigned Idx = 0;
  2377. bool Format = false;
  2378. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  2379. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  2380. Idx = 2;
  2381. Format = true;
  2382. }
  2383. else
  2384. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  2385. if (S.GetFormatNSStringIdx(I, Idx)) {
  2386. Format = true;
  2387. break;
  2388. }
  2389. }
  2390. if (!Format || NumArgs <= Idx)
  2391. return;
  2392. const Expr *FormatExpr = Args[Idx];
  2393. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  2394. FormatExpr = CSCE->getSubExpr();
  2395. const StringLiteral *FormatString;
  2396. if (const ObjCStringLiteral *OSL =
  2397. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  2398. FormatString = OSL->getString();
  2399. else
  2400. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  2401. if (!FormatString)
  2402. return;
  2403. if (S.FormatStringHasSArg(FormatString)) {
  2404. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  2405. << "%s" << 1 << 1;
  2406. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  2407. << FDecl->getDeclName();
  2408. }
  2409. }
  2410. /// Determine whether the given type has a non-null nullability annotation.
  2411. static bool isNonNullType(ASTContext &ctx, QualType type) {
  2412. if (auto nullability = type->getNullability(ctx))
  2413. return *nullability == NullabilityKind::NonNull;
  2414. return false;
  2415. }
  2416. static void CheckNonNullArguments(Sema &S,
  2417. const NamedDecl *FDecl,
  2418. const FunctionProtoType *Proto,
  2419. ArrayRef<const Expr *> Args,
  2420. SourceLocation CallSiteLoc) {
  2421. assert((FDecl || Proto) && "Need a function declaration or prototype");
  2422. // Check the attributes attached to the method/function itself.
  2423. llvm::SmallBitVector NonNullArgs;
  2424. if (FDecl) {
  2425. // Handle the nonnull attribute on the function/method declaration itself.
  2426. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  2427. if (!NonNull->args_size()) {
  2428. // Easy case: all pointer arguments are nonnull.
  2429. for (const auto *Arg : Args)
  2430. if (S.isValidPointerAttrType(Arg->getType()))
  2431. CheckNonNullArgument(S, Arg, CallSiteLoc);
  2432. return;
  2433. }
  2434. for (unsigned Val : NonNull->args()) {
  2435. if (Val >= Args.size())
  2436. continue;
  2437. if (NonNullArgs.empty())
  2438. NonNullArgs.resize(Args.size());
  2439. NonNullArgs.set(Val);
  2440. }
  2441. }
  2442. }
  2443. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  2444. // Handle the nonnull attribute on the parameters of the
  2445. // function/method.
  2446. ArrayRef<ParmVarDecl*> parms;
  2447. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  2448. parms = FD->parameters();
  2449. else
  2450. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  2451. unsigned ParamIndex = 0;
  2452. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  2453. I != E; ++I, ++ParamIndex) {
  2454. const ParmVarDecl *PVD = *I;
  2455. if (PVD->hasAttr<NonNullAttr>() ||
  2456. isNonNullType(S.Context, PVD->getType())) {
  2457. if (NonNullArgs.empty())
  2458. NonNullArgs.resize(Args.size());
  2459. NonNullArgs.set(ParamIndex);
  2460. }
  2461. }
  2462. } else {
  2463. // If we have a non-function, non-method declaration but no
  2464. // function prototype, try to dig out the function prototype.
  2465. if (!Proto) {
  2466. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  2467. QualType type = VD->getType().getNonReferenceType();
  2468. if (auto pointerType = type->getAs<PointerType>())
  2469. type = pointerType->getPointeeType();
  2470. else if (auto blockType = type->getAs<BlockPointerType>())
  2471. type = blockType->getPointeeType();
  2472. // FIXME: data member pointers?
  2473. // Dig out the function prototype, if there is one.
  2474. Proto = type->getAs<FunctionProtoType>();
  2475. }
  2476. }
  2477. // Fill in non-null argument information from the nullability
  2478. // information on the parameter types (if we have them).
  2479. if (Proto) {
  2480. unsigned Index = 0;
  2481. for (auto paramType : Proto->getParamTypes()) {
  2482. if (isNonNullType(S.Context, paramType)) {
  2483. if (NonNullArgs.empty())
  2484. NonNullArgs.resize(Args.size());
  2485. NonNullArgs.set(Index);
  2486. }
  2487. ++Index;
  2488. }
  2489. }
  2490. }
  2491. // Check for non-null arguments.
  2492. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  2493. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  2494. if (NonNullArgs[ArgIndex])
  2495. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  2496. }
  2497. }
  2498. /// Handles the checks for format strings, non-POD arguments to vararg
  2499. /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
  2500. /// attributes.
  2501. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  2502. const Expr *ThisArg, ArrayRef<const Expr *> Args,
  2503. bool IsMemberFunction, SourceLocation Loc,
  2504. SourceRange Range, VariadicCallType CallType) {
  2505. // FIXME: We should check as much as we can in the template definition.
  2506. if (CurContext->isDependentContext())
  2507. return;
  2508. // Printf and scanf checking.
  2509. llvm::SmallBitVector CheckedVarArgs;
  2510. if (FDecl) {
  2511. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  2512. // Only create vector if there are format attributes.
  2513. CheckedVarArgs.resize(Args.size());
  2514. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  2515. CheckedVarArgs);
  2516. }
  2517. }
  2518. // Refuse POD arguments that weren't caught by the format string
  2519. // checks above.
  2520. auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
  2521. if (CallType != VariadicDoesNotApply &&
  2522. (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
  2523. unsigned NumParams = Proto ? Proto->getNumParams()
  2524. : FDecl && isa<FunctionDecl>(FDecl)
  2525. ? cast<FunctionDecl>(FDecl)->getNumParams()
  2526. : FDecl && isa<ObjCMethodDecl>(FDecl)
  2527. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  2528. : 0;
  2529. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  2530. // Args[ArgIdx] can be null in malformed code.
  2531. if (const Expr *Arg = Args[ArgIdx]) {
  2532. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  2533. checkVariadicArgument(Arg, CallType);
  2534. }
  2535. }
  2536. }
  2537. if (FDecl || Proto) {
  2538. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  2539. // Type safety checking.
  2540. if (FDecl) {
  2541. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  2542. CheckArgumentWithTypeTag(I, Args, Loc);
  2543. }
  2544. }
  2545. if (FD)
  2546. diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
  2547. }
  2548. /// CheckConstructorCall - Check a constructor call for correctness and safety
  2549. /// properties not enforced by the C type system.
  2550. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  2551. ArrayRef<const Expr *> Args,
  2552. const FunctionProtoType *Proto,
  2553. SourceLocation Loc) {
  2554. VariadicCallType CallType =
  2555. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  2556. checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
  2557. Loc, SourceRange(), CallType);
  2558. }
  2559. /// CheckFunctionCall - Check a direct function call for various correctness
  2560. /// and safety properties not strictly enforced by the C type system.
  2561. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  2562. const FunctionProtoType *Proto) {
  2563. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  2564. isa<CXXMethodDecl>(FDecl);
  2565. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  2566. IsMemberOperatorCall;
  2567. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  2568. TheCall->getCallee());
  2569. Expr** Args = TheCall->getArgs();
  2570. unsigned NumArgs = TheCall->getNumArgs();
  2571. Expr *ImplicitThis = nullptr;
  2572. if (IsMemberOperatorCall) {
  2573. // If this is a call to a member operator, hide the first argument
  2574. // from checkCall.
  2575. // FIXME: Our choice of AST representation here is less than ideal.
  2576. ImplicitThis = Args[0];
  2577. ++Args;
  2578. --NumArgs;
  2579. } else if (IsMemberFunction)
  2580. ImplicitThis =
  2581. cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
  2582. checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
  2583. IsMemberFunction, TheCall->getRParenLoc(),
  2584. TheCall->getCallee()->getSourceRange(), CallType);
  2585. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  2586. // None of the checks below are needed for functions that don't have
  2587. // simple names (e.g., C++ conversion functions).
  2588. if (!FnInfo)
  2589. return false;
  2590. CheckAbsoluteValueFunction(TheCall, FDecl);
  2591. CheckMaxUnsignedZero(TheCall, FDecl);
  2592. if (getLangOpts().ObjC1)
  2593. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  2594. unsigned CMId = FDecl->getMemoryFunctionKind();
  2595. if (CMId == 0)
  2596. return false;
  2597. // Handle memory setting and copying functions.
  2598. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  2599. CheckStrlcpycatArguments(TheCall, FnInfo);
  2600. else if (CMId == Builtin::BIstrncat)
  2601. CheckStrncatArguments(TheCall, FnInfo);
  2602. else
  2603. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  2604. return false;
  2605. }
  2606. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  2607. ArrayRef<const Expr *> Args) {
  2608. VariadicCallType CallType =
  2609. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  2610. checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
  2611. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  2612. CallType);
  2613. return false;
  2614. }
  2615. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  2616. const FunctionProtoType *Proto) {
  2617. QualType Ty;
  2618. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  2619. Ty = V->getType().getNonReferenceType();
  2620. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  2621. Ty = F->getType().getNonReferenceType();
  2622. else
  2623. return false;
  2624. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  2625. !Ty->isFunctionProtoType())
  2626. return false;
  2627. VariadicCallType CallType;
  2628. if (!Proto || !Proto->isVariadic()) {
  2629. CallType = VariadicDoesNotApply;
  2630. } else if (Ty->isBlockPointerType()) {
  2631. CallType = VariadicBlock;
  2632. } else { // Ty->isFunctionPointerType()
  2633. CallType = VariadicFunction;
  2634. }
  2635. checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
  2636. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  2637. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  2638. TheCall->getCallee()->getSourceRange(), CallType);
  2639. return false;
  2640. }
  2641. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  2642. /// such as function pointers returned from functions.
  2643. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  2644. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  2645. TheCall->getCallee());
  2646. checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
  2647. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  2648. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  2649. TheCall->getCallee()->getSourceRange(), CallType);
  2650. return false;
  2651. }
  2652. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  2653. if (!llvm::isValidAtomicOrderingCABI(Ordering))
  2654. return false;
  2655. auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
  2656. switch (Op) {
  2657. case AtomicExpr::AO__c11_atomic_init:
  2658. case AtomicExpr::AO__opencl_atomic_init:
  2659. llvm_unreachable("There is no ordering argument for an init");
  2660. case AtomicExpr::AO__c11_atomic_load:
  2661. case AtomicExpr::AO__opencl_atomic_load:
  2662. case AtomicExpr::AO__atomic_load_n:
  2663. case AtomicExpr::AO__atomic_load:
  2664. return OrderingCABI != llvm::AtomicOrderingCABI::release &&
  2665. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  2666. case AtomicExpr::AO__c11_atomic_store:
  2667. case AtomicExpr::AO__opencl_atomic_store:
  2668. case AtomicExpr::AO__atomic_store:
  2669. case AtomicExpr::AO__atomic_store_n:
  2670. return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
  2671. OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
  2672. OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
  2673. default:
  2674. return true;
  2675. }
  2676. }
  2677. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  2678. AtomicExpr::AtomicOp Op) {
  2679. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  2680. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  2681. // All the non-OpenCL operations take one of the following forms.
  2682. // The OpenCL operations take the __c11 forms with one extra argument for
  2683. // synchronization scope.
  2684. enum {
  2685. // C __c11_atomic_init(A *, C)
  2686. Init,
  2687. // C __c11_atomic_load(A *, int)
  2688. Load,
  2689. // void __atomic_load(A *, CP, int)
  2690. LoadCopy,
  2691. // void __atomic_store(A *, CP, int)
  2692. Copy,
  2693. // C __c11_atomic_add(A *, M, int)
  2694. Arithmetic,
  2695. // C __atomic_exchange_n(A *, CP, int)
  2696. Xchg,
  2697. // void __atomic_exchange(A *, C *, CP, int)
  2698. GNUXchg,
  2699. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  2700. C11CmpXchg,
  2701. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  2702. GNUCmpXchg
  2703. } Form = Init;
  2704. const unsigned NumForm = GNUCmpXchg + 1;
  2705. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
  2706. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
  2707. // where:
  2708. // C is an appropriate type,
  2709. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  2710. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  2711. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  2712. // the int parameters are for orderings.
  2713. static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
  2714. && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
  2715. "need to update code for modified forms");
  2716. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  2717. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  2718. AtomicExpr::AO__atomic_load,
  2719. "need to update code for modified C11 atomics");
  2720. bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
  2721. Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
  2722. bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
  2723. Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
  2724. IsOpenCL;
  2725. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  2726. Op == AtomicExpr::AO__atomic_store_n ||
  2727. Op == AtomicExpr::AO__atomic_exchange_n ||
  2728. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  2729. bool IsAddSub = false;
  2730. switch (Op) {
  2731. case AtomicExpr::AO__c11_atomic_init:
  2732. case AtomicExpr::AO__opencl_atomic_init:
  2733. Form = Init;
  2734. break;
  2735. case AtomicExpr::AO__c11_atomic_load:
  2736. case AtomicExpr::AO__opencl_atomic_load:
  2737. case AtomicExpr::AO__atomic_load_n:
  2738. Form = Load;
  2739. break;
  2740. case AtomicExpr::AO__atomic_load:
  2741. Form = LoadCopy;
  2742. break;
  2743. case AtomicExpr::AO__c11_atomic_store:
  2744. case AtomicExpr::AO__opencl_atomic_store:
  2745. case AtomicExpr::AO__atomic_store:
  2746. case AtomicExpr::AO__atomic_store_n:
  2747. Form = Copy;
  2748. break;
  2749. case AtomicExpr::AO__c11_atomic_fetch_add:
  2750. case AtomicExpr::AO__c11_atomic_fetch_sub:
  2751. case AtomicExpr::AO__opencl_atomic_fetch_add:
  2752. case AtomicExpr::AO__opencl_atomic_fetch_sub:
  2753. case AtomicExpr::AO__opencl_atomic_fetch_min:
  2754. case AtomicExpr::AO__opencl_atomic_fetch_max:
  2755. case AtomicExpr::AO__atomic_fetch_add:
  2756. case AtomicExpr::AO__atomic_fetch_sub:
  2757. case AtomicExpr::AO__atomic_add_fetch:
  2758. case AtomicExpr::AO__atomic_sub_fetch:
  2759. IsAddSub = true;
  2760. LLVM_FALLTHROUGH;
  2761. case AtomicExpr::AO__c11_atomic_fetch_and:
  2762. case AtomicExpr::AO__c11_atomic_fetch_or:
  2763. case AtomicExpr::AO__c11_atomic_fetch_xor:
  2764. case AtomicExpr::AO__opencl_atomic_fetch_and:
  2765. case AtomicExpr::AO__opencl_atomic_fetch_or:
  2766. case AtomicExpr::AO__opencl_atomic_fetch_xor:
  2767. case AtomicExpr::AO__atomic_fetch_and:
  2768. case AtomicExpr::AO__atomic_fetch_or:
  2769. case AtomicExpr::AO__atomic_fetch_xor:
  2770. case AtomicExpr::AO__atomic_fetch_nand:
  2771. case AtomicExpr::AO__atomic_and_fetch:
  2772. case AtomicExpr::AO__atomic_or_fetch:
  2773. case AtomicExpr::AO__atomic_xor_fetch:
  2774. case AtomicExpr::AO__atomic_nand_fetch:
  2775. Form = Arithmetic;
  2776. break;
  2777. case AtomicExpr::AO__c11_atomic_exchange:
  2778. case AtomicExpr::AO__opencl_atomic_exchange:
  2779. case AtomicExpr::AO__atomic_exchange_n:
  2780. Form = Xchg;
  2781. break;
  2782. case AtomicExpr::AO__atomic_exchange:
  2783. Form = GNUXchg;
  2784. break;
  2785. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  2786. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  2787. case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
  2788. case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
  2789. Form = C11CmpXchg;
  2790. break;
  2791. case AtomicExpr::AO__atomic_compare_exchange:
  2792. case AtomicExpr::AO__atomic_compare_exchange_n:
  2793. Form = GNUCmpXchg;
  2794. break;
  2795. }
  2796. unsigned AdjustedNumArgs = NumArgs[Form];
  2797. if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
  2798. ++AdjustedNumArgs;
  2799. // Check we have the right number of arguments.
  2800. if (TheCall->getNumArgs() < AdjustedNumArgs) {
  2801. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  2802. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  2803. << TheCall->getCallee()->getSourceRange();
  2804. return ExprError();
  2805. } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
  2806. Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
  2807. diag::err_typecheck_call_too_many_args)
  2808. << 0 << AdjustedNumArgs << TheCall->getNumArgs()
  2809. << TheCall->getCallee()->getSourceRange();
  2810. return ExprError();
  2811. }
  2812. // Inspect the first argument of the atomic operation.
  2813. Expr *Ptr = TheCall->getArg(0);
  2814. ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
  2815. if (ConvertedPtr.isInvalid())
  2816. return ExprError();
  2817. Ptr = ConvertedPtr.get();
  2818. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  2819. if (!pointerType) {
  2820. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  2821. << Ptr->getType() << Ptr->getSourceRange();
  2822. return ExprError();
  2823. }
  2824. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  2825. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  2826. QualType ValType = AtomTy; // 'C'
  2827. if (IsC11) {
  2828. if (!AtomTy->isAtomicType()) {
  2829. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  2830. << Ptr->getType() << Ptr->getSourceRange();
  2831. return ExprError();
  2832. }
  2833. if (AtomTy.isConstQualified() ||
  2834. AtomTy.getAddressSpace() == LangAS::opencl_constant) {
  2835. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
  2836. << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
  2837. << Ptr->getSourceRange();
  2838. return ExprError();
  2839. }
  2840. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  2841. } else if (Form != Load && Form != LoadCopy) {
  2842. if (ValType.isConstQualified()) {
  2843. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
  2844. << Ptr->getType() << Ptr->getSourceRange();
  2845. return ExprError();
  2846. }
  2847. }
  2848. // For an arithmetic operation, the implied arithmetic must be well-formed.
  2849. if (Form == Arithmetic) {
  2850. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  2851. if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
  2852. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  2853. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  2854. return ExprError();
  2855. }
  2856. if (!IsAddSub && !ValType->isIntegerType()) {
  2857. Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
  2858. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  2859. return ExprError();
  2860. }
  2861. if (IsC11 && ValType->isPointerType() &&
  2862. RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
  2863. diag::err_incomplete_type)) {
  2864. return ExprError();
  2865. }
  2866. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  2867. // For __atomic_*_n operations, the value type must be a scalar integral or
  2868. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  2869. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  2870. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  2871. return ExprError();
  2872. }
  2873. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  2874. !AtomTy->isScalarType()) {
  2875. // For GNU atomics, require a trivially-copyable type. This is not part of
  2876. // the GNU atomics specification, but we enforce it for sanity.
  2877. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
  2878. << Ptr->getType() << Ptr->getSourceRange();
  2879. return ExprError();
  2880. }
  2881. switch (ValType.getObjCLifetime()) {
  2882. case Qualifiers::OCL_None:
  2883. case Qualifiers::OCL_ExplicitNone:
  2884. // okay
  2885. break;
  2886. case Qualifiers::OCL_Weak:
  2887. case Qualifiers::OCL_Strong:
  2888. case Qualifiers::OCL_Autoreleasing:
  2889. // FIXME: Can this happen? By this point, ValType should be known
  2890. // to be trivially copyable.
  2891. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  2892. << ValType << Ptr->getSourceRange();
  2893. return ExprError();
  2894. }
  2895. // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
  2896. // volatile-ness of the pointee-type inject itself into the result or the
  2897. // other operands. Similarly atomic_load can take a pointer to a const 'A'.
  2898. ValType.removeLocalVolatile();
  2899. ValType.removeLocalConst();
  2900. QualType ResultType = ValType;
  2901. if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
  2902. Form == Init)
  2903. ResultType = Context.VoidTy;
  2904. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  2905. ResultType = Context.BoolTy;
  2906. // The type of a parameter passed 'by value'. In the GNU atomics, such
  2907. // arguments are actually passed as pointers.
  2908. QualType ByValType = ValType; // 'CP'
  2909. if (!IsC11 && !IsN)
  2910. ByValType = Ptr->getType();
  2911. // The first argument --- the pointer --- has a fixed type; we
  2912. // deduce the types of the rest of the arguments accordingly. Walk
  2913. // the remaining arguments, converting them to the deduced value type.
  2914. for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
  2915. QualType Ty;
  2916. if (i < NumVals[Form] + 1) {
  2917. switch (i) {
  2918. case 1:
  2919. // The second argument is the non-atomic operand. For arithmetic, this
  2920. // is always passed by value, and for a compare_exchange it is always
  2921. // passed by address. For the rest, GNU uses by-address and C11 uses
  2922. // by-value.
  2923. assert(Form != Load);
  2924. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  2925. Ty = ValType;
  2926. else if (Form == Copy || Form == Xchg)
  2927. Ty = ByValType;
  2928. else if (Form == Arithmetic)
  2929. Ty = Context.getPointerDiffType();
  2930. else {
  2931. Expr *ValArg = TheCall->getArg(i);
  2932. // Treat this argument as _Nonnull as we want to show a warning if
  2933. // NULL is passed into it.
  2934. CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
  2935. LangAS AS = LangAS::Default;
  2936. // Keep address space of non-atomic pointer type.
  2937. if (const PointerType *PtrTy =
  2938. ValArg->getType()->getAs<PointerType>()) {
  2939. AS = PtrTy->getPointeeType().getAddressSpace();
  2940. }
  2941. Ty = Context.getPointerType(
  2942. Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
  2943. }
  2944. break;
  2945. case 2:
  2946. // The third argument to compare_exchange / GNU exchange is a
  2947. // (pointer to a) desired value.
  2948. Ty = ByValType;
  2949. break;
  2950. case 3:
  2951. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  2952. Ty = Context.BoolTy;
  2953. break;
  2954. }
  2955. } else {
  2956. // The order(s) and scope are always converted to int.
  2957. Ty = Context.IntTy;
  2958. }
  2959. InitializedEntity Entity =
  2960. InitializedEntity::InitializeParameter(Context, Ty, false);
  2961. ExprResult Arg = TheCall->getArg(i);
  2962. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  2963. if (Arg.isInvalid())
  2964. return true;
  2965. TheCall->setArg(i, Arg.get());
  2966. }
  2967. // Permute the arguments into a 'consistent' order.
  2968. SmallVector<Expr*, 5> SubExprs;
  2969. SubExprs.push_back(Ptr);
  2970. switch (Form) {
  2971. case Init:
  2972. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  2973. SubExprs.push_back(TheCall->getArg(1)); // Val1
  2974. break;
  2975. case Load:
  2976. SubExprs.push_back(TheCall->getArg(1)); // Order
  2977. break;
  2978. case LoadCopy:
  2979. case Copy:
  2980. case Arithmetic:
  2981. case Xchg:
  2982. SubExprs.push_back(TheCall->getArg(2)); // Order
  2983. SubExprs.push_back(TheCall->getArg(1)); // Val1
  2984. break;
  2985. case GNUXchg:
  2986. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  2987. SubExprs.push_back(TheCall->getArg(3)); // Order
  2988. SubExprs.push_back(TheCall->getArg(1)); // Val1
  2989. SubExprs.push_back(TheCall->getArg(2)); // Val2
  2990. break;
  2991. case C11CmpXchg:
  2992. SubExprs.push_back(TheCall->getArg(3)); // Order
  2993. SubExprs.push_back(TheCall->getArg(1)); // Val1
  2994. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  2995. SubExprs.push_back(TheCall->getArg(2)); // Val2
  2996. break;
  2997. case GNUCmpXchg:
  2998. SubExprs.push_back(TheCall->getArg(4)); // Order
  2999. SubExprs.push_back(TheCall->getArg(1)); // Val1
  3000. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  3001. SubExprs.push_back(TheCall->getArg(2)); // Val2
  3002. SubExprs.push_back(TheCall->getArg(3)); // Weak
  3003. break;
  3004. }
  3005. if (SubExprs.size() >= 2 && Form != Init) {
  3006. llvm::APSInt Result(32);
  3007. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  3008. !isValidOrderingForOp(Result.getSExtValue(), Op))
  3009. Diag(SubExprs[1]->getLocStart(),
  3010. diag::warn_atomic_op_has_invalid_memory_order)
  3011. << SubExprs[1]->getSourceRange();
  3012. }
  3013. if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
  3014. auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
  3015. llvm::APSInt Result(32);
  3016. if (Scope->isIntegerConstantExpr(Result, Context) &&
  3017. !ScopeModel->isValid(Result.getZExtValue())) {
  3018. Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
  3019. << Scope->getSourceRange();
  3020. }
  3021. SubExprs.push_back(Scope);
  3022. }
  3023. AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  3024. SubExprs, ResultType, Op,
  3025. TheCall->getRParenLoc());
  3026. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  3027. Op == AtomicExpr::AO__c11_atomic_store ||
  3028. Op == AtomicExpr::AO__opencl_atomic_load ||
  3029. Op == AtomicExpr::AO__opencl_atomic_store ) &&
  3030. Context.AtomicUsesUnsupportedLibcall(AE))
  3031. Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
  3032. << ((Op == AtomicExpr::AO__c11_atomic_load ||
  3033. Op == AtomicExpr::AO__opencl_atomic_load)
  3034. ? 0 : 1);
  3035. return AE;
  3036. }
  3037. /// checkBuiltinArgument - Given a call to a builtin function, perform
  3038. /// normal type-checking on the given argument, updating the call in
  3039. /// place. This is useful when a builtin function requires custom
  3040. /// type-checking for some of its arguments but not necessarily all of
  3041. /// them.
  3042. ///
  3043. /// Returns true on error.
  3044. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  3045. FunctionDecl *Fn = E->getDirectCallee();
  3046. assert(Fn && "builtin call without direct callee!");
  3047. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  3048. InitializedEntity Entity =
  3049. InitializedEntity::InitializeParameter(S.Context, Param);
  3050. ExprResult Arg = E->getArg(0);
  3051. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  3052. if (Arg.isInvalid())
  3053. return true;
  3054. E->setArg(ArgIndex, Arg.get());
  3055. return false;
  3056. }
  3057. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  3058. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  3059. /// type of its first argument. The main ActOnCallExpr routines have already
  3060. /// promoted the types of arguments because all of these calls are prototyped as
  3061. /// void(...).
  3062. ///
  3063. /// This function goes through and does final semantic checking for these
  3064. /// builtins,
  3065. ExprResult
  3066. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  3067. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  3068. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  3069. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  3070. // Ensure that we have at least one argument to do type inference from.
  3071. if (TheCall->getNumArgs() < 1) {
  3072. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  3073. << 0 << 1 << TheCall->getNumArgs()
  3074. << TheCall->getCallee()->getSourceRange();
  3075. return ExprError();
  3076. }
  3077. // Inspect the first argument of the atomic builtin. This should always be
  3078. // a pointer type, whose element is an integral scalar or pointer type.
  3079. // Because it is a pointer type, we don't have to worry about any implicit
  3080. // casts here.
  3081. // FIXME: We don't allow floating point scalars as input.
  3082. Expr *FirstArg = TheCall->getArg(0);
  3083. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  3084. if (FirstArgResult.isInvalid())
  3085. return ExprError();
  3086. FirstArg = FirstArgResult.get();
  3087. TheCall->setArg(0, FirstArg);
  3088. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  3089. if (!pointerType) {
  3090. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  3091. << FirstArg->getType() << FirstArg->getSourceRange();
  3092. return ExprError();
  3093. }
  3094. QualType ValType = pointerType->getPointeeType();
  3095. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  3096. !ValType->isBlockPointerType()) {
  3097. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  3098. << FirstArg->getType() << FirstArg->getSourceRange();
  3099. return ExprError();
  3100. }
  3101. switch (ValType.getObjCLifetime()) {
  3102. case Qualifiers::OCL_None:
  3103. case Qualifiers::OCL_ExplicitNone:
  3104. // okay
  3105. break;
  3106. case Qualifiers::OCL_Weak:
  3107. case Qualifiers::OCL_Strong:
  3108. case Qualifiers::OCL_Autoreleasing:
  3109. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  3110. << ValType << FirstArg->getSourceRange();
  3111. return ExprError();
  3112. }
  3113. // Strip any qualifiers off ValType.
  3114. ValType = ValType.getUnqualifiedType();
  3115. // The majority of builtins return a value, but a few have special return
  3116. // types, so allow them to override appropriately below.
  3117. QualType ResultType = ValType;
  3118. // We need to figure out which concrete builtin this maps onto. For example,
  3119. // __sync_fetch_and_add with a 2 byte object turns into
  3120. // __sync_fetch_and_add_2.
  3121. #define BUILTIN_ROW(x) \
  3122. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  3123. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  3124. static const unsigned BuiltinIndices[][5] = {
  3125. BUILTIN_ROW(__sync_fetch_and_add),
  3126. BUILTIN_ROW(__sync_fetch_and_sub),
  3127. BUILTIN_ROW(__sync_fetch_and_or),
  3128. BUILTIN_ROW(__sync_fetch_and_and),
  3129. BUILTIN_ROW(__sync_fetch_and_xor),
  3130. BUILTIN_ROW(__sync_fetch_and_nand),
  3131. BUILTIN_ROW(__sync_add_and_fetch),
  3132. BUILTIN_ROW(__sync_sub_and_fetch),
  3133. BUILTIN_ROW(__sync_and_and_fetch),
  3134. BUILTIN_ROW(__sync_or_and_fetch),
  3135. BUILTIN_ROW(__sync_xor_and_fetch),
  3136. BUILTIN_ROW(__sync_nand_and_fetch),
  3137. BUILTIN_ROW(__sync_val_compare_and_swap),
  3138. BUILTIN_ROW(__sync_bool_compare_and_swap),
  3139. BUILTIN_ROW(__sync_lock_test_and_set),
  3140. BUILTIN_ROW(__sync_lock_release),
  3141. BUILTIN_ROW(__sync_swap)
  3142. };
  3143. #undef BUILTIN_ROW
  3144. // Determine the index of the size.
  3145. unsigned SizeIndex;
  3146. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  3147. case 1: SizeIndex = 0; break;
  3148. case 2: SizeIndex = 1; break;
  3149. case 4: SizeIndex = 2; break;
  3150. case 8: SizeIndex = 3; break;
  3151. case 16: SizeIndex = 4; break;
  3152. default:
  3153. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  3154. << FirstArg->getType() << FirstArg->getSourceRange();
  3155. return ExprError();
  3156. }
  3157. // Each of these builtins has one pointer argument, followed by some number of
  3158. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  3159. // that we ignore. Find out which row of BuiltinIndices to read from as well
  3160. // as the number of fixed args.
  3161. unsigned BuiltinID = FDecl->getBuiltinID();
  3162. unsigned BuiltinIndex, NumFixed = 1;
  3163. bool WarnAboutSemanticsChange = false;
  3164. switch (BuiltinID) {
  3165. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  3166. case Builtin::BI__sync_fetch_and_add:
  3167. case Builtin::BI__sync_fetch_and_add_1:
  3168. case Builtin::BI__sync_fetch_and_add_2:
  3169. case Builtin::BI__sync_fetch_and_add_4:
  3170. case Builtin::BI__sync_fetch_and_add_8:
  3171. case Builtin::BI__sync_fetch_and_add_16:
  3172. BuiltinIndex = 0;
  3173. break;
  3174. case Builtin::BI__sync_fetch_and_sub:
  3175. case Builtin::BI__sync_fetch_and_sub_1:
  3176. case Builtin::BI__sync_fetch_and_sub_2:
  3177. case Builtin::BI__sync_fetch_and_sub_4:
  3178. case Builtin::BI__sync_fetch_and_sub_8:
  3179. case Builtin::BI__sync_fetch_and_sub_16:
  3180. BuiltinIndex = 1;
  3181. break;
  3182. case Builtin::BI__sync_fetch_and_or:
  3183. case Builtin::BI__sync_fetch_and_or_1:
  3184. case Builtin::BI__sync_fetch_and_or_2:
  3185. case Builtin::BI__sync_fetch_and_or_4:
  3186. case Builtin::BI__sync_fetch_and_or_8:
  3187. case Builtin::BI__sync_fetch_and_or_16:
  3188. BuiltinIndex = 2;
  3189. break;
  3190. case Builtin::BI__sync_fetch_and_and:
  3191. case Builtin::BI__sync_fetch_and_and_1:
  3192. case Builtin::BI__sync_fetch_and_and_2:
  3193. case Builtin::BI__sync_fetch_and_and_4:
  3194. case Builtin::BI__sync_fetch_and_and_8:
  3195. case Builtin::BI__sync_fetch_and_and_16:
  3196. BuiltinIndex = 3;
  3197. break;
  3198. case Builtin::BI__sync_fetch_and_xor:
  3199. case Builtin::BI__sync_fetch_and_xor_1:
  3200. case Builtin::BI__sync_fetch_and_xor_2:
  3201. case Builtin::BI__sync_fetch_and_xor_4:
  3202. case Builtin::BI__sync_fetch_and_xor_8:
  3203. case Builtin::BI__sync_fetch_and_xor_16:
  3204. BuiltinIndex = 4;
  3205. break;
  3206. case Builtin::BI__sync_fetch_and_nand:
  3207. case Builtin::BI__sync_fetch_and_nand_1:
  3208. case Builtin::BI__sync_fetch_and_nand_2:
  3209. case Builtin::BI__sync_fetch_and_nand_4:
  3210. case Builtin::BI__sync_fetch_and_nand_8:
  3211. case Builtin::BI__sync_fetch_and_nand_16:
  3212. BuiltinIndex = 5;
  3213. WarnAboutSemanticsChange = true;
  3214. break;
  3215. case Builtin::BI__sync_add_and_fetch:
  3216. case Builtin::BI__sync_add_and_fetch_1:
  3217. case Builtin::BI__sync_add_and_fetch_2:
  3218. case Builtin::BI__sync_add_and_fetch_4:
  3219. case Builtin::BI__sync_add_and_fetch_8:
  3220. case Builtin::BI__sync_add_and_fetch_16:
  3221. BuiltinIndex = 6;
  3222. break;
  3223. case Builtin::BI__sync_sub_and_fetch:
  3224. case Builtin::BI__sync_sub_and_fetch_1:
  3225. case Builtin::BI__sync_sub_and_fetch_2:
  3226. case Builtin::BI__sync_sub_and_fetch_4:
  3227. case Builtin::BI__sync_sub_and_fetch_8:
  3228. case Builtin::BI__sync_sub_and_fetch_16:
  3229. BuiltinIndex = 7;
  3230. break;
  3231. case Builtin::BI__sync_and_and_fetch:
  3232. case Builtin::BI__sync_and_and_fetch_1:
  3233. case Builtin::BI__sync_and_and_fetch_2:
  3234. case Builtin::BI__sync_and_and_fetch_4:
  3235. case Builtin::BI__sync_and_and_fetch_8:
  3236. case Builtin::BI__sync_and_and_fetch_16:
  3237. BuiltinIndex = 8;
  3238. break;
  3239. case Builtin::BI__sync_or_and_fetch:
  3240. case Builtin::BI__sync_or_and_fetch_1:
  3241. case Builtin::BI__sync_or_and_fetch_2:
  3242. case Builtin::BI__sync_or_and_fetch_4:
  3243. case Builtin::BI__sync_or_and_fetch_8:
  3244. case Builtin::BI__sync_or_and_fetch_16:
  3245. BuiltinIndex = 9;
  3246. break;
  3247. case Builtin::BI__sync_xor_and_fetch:
  3248. case Builtin::BI__sync_xor_and_fetch_1:
  3249. case Builtin::BI__sync_xor_and_fetch_2:
  3250. case Builtin::BI__sync_xor_and_fetch_4:
  3251. case Builtin::BI__sync_xor_and_fetch_8:
  3252. case Builtin::BI__sync_xor_and_fetch_16:
  3253. BuiltinIndex = 10;
  3254. break;
  3255. case Builtin::BI__sync_nand_and_fetch:
  3256. case Builtin::BI__sync_nand_and_fetch_1:
  3257. case Builtin::BI__sync_nand_and_fetch_2:
  3258. case Builtin::BI__sync_nand_and_fetch_4:
  3259. case Builtin::BI__sync_nand_and_fetch_8:
  3260. case Builtin::BI__sync_nand_and_fetch_16:
  3261. BuiltinIndex = 11;
  3262. WarnAboutSemanticsChange = true;
  3263. break;
  3264. case Builtin::BI__sync_val_compare_and_swap:
  3265. case Builtin::BI__sync_val_compare_and_swap_1:
  3266. case Builtin::BI__sync_val_compare_and_swap_2:
  3267. case Builtin::BI__sync_val_compare_and_swap_4:
  3268. case Builtin::BI__sync_val_compare_and_swap_8:
  3269. case Builtin::BI__sync_val_compare_and_swap_16:
  3270. BuiltinIndex = 12;
  3271. NumFixed = 2;
  3272. break;
  3273. case Builtin::BI__sync_bool_compare_and_swap:
  3274. case Builtin::BI__sync_bool_compare_and_swap_1:
  3275. case Builtin::BI__sync_bool_compare_and_swap_2:
  3276. case Builtin::BI__sync_bool_compare_and_swap_4:
  3277. case Builtin::BI__sync_bool_compare_and_swap_8:
  3278. case Builtin::BI__sync_bool_compare_and_swap_16:
  3279. BuiltinIndex = 13;
  3280. NumFixed = 2;
  3281. ResultType = Context.BoolTy;
  3282. break;
  3283. case Builtin::BI__sync_lock_test_and_set:
  3284. case Builtin::BI__sync_lock_test_and_set_1:
  3285. case Builtin::BI__sync_lock_test_and_set_2:
  3286. case Builtin::BI__sync_lock_test_and_set_4:
  3287. case Builtin::BI__sync_lock_test_and_set_8:
  3288. case Builtin::BI__sync_lock_test_and_set_16:
  3289. BuiltinIndex = 14;
  3290. break;
  3291. case Builtin::BI__sync_lock_release:
  3292. case Builtin::BI__sync_lock_release_1:
  3293. case Builtin::BI__sync_lock_release_2:
  3294. case Builtin::BI__sync_lock_release_4:
  3295. case Builtin::BI__sync_lock_release_8:
  3296. case Builtin::BI__sync_lock_release_16:
  3297. BuiltinIndex = 15;
  3298. NumFixed = 0;
  3299. ResultType = Context.VoidTy;
  3300. break;
  3301. case Builtin::BI__sync_swap:
  3302. case Builtin::BI__sync_swap_1:
  3303. case Builtin::BI__sync_swap_2:
  3304. case Builtin::BI__sync_swap_4:
  3305. case Builtin::BI__sync_swap_8:
  3306. case Builtin::BI__sync_swap_16:
  3307. BuiltinIndex = 16;
  3308. break;
  3309. }
  3310. // Now that we know how many fixed arguments we expect, first check that we
  3311. // have at least that many.
  3312. if (TheCall->getNumArgs() < 1+NumFixed) {
  3313. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  3314. << 0 << 1+NumFixed << TheCall->getNumArgs()
  3315. << TheCall->getCallee()->getSourceRange();
  3316. return ExprError();
  3317. }
  3318. if (WarnAboutSemanticsChange) {
  3319. Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
  3320. << TheCall->getCallee()->getSourceRange();
  3321. }
  3322. // Get the decl for the concrete builtin from this, we can tell what the
  3323. // concrete integer type we should convert to is.
  3324. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  3325. const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
  3326. FunctionDecl *NewBuiltinDecl;
  3327. if (NewBuiltinID == BuiltinID)
  3328. NewBuiltinDecl = FDecl;
  3329. else {
  3330. // Perform builtin lookup to avoid redeclaring it.
  3331. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  3332. LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
  3333. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  3334. assert(Res.getFoundDecl());
  3335. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  3336. if (!NewBuiltinDecl)
  3337. return ExprError();
  3338. }
  3339. // The first argument --- the pointer --- has a fixed type; we
  3340. // deduce the types of the rest of the arguments accordingly. Walk
  3341. // the remaining arguments, converting them to the deduced value type.
  3342. for (unsigned i = 0; i != NumFixed; ++i) {
  3343. ExprResult Arg = TheCall->getArg(i+1);
  3344. // GCC does an implicit conversion to the pointer or integer ValType. This
  3345. // can fail in some cases (1i -> int**), check for this error case now.
  3346. // Initialize the argument.
  3347. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  3348. ValType, /*consume*/ false);
  3349. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  3350. if (Arg.isInvalid())
  3351. return ExprError();
  3352. // Okay, we have something that *can* be converted to the right type. Check
  3353. // to see if there is a potentially weird extension going on here. This can
  3354. // happen when you do an atomic operation on something like an char* and
  3355. // pass in 42. The 42 gets converted to char. This is even more strange
  3356. // for things like 45.123 -> char, etc.
  3357. // FIXME: Do this check.
  3358. TheCall->setArg(i+1, Arg.get());
  3359. }
  3360. ASTContext& Context = this->getASTContext();
  3361. // Create a new DeclRefExpr to refer to the new decl.
  3362. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  3363. Context,
  3364. DRE->getQualifierLoc(),
  3365. SourceLocation(),
  3366. NewBuiltinDecl,
  3367. /*enclosing*/ false,
  3368. DRE->getLocation(),
  3369. Context.BuiltinFnTy,
  3370. DRE->getValueKind());
  3371. // Set the callee in the CallExpr.
  3372. // FIXME: This loses syntactic information.
  3373. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  3374. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  3375. CK_BuiltinFnToFnPtr);
  3376. TheCall->setCallee(PromotedCall.get());
  3377. // Change the result type of the call to match the original value type. This
  3378. // is arbitrary, but the codegen for these builtins ins design to handle it
  3379. // gracefully.
  3380. TheCall->setType(ResultType);
  3381. return TheCallResult;
  3382. }
  3383. /// SemaBuiltinNontemporalOverloaded - We have a call to
  3384. /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
  3385. /// overloaded function based on the pointer type of its last argument.
  3386. ///
  3387. /// This function goes through and does final semantic checking for these
  3388. /// builtins.
  3389. ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
  3390. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  3391. DeclRefExpr *DRE =
  3392. cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  3393. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  3394. unsigned BuiltinID = FDecl->getBuiltinID();
  3395. assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
  3396. BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
  3397. "Unexpected nontemporal load/store builtin!");
  3398. bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
  3399. unsigned numArgs = isStore ? 2 : 1;
  3400. // Ensure that we have the proper number of arguments.
  3401. if (checkArgCount(*this, TheCall, numArgs))
  3402. return ExprError();
  3403. // Inspect the last argument of the nontemporal builtin. This should always
  3404. // be a pointer type, from which we imply the type of the memory access.
  3405. // Because it is a pointer type, we don't have to worry about any implicit
  3406. // casts here.
  3407. Expr *PointerArg = TheCall->getArg(numArgs - 1);
  3408. ExprResult PointerArgResult =
  3409. DefaultFunctionArrayLvalueConversion(PointerArg);
  3410. if (PointerArgResult.isInvalid())
  3411. return ExprError();
  3412. PointerArg = PointerArgResult.get();
  3413. TheCall->setArg(numArgs - 1, PointerArg);
  3414. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  3415. if (!pointerType) {
  3416. Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
  3417. << PointerArg->getType() << PointerArg->getSourceRange();
  3418. return ExprError();
  3419. }
  3420. QualType ValType = pointerType->getPointeeType();
  3421. // Strip any qualifiers off ValType.
  3422. ValType = ValType.getUnqualifiedType();
  3423. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  3424. !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
  3425. !ValType->isVectorType()) {
  3426. Diag(DRE->getLocStart(),
  3427. diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
  3428. << PointerArg->getType() << PointerArg->getSourceRange();
  3429. return ExprError();
  3430. }
  3431. if (!isStore) {
  3432. TheCall->setType(ValType);
  3433. return TheCallResult;
  3434. }
  3435. ExprResult ValArg = TheCall->getArg(0);
  3436. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  3437. Context, ValType, /*consume*/ false);
  3438. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  3439. if (ValArg.isInvalid())
  3440. return ExprError();
  3441. TheCall->setArg(0, ValArg.get());
  3442. TheCall->setType(Context.VoidTy);
  3443. return TheCallResult;
  3444. }
  3445. /// CheckObjCString - Checks that the argument to the builtin
  3446. /// CFString constructor is correct
  3447. /// Note: It might also make sense to do the UTF-16 conversion here (would
  3448. /// simplify the backend).
  3449. bool Sema::CheckObjCString(Expr *Arg) {
  3450. Arg = Arg->IgnoreParenCasts();
  3451. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  3452. if (!Literal || !Literal->isAscii()) {
  3453. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  3454. << Arg->getSourceRange();
  3455. return true;
  3456. }
  3457. if (Literal->containsNonAsciiOrNull()) {
  3458. StringRef String = Literal->getString();
  3459. unsigned NumBytes = String.size();
  3460. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
  3461. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  3462. llvm::UTF16 *ToPtr = &ToBuf[0];
  3463. llvm::ConversionResult Result =
  3464. llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  3465. ToPtr + NumBytes, llvm::strictConversion);
  3466. // Check for conversion failure.
  3467. if (Result != llvm::conversionOK)
  3468. Diag(Arg->getLocStart(),
  3469. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  3470. }
  3471. return false;
  3472. }
  3473. /// CheckObjCString - Checks that the format string argument to the os_log()
  3474. /// and os_trace() functions is correct, and converts it to const char *.
  3475. ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
  3476. Arg = Arg->IgnoreParenCasts();
  3477. auto *Literal = dyn_cast<StringLiteral>(Arg);
  3478. if (!Literal) {
  3479. if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
  3480. Literal = ObjcLiteral->getString();
  3481. }
  3482. }
  3483. if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
  3484. return ExprError(
  3485. Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
  3486. << Arg->getSourceRange());
  3487. }
  3488. ExprResult Result(Literal);
  3489. QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
  3490. InitializedEntity Entity =
  3491. InitializedEntity::InitializeParameter(Context, ResultTy, false);
  3492. Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
  3493. return Result;
  3494. }
  3495. /// Check that the user is calling the appropriate va_start builtin for the
  3496. /// target and calling convention.
  3497. static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
  3498. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  3499. bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
  3500. bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
  3501. bool IsWindows = TT.isOSWindows();
  3502. bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
  3503. if (IsX64 || IsAArch64) {
  3504. CallingConv CC = CC_C;
  3505. if (const FunctionDecl *FD = S.getCurFunctionDecl())
  3506. CC = FD->getType()->getAs<FunctionType>()->getCallConv();
  3507. if (IsMSVAStart) {
  3508. // Don't allow this in System V ABI functions.
  3509. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
  3510. return S.Diag(Fn->getLocStart(),
  3511. diag::err_ms_va_start_used_in_sysv_function);
  3512. } else {
  3513. // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
  3514. // On x64 Windows, don't allow this in System V ABI functions.
  3515. // (Yes, that means there's no corresponding way to support variadic
  3516. // System V ABI functions on Windows.)
  3517. if ((IsWindows && CC == CC_X86_64SysV) ||
  3518. (!IsWindows && CC == CC_Win64))
  3519. return S.Diag(Fn->getLocStart(),
  3520. diag::err_va_start_used_in_wrong_abi_function)
  3521. << !IsWindows;
  3522. }
  3523. return false;
  3524. }
  3525. if (IsMSVAStart)
  3526. return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
  3527. return false;
  3528. }
  3529. static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
  3530. ParmVarDecl **LastParam = nullptr) {
  3531. // Determine whether the current function, block, or obj-c method is variadic
  3532. // and get its parameter list.
  3533. bool IsVariadic = false;
  3534. ArrayRef<ParmVarDecl *> Params;
  3535. DeclContext *Caller = S.CurContext;
  3536. if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
  3537. IsVariadic = Block->isVariadic();
  3538. Params = Block->parameters();
  3539. } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
  3540. IsVariadic = FD->isVariadic();
  3541. Params = FD->parameters();
  3542. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
  3543. IsVariadic = MD->isVariadic();
  3544. // FIXME: This isn't correct for methods (results in bogus warning).
  3545. Params = MD->parameters();
  3546. } else if (isa<CapturedDecl>(Caller)) {
  3547. // We don't support va_start in a CapturedDecl.
  3548. S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
  3549. return true;
  3550. } else {
  3551. // This must be some other declcontext that parses exprs.
  3552. S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
  3553. return true;
  3554. }
  3555. if (!IsVariadic) {
  3556. S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
  3557. return true;
  3558. }
  3559. if (LastParam)
  3560. *LastParam = Params.empty() ? nullptr : Params.back();
  3561. return false;
  3562. }
  3563. /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
  3564. /// for validity. Emit an error and return true on failure; return false
  3565. /// on success.
  3566. bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
  3567. Expr *Fn = TheCall->getCallee();
  3568. if (checkVAStartABI(*this, BuiltinID, Fn))
  3569. return true;
  3570. if (TheCall->getNumArgs() > 2) {
  3571. Diag(TheCall->getArg(2)->getLocStart(),
  3572. diag::err_typecheck_call_too_many_args)
  3573. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  3574. << Fn->getSourceRange()
  3575. << SourceRange(TheCall->getArg(2)->getLocStart(),
  3576. (*(TheCall->arg_end()-1))->getLocEnd());
  3577. return true;
  3578. }
  3579. if (TheCall->getNumArgs() < 2) {
  3580. return Diag(TheCall->getLocEnd(),
  3581. diag::err_typecheck_call_too_few_args_at_least)
  3582. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  3583. }
  3584. // Type-check the first argument normally.
  3585. if (checkBuiltinArgument(*this, TheCall, 0))
  3586. return true;
  3587. // Check that the current function is variadic, and get its last parameter.
  3588. ParmVarDecl *LastParam;
  3589. if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
  3590. return true;
  3591. // Verify that the second argument to the builtin is the last argument of the
  3592. // current function or method.
  3593. bool SecondArgIsLastNamedArgument = false;
  3594. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  3595. // These are valid if SecondArgIsLastNamedArgument is false after the next
  3596. // block.
  3597. QualType Type;
  3598. SourceLocation ParamLoc;
  3599. bool IsCRegister = false;
  3600. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  3601. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  3602. SecondArgIsLastNamedArgument = PV == LastParam;
  3603. Type = PV->getType();
  3604. ParamLoc = PV->getLocation();
  3605. IsCRegister =
  3606. PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
  3607. }
  3608. }
  3609. if (!SecondArgIsLastNamedArgument)
  3610. Diag(TheCall->getArg(1)->getLocStart(),
  3611. diag::warn_second_arg_of_va_start_not_last_named_param);
  3612. else if (IsCRegister || Type->isReferenceType() ||
  3613. Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
  3614. // Promotable integers are UB, but enumerations need a bit of
  3615. // extra checking to see what their promotable type actually is.
  3616. if (!Type->isPromotableIntegerType())
  3617. return false;
  3618. if (!Type->isEnumeralType())
  3619. return true;
  3620. const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
  3621. return !(ED &&
  3622. Context.typesAreCompatible(ED->getPromotionType(), Type));
  3623. }()) {
  3624. unsigned Reason = 0;
  3625. if (Type->isReferenceType()) Reason = 1;
  3626. else if (IsCRegister) Reason = 2;
  3627. Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
  3628. Diag(ParamLoc, diag::note_parameter_type) << Type;
  3629. }
  3630. TheCall->setType(Context.VoidTy);
  3631. return false;
  3632. }
  3633. bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
  3634. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  3635. // const char *named_addr);
  3636. Expr *Func = Call->getCallee();
  3637. if (Call->getNumArgs() < 3)
  3638. return Diag(Call->getLocEnd(),
  3639. diag::err_typecheck_call_too_few_args_at_least)
  3640. << 0 /*function call*/ << 3 << Call->getNumArgs();
  3641. // Type-check the first argument normally.
  3642. if (checkBuiltinArgument(*this, Call, 0))
  3643. return true;
  3644. // Check that the current function is variadic.
  3645. if (checkVAStartIsInVariadicFunction(*this, Func))
  3646. return true;
  3647. // __va_start on Windows does not validate the parameter qualifiers
  3648. const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
  3649. const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
  3650. const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
  3651. const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
  3652. const QualType &ConstCharPtrTy =
  3653. Context.getPointerType(Context.CharTy.withConst());
  3654. if (!Arg1Ty->isPointerType() ||
  3655. Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
  3656. Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
  3657. << Arg1->getType() << ConstCharPtrTy
  3658. << 1 /* different class */
  3659. << 0 /* qualifier difference */
  3660. << 3 /* parameter mismatch */
  3661. << 2 << Arg1->getType() << ConstCharPtrTy;
  3662. const QualType SizeTy = Context.getSizeType();
  3663. if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
  3664. Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
  3665. << Arg2->getType() << SizeTy
  3666. << 1 /* different class */
  3667. << 0 /* qualifier difference */
  3668. << 3 /* parameter mismatch */
  3669. << 3 << Arg2->getType() << SizeTy;
  3670. return false;
  3671. }
  3672. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  3673. /// friends. This is declared to take (...), so we have to check everything.
  3674. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  3675. if (TheCall->getNumArgs() < 2)
  3676. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  3677. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  3678. if (TheCall->getNumArgs() > 2)
  3679. return Diag(TheCall->getArg(2)->getLocStart(),
  3680. diag::err_typecheck_call_too_many_args)
  3681. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  3682. << SourceRange(TheCall->getArg(2)->getLocStart(),
  3683. (*(TheCall->arg_end()-1))->getLocEnd());
  3684. ExprResult OrigArg0 = TheCall->getArg(0);
  3685. ExprResult OrigArg1 = TheCall->getArg(1);
  3686. // Do standard promotions between the two arguments, returning their common
  3687. // type.
  3688. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  3689. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  3690. return true;
  3691. // Make sure any conversions are pushed back into the call; this is
  3692. // type safe since unordered compare builtins are declared as "_Bool
  3693. // foo(...)".
  3694. TheCall->setArg(0, OrigArg0.get());
  3695. TheCall->setArg(1, OrigArg1.get());
  3696. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  3697. return false;
  3698. // If the common type isn't a real floating type, then the arguments were
  3699. // invalid for this operation.
  3700. if (Res.isNull() || !Res->isRealFloatingType())
  3701. return Diag(OrigArg0.get()->getLocStart(),
  3702. diag::err_typecheck_call_invalid_ordered_compare)
  3703. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  3704. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  3705. return false;
  3706. }
  3707. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  3708. /// __builtin_isnan and friends. This is declared to take (...), so we have
  3709. /// to check everything. We expect the last argument to be a floating point
  3710. /// value.
  3711. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  3712. if (TheCall->getNumArgs() < NumArgs)
  3713. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  3714. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  3715. if (TheCall->getNumArgs() > NumArgs)
  3716. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  3717. diag::err_typecheck_call_too_many_args)
  3718. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  3719. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  3720. (*(TheCall->arg_end()-1))->getLocEnd());
  3721. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  3722. if (OrigArg->isTypeDependent())
  3723. return false;
  3724. // This operation requires a non-_Complex floating-point number.
  3725. if (!OrigArg->getType()->isRealFloatingType())
  3726. return Diag(OrigArg->getLocStart(),
  3727. diag::err_typecheck_call_invalid_unary_fp)
  3728. << OrigArg->getType() << OrigArg->getSourceRange();
  3729. // If this is an implicit conversion from float -> float or double, remove it.
  3730. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  3731. // Only remove standard FloatCasts, leaving other casts inplace
  3732. if (Cast->getCastKind() == CK_FloatingCast) {
  3733. Expr *CastArg = Cast->getSubExpr();
  3734. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  3735. assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
  3736. Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
  3737. "promotion from float to either float or double is the only expected cast here");
  3738. Cast->setSubExpr(nullptr);
  3739. TheCall->setArg(NumArgs-1, CastArg);
  3740. }
  3741. }
  3742. }
  3743. return false;
  3744. }
  3745. // Customized Sema Checking for VSX builtins that have the following signature:
  3746. // vector [...] builtinName(vector [...], vector [...], const int);
  3747. // Which takes the same type of vectors (any legal vector type) for the first
  3748. // two arguments and takes compile time constant for the third argument.
  3749. // Example builtins are :
  3750. // vector double vec_xxpermdi(vector double, vector double, int);
  3751. // vector short vec_xxsldwi(vector short, vector short, int);
  3752. bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
  3753. unsigned ExpectedNumArgs = 3;
  3754. if (TheCall->getNumArgs() < ExpectedNumArgs)
  3755. return Diag(TheCall->getLocEnd(),
  3756. diag::err_typecheck_call_too_few_args_at_least)
  3757. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  3758. << TheCall->getSourceRange();
  3759. if (TheCall->getNumArgs() > ExpectedNumArgs)
  3760. return Diag(TheCall->getLocEnd(),
  3761. diag::err_typecheck_call_too_many_args_at_most)
  3762. << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
  3763. << TheCall->getSourceRange();
  3764. // Check the third argument is a compile time constant
  3765. llvm::APSInt Value;
  3766. if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
  3767. return Diag(TheCall->getLocStart(),
  3768. diag::err_vsx_builtin_nonconstant_argument)
  3769. << 3 /* argument index */ << TheCall->getDirectCallee()
  3770. << SourceRange(TheCall->getArg(2)->getLocStart(),
  3771. TheCall->getArg(2)->getLocEnd());
  3772. QualType Arg1Ty = TheCall->getArg(0)->getType();
  3773. QualType Arg2Ty = TheCall->getArg(1)->getType();
  3774. // Check the type of argument 1 and argument 2 are vectors.
  3775. SourceLocation BuiltinLoc = TheCall->getLocStart();
  3776. if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
  3777. (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
  3778. return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
  3779. << TheCall->getDirectCallee()
  3780. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3781. TheCall->getArg(1)->getLocEnd());
  3782. }
  3783. // Check the first two arguments are the same type.
  3784. if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
  3785. return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
  3786. << TheCall->getDirectCallee()
  3787. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3788. TheCall->getArg(1)->getLocEnd());
  3789. }
  3790. // When default clang type checking is turned off and the customized type
  3791. // checking is used, the returning type of the function must be explicitly
  3792. // set. Otherwise it is _Bool by default.
  3793. TheCall->setType(Arg1Ty);
  3794. return false;
  3795. }
  3796. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  3797. // This is declared to take (...), so we have to check everything.
  3798. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  3799. if (TheCall->getNumArgs() < 2)
  3800. return ExprError(Diag(TheCall->getLocEnd(),
  3801. diag::err_typecheck_call_too_few_args_at_least)
  3802. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  3803. << TheCall->getSourceRange());
  3804. // Determine which of the following types of shufflevector we're checking:
  3805. // 1) unary, vector mask: (lhs, mask)
  3806. // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
  3807. QualType resType = TheCall->getArg(0)->getType();
  3808. unsigned numElements = 0;
  3809. if (!TheCall->getArg(0)->isTypeDependent() &&
  3810. !TheCall->getArg(1)->isTypeDependent()) {
  3811. QualType LHSType = TheCall->getArg(0)->getType();
  3812. QualType RHSType = TheCall->getArg(1)->getType();
  3813. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  3814. return ExprError(Diag(TheCall->getLocStart(),
  3815. diag::err_vec_builtin_non_vector)
  3816. << TheCall->getDirectCallee()
  3817. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3818. TheCall->getArg(1)->getLocEnd()));
  3819. numElements = LHSType->getAs<VectorType>()->getNumElements();
  3820. unsigned numResElements = TheCall->getNumArgs() - 2;
  3821. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  3822. // with mask. If so, verify that RHS is an integer vector type with the
  3823. // same number of elts as lhs.
  3824. if (TheCall->getNumArgs() == 2) {
  3825. if (!RHSType->hasIntegerRepresentation() ||
  3826. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  3827. return ExprError(Diag(TheCall->getLocStart(),
  3828. diag::err_vec_builtin_incompatible_vector)
  3829. << TheCall->getDirectCallee()
  3830. << SourceRange(TheCall->getArg(1)->getLocStart(),
  3831. TheCall->getArg(1)->getLocEnd()));
  3832. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  3833. return ExprError(Diag(TheCall->getLocStart(),
  3834. diag::err_vec_builtin_incompatible_vector)
  3835. << TheCall->getDirectCallee()
  3836. << SourceRange(TheCall->getArg(0)->getLocStart(),
  3837. TheCall->getArg(1)->getLocEnd()));
  3838. } else if (numElements != numResElements) {
  3839. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  3840. resType = Context.getVectorType(eltType, numResElements,
  3841. VectorType::GenericVector);
  3842. }
  3843. }
  3844. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  3845. if (TheCall->getArg(i)->isTypeDependent() ||
  3846. TheCall->getArg(i)->isValueDependent())
  3847. continue;
  3848. llvm::APSInt Result(32);
  3849. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  3850. return ExprError(Diag(TheCall->getLocStart(),
  3851. diag::err_shufflevector_nonconstant_argument)
  3852. << TheCall->getArg(i)->getSourceRange());
  3853. // Allow -1 which will be translated to undef in the IR.
  3854. if (Result.isSigned() && Result.isAllOnesValue())
  3855. continue;
  3856. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  3857. return ExprError(Diag(TheCall->getLocStart(),
  3858. diag::err_shufflevector_argument_too_large)
  3859. << TheCall->getArg(i)->getSourceRange());
  3860. }
  3861. SmallVector<Expr*, 32> exprs;
  3862. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  3863. exprs.push_back(TheCall->getArg(i));
  3864. TheCall->setArg(i, nullptr);
  3865. }
  3866. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  3867. TheCall->getCallee()->getLocStart(),
  3868. TheCall->getRParenLoc());
  3869. }
  3870. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  3871. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  3872. SourceLocation BuiltinLoc,
  3873. SourceLocation RParenLoc) {
  3874. ExprValueKind VK = VK_RValue;
  3875. ExprObjectKind OK = OK_Ordinary;
  3876. QualType DstTy = TInfo->getType();
  3877. QualType SrcTy = E->getType();
  3878. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  3879. return ExprError(Diag(BuiltinLoc,
  3880. diag::err_convertvector_non_vector)
  3881. << E->getSourceRange());
  3882. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  3883. return ExprError(Diag(BuiltinLoc,
  3884. diag::err_convertvector_non_vector_type));
  3885. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  3886. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  3887. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  3888. if (SrcElts != DstElts)
  3889. return ExprError(Diag(BuiltinLoc,
  3890. diag::err_convertvector_incompatible_vector)
  3891. << E->getSourceRange());
  3892. }
  3893. return new (Context)
  3894. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  3895. }
  3896. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  3897. // This is declared to take (const void*, ...) and can take two
  3898. // optional constant int args.
  3899. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  3900. unsigned NumArgs = TheCall->getNumArgs();
  3901. if (NumArgs > 3)
  3902. return Diag(TheCall->getLocEnd(),
  3903. diag::err_typecheck_call_too_many_args_at_most)
  3904. << 0 /*function call*/ << 3 << NumArgs
  3905. << TheCall->getSourceRange();
  3906. // Argument 0 is checked for us and the remaining arguments must be
  3907. // constant integers.
  3908. for (unsigned i = 1; i != NumArgs; ++i)
  3909. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  3910. return true;
  3911. return false;
  3912. }
  3913. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  3914. // __assume does not evaluate its arguments, and should warn if its argument
  3915. // has side effects.
  3916. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  3917. Expr *Arg = TheCall->getArg(0);
  3918. if (Arg->isInstantiationDependent()) return false;
  3919. if (Arg->HasSideEffects(Context))
  3920. Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
  3921. << Arg->getSourceRange()
  3922. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  3923. return false;
  3924. }
  3925. /// Handle __builtin_alloca_with_align. This is declared
  3926. /// as (size_t, size_t) where the second size_t must be a power of 2 greater
  3927. /// than 8.
  3928. bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
  3929. // The alignment must be a constant integer.
  3930. Expr *Arg = TheCall->getArg(1);
  3931. // We can't check the value of a dependent argument.
  3932. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  3933. if (const auto *UE =
  3934. dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
  3935. if (UE->getKind() == UETT_AlignOf)
  3936. Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
  3937. << Arg->getSourceRange();
  3938. llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
  3939. if (!Result.isPowerOf2())
  3940. return Diag(TheCall->getLocStart(),
  3941. diag::err_alignment_not_power_of_two)
  3942. << Arg->getSourceRange();
  3943. if (Result < Context.getCharWidth())
  3944. return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
  3945. << (unsigned)Context.getCharWidth()
  3946. << Arg->getSourceRange();
  3947. if (Result > std::numeric_limits<int32_t>::max())
  3948. return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
  3949. << std::numeric_limits<int32_t>::max()
  3950. << Arg->getSourceRange();
  3951. }
  3952. return false;
  3953. }
  3954. /// Handle __builtin_assume_aligned. This is declared
  3955. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  3956. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  3957. unsigned NumArgs = TheCall->getNumArgs();
  3958. if (NumArgs > 3)
  3959. return Diag(TheCall->getLocEnd(),
  3960. diag::err_typecheck_call_too_many_args_at_most)
  3961. << 0 /*function call*/ << 3 << NumArgs
  3962. << TheCall->getSourceRange();
  3963. // The alignment must be a constant integer.
  3964. Expr *Arg = TheCall->getArg(1);
  3965. // We can't check the value of a dependent argument.
  3966. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  3967. llvm::APSInt Result;
  3968. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  3969. return true;
  3970. if (!Result.isPowerOf2())
  3971. return Diag(TheCall->getLocStart(),
  3972. diag::err_alignment_not_power_of_two)
  3973. << Arg->getSourceRange();
  3974. }
  3975. if (NumArgs > 2) {
  3976. ExprResult Arg(TheCall->getArg(2));
  3977. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  3978. Context.getSizeType(), false);
  3979. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  3980. if (Arg.isInvalid()) return true;
  3981. TheCall->setArg(2, Arg.get());
  3982. }
  3983. return false;
  3984. }
  3985. bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
  3986. unsigned BuiltinID =
  3987. cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
  3988. bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
  3989. unsigned NumArgs = TheCall->getNumArgs();
  3990. unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
  3991. if (NumArgs < NumRequiredArgs) {
  3992. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  3993. << 0 /* function call */ << NumRequiredArgs << NumArgs
  3994. << TheCall->getSourceRange();
  3995. }
  3996. if (NumArgs >= NumRequiredArgs + 0x100) {
  3997. return Diag(TheCall->getLocEnd(),
  3998. diag::err_typecheck_call_too_many_args_at_most)
  3999. << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
  4000. << TheCall->getSourceRange();
  4001. }
  4002. unsigned i = 0;
  4003. // For formatting call, check buffer arg.
  4004. if (!IsSizeCall) {
  4005. ExprResult Arg(TheCall->getArg(i));
  4006. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4007. Context, Context.VoidPtrTy, false);
  4008. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4009. if (Arg.isInvalid())
  4010. return true;
  4011. TheCall->setArg(i, Arg.get());
  4012. i++;
  4013. }
  4014. // Check string literal arg.
  4015. unsigned FormatIdx = i;
  4016. {
  4017. ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
  4018. if (Arg.isInvalid())
  4019. return true;
  4020. TheCall->setArg(i, Arg.get());
  4021. i++;
  4022. }
  4023. // Make sure variadic args are scalar.
  4024. unsigned FirstDataArg = i;
  4025. while (i < NumArgs) {
  4026. ExprResult Arg = DefaultVariadicArgumentPromotion(
  4027. TheCall->getArg(i), VariadicFunction, nullptr);
  4028. if (Arg.isInvalid())
  4029. return true;
  4030. CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
  4031. if (ArgSize.getQuantity() >= 0x100) {
  4032. return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
  4033. << i << (int)ArgSize.getQuantity() << 0xff
  4034. << TheCall->getSourceRange();
  4035. }
  4036. TheCall->setArg(i, Arg.get());
  4037. i++;
  4038. }
  4039. // Check formatting specifiers. NOTE: We're only doing this for the non-size
  4040. // call to avoid duplicate diagnostics.
  4041. if (!IsSizeCall) {
  4042. llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
  4043. ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
  4044. bool Success = CheckFormatArguments(
  4045. Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
  4046. VariadicFunction, TheCall->getLocStart(), SourceRange(),
  4047. CheckedVarArgs);
  4048. if (!Success)
  4049. return true;
  4050. }
  4051. if (IsSizeCall) {
  4052. TheCall->setType(Context.getSizeType());
  4053. } else {
  4054. TheCall->setType(Context.VoidPtrTy);
  4055. }
  4056. return false;
  4057. }
  4058. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  4059. /// TheCall is a constant expression.
  4060. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  4061. llvm::APSInt &Result) {
  4062. Expr *Arg = TheCall->getArg(ArgNum);
  4063. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  4064. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  4065. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  4066. if (!Arg->isIntegerConstantExpr(Result, Context))
  4067. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  4068. << FDecl->getDeclName() << Arg->getSourceRange();
  4069. return false;
  4070. }
  4071. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  4072. /// TheCall is a constant expression in the range [Low, High].
  4073. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  4074. int Low, int High) {
  4075. llvm::APSInt Result;
  4076. // We can't check the value of a dependent argument.
  4077. Expr *Arg = TheCall->getArg(ArgNum);
  4078. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4079. return false;
  4080. // Check constant-ness first.
  4081. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4082. return true;
  4083. if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
  4084. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  4085. << Low << High << Arg->getSourceRange();
  4086. return false;
  4087. }
  4088. /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
  4089. /// TheCall is a constant expression is a multiple of Num..
  4090. bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
  4091. unsigned Num) {
  4092. llvm::APSInt Result;
  4093. // We can't check the value of a dependent argument.
  4094. Expr *Arg = TheCall->getArg(ArgNum);
  4095. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4096. return false;
  4097. // Check constant-ness first.
  4098. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  4099. return true;
  4100. if (Result.getSExtValue() % Num != 0)
  4101. return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
  4102. << Num << Arg->getSourceRange();
  4103. return false;
  4104. }
  4105. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  4106. /// TheCall is an ARM/AArch64 special register string literal.
  4107. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  4108. int ArgNum, unsigned ExpectedFieldNum,
  4109. bool AllowName) {
  4110. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  4111. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  4112. BuiltinID == ARM::BI__builtin_arm_rsr ||
  4113. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  4114. BuiltinID == ARM::BI__builtin_arm_wsr ||
  4115. BuiltinID == ARM::BI__builtin_arm_wsrp;
  4116. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  4117. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  4118. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  4119. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  4120. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  4121. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  4122. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  4123. // We can't check the value of a dependent argument.
  4124. Expr *Arg = TheCall->getArg(ArgNum);
  4125. if (Arg->isTypeDependent() || Arg->isValueDependent())
  4126. return false;
  4127. // Check if the argument is a string literal.
  4128. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  4129. return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  4130. << Arg->getSourceRange();
  4131. // Check the type of special register given.
  4132. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  4133. SmallVector<StringRef, 6> Fields;
  4134. Reg.split(Fields, ":");
  4135. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  4136. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  4137. << Arg->getSourceRange();
  4138. // If the string is the name of a register then we cannot check that it is
  4139. // valid here but if the string is of one the forms described in ACLE then we
  4140. // can check that the supplied fields are integers and within the valid
  4141. // ranges.
  4142. if (Fields.size() > 1) {
  4143. bool FiveFields = Fields.size() == 5;
  4144. bool ValidString = true;
  4145. if (IsARMBuiltin) {
  4146. ValidString &= Fields[0].startswith_lower("cp") ||
  4147. Fields[0].startswith_lower("p");
  4148. if (ValidString)
  4149. Fields[0] =
  4150. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  4151. ValidString &= Fields[2].startswith_lower("c");
  4152. if (ValidString)
  4153. Fields[2] = Fields[2].drop_front(1);
  4154. if (FiveFields) {
  4155. ValidString &= Fields[3].startswith_lower("c");
  4156. if (ValidString)
  4157. Fields[3] = Fields[3].drop_front(1);
  4158. }
  4159. }
  4160. SmallVector<int, 5> Ranges;
  4161. if (FiveFields)
  4162. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
  4163. else
  4164. Ranges.append({15, 7, 15});
  4165. for (unsigned i=0; i<Fields.size(); ++i) {
  4166. int IntField;
  4167. ValidString &= !Fields[i].getAsInteger(10, IntField);
  4168. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  4169. }
  4170. if (!ValidString)
  4171. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  4172. << Arg->getSourceRange();
  4173. } else if (IsAArch64Builtin && Fields.size() == 1) {
  4174. // If the register name is one of those that appear in the condition below
  4175. // and the special register builtin being used is one of the write builtins,
  4176. // then we require that the argument provided for writing to the register
  4177. // is an integer constant expression. This is because it will be lowered to
  4178. // an MSR (immediate) instruction, so we need to know the immediate at
  4179. // compile time.
  4180. if (TheCall->getNumArgs() != 2)
  4181. return false;
  4182. std::string RegLower = Reg.lower();
  4183. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  4184. RegLower != "pan" && RegLower != "uao")
  4185. return false;
  4186. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  4187. }
  4188. return false;
  4189. }
  4190. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  4191. /// This checks that the target supports __builtin_longjmp and
  4192. /// that val is a constant 1.
  4193. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  4194. if (!Context.getTargetInfo().hasSjLjLowering())
  4195. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
  4196. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  4197. Expr *Arg = TheCall->getArg(1);
  4198. llvm::APSInt Result;
  4199. // TODO: This is less than ideal. Overload this to take a value.
  4200. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  4201. return true;
  4202. if (Result != 1)
  4203. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  4204. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  4205. return false;
  4206. }
  4207. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  4208. /// This checks that the target supports __builtin_setjmp.
  4209. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  4210. if (!Context.getTargetInfo().hasSjLjLowering())
  4211. return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
  4212. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  4213. return false;
  4214. }
  4215. namespace {
  4216. class UncoveredArgHandler {
  4217. enum { Unknown = -1, AllCovered = -2 };
  4218. signed FirstUncoveredArg = Unknown;
  4219. SmallVector<const Expr *, 4> DiagnosticExprs;
  4220. public:
  4221. UncoveredArgHandler() = default;
  4222. bool hasUncoveredArg() const {
  4223. return (FirstUncoveredArg >= 0);
  4224. }
  4225. unsigned getUncoveredArg() const {
  4226. assert(hasUncoveredArg() && "no uncovered argument");
  4227. return FirstUncoveredArg;
  4228. }
  4229. void setAllCovered() {
  4230. // A string has been found with all arguments covered, so clear out
  4231. // the diagnostics.
  4232. DiagnosticExprs.clear();
  4233. FirstUncoveredArg = AllCovered;
  4234. }
  4235. void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
  4236. assert(NewFirstUncoveredArg >= 0 && "Outside range");
  4237. // Don't update if a previous string covers all arguments.
  4238. if (FirstUncoveredArg == AllCovered)
  4239. return;
  4240. // UncoveredArgHandler tracks the highest uncovered argument index
  4241. // and with it all the strings that match this index.
  4242. if (NewFirstUncoveredArg == FirstUncoveredArg)
  4243. DiagnosticExprs.push_back(StrExpr);
  4244. else if (NewFirstUncoveredArg > FirstUncoveredArg) {
  4245. DiagnosticExprs.clear();
  4246. DiagnosticExprs.push_back(StrExpr);
  4247. FirstUncoveredArg = NewFirstUncoveredArg;
  4248. }
  4249. }
  4250. void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
  4251. };
  4252. enum StringLiteralCheckType {
  4253. SLCT_NotALiteral,
  4254. SLCT_UncheckedLiteral,
  4255. SLCT_CheckedLiteral
  4256. };
  4257. } // namespace
  4258. static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
  4259. BinaryOperatorKind BinOpKind,
  4260. bool AddendIsRight) {
  4261. unsigned BitWidth = Offset.getBitWidth();
  4262. unsigned AddendBitWidth = Addend.getBitWidth();
  4263. // There might be negative interim results.
  4264. if (Addend.isUnsigned()) {
  4265. Addend = Addend.zext(++AddendBitWidth);
  4266. Addend.setIsSigned(true);
  4267. }
  4268. // Adjust the bit width of the APSInts.
  4269. if (AddendBitWidth > BitWidth) {
  4270. Offset = Offset.sext(AddendBitWidth);
  4271. BitWidth = AddendBitWidth;
  4272. } else if (BitWidth > AddendBitWidth) {
  4273. Addend = Addend.sext(BitWidth);
  4274. }
  4275. bool Ov = false;
  4276. llvm::APSInt ResOffset = Offset;
  4277. if (BinOpKind == BO_Add)
  4278. ResOffset = Offset.sadd_ov(Addend, Ov);
  4279. else {
  4280. assert(AddendIsRight && BinOpKind == BO_Sub &&
  4281. "operator must be add or sub with addend on the right");
  4282. ResOffset = Offset.ssub_ov(Addend, Ov);
  4283. }
  4284. // We add an offset to a pointer here so we should support an offset as big as
  4285. // possible.
  4286. if (Ov) {
  4287. assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
  4288. "index (intermediate) result too big");
  4289. Offset = Offset.sext(2 * BitWidth);
  4290. sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
  4291. return;
  4292. }
  4293. Offset = ResOffset;
  4294. }
  4295. namespace {
  4296. // This is a wrapper class around StringLiteral to support offsetted string
  4297. // literals as format strings. It takes the offset into account when returning
  4298. // the string and its length or the source locations to display notes correctly.
  4299. class FormatStringLiteral {
  4300. const StringLiteral *FExpr;
  4301. int64_t Offset;
  4302. public:
  4303. FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
  4304. : FExpr(fexpr), Offset(Offset) {}
  4305. StringRef getString() const {
  4306. return FExpr->getString().drop_front(Offset);
  4307. }
  4308. unsigned getByteLength() const {
  4309. return FExpr->getByteLength() - getCharByteWidth() * Offset;
  4310. }
  4311. unsigned getLength() const { return FExpr->getLength() - Offset; }
  4312. unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
  4313. StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
  4314. QualType getType() const { return FExpr->getType(); }
  4315. bool isAscii() const { return FExpr->isAscii(); }
  4316. bool isWide() const { return FExpr->isWide(); }
  4317. bool isUTF8() const { return FExpr->isUTF8(); }
  4318. bool isUTF16() const { return FExpr->isUTF16(); }
  4319. bool isUTF32() const { return FExpr->isUTF32(); }
  4320. bool isPascal() const { return FExpr->isPascal(); }
  4321. SourceLocation getLocationOfByte(
  4322. unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
  4323. const TargetInfo &Target, unsigned *StartToken = nullptr,
  4324. unsigned *StartTokenByteOffset = nullptr) const {
  4325. return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
  4326. StartToken, StartTokenByteOffset);
  4327. }
  4328. SourceLocation getLocStart() const LLVM_READONLY {
  4329. return FExpr->getLocStart().getLocWithOffset(Offset);
  4330. }
  4331. SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
  4332. };
  4333. } // namespace
  4334. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  4335. const Expr *OrigFormatExpr,
  4336. ArrayRef<const Expr *> Args,
  4337. bool HasVAListArg, unsigned format_idx,
  4338. unsigned firstDataArg,
  4339. Sema::FormatStringType Type,
  4340. bool inFunctionCall,
  4341. Sema::VariadicCallType CallType,
  4342. llvm::SmallBitVector &CheckedVarArgs,
  4343. UncoveredArgHandler &UncoveredArg);
  4344. // Determine if an expression is a string literal or constant string.
  4345. // If this function returns false on the arguments to a function expecting a
  4346. // format string, we will usually need to emit a warning.
  4347. // True string literals are then checked by CheckFormatString.
  4348. static StringLiteralCheckType
  4349. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  4350. bool HasVAListArg, unsigned format_idx,
  4351. unsigned firstDataArg, Sema::FormatStringType Type,
  4352. Sema::VariadicCallType CallType, bool InFunctionCall,
  4353. llvm::SmallBitVector &CheckedVarArgs,
  4354. UncoveredArgHandler &UncoveredArg,
  4355. llvm::APSInt Offset) {
  4356. tryAgain:
  4357. assert(Offset.isSigned() && "invalid offset");
  4358. if (E->isTypeDependent() || E->isValueDependent())
  4359. return SLCT_NotALiteral;
  4360. E = E->IgnoreParenCasts();
  4361. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  4362. // Technically -Wformat-nonliteral does not warn about this case.
  4363. // The behavior of printf and friends in this case is implementation
  4364. // dependent. Ideally if the format string cannot be null then
  4365. // it should have a 'nonnull' attribute in the function prototype.
  4366. return SLCT_UncheckedLiteral;
  4367. switch (E->getStmtClass()) {
  4368. case Stmt::BinaryConditionalOperatorClass:
  4369. case Stmt::ConditionalOperatorClass: {
  4370. // The expression is a literal if both sub-expressions were, and it was
  4371. // completely checked only if both sub-expressions were checked.
  4372. const AbstractConditionalOperator *C =
  4373. cast<AbstractConditionalOperator>(E);
  4374. // Determine whether it is necessary to check both sub-expressions, for
  4375. // example, because the condition expression is a constant that can be
  4376. // evaluated at compile time.
  4377. bool CheckLeft = true, CheckRight = true;
  4378. bool Cond;
  4379. if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
  4380. if (Cond)
  4381. CheckRight = false;
  4382. else
  4383. CheckLeft = false;
  4384. }
  4385. // We need to maintain the offsets for the right and the left hand side
  4386. // separately to check if every possible indexed expression is a valid
  4387. // string literal. They might have different offsets for different string
  4388. // literals in the end.
  4389. StringLiteralCheckType Left;
  4390. if (!CheckLeft)
  4391. Left = SLCT_UncheckedLiteral;
  4392. else {
  4393. Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
  4394. HasVAListArg, format_idx, firstDataArg,
  4395. Type, CallType, InFunctionCall,
  4396. CheckedVarArgs, UncoveredArg, Offset);
  4397. if (Left == SLCT_NotALiteral || !CheckRight) {
  4398. return Left;
  4399. }
  4400. }
  4401. StringLiteralCheckType Right =
  4402. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  4403. HasVAListArg, format_idx, firstDataArg,
  4404. Type, CallType, InFunctionCall, CheckedVarArgs,
  4405. UncoveredArg, Offset);
  4406. return (CheckLeft && Left < Right) ? Left : Right;
  4407. }
  4408. case Stmt::ImplicitCastExprClass:
  4409. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  4410. goto tryAgain;
  4411. case Stmt::OpaqueValueExprClass:
  4412. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  4413. E = src;
  4414. goto tryAgain;
  4415. }
  4416. return SLCT_NotALiteral;
  4417. case Stmt::PredefinedExprClass:
  4418. // While __func__, etc., are technically not string literals, they
  4419. // cannot contain format specifiers and thus are not a security
  4420. // liability.
  4421. return SLCT_UncheckedLiteral;
  4422. case Stmt::DeclRefExprClass: {
  4423. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  4424. // As an exception, do not flag errors for variables binding to
  4425. // const string literals.
  4426. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  4427. bool isConstant = false;
  4428. QualType T = DR->getType();
  4429. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  4430. isConstant = AT->getElementType().isConstant(S.Context);
  4431. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  4432. isConstant = T.isConstant(S.Context) &&
  4433. PT->getPointeeType().isConstant(S.Context);
  4434. } else if (T->isObjCObjectPointerType()) {
  4435. // In ObjC, there is usually no "const ObjectPointer" type,
  4436. // so don't check if the pointee type is constant.
  4437. isConstant = T.isConstant(S.Context);
  4438. }
  4439. if (isConstant) {
  4440. if (const Expr *Init = VD->getAnyInitializer()) {
  4441. // Look through initializers like const char c[] = { "foo" }
  4442. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  4443. if (InitList->isStringLiteralInit())
  4444. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  4445. }
  4446. return checkFormatStringExpr(S, Init, Args,
  4447. HasVAListArg, format_idx,
  4448. firstDataArg, Type, CallType,
  4449. /*InFunctionCall*/ false, CheckedVarArgs,
  4450. UncoveredArg, Offset);
  4451. }
  4452. }
  4453. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  4454. // special check to see if the format string is a function parameter
  4455. // of the function calling the printf function. If the function
  4456. // has an attribute indicating it is a printf-like function, then we
  4457. // should suppress warnings concerning non-literals being used in a call
  4458. // to a vprintf function. For example:
  4459. //
  4460. // void
  4461. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  4462. // va_list ap;
  4463. // va_start(ap, fmt);
  4464. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  4465. // ...
  4466. // }
  4467. if (HasVAListArg) {
  4468. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  4469. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  4470. int PVIndex = PV->getFunctionScopeIndex() + 1;
  4471. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  4472. // adjust for implicit parameter
  4473. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  4474. if (MD->isInstance())
  4475. ++PVIndex;
  4476. // We also check if the formats are compatible.
  4477. // We can't pass a 'scanf' string to a 'printf' function.
  4478. if (PVIndex == PVFormat->getFormatIdx() &&
  4479. Type == S.GetFormatStringType(PVFormat))
  4480. return SLCT_UncheckedLiteral;
  4481. }
  4482. }
  4483. }
  4484. }
  4485. }
  4486. return SLCT_NotALiteral;
  4487. }
  4488. case Stmt::CallExprClass:
  4489. case Stmt::CXXMemberCallExprClass: {
  4490. const CallExpr *CE = cast<CallExpr>(E);
  4491. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  4492. if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
  4493. unsigned ArgIndex = FA->getFormatIdx();
  4494. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  4495. if (MD->isInstance())
  4496. --ArgIndex;
  4497. const Expr *Arg = CE->getArg(ArgIndex - 1);
  4498. return checkFormatStringExpr(S, Arg, Args,
  4499. HasVAListArg, format_idx, firstDataArg,
  4500. Type, CallType, InFunctionCall,
  4501. CheckedVarArgs, UncoveredArg, Offset);
  4502. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  4503. unsigned BuiltinID = FD->getBuiltinID();
  4504. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  4505. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  4506. const Expr *Arg = CE->getArg(0);
  4507. return checkFormatStringExpr(S, Arg, Args,
  4508. HasVAListArg, format_idx,
  4509. firstDataArg, Type, CallType,
  4510. InFunctionCall, CheckedVarArgs,
  4511. UncoveredArg, Offset);
  4512. }
  4513. }
  4514. }
  4515. return SLCT_NotALiteral;
  4516. }
  4517. case Stmt::ObjCMessageExprClass: {
  4518. const auto *ME = cast<ObjCMessageExpr>(E);
  4519. if (const auto *ND = ME->getMethodDecl()) {
  4520. if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
  4521. unsigned ArgIndex = FA->getFormatIdx();
  4522. const Expr *Arg = ME->getArg(ArgIndex - 1);
  4523. return checkFormatStringExpr(
  4524. S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
  4525. CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
  4526. }
  4527. }
  4528. return SLCT_NotALiteral;
  4529. }
  4530. case Stmt::ObjCStringLiteralClass:
  4531. case Stmt::StringLiteralClass: {
  4532. const StringLiteral *StrE = nullptr;
  4533. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  4534. StrE = ObjCFExpr->getString();
  4535. else
  4536. StrE = cast<StringLiteral>(E);
  4537. if (StrE) {
  4538. if (Offset.isNegative() || Offset > StrE->getLength()) {
  4539. // TODO: It would be better to have an explicit warning for out of
  4540. // bounds literals.
  4541. return SLCT_NotALiteral;
  4542. }
  4543. FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
  4544. CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
  4545. firstDataArg, Type, InFunctionCall, CallType,
  4546. CheckedVarArgs, UncoveredArg);
  4547. return SLCT_CheckedLiteral;
  4548. }
  4549. return SLCT_NotALiteral;
  4550. }
  4551. case Stmt::BinaryOperatorClass: {
  4552. llvm::APSInt LResult;
  4553. llvm::APSInt RResult;
  4554. const BinaryOperator *BinOp = cast<BinaryOperator>(E);
  4555. // A string literal + an int offset is still a string literal.
  4556. if (BinOp->isAdditiveOp()) {
  4557. bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
  4558. bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
  4559. if (LIsInt != RIsInt) {
  4560. BinaryOperatorKind BinOpKind = BinOp->getOpcode();
  4561. if (LIsInt) {
  4562. if (BinOpKind == BO_Add) {
  4563. sumOffsets(Offset, LResult, BinOpKind, RIsInt);
  4564. E = BinOp->getRHS();
  4565. goto tryAgain;
  4566. }
  4567. } else {
  4568. sumOffsets(Offset, RResult, BinOpKind, RIsInt);
  4569. E = BinOp->getLHS();
  4570. goto tryAgain;
  4571. }
  4572. }
  4573. }
  4574. return SLCT_NotALiteral;
  4575. }
  4576. case Stmt::UnaryOperatorClass: {
  4577. const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
  4578. auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
  4579. if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
  4580. llvm::APSInt IndexResult;
  4581. if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
  4582. sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
  4583. E = ASE->getBase();
  4584. goto tryAgain;
  4585. }
  4586. }
  4587. return SLCT_NotALiteral;
  4588. }
  4589. default:
  4590. return SLCT_NotALiteral;
  4591. }
  4592. }
  4593. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  4594. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  4595. .Case("scanf", FST_Scanf)
  4596. .Cases("printf", "printf0", FST_Printf)
  4597. .Cases("NSString", "CFString", FST_NSString)
  4598. .Case("strftime", FST_Strftime)
  4599. .Case("strfmon", FST_Strfmon)
  4600. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  4601. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  4602. .Case("os_trace", FST_OSLog)
  4603. .Case("os_log", FST_OSLog)
  4604. .Default(FST_Unknown);
  4605. }
  4606. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  4607. /// functions) for correct use of format strings.
  4608. /// Returns true if a format string has been fully checked.
  4609. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  4610. ArrayRef<const Expr *> Args,
  4611. bool IsCXXMember,
  4612. VariadicCallType CallType,
  4613. SourceLocation Loc, SourceRange Range,
  4614. llvm::SmallBitVector &CheckedVarArgs) {
  4615. FormatStringInfo FSI;
  4616. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  4617. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  4618. FSI.FirstDataArg, GetFormatStringType(Format),
  4619. CallType, Loc, Range, CheckedVarArgs);
  4620. return false;
  4621. }
  4622. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  4623. bool HasVAListArg, unsigned format_idx,
  4624. unsigned firstDataArg, FormatStringType Type,
  4625. VariadicCallType CallType,
  4626. SourceLocation Loc, SourceRange Range,
  4627. llvm::SmallBitVector &CheckedVarArgs) {
  4628. // CHECK: printf/scanf-like function is called with no format string.
  4629. if (format_idx >= Args.size()) {
  4630. Diag(Loc, diag::warn_missing_format_string) << Range;
  4631. return false;
  4632. }
  4633. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  4634. // CHECK: format string is not a string literal.
  4635. //
  4636. // Dynamically generated format strings are difficult to
  4637. // automatically vet at compile time. Requiring that format strings
  4638. // are string literals: (1) permits the checking of format strings by
  4639. // the compiler and thereby (2) can practically remove the source of
  4640. // many format string exploits.
  4641. // Format string can be either ObjC string (e.g. @"%d") or
  4642. // C string (e.g. "%d")
  4643. // ObjC string uses the same format specifiers as C string, so we can use
  4644. // the same format string checking logic for both ObjC and C strings.
  4645. UncoveredArgHandler UncoveredArg;
  4646. StringLiteralCheckType CT =
  4647. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  4648. format_idx, firstDataArg, Type, CallType,
  4649. /*IsFunctionCall*/ true, CheckedVarArgs,
  4650. UncoveredArg,
  4651. /*no string offset*/ llvm::APSInt(64, false) = 0);
  4652. // Generate a diagnostic where an uncovered argument is detected.
  4653. if (UncoveredArg.hasUncoveredArg()) {
  4654. unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
  4655. assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
  4656. UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
  4657. }
  4658. if (CT != SLCT_NotALiteral)
  4659. // Literal format string found, check done!
  4660. return CT == SLCT_CheckedLiteral;
  4661. // Strftime is particular as it always uses a single 'time' argument,
  4662. // so it is safe to pass a non-literal string.
  4663. if (Type == FST_Strftime)
  4664. return false;
  4665. // Do not emit diag when the string param is a macro expansion and the
  4666. // format is either NSString or CFString. This is a hack to prevent
  4667. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  4668. // which are usually used in place of NS and CF string literals.
  4669. SourceLocation FormatLoc = Args[format_idx]->getLocStart();
  4670. if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
  4671. return false;
  4672. // If there are no arguments specified, warn with -Wformat-security, otherwise
  4673. // warn only with -Wformat-nonliteral.
  4674. if (Args.size() == firstDataArg) {
  4675. Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
  4676. << OrigFormatExpr->getSourceRange();
  4677. switch (Type) {
  4678. default:
  4679. break;
  4680. case FST_Kprintf:
  4681. case FST_FreeBSDKPrintf:
  4682. case FST_Printf:
  4683. Diag(FormatLoc, diag::note_format_security_fixit)
  4684. << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
  4685. break;
  4686. case FST_NSString:
  4687. Diag(FormatLoc, diag::note_format_security_fixit)
  4688. << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
  4689. break;
  4690. }
  4691. } else {
  4692. Diag(FormatLoc, diag::warn_format_nonliteral)
  4693. << OrigFormatExpr->getSourceRange();
  4694. }
  4695. return false;
  4696. }
  4697. namespace {
  4698. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  4699. protected:
  4700. Sema &S;
  4701. const FormatStringLiteral *FExpr;
  4702. const Expr *OrigFormatExpr;
  4703. const Sema::FormatStringType FSType;
  4704. const unsigned FirstDataArg;
  4705. const unsigned NumDataArgs;
  4706. const char *Beg; // Start of format string.
  4707. const bool HasVAListArg;
  4708. ArrayRef<const Expr *> Args;
  4709. unsigned FormatIdx;
  4710. llvm::SmallBitVector CoveredArgs;
  4711. bool usesPositionalArgs = false;
  4712. bool atFirstArg = true;
  4713. bool inFunctionCall;
  4714. Sema::VariadicCallType CallType;
  4715. llvm::SmallBitVector &CheckedVarArgs;
  4716. UncoveredArgHandler &UncoveredArg;
  4717. public:
  4718. CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
  4719. const Expr *origFormatExpr,
  4720. const Sema::FormatStringType type, unsigned firstDataArg,
  4721. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  4722. ArrayRef<const Expr *> Args, unsigned formatIdx,
  4723. bool inFunctionCall, Sema::VariadicCallType callType,
  4724. llvm::SmallBitVector &CheckedVarArgs,
  4725. UncoveredArgHandler &UncoveredArg)
  4726. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
  4727. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
  4728. HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
  4729. inFunctionCall(inFunctionCall), CallType(callType),
  4730. CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
  4731. CoveredArgs.resize(numDataArgs);
  4732. CoveredArgs.reset();
  4733. }
  4734. void DoneProcessing();
  4735. void HandleIncompleteSpecifier(const char *startSpecifier,
  4736. unsigned specifierLen) override;
  4737. void HandleInvalidLengthModifier(
  4738. const analyze_format_string::FormatSpecifier &FS,
  4739. const analyze_format_string::ConversionSpecifier &CS,
  4740. const char *startSpecifier, unsigned specifierLen,
  4741. unsigned DiagID);
  4742. void HandleNonStandardLengthModifier(
  4743. const analyze_format_string::FormatSpecifier &FS,
  4744. const char *startSpecifier, unsigned specifierLen);
  4745. void HandleNonStandardConversionSpecifier(
  4746. const analyze_format_string::ConversionSpecifier &CS,
  4747. const char *startSpecifier, unsigned specifierLen);
  4748. void HandlePosition(const char *startPos, unsigned posLen) override;
  4749. void HandleInvalidPosition(const char *startSpecifier,
  4750. unsigned specifierLen,
  4751. analyze_format_string::PositionContext p) override;
  4752. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  4753. void HandleNullChar(const char *nullCharacter) override;
  4754. template <typename Range>
  4755. static void
  4756. EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
  4757. const PartialDiagnostic &PDiag, SourceLocation StringLoc,
  4758. bool IsStringLocation, Range StringRange,
  4759. ArrayRef<FixItHint> Fixit = None);
  4760. protected:
  4761. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  4762. const char *startSpec,
  4763. unsigned specifierLen,
  4764. const char *csStart, unsigned csLen);
  4765. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  4766. const char *startSpec,
  4767. unsigned specifierLen);
  4768. SourceRange getFormatStringRange();
  4769. CharSourceRange getSpecifierRange(const char *startSpecifier,
  4770. unsigned specifierLen);
  4771. SourceLocation getLocationOfByte(const char *x);
  4772. const Expr *getDataArg(unsigned i) const;
  4773. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  4774. const analyze_format_string::ConversionSpecifier &CS,
  4775. const char *startSpecifier, unsigned specifierLen,
  4776. unsigned argIndex);
  4777. template <typename Range>
  4778. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  4779. bool IsStringLocation, Range StringRange,
  4780. ArrayRef<FixItHint> Fixit = None);
  4781. };
  4782. } // namespace
  4783. SourceRange CheckFormatHandler::getFormatStringRange() {
  4784. return OrigFormatExpr->getSourceRange();
  4785. }
  4786. CharSourceRange CheckFormatHandler::
  4787. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  4788. SourceLocation Start = getLocationOfByte(startSpecifier);
  4789. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  4790. // Advance the end SourceLocation by one due to half-open ranges.
  4791. End = End.getLocWithOffset(1);
  4792. return CharSourceRange::getCharRange(Start, End);
  4793. }
  4794. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  4795. return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
  4796. S.getLangOpts(), S.Context.getTargetInfo());
  4797. }
  4798. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  4799. unsigned specifierLen){
  4800. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  4801. getLocationOfByte(startSpecifier),
  4802. /*IsStringLocation*/true,
  4803. getSpecifierRange(startSpecifier, specifierLen));
  4804. }
  4805. void CheckFormatHandler::HandleInvalidLengthModifier(
  4806. const analyze_format_string::FormatSpecifier &FS,
  4807. const analyze_format_string::ConversionSpecifier &CS,
  4808. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  4809. using namespace analyze_format_string;
  4810. const LengthModifier &LM = FS.getLengthModifier();
  4811. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  4812. // See if we know how to fix this length modifier.
  4813. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  4814. if (FixedLM) {
  4815. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  4816. getLocationOfByte(LM.getStart()),
  4817. /*IsStringLocation*/true,
  4818. getSpecifierRange(startSpecifier, specifierLen));
  4819. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  4820. << FixedLM->toString()
  4821. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  4822. } else {
  4823. FixItHint Hint;
  4824. if (DiagID == diag::warn_format_nonsensical_length)
  4825. Hint = FixItHint::CreateRemoval(LMRange);
  4826. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  4827. getLocationOfByte(LM.getStart()),
  4828. /*IsStringLocation*/true,
  4829. getSpecifierRange(startSpecifier, specifierLen),
  4830. Hint);
  4831. }
  4832. }
  4833. void CheckFormatHandler::HandleNonStandardLengthModifier(
  4834. const analyze_format_string::FormatSpecifier &FS,
  4835. const char *startSpecifier, unsigned specifierLen) {
  4836. using namespace analyze_format_string;
  4837. const LengthModifier &LM = FS.getLengthModifier();
  4838. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  4839. // See if we know how to fix this length modifier.
  4840. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  4841. if (FixedLM) {
  4842. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4843. << LM.toString() << 0,
  4844. getLocationOfByte(LM.getStart()),
  4845. /*IsStringLocation*/true,
  4846. getSpecifierRange(startSpecifier, specifierLen));
  4847. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  4848. << FixedLM->toString()
  4849. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  4850. } else {
  4851. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4852. << LM.toString() << 0,
  4853. getLocationOfByte(LM.getStart()),
  4854. /*IsStringLocation*/true,
  4855. getSpecifierRange(startSpecifier, specifierLen));
  4856. }
  4857. }
  4858. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  4859. const analyze_format_string::ConversionSpecifier &CS,
  4860. const char *startSpecifier, unsigned specifierLen) {
  4861. using namespace analyze_format_string;
  4862. // See if we know how to fix this conversion specifier.
  4863. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  4864. if (FixedCS) {
  4865. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4866. << CS.toString() << /*conversion specifier*/1,
  4867. getLocationOfByte(CS.getStart()),
  4868. /*IsStringLocation*/true,
  4869. getSpecifierRange(startSpecifier, specifierLen));
  4870. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  4871. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  4872. << FixedCS->toString()
  4873. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  4874. } else {
  4875. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  4876. << CS.toString() << /*conversion specifier*/1,
  4877. getLocationOfByte(CS.getStart()),
  4878. /*IsStringLocation*/true,
  4879. getSpecifierRange(startSpecifier, specifierLen));
  4880. }
  4881. }
  4882. void CheckFormatHandler::HandlePosition(const char *startPos,
  4883. unsigned posLen) {
  4884. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  4885. getLocationOfByte(startPos),
  4886. /*IsStringLocation*/true,
  4887. getSpecifierRange(startPos, posLen));
  4888. }
  4889. void
  4890. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  4891. analyze_format_string::PositionContext p) {
  4892. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  4893. << (unsigned) p,
  4894. getLocationOfByte(startPos), /*IsStringLocation*/true,
  4895. getSpecifierRange(startPos, posLen));
  4896. }
  4897. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  4898. unsigned posLen) {
  4899. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  4900. getLocationOfByte(startPos),
  4901. /*IsStringLocation*/true,
  4902. getSpecifierRange(startPos, posLen));
  4903. }
  4904. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  4905. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  4906. // The presence of a null character is likely an error.
  4907. EmitFormatDiagnostic(
  4908. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  4909. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  4910. getFormatStringRange());
  4911. }
  4912. }
  4913. // Note that this may return NULL if there was an error parsing or building
  4914. // one of the argument expressions.
  4915. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  4916. return Args[FirstDataArg + i];
  4917. }
  4918. void CheckFormatHandler::DoneProcessing() {
  4919. // Does the number of data arguments exceed the number of
  4920. // format conversions in the format string?
  4921. if (!HasVAListArg) {
  4922. // Find any arguments that weren't covered.
  4923. CoveredArgs.flip();
  4924. signed notCoveredArg = CoveredArgs.find_first();
  4925. if (notCoveredArg >= 0) {
  4926. assert((unsigned)notCoveredArg < NumDataArgs);
  4927. UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
  4928. } else {
  4929. UncoveredArg.setAllCovered();
  4930. }
  4931. }
  4932. }
  4933. void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
  4934. const Expr *ArgExpr) {
  4935. assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
  4936. "Invalid state");
  4937. if (!ArgExpr)
  4938. return;
  4939. SourceLocation Loc = ArgExpr->getLocStart();
  4940. if (S.getSourceManager().isInSystemMacro(Loc))
  4941. return;
  4942. PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
  4943. for (auto E : DiagnosticExprs)
  4944. PDiag << E->getSourceRange();
  4945. CheckFormatHandler::EmitFormatDiagnostic(
  4946. S, IsFunctionCall, DiagnosticExprs[0],
  4947. PDiag, Loc, /*IsStringLocation*/false,
  4948. DiagnosticExprs[0]->getSourceRange());
  4949. }
  4950. bool
  4951. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  4952. SourceLocation Loc,
  4953. const char *startSpec,
  4954. unsigned specifierLen,
  4955. const char *csStart,
  4956. unsigned csLen) {
  4957. bool keepGoing = true;
  4958. if (argIndex < NumDataArgs) {
  4959. // Consider the argument coverered, even though the specifier doesn't
  4960. // make sense.
  4961. CoveredArgs.set(argIndex);
  4962. }
  4963. else {
  4964. // If argIndex exceeds the number of data arguments we
  4965. // don't issue a warning because that is just a cascade of warnings (and
  4966. // they may have intended '%%' anyway). We don't want to continue processing
  4967. // the format string after this point, however, as we will like just get
  4968. // gibberish when trying to match arguments.
  4969. keepGoing = false;
  4970. }
  4971. StringRef Specifier(csStart, csLen);
  4972. // If the specifier in non-printable, it could be the first byte of a UTF-8
  4973. // sequence. In that case, print the UTF-8 code point. If not, print the byte
  4974. // hex value.
  4975. std::string CodePointStr;
  4976. if (!llvm::sys::locale::isPrint(*csStart)) {
  4977. llvm::UTF32 CodePoint;
  4978. const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
  4979. const llvm::UTF8 *E =
  4980. reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
  4981. llvm::ConversionResult Result =
  4982. llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
  4983. if (Result != llvm::conversionOK) {
  4984. unsigned char FirstChar = *csStart;
  4985. CodePoint = (llvm::UTF32)FirstChar;
  4986. }
  4987. llvm::raw_string_ostream OS(CodePointStr);
  4988. if (CodePoint < 256)
  4989. OS << "\\x" << llvm::format("%02x", CodePoint);
  4990. else if (CodePoint <= 0xFFFF)
  4991. OS << "\\u" << llvm::format("%04x", CodePoint);
  4992. else
  4993. OS << "\\U" << llvm::format("%08x", CodePoint);
  4994. OS.flush();
  4995. Specifier = CodePointStr;
  4996. }
  4997. EmitFormatDiagnostic(
  4998. S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
  4999. /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
  5000. return keepGoing;
  5001. }
  5002. void
  5003. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  5004. const char *startSpec,
  5005. unsigned specifierLen) {
  5006. EmitFormatDiagnostic(
  5007. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  5008. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  5009. }
  5010. bool
  5011. CheckFormatHandler::CheckNumArgs(
  5012. const analyze_format_string::FormatSpecifier &FS,
  5013. const analyze_format_string::ConversionSpecifier &CS,
  5014. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  5015. if (argIndex >= NumDataArgs) {
  5016. PartialDiagnostic PDiag = FS.usesPositionalArg()
  5017. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  5018. << (argIndex+1) << NumDataArgs)
  5019. : S.PDiag(diag::warn_printf_insufficient_data_args);
  5020. EmitFormatDiagnostic(
  5021. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  5022. getSpecifierRange(startSpecifier, specifierLen));
  5023. // Since more arguments than conversion tokens are given, by extension
  5024. // all arguments are covered, so mark this as so.
  5025. UncoveredArg.setAllCovered();
  5026. return false;
  5027. }
  5028. return true;
  5029. }
  5030. template<typename Range>
  5031. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  5032. SourceLocation Loc,
  5033. bool IsStringLocation,
  5034. Range StringRange,
  5035. ArrayRef<FixItHint> FixIt) {
  5036. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  5037. Loc, IsStringLocation, StringRange, FixIt);
  5038. }
  5039. /// \brief If the format string is not within the funcion call, emit a note
  5040. /// so that the function call and string are in diagnostic messages.
  5041. ///
  5042. /// \param InFunctionCall if true, the format string is within the function
  5043. /// call and only one diagnostic message will be produced. Otherwise, an
  5044. /// extra note will be emitted pointing to location of the format string.
  5045. ///
  5046. /// \param ArgumentExpr the expression that is passed as the format string
  5047. /// argument in the function call. Used for getting locations when two
  5048. /// diagnostics are emitted.
  5049. ///
  5050. /// \param PDiag the callee should already have provided any strings for the
  5051. /// diagnostic message. This function only adds locations and fixits
  5052. /// to diagnostics.
  5053. ///
  5054. /// \param Loc primary location for diagnostic. If two diagnostics are
  5055. /// required, one will be at Loc and a new SourceLocation will be created for
  5056. /// the other one.
  5057. ///
  5058. /// \param IsStringLocation if true, Loc points to the format string should be
  5059. /// used for the note. Otherwise, Loc points to the argument list and will
  5060. /// be used with PDiag.
  5061. ///
  5062. /// \param StringRange some or all of the string to highlight. This is
  5063. /// templated so it can accept either a CharSourceRange or a SourceRange.
  5064. ///
  5065. /// \param FixIt optional fix it hint for the format string.
  5066. template <typename Range>
  5067. void CheckFormatHandler::EmitFormatDiagnostic(
  5068. Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
  5069. const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
  5070. Range StringRange, ArrayRef<FixItHint> FixIt) {
  5071. if (InFunctionCall) {
  5072. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  5073. D << StringRange;
  5074. D << FixIt;
  5075. } else {
  5076. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  5077. << ArgumentExpr->getSourceRange();
  5078. const Sema::SemaDiagnosticBuilder &Note =
  5079. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  5080. diag::note_format_string_defined);
  5081. Note << StringRange;
  5082. Note << FixIt;
  5083. }
  5084. }
  5085. //===--- CHECK: Printf format string checking ------------------------------===//
  5086. namespace {
  5087. class CheckPrintfHandler : public CheckFormatHandler {
  5088. public:
  5089. CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
  5090. const Expr *origFormatExpr,
  5091. const Sema::FormatStringType type, unsigned firstDataArg,
  5092. unsigned numDataArgs, bool isObjC, const char *beg,
  5093. bool hasVAListArg, ArrayRef<const Expr *> Args,
  5094. unsigned formatIdx, bool inFunctionCall,
  5095. Sema::VariadicCallType CallType,
  5096. llvm::SmallBitVector &CheckedVarArgs,
  5097. UncoveredArgHandler &UncoveredArg)
  5098. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  5099. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  5100. inFunctionCall, CallType, CheckedVarArgs,
  5101. UncoveredArg) {}
  5102. bool isObjCContext() const { return FSType == Sema::FST_NSString; }
  5103. /// Returns true if '%@' specifiers are allowed in the format string.
  5104. bool allowsObjCArg() const {
  5105. return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
  5106. FSType == Sema::FST_OSTrace;
  5107. }
  5108. bool HandleInvalidPrintfConversionSpecifier(
  5109. const analyze_printf::PrintfSpecifier &FS,
  5110. const char *startSpecifier,
  5111. unsigned specifierLen) override;
  5112. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  5113. const char *startSpecifier,
  5114. unsigned specifierLen) override;
  5115. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  5116. const char *StartSpecifier,
  5117. unsigned SpecifierLen,
  5118. const Expr *E);
  5119. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  5120. const char *startSpecifier, unsigned specifierLen);
  5121. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  5122. const analyze_printf::OptionalAmount &Amt,
  5123. unsigned type,
  5124. const char *startSpecifier, unsigned specifierLen);
  5125. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  5126. const analyze_printf::OptionalFlag &flag,
  5127. const char *startSpecifier, unsigned specifierLen);
  5128. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  5129. const analyze_printf::OptionalFlag &ignoredFlag,
  5130. const analyze_printf::OptionalFlag &flag,
  5131. const char *startSpecifier, unsigned specifierLen);
  5132. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  5133. const Expr *E);
  5134. void HandleEmptyObjCModifierFlag(const char *startFlag,
  5135. unsigned flagLen) override;
  5136. void HandleInvalidObjCModifierFlag(const char *startFlag,
  5137. unsigned flagLen) override;
  5138. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  5139. const char *flagsEnd,
  5140. const char *conversionPosition)
  5141. override;
  5142. };
  5143. } // namespace
  5144. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  5145. const analyze_printf::PrintfSpecifier &FS,
  5146. const char *startSpecifier,
  5147. unsigned specifierLen) {
  5148. const analyze_printf::PrintfConversionSpecifier &CS =
  5149. FS.getConversionSpecifier();
  5150. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  5151. getLocationOfByte(CS.getStart()),
  5152. startSpecifier, specifierLen,
  5153. CS.getStart(), CS.getLength());
  5154. }
  5155. bool CheckPrintfHandler::HandleAmount(
  5156. const analyze_format_string::OptionalAmount &Amt,
  5157. unsigned k, const char *startSpecifier,
  5158. unsigned specifierLen) {
  5159. if (Amt.hasDataArgument()) {
  5160. if (!HasVAListArg) {
  5161. unsigned argIndex = Amt.getArgIndex();
  5162. if (argIndex >= NumDataArgs) {
  5163. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  5164. << k,
  5165. getLocationOfByte(Amt.getStart()),
  5166. /*IsStringLocation*/true,
  5167. getSpecifierRange(startSpecifier, specifierLen));
  5168. // Don't do any more checking. We will just emit
  5169. // spurious errors.
  5170. return false;
  5171. }
  5172. // Type check the data argument. It should be an 'int'.
  5173. // Although not in conformance with C99, we also allow the argument to be
  5174. // an 'unsigned int' as that is a reasonably safe case. GCC also
  5175. // doesn't emit a warning for that case.
  5176. CoveredArgs.set(argIndex);
  5177. const Expr *Arg = getDataArg(argIndex);
  5178. if (!Arg)
  5179. return false;
  5180. QualType T = Arg->getType();
  5181. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  5182. assert(AT.isValid());
  5183. if (!AT.matchesType(S.Context, T)) {
  5184. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  5185. << k << AT.getRepresentativeTypeName(S.Context)
  5186. << T << Arg->getSourceRange(),
  5187. getLocationOfByte(Amt.getStart()),
  5188. /*IsStringLocation*/true,
  5189. getSpecifierRange(startSpecifier, specifierLen));
  5190. // Don't do any more checking. We will just emit
  5191. // spurious errors.
  5192. return false;
  5193. }
  5194. }
  5195. }
  5196. return true;
  5197. }
  5198. void CheckPrintfHandler::HandleInvalidAmount(
  5199. const analyze_printf::PrintfSpecifier &FS,
  5200. const analyze_printf::OptionalAmount &Amt,
  5201. unsigned type,
  5202. const char *startSpecifier,
  5203. unsigned specifierLen) {
  5204. const analyze_printf::PrintfConversionSpecifier &CS =
  5205. FS.getConversionSpecifier();
  5206. FixItHint fixit =
  5207. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  5208. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  5209. Amt.getConstantLength()))
  5210. : FixItHint();
  5211. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  5212. << type << CS.toString(),
  5213. getLocationOfByte(Amt.getStart()),
  5214. /*IsStringLocation*/true,
  5215. getSpecifierRange(startSpecifier, specifierLen),
  5216. fixit);
  5217. }
  5218. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  5219. const analyze_printf::OptionalFlag &flag,
  5220. const char *startSpecifier,
  5221. unsigned specifierLen) {
  5222. // Warn about pointless flag with a fixit removal.
  5223. const analyze_printf::PrintfConversionSpecifier &CS =
  5224. FS.getConversionSpecifier();
  5225. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  5226. << flag.toString() << CS.toString(),
  5227. getLocationOfByte(flag.getPosition()),
  5228. /*IsStringLocation*/true,
  5229. getSpecifierRange(startSpecifier, specifierLen),
  5230. FixItHint::CreateRemoval(
  5231. getSpecifierRange(flag.getPosition(), 1)));
  5232. }
  5233. void CheckPrintfHandler::HandleIgnoredFlag(
  5234. const analyze_printf::PrintfSpecifier &FS,
  5235. const analyze_printf::OptionalFlag &ignoredFlag,
  5236. const analyze_printf::OptionalFlag &flag,
  5237. const char *startSpecifier,
  5238. unsigned specifierLen) {
  5239. // Warn about ignored flag with a fixit removal.
  5240. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  5241. << ignoredFlag.toString() << flag.toString(),
  5242. getLocationOfByte(ignoredFlag.getPosition()),
  5243. /*IsStringLocation*/true,
  5244. getSpecifierRange(startSpecifier, specifierLen),
  5245. FixItHint::CreateRemoval(
  5246. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  5247. }
  5248. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  5249. unsigned flagLen) {
  5250. // Warn about an empty flag.
  5251. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  5252. getLocationOfByte(startFlag),
  5253. /*IsStringLocation*/true,
  5254. getSpecifierRange(startFlag, flagLen));
  5255. }
  5256. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  5257. unsigned flagLen) {
  5258. // Warn about an invalid flag.
  5259. auto Range = getSpecifierRange(startFlag, flagLen);
  5260. StringRef flag(startFlag, flagLen);
  5261. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  5262. getLocationOfByte(startFlag),
  5263. /*IsStringLocation*/true,
  5264. Range, FixItHint::CreateRemoval(Range));
  5265. }
  5266. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  5267. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  5268. // Warn about using '[...]' without a '@' conversion.
  5269. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  5270. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  5271. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  5272. getLocationOfByte(conversionPosition),
  5273. /*IsStringLocation*/true,
  5274. Range, FixItHint::CreateRemoval(Range));
  5275. }
  5276. // Determines if the specified is a C++ class or struct containing
  5277. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  5278. // "c_str()").
  5279. template<typename MemberKind>
  5280. static llvm::SmallPtrSet<MemberKind*, 1>
  5281. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  5282. const RecordType *RT = Ty->getAs<RecordType>();
  5283. llvm::SmallPtrSet<MemberKind*, 1> Results;
  5284. if (!RT)
  5285. return Results;
  5286. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  5287. if (!RD || !RD->getDefinition())
  5288. return Results;
  5289. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  5290. Sema::LookupMemberName);
  5291. R.suppressDiagnostics();
  5292. // We just need to include all members of the right kind turned up by the
  5293. // filter, at this point.
  5294. if (S.LookupQualifiedName(R, RT->getDecl()))
  5295. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  5296. NamedDecl *decl = (*I)->getUnderlyingDecl();
  5297. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  5298. Results.insert(FK);
  5299. }
  5300. return Results;
  5301. }
  5302. /// Check if we could call '.c_str()' on an object.
  5303. ///
  5304. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  5305. /// allow the call, or if it would be ambiguous).
  5306. bool Sema::hasCStrMethod(const Expr *E) {
  5307. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  5308. MethodSet Results =
  5309. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  5310. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  5311. MI != ME; ++MI)
  5312. if ((*MI)->getMinRequiredArguments() == 0)
  5313. return true;
  5314. return false;
  5315. }
  5316. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  5317. // better diagnostic if so. AT is assumed to be valid.
  5318. // Returns true when a c_str() conversion method is found.
  5319. bool CheckPrintfHandler::checkForCStrMembers(
  5320. const analyze_printf::ArgType &AT, const Expr *E) {
  5321. using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
  5322. MethodSet Results =
  5323. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  5324. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  5325. MI != ME; ++MI) {
  5326. const CXXMethodDecl *Method = *MI;
  5327. if (Method->getMinRequiredArguments() == 0 &&
  5328. AT.matchesType(S.Context, Method->getReturnType())) {
  5329. // FIXME: Suggest parens if the expression needs them.
  5330. SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
  5331. S.Diag(E->getLocStart(), diag::note_printf_c_str)
  5332. << "c_str()"
  5333. << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  5334. return true;
  5335. }
  5336. }
  5337. return false;
  5338. }
  5339. bool
  5340. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  5341. &FS,
  5342. const char *startSpecifier,
  5343. unsigned specifierLen) {
  5344. using namespace analyze_format_string;
  5345. using namespace analyze_printf;
  5346. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  5347. if (FS.consumesDataArgument()) {
  5348. if (atFirstArg) {
  5349. atFirstArg = false;
  5350. usesPositionalArgs = FS.usesPositionalArg();
  5351. }
  5352. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  5353. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  5354. startSpecifier, specifierLen);
  5355. return false;
  5356. }
  5357. }
  5358. // First check if the field width, precision, and conversion specifier
  5359. // have matching data arguments.
  5360. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  5361. startSpecifier, specifierLen)) {
  5362. return false;
  5363. }
  5364. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  5365. startSpecifier, specifierLen)) {
  5366. return false;
  5367. }
  5368. if (!CS.consumesDataArgument()) {
  5369. // FIXME: Technically specifying a precision or field width here
  5370. // makes no sense. Worth issuing a warning at some point.
  5371. return true;
  5372. }
  5373. // Consume the argument.
  5374. unsigned argIndex = FS.getArgIndex();
  5375. if (argIndex < NumDataArgs) {
  5376. // The check to see if the argIndex is valid will come later.
  5377. // We set the bit here because we may exit early from this
  5378. // function if we encounter some other error.
  5379. CoveredArgs.set(argIndex);
  5380. }
  5381. // FreeBSD kernel extensions.
  5382. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  5383. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  5384. // We need at least two arguments.
  5385. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  5386. return false;
  5387. // Claim the second argument.
  5388. CoveredArgs.set(argIndex + 1);
  5389. // Type check the first argument (int for %b, pointer for %D)
  5390. const Expr *Ex = getDataArg(argIndex);
  5391. const analyze_printf::ArgType &AT =
  5392. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  5393. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  5394. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  5395. EmitFormatDiagnostic(
  5396. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  5397. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  5398. << false << Ex->getSourceRange(),
  5399. Ex->getLocStart(), /*IsStringLocation*/false,
  5400. getSpecifierRange(startSpecifier, specifierLen));
  5401. // Type check the second argument (char * for both %b and %D)
  5402. Ex = getDataArg(argIndex + 1);
  5403. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  5404. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  5405. EmitFormatDiagnostic(
  5406. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  5407. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  5408. << false << Ex->getSourceRange(),
  5409. Ex->getLocStart(), /*IsStringLocation*/false,
  5410. getSpecifierRange(startSpecifier, specifierLen));
  5411. return true;
  5412. }
  5413. // Check for using an Objective-C specific conversion specifier
  5414. // in a non-ObjC literal.
  5415. if (!allowsObjCArg() && CS.isObjCArg()) {
  5416. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  5417. specifierLen);
  5418. }
  5419. // %P can only be used with os_log.
  5420. if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
  5421. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  5422. specifierLen);
  5423. }
  5424. // %n is not allowed with os_log.
  5425. if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
  5426. EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
  5427. getLocationOfByte(CS.getStart()),
  5428. /*IsStringLocation*/ false,
  5429. getSpecifierRange(startSpecifier, specifierLen));
  5430. return true;
  5431. }
  5432. // Only scalars are allowed for os_trace.
  5433. if (FSType == Sema::FST_OSTrace &&
  5434. (CS.getKind() == ConversionSpecifier::PArg ||
  5435. CS.getKind() == ConversionSpecifier::sArg ||
  5436. CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
  5437. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  5438. specifierLen);
  5439. }
  5440. // Check for use of public/private annotation outside of os_log().
  5441. if (FSType != Sema::FST_OSLog) {
  5442. if (FS.isPublic().isSet()) {
  5443. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  5444. << "public",
  5445. getLocationOfByte(FS.isPublic().getPosition()),
  5446. /*IsStringLocation*/ false,
  5447. getSpecifierRange(startSpecifier, specifierLen));
  5448. }
  5449. if (FS.isPrivate().isSet()) {
  5450. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
  5451. << "private",
  5452. getLocationOfByte(FS.isPrivate().getPosition()),
  5453. /*IsStringLocation*/ false,
  5454. getSpecifierRange(startSpecifier, specifierLen));
  5455. }
  5456. }
  5457. // Check for invalid use of field width
  5458. if (!FS.hasValidFieldWidth()) {
  5459. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  5460. startSpecifier, specifierLen);
  5461. }
  5462. // Check for invalid use of precision
  5463. if (!FS.hasValidPrecision()) {
  5464. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  5465. startSpecifier, specifierLen);
  5466. }
  5467. // Precision is mandatory for %P specifier.
  5468. if (CS.getKind() == ConversionSpecifier::PArg &&
  5469. FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
  5470. EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
  5471. getLocationOfByte(startSpecifier),
  5472. /*IsStringLocation*/ false,
  5473. getSpecifierRange(startSpecifier, specifierLen));
  5474. }
  5475. // Check each flag does not conflict with any other component.
  5476. if (!FS.hasValidThousandsGroupingPrefix())
  5477. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  5478. if (!FS.hasValidLeadingZeros())
  5479. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  5480. if (!FS.hasValidPlusPrefix())
  5481. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  5482. if (!FS.hasValidSpacePrefix())
  5483. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  5484. if (!FS.hasValidAlternativeForm())
  5485. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  5486. if (!FS.hasValidLeftJustified())
  5487. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  5488. // Check that flags are not ignored by another flag
  5489. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  5490. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  5491. startSpecifier, specifierLen);
  5492. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  5493. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  5494. startSpecifier, specifierLen);
  5495. // Check the length modifier is valid with the given conversion specifier.
  5496. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  5497. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5498. diag::warn_format_nonsensical_length);
  5499. else if (!FS.hasStandardLengthModifier())
  5500. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  5501. else if (!FS.hasStandardLengthConversionCombination())
  5502. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5503. diag::warn_format_non_standard_conversion_spec);
  5504. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  5505. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  5506. // The remaining checks depend on the data arguments.
  5507. if (HasVAListArg)
  5508. return true;
  5509. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  5510. return false;
  5511. const Expr *Arg = getDataArg(argIndex);
  5512. if (!Arg)
  5513. return true;
  5514. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  5515. }
  5516. static bool requiresParensToAddCast(const Expr *E) {
  5517. // FIXME: We should have a general way to reason about operator
  5518. // precedence and whether parens are actually needed here.
  5519. // Take care of a few common cases where they aren't.
  5520. const Expr *Inside = E->IgnoreImpCasts();
  5521. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  5522. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  5523. switch (Inside->getStmtClass()) {
  5524. case Stmt::ArraySubscriptExprClass:
  5525. case Stmt::CallExprClass:
  5526. case Stmt::CharacterLiteralClass:
  5527. case Stmt::CXXBoolLiteralExprClass:
  5528. case Stmt::DeclRefExprClass:
  5529. case Stmt::FloatingLiteralClass:
  5530. case Stmt::IntegerLiteralClass:
  5531. case Stmt::MemberExprClass:
  5532. case Stmt::ObjCArrayLiteralClass:
  5533. case Stmt::ObjCBoolLiteralExprClass:
  5534. case Stmt::ObjCBoxedExprClass:
  5535. case Stmt::ObjCDictionaryLiteralClass:
  5536. case Stmt::ObjCEncodeExprClass:
  5537. case Stmt::ObjCIvarRefExprClass:
  5538. case Stmt::ObjCMessageExprClass:
  5539. case Stmt::ObjCPropertyRefExprClass:
  5540. case Stmt::ObjCStringLiteralClass:
  5541. case Stmt::ObjCSubscriptRefExprClass:
  5542. case Stmt::ParenExprClass:
  5543. case Stmt::StringLiteralClass:
  5544. case Stmt::UnaryOperatorClass:
  5545. return false;
  5546. default:
  5547. return true;
  5548. }
  5549. }
  5550. static std::pair<QualType, StringRef>
  5551. shouldNotPrintDirectly(const ASTContext &Context,
  5552. QualType IntendedTy,
  5553. const Expr *E) {
  5554. // Use a 'while' to peel off layers of typedefs.
  5555. QualType TyTy = IntendedTy;
  5556. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  5557. StringRef Name = UserTy->getDecl()->getName();
  5558. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  5559. .Case("CFIndex", Context.getNSIntegerType())
  5560. .Case("NSInteger", Context.getNSIntegerType())
  5561. .Case("NSUInteger", Context.getNSUIntegerType())
  5562. .Case("SInt32", Context.IntTy)
  5563. .Case("UInt32", Context.UnsignedIntTy)
  5564. .Default(QualType());
  5565. if (!CastTy.isNull())
  5566. return std::make_pair(CastTy, Name);
  5567. TyTy = UserTy->desugar();
  5568. }
  5569. // Strip parens if necessary.
  5570. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  5571. return shouldNotPrintDirectly(Context,
  5572. PE->getSubExpr()->getType(),
  5573. PE->getSubExpr());
  5574. // If this is a conditional expression, then its result type is constructed
  5575. // via usual arithmetic conversions and thus there might be no necessary
  5576. // typedef sugar there. Recurse to operands to check for NSInteger &
  5577. // Co. usage condition.
  5578. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  5579. QualType TrueTy, FalseTy;
  5580. StringRef TrueName, FalseName;
  5581. std::tie(TrueTy, TrueName) =
  5582. shouldNotPrintDirectly(Context,
  5583. CO->getTrueExpr()->getType(),
  5584. CO->getTrueExpr());
  5585. std::tie(FalseTy, FalseName) =
  5586. shouldNotPrintDirectly(Context,
  5587. CO->getFalseExpr()->getType(),
  5588. CO->getFalseExpr());
  5589. if (TrueTy == FalseTy)
  5590. return std::make_pair(TrueTy, TrueName);
  5591. else if (TrueTy.isNull())
  5592. return std::make_pair(FalseTy, FalseName);
  5593. else if (FalseTy.isNull())
  5594. return std::make_pair(TrueTy, TrueName);
  5595. }
  5596. return std::make_pair(QualType(), StringRef());
  5597. }
  5598. bool
  5599. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  5600. const char *StartSpecifier,
  5601. unsigned SpecifierLen,
  5602. const Expr *E) {
  5603. using namespace analyze_format_string;
  5604. using namespace analyze_printf;
  5605. // Now type check the data expression that matches the
  5606. // format specifier.
  5607. const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
  5608. if (!AT.isValid())
  5609. return true;
  5610. QualType ExprTy = E->getType();
  5611. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  5612. ExprTy = TET->getUnderlyingExpr()->getType();
  5613. }
  5614. analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
  5615. if (match == analyze_printf::ArgType::Match) {
  5616. return true;
  5617. }
  5618. // Look through argument promotions for our error message's reported type.
  5619. // This includes the integral and floating promotions, but excludes array
  5620. // and function pointer decay; seeing that an argument intended to be a
  5621. // string has type 'char [6]' is probably more confusing than 'char *'.
  5622. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  5623. if (ICE->getCastKind() == CK_IntegralCast ||
  5624. ICE->getCastKind() == CK_FloatingCast) {
  5625. E = ICE->getSubExpr();
  5626. ExprTy = E->getType();
  5627. // Check if we didn't match because of an implicit cast from a 'char'
  5628. // or 'short' to an 'int'. This is done because printf is a varargs
  5629. // function.
  5630. if (ICE->getType() == S.Context.IntTy ||
  5631. ICE->getType() == S.Context.UnsignedIntTy) {
  5632. // All further checking is done on the subexpression.
  5633. if (AT.matchesType(S.Context, ExprTy))
  5634. return true;
  5635. }
  5636. }
  5637. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  5638. // Special case for 'a', which has type 'int' in C.
  5639. // Note, however, that we do /not/ want to treat multibyte constants like
  5640. // 'MooV' as characters! This form is deprecated but still exists.
  5641. if (ExprTy == S.Context.IntTy)
  5642. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  5643. ExprTy = S.Context.CharTy;
  5644. }
  5645. // Look through enums to their underlying type.
  5646. bool IsEnum = false;
  5647. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  5648. ExprTy = EnumTy->getDecl()->getIntegerType();
  5649. IsEnum = true;
  5650. }
  5651. // %C in an Objective-C context prints a unichar, not a wchar_t.
  5652. // If the argument is an integer of some kind, believe the %C and suggest
  5653. // a cast instead of changing the conversion specifier.
  5654. QualType IntendedTy = ExprTy;
  5655. if (isObjCContext() &&
  5656. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  5657. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  5658. !ExprTy->isCharType()) {
  5659. // 'unichar' is defined as a typedef of unsigned short, but we should
  5660. // prefer using the typedef if it is visible.
  5661. IntendedTy = S.Context.UnsignedShortTy;
  5662. // While we are here, check if the value is an IntegerLiteral that happens
  5663. // to be within the valid range.
  5664. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  5665. const llvm::APInt &V = IL->getValue();
  5666. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  5667. return true;
  5668. }
  5669. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
  5670. Sema::LookupOrdinaryName);
  5671. if (S.LookupName(Result, S.getCurScope())) {
  5672. NamedDecl *ND = Result.getFoundDecl();
  5673. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  5674. if (TD->getUnderlyingType() == IntendedTy)
  5675. IntendedTy = S.Context.getTypedefType(TD);
  5676. }
  5677. }
  5678. }
  5679. // Special-case some of Darwin's platform-independence types by suggesting
  5680. // casts to primitive types that are known to be large enough.
  5681. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  5682. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  5683. QualType CastTy;
  5684. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  5685. if (!CastTy.isNull()) {
  5686. IntendedTy = CastTy;
  5687. ShouldNotPrintDirectly = true;
  5688. }
  5689. }
  5690. // We may be able to offer a FixItHint if it is a supported type.
  5691. PrintfSpecifier fixedFS = FS;
  5692. bool success =
  5693. fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
  5694. if (success) {
  5695. // Get the fix string from the fixed format specifier
  5696. SmallString<16> buf;
  5697. llvm::raw_svector_ostream os(buf);
  5698. fixedFS.toString(os);
  5699. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  5700. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  5701. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  5702. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  5703. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  5704. }
  5705. // In this case, the specifier is wrong and should be changed to match
  5706. // the argument.
  5707. EmitFormatDiagnostic(S.PDiag(diag)
  5708. << AT.getRepresentativeTypeName(S.Context)
  5709. << IntendedTy << IsEnum << E->getSourceRange(),
  5710. E->getLocStart(),
  5711. /*IsStringLocation*/ false, SpecRange,
  5712. FixItHint::CreateReplacement(SpecRange, os.str()));
  5713. } else {
  5714. // The canonical type for formatting this value is different from the
  5715. // actual type of the expression. (This occurs, for example, with Darwin's
  5716. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  5717. // should be printed as 'long' for 64-bit compatibility.)
  5718. // Rather than emitting a normal format/argument mismatch, we want to
  5719. // add a cast to the recommended type (and correct the format string
  5720. // if necessary).
  5721. SmallString<16> CastBuf;
  5722. llvm::raw_svector_ostream CastFix(CastBuf);
  5723. CastFix << "(";
  5724. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  5725. CastFix << ")";
  5726. SmallVector<FixItHint,4> Hints;
  5727. if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
  5728. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  5729. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  5730. // If there's already a cast present, just replace it.
  5731. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  5732. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  5733. } else if (!requiresParensToAddCast(E)) {
  5734. // If the expression has high enough precedence,
  5735. // just write the C-style cast.
  5736. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  5737. CastFix.str()));
  5738. } else {
  5739. // Otherwise, add parens around the expression as well as the cast.
  5740. CastFix << "(";
  5741. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  5742. CastFix.str()));
  5743. SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
  5744. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  5745. }
  5746. if (ShouldNotPrintDirectly) {
  5747. // The expression has a type that should not be printed directly.
  5748. // We extract the name from the typedef because we don't want to show
  5749. // the underlying type in the diagnostic.
  5750. StringRef Name;
  5751. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  5752. Name = TypedefTy->getDecl()->getName();
  5753. else
  5754. Name = CastTyName;
  5755. EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
  5756. << Name << IntendedTy << IsEnum
  5757. << E->getSourceRange(),
  5758. E->getLocStart(), /*IsStringLocation=*/false,
  5759. SpecRange, Hints);
  5760. } else {
  5761. // In this case, the expression could be printed using a different
  5762. // specifier, but we've decided that the specifier is probably correct
  5763. // and we should cast instead. Just use the normal warning message.
  5764. EmitFormatDiagnostic(
  5765. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  5766. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  5767. << E->getSourceRange(),
  5768. E->getLocStart(), /*IsStringLocation*/false,
  5769. SpecRange, Hints);
  5770. }
  5771. }
  5772. } else {
  5773. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  5774. SpecifierLen);
  5775. // Since the warning for passing non-POD types to variadic functions
  5776. // was deferred until now, we emit a warning for non-POD
  5777. // arguments here.
  5778. switch (S.isValidVarArgType(ExprTy)) {
  5779. case Sema::VAK_Valid:
  5780. case Sema::VAK_ValidInCXX11: {
  5781. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  5782. if (match == analyze_printf::ArgType::NoMatchPedantic) {
  5783. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  5784. }
  5785. EmitFormatDiagnostic(
  5786. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  5787. << IsEnum << CSR << E->getSourceRange(),
  5788. E->getLocStart(), /*IsStringLocation*/ false, CSR);
  5789. break;
  5790. }
  5791. case Sema::VAK_Undefined:
  5792. case Sema::VAK_MSVCUndefined:
  5793. EmitFormatDiagnostic(
  5794. S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  5795. << S.getLangOpts().CPlusPlus11
  5796. << ExprTy
  5797. << CallType
  5798. << AT.getRepresentativeTypeName(S.Context)
  5799. << CSR
  5800. << E->getSourceRange(),
  5801. E->getLocStart(), /*IsStringLocation*/false, CSR);
  5802. checkForCStrMembers(AT, E);
  5803. break;
  5804. case Sema::VAK_Invalid:
  5805. if (ExprTy->isObjCObjectType())
  5806. EmitFormatDiagnostic(
  5807. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  5808. << S.getLangOpts().CPlusPlus11
  5809. << ExprTy
  5810. << CallType
  5811. << AT.getRepresentativeTypeName(S.Context)
  5812. << CSR
  5813. << E->getSourceRange(),
  5814. E->getLocStart(), /*IsStringLocation*/false, CSR);
  5815. else
  5816. // FIXME: If this is an initializer list, suggest removing the braces
  5817. // or inserting a cast to the target type.
  5818. S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
  5819. << isa<InitListExpr>(E) << ExprTy << CallType
  5820. << AT.getRepresentativeTypeName(S.Context)
  5821. << E->getSourceRange();
  5822. break;
  5823. }
  5824. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  5825. "format string specifier index out of range");
  5826. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  5827. }
  5828. return true;
  5829. }
  5830. //===--- CHECK: Scanf format string checking ------------------------------===//
  5831. namespace {
  5832. class CheckScanfHandler : public CheckFormatHandler {
  5833. public:
  5834. CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
  5835. const Expr *origFormatExpr, Sema::FormatStringType type,
  5836. unsigned firstDataArg, unsigned numDataArgs,
  5837. const char *beg, bool hasVAListArg,
  5838. ArrayRef<const Expr *> Args, unsigned formatIdx,
  5839. bool inFunctionCall, Sema::VariadicCallType CallType,
  5840. llvm::SmallBitVector &CheckedVarArgs,
  5841. UncoveredArgHandler &UncoveredArg)
  5842. : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
  5843. numDataArgs, beg, hasVAListArg, Args, formatIdx,
  5844. inFunctionCall, CallType, CheckedVarArgs,
  5845. UncoveredArg) {}
  5846. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  5847. const char *startSpecifier,
  5848. unsigned specifierLen) override;
  5849. bool HandleInvalidScanfConversionSpecifier(
  5850. const analyze_scanf::ScanfSpecifier &FS,
  5851. const char *startSpecifier,
  5852. unsigned specifierLen) override;
  5853. void HandleIncompleteScanList(const char *start, const char *end) override;
  5854. };
  5855. } // namespace
  5856. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  5857. const char *end) {
  5858. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  5859. getLocationOfByte(end), /*IsStringLocation*/true,
  5860. getSpecifierRange(start, end - start));
  5861. }
  5862. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  5863. const analyze_scanf::ScanfSpecifier &FS,
  5864. const char *startSpecifier,
  5865. unsigned specifierLen) {
  5866. const analyze_scanf::ScanfConversionSpecifier &CS =
  5867. FS.getConversionSpecifier();
  5868. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  5869. getLocationOfByte(CS.getStart()),
  5870. startSpecifier, specifierLen,
  5871. CS.getStart(), CS.getLength());
  5872. }
  5873. bool CheckScanfHandler::HandleScanfSpecifier(
  5874. const analyze_scanf::ScanfSpecifier &FS,
  5875. const char *startSpecifier,
  5876. unsigned specifierLen) {
  5877. using namespace analyze_scanf;
  5878. using namespace analyze_format_string;
  5879. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  5880. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  5881. // be used to decide if we are using positional arguments consistently.
  5882. if (FS.consumesDataArgument()) {
  5883. if (atFirstArg) {
  5884. atFirstArg = false;
  5885. usesPositionalArgs = FS.usesPositionalArg();
  5886. }
  5887. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  5888. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  5889. startSpecifier, specifierLen);
  5890. return false;
  5891. }
  5892. }
  5893. // Check if the field with is non-zero.
  5894. const OptionalAmount &Amt = FS.getFieldWidth();
  5895. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  5896. if (Amt.getConstantAmount() == 0) {
  5897. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  5898. Amt.getConstantLength());
  5899. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  5900. getLocationOfByte(Amt.getStart()),
  5901. /*IsStringLocation*/true, R,
  5902. FixItHint::CreateRemoval(R));
  5903. }
  5904. }
  5905. if (!FS.consumesDataArgument()) {
  5906. // FIXME: Technically specifying a precision or field width here
  5907. // makes no sense. Worth issuing a warning at some point.
  5908. return true;
  5909. }
  5910. // Consume the argument.
  5911. unsigned argIndex = FS.getArgIndex();
  5912. if (argIndex < NumDataArgs) {
  5913. // The check to see if the argIndex is valid will come later.
  5914. // We set the bit here because we may exit early from this
  5915. // function if we encounter some other error.
  5916. CoveredArgs.set(argIndex);
  5917. }
  5918. // Check the length modifier is valid with the given conversion specifier.
  5919. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  5920. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5921. diag::warn_format_nonsensical_length);
  5922. else if (!FS.hasStandardLengthModifier())
  5923. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  5924. else if (!FS.hasStandardLengthConversionCombination())
  5925. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  5926. diag::warn_format_non_standard_conversion_spec);
  5927. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  5928. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  5929. // The remaining checks depend on the data arguments.
  5930. if (HasVAListArg)
  5931. return true;
  5932. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  5933. return false;
  5934. // Check that the argument type matches the format specifier.
  5935. const Expr *Ex = getDataArg(argIndex);
  5936. if (!Ex)
  5937. return true;
  5938. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  5939. if (!AT.isValid()) {
  5940. return true;
  5941. }
  5942. analyze_format_string::ArgType::MatchKind match =
  5943. AT.matchesType(S.Context, Ex->getType());
  5944. if (match == analyze_format_string::ArgType::Match) {
  5945. return true;
  5946. }
  5947. ScanfSpecifier fixedFS = FS;
  5948. bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  5949. S.getLangOpts(), S.Context);
  5950. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  5951. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  5952. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  5953. }
  5954. if (success) {
  5955. // Get the fix string from the fixed format specifier.
  5956. SmallString<128> buf;
  5957. llvm::raw_svector_ostream os(buf);
  5958. fixedFS.toString(os);
  5959. EmitFormatDiagnostic(
  5960. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
  5961. << Ex->getType() << false << Ex->getSourceRange(),
  5962. Ex->getLocStart(),
  5963. /*IsStringLocation*/ false,
  5964. getSpecifierRange(startSpecifier, specifierLen),
  5965. FixItHint::CreateReplacement(
  5966. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  5967. } else {
  5968. EmitFormatDiagnostic(S.PDiag(diag)
  5969. << AT.getRepresentativeTypeName(S.Context)
  5970. << Ex->getType() << false << Ex->getSourceRange(),
  5971. Ex->getLocStart(),
  5972. /*IsStringLocation*/ false,
  5973. getSpecifierRange(startSpecifier, specifierLen));
  5974. }
  5975. return true;
  5976. }
  5977. static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
  5978. const Expr *OrigFormatExpr,
  5979. ArrayRef<const Expr *> Args,
  5980. bool HasVAListArg, unsigned format_idx,
  5981. unsigned firstDataArg,
  5982. Sema::FormatStringType Type,
  5983. bool inFunctionCall,
  5984. Sema::VariadicCallType CallType,
  5985. llvm::SmallBitVector &CheckedVarArgs,
  5986. UncoveredArgHandler &UncoveredArg) {
  5987. // CHECK: is the format string a wide literal?
  5988. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  5989. CheckFormatHandler::EmitFormatDiagnostic(
  5990. S, inFunctionCall, Args[format_idx],
  5991. S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  5992. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  5993. return;
  5994. }
  5995. // Str - The format string. NOTE: this is NOT null-terminated!
  5996. StringRef StrRef = FExpr->getString();
  5997. const char *Str = StrRef.data();
  5998. // Account for cases where the string literal is truncated in a declaration.
  5999. const ConstantArrayType *T =
  6000. S.Context.getAsConstantArrayType(FExpr->getType());
  6001. assert(T && "String literal not of constant array type!");
  6002. size_t TypeSize = T->getSize().getZExtValue();
  6003. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  6004. const unsigned numDataArgs = Args.size() - firstDataArg;
  6005. // Emit a warning if the string literal is truncated and does not contain an
  6006. // embedded null character.
  6007. if (TypeSize <= StrRef.size() &&
  6008. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  6009. CheckFormatHandler::EmitFormatDiagnostic(
  6010. S, inFunctionCall, Args[format_idx],
  6011. S.PDiag(diag::warn_printf_format_string_not_null_terminated),
  6012. FExpr->getLocStart(),
  6013. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  6014. return;
  6015. }
  6016. // CHECK: empty format string?
  6017. if (StrLen == 0 && numDataArgs > 0) {
  6018. CheckFormatHandler::EmitFormatDiagnostic(
  6019. S, inFunctionCall, Args[format_idx],
  6020. S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  6021. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  6022. return;
  6023. }
  6024. if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
  6025. Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
  6026. Type == Sema::FST_OSTrace) {
  6027. CheckPrintfHandler H(
  6028. S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
  6029. (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
  6030. HasVAListArg, Args, format_idx, inFunctionCall, CallType,
  6031. CheckedVarArgs, UncoveredArg);
  6032. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  6033. S.getLangOpts(),
  6034. S.Context.getTargetInfo(),
  6035. Type == Sema::FST_FreeBSDKPrintf))
  6036. H.DoneProcessing();
  6037. } else if (Type == Sema::FST_Scanf) {
  6038. CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
  6039. numDataArgs, Str, HasVAListArg, Args, format_idx,
  6040. inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
  6041. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  6042. S.getLangOpts(),
  6043. S.Context.getTargetInfo()))
  6044. H.DoneProcessing();
  6045. } // TODO: handle other formats
  6046. }
  6047. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  6048. // Str - The format string. NOTE: this is NOT null-terminated!
  6049. StringRef StrRef = FExpr->getString();
  6050. const char *Str = StrRef.data();
  6051. // Account for cases where the string literal is truncated in a declaration.
  6052. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  6053. assert(T && "String literal not of constant array type!");
  6054. size_t TypeSize = T->getSize().getZExtValue();
  6055. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  6056. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  6057. getLangOpts(),
  6058. Context.getTargetInfo());
  6059. }
  6060. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  6061. // Returns the related absolute value function that is larger, of 0 if one
  6062. // does not exist.
  6063. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  6064. switch (AbsFunction) {
  6065. default:
  6066. return 0;
  6067. case Builtin::BI__builtin_abs:
  6068. return Builtin::BI__builtin_labs;
  6069. case Builtin::BI__builtin_labs:
  6070. return Builtin::BI__builtin_llabs;
  6071. case Builtin::BI__builtin_llabs:
  6072. return 0;
  6073. case Builtin::BI__builtin_fabsf:
  6074. return Builtin::BI__builtin_fabs;
  6075. case Builtin::BI__builtin_fabs:
  6076. return Builtin::BI__builtin_fabsl;
  6077. case Builtin::BI__builtin_fabsl:
  6078. return 0;
  6079. case Builtin::BI__builtin_cabsf:
  6080. return Builtin::BI__builtin_cabs;
  6081. case Builtin::BI__builtin_cabs:
  6082. return Builtin::BI__builtin_cabsl;
  6083. case Builtin::BI__builtin_cabsl:
  6084. return 0;
  6085. case Builtin::BIabs:
  6086. return Builtin::BIlabs;
  6087. case Builtin::BIlabs:
  6088. return Builtin::BIllabs;
  6089. case Builtin::BIllabs:
  6090. return 0;
  6091. case Builtin::BIfabsf:
  6092. return Builtin::BIfabs;
  6093. case Builtin::BIfabs:
  6094. return Builtin::BIfabsl;
  6095. case Builtin::BIfabsl:
  6096. return 0;
  6097. case Builtin::BIcabsf:
  6098. return Builtin::BIcabs;
  6099. case Builtin::BIcabs:
  6100. return Builtin::BIcabsl;
  6101. case Builtin::BIcabsl:
  6102. return 0;
  6103. }
  6104. }
  6105. // Returns the argument type of the absolute value function.
  6106. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  6107. unsigned AbsType) {
  6108. if (AbsType == 0)
  6109. return QualType();
  6110. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  6111. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  6112. if (Error != ASTContext::GE_None)
  6113. return QualType();
  6114. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  6115. if (!FT)
  6116. return QualType();
  6117. if (FT->getNumParams() != 1)
  6118. return QualType();
  6119. return FT->getParamType(0);
  6120. }
  6121. // Returns the best absolute value function, or zero, based on type and
  6122. // current absolute value function.
  6123. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  6124. unsigned AbsFunctionKind) {
  6125. unsigned BestKind = 0;
  6126. uint64_t ArgSize = Context.getTypeSize(ArgType);
  6127. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  6128. Kind = getLargerAbsoluteValueFunction(Kind)) {
  6129. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  6130. if (Context.getTypeSize(ParamType) >= ArgSize) {
  6131. if (BestKind == 0)
  6132. BestKind = Kind;
  6133. else if (Context.hasSameType(ParamType, ArgType)) {
  6134. BestKind = Kind;
  6135. break;
  6136. }
  6137. }
  6138. }
  6139. return BestKind;
  6140. }
  6141. enum AbsoluteValueKind {
  6142. AVK_Integer,
  6143. AVK_Floating,
  6144. AVK_Complex
  6145. };
  6146. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  6147. if (T->isIntegralOrEnumerationType())
  6148. return AVK_Integer;
  6149. if (T->isRealFloatingType())
  6150. return AVK_Floating;
  6151. if (T->isAnyComplexType())
  6152. return AVK_Complex;
  6153. llvm_unreachable("Type not integer, floating, or complex");
  6154. }
  6155. // Changes the absolute value function to a different type. Preserves whether
  6156. // the function is a builtin.
  6157. static unsigned changeAbsFunction(unsigned AbsKind,
  6158. AbsoluteValueKind ValueKind) {
  6159. switch (ValueKind) {
  6160. case AVK_Integer:
  6161. switch (AbsKind) {
  6162. default:
  6163. return 0;
  6164. case Builtin::BI__builtin_fabsf:
  6165. case Builtin::BI__builtin_fabs:
  6166. case Builtin::BI__builtin_fabsl:
  6167. case Builtin::BI__builtin_cabsf:
  6168. case Builtin::BI__builtin_cabs:
  6169. case Builtin::BI__builtin_cabsl:
  6170. return Builtin::BI__builtin_abs;
  6171. case Builtin::BIfabsf:
  6172. case Builtin::BIfabs:
  6173. case Builtin::BIfabsl:
  6174. case Builtin::BIcabsf:
  6175. case Builtin::BIcabs:
  6176. case Builtin::BIcabsl:
  6177. return Builtin::BIabs;
  6178. }
  6179. case AVK_Floating:
  6180. switch (AbsKind) {
  6181. default:
  6182. return 0;
  6183. case Builtin::BI__builtin_abs:
  6184. case Builtin::BI__builtin_labs:
  6185. case Builtin::BI__builtin_llabs:
  6186. case Builtin::BI__builtin_cabsf:
  6187. case Builtin::BI__builtin_cabs:
  6188. case Builtin::BI__builtin_cabsl:
  6189. return Builtin::BI__builtin_fabsf;
  6190. case Builtin::BIabs:
  6191. case Builtin::BIlabs:
  6192. case Builtin::BIllabs:
  6193. case Builtin::BIcabsf:
  6194. case Builtin::BIcabs:
  6195. case Builtin::BIcabsl:
  6196. return Builtin::BIfabsf;
  6197. }
  6198. case AVK_Complex:
  6199. switch (AbsKind) {
  6200. default:
  6201. return 0;
  6202. case Builtin::BI__builtin_abs:
  6203. case Builtin::BI__builtin_labs:
  6204. case Builtin::BI__builtin_llabs:
  6205. case Builtin::BI__builtin_fabsf:
  6206. case Builtin::BI__builtin_fabs:
  6207. case Builtin::BI__builtin_fabsl:
  6208. return Builtin::BI__builtin_cabsf;
  6209. case Builtin::BIabs:
  6210. case Builtin::BIlabs:
  6211. case Builtin::BIllabs:
  6212. case Builtin::BIfabsf:
  6213. case Builtin::BIfabs:
  6214. case Builtin::BIfabsl:
  6215. return Builtin::BIcabsf;
  6216. }
  6217. }
  6218. llvm_unreachable("Unable to convert function");
  6219. }
  6220. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  6221. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  6222. if (!FnInfo)
  6223. return 0;
  6224. switch (FDecl->getBuiltinID()) {
  6225. default:
  6226. return 0;
  6227. case Builtin::BI__builtin_abs:
  6228. case Builtin::BI__builtin_fabs:
  6229. case Builtin::BI__builtin_fabsf:
  6230. case Builtin::BI__builtin_fabsl:
  6231. case Builtin::BI__builtin_labs:
  6232. case Builtin::BI__builtin_llabs:
  6233. case Builtin::BI__builtin_cabs:
  6234. case Builtin::BI__builtin_cabsf:
  6235. case Builtin::BI__builtin_cabsl:
  6236. case Builtin::BIabs:
  6237. case Builtin::BIlabs:
  6238. case Builtin::BIllabs:
  6239. case Builtin::BIfabs:
  6240. case Builtin::BIfabsf:
  6241. case Builtin::BIfabsl:
  6242. case Builtin::BIcabs:
  6243. case Builtin::BIcabsf:
  6244. case Builtin::BIcabsl:
  6245. return FDecl->getBuiltinID();
  6246. }
  6247. llvm_unreachable("Unknown Builtin type");
  6248. }
  6249. // If the replacement is valid, emit a note with replacement function.
  6250. // Additionally, suggest including the proper header if not already included.
  6251. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  6252. unsigned AbsKind, QualType ArgType) {
  6253. bool EmitHeaderHint = true;
  6254. const char *HeaderName = nullptr;
  6255. const char *FunctionName = nullptr;
  6256. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  6257. FunctionName = "std::abs";
  6258. if (ArgType->isIntegralOrEnumerationType()) {
  6259. HeaderName = "cstdlib";
  6260. } else if (ArgType->isRealFloatingType()) {
  6261. HeaderName = "cmath";
  6262. } else {
  6263. llvm_unreachable("Invalid Type");
  6264. }
  6265. // Lookup all std::abs
  6266. if (NamespaceDecl *Std = S.getStdNamespace()) {
  6267. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  6268. R.suppressDiagnostics();
  6269. S.LookupQualifiedName(R, Std);
  6270. for (const auto *I : R) {
  6271. const FunctionDecl *FDecl = nullptr;
  6272. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  6273. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  6274. } else {
  6275. FDecl = dyn_cast<FunctionDecl>(I);
  6276. }
  6277. if (!FDecl)
  6278. continue;
  6279. // Found std::abs(), check that they are the right ones.
  6280. if (FDecl->getNumParams() != 1)
  6281. continue;
  6282. // Check that the parameter type can handle the argument.
  6283. QualType ParamType = FDecl->getParamDecl(0)->getType();
  6284. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  6285. S.Context.getTypeSize(ArgType) <=
  6286. S.Context.getTypeSize(ParamType)) {
  6287. // Found a function, don't need the header hint.
  6288. EmitHeaderHint = false;
  6289. break;
  6290. }
  6291. }
  6292. }
  6293. } else {
  6294. FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
  6295. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  6296. if (HeaderName) {
  6297. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  6298. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  6299. R.suppressDiagnostics();
  6300. S.LookupName(R, S.getCurScope());
  6301. if (R.isSingleResult()) {
  6302. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  6303. if (FD && FD->getBuiltinID() == AbsKind) {
  6304. EmitHeaderHint = false;
  6305. } else {
  6306. return;
  6307. }
  6308. } else if (!R.empty()) {
  6309. return;
  6310. }
  6311. }
  6312. }
  6313. S.Diag(Loc, diag::note_replace_abs_function)
  6314. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  6315. if (!HeaderName)
  6316. return;
  6317. if (!EmitHeaderHint)
  6318. return;
  6319. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  6320. << FunctionName;
  6321. }
  6322. template <std::size_t StrLen>
  6323. static bool IsStdFunction(const FunctionDecl *FDecl,
  6324. const char (&Str)[StrLen]) {
  6325. if (!FDecl)
  6326. return false;
  6327. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
  6328. return false;
  6329. if (!FDecl->isInStdNamespace())
  6330. return false;
  6331. return true;
  6332. }
  6333. // Warn when using the wrong abs() function.
  6334. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  6335. const FunctionDecl *FDecl) {
  6336. if (Call->getNumArgs() != 1)
  6337. return;
  6338. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  6339. bool IsStdAbs = IsStdFunction(FDecl, "abs");
  6340. if (AbsKind == 0 && !IsStdAbs)
  6341. return;
  6342. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  6343. QualType ParamType = Call->getArg(0)->getType();
  6344. // Unsigned types cannot be negative. Suggest removing the absolute value
  6345. // function call.
  6346. if (ArgType->isUnsignedIntegerType()) {
  6347. const char *FunctionName =
  6348. IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
  6349. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  6350. Diag(Call->getExprLoc(), diag::note_remove_abs)
  6351. << FunctionName
  6352. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  6353. return;
  6354. }
  6355. // Taking the absolute value of a pointer is very suspicious, they probably
  6356. // wanted to index into an array, dereference a pointer, call a function, etc.
  6357. if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
  6358. unsigned DiagType = 0;
  6359. if (ArgType->isFunctionType())
  6360. DiagType = 1;
  6361. else if (ArgType->isArrayType())
  6362. DiagType = 2;
  6363. Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
  6364. return;
  6365. }
  6366. // std::abs has overloads which prevent most of the absolute value problems
  6367. // from occurring.
  6368. if (IsStdAbs)
  6369. return;
  6370. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  6371. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  6372. // The argument and parameter are the same kind. Check if they are the right
  6373. // size.
  6374. if (ArgValueKind == ParamValueKind) {
  6375. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  6376. return;
  6377. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  6378. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  6379. << FDecl << ArgType << ParamType;
  6380. if (NewAbsKind == 0)
  6381. return;
  6382. emitReplacement(*this, Call->getExprLoc(),
  6383. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  6384. return;
  6385. }
  6386. // ArgValueKind != ParamValueKind
  6387. // The wrong type of absolute value function was used. Attempt to find the
  6388. // proper one.
  6389. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  6390. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  6391. if (NewAbsKind == 0)
  6392. return;
  6393. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  6394. << FDecl << ParamValueKind << ArgValueKind;
  6395. emitReplacement(*this, Call->getExprLoc(),
  6396. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  6397. }
  6398. //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
  6399. void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
  6400. const FunctionDecl *FDecl) {
  6401. if (!Call || !FDecl) return;
  6402. // Ignore template specializations and macros.
  6403. if (inTemplateInstantiation()) return;
  6404. if (Call->getExprLoc().isMacroID()) return;
  6405. // Only care about the one template argument, two function parameter std::max
  6406. if (Call->getNumArgs() != 2) return;
  6407. if (!IsStdFunction(FDecl, "max")) return;
  6408. const auto * ArgList = FDecl->getTemplateSpecializationArgs();
  6409. if (!ArgList) return;
  6410. if (ArgList->size() != 1) return;
  6411. // Check that template type argument is unsigned integer.
  6412. const auto& TA = ArgList->get(0);
  6413. if (TA.getKind() != TemplateArgument::Type) return;
  6414. QualType ArgType = TA.getAsType();
  6415. if (!ArgType->isUnsignedIntegerType()) return;
  6416. // See if either argument is a literal zero.
  6417. auto IsLiteralZeroArg = [](const Expr* E) -> bool {
  6418. const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  6419. if (!MTE) return false;
  6420. const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
  6421. if (!Num) return false;
  6422. if (Num->getValue() != 0) return false;
  6423. return true;
  6424. };
  6425. const Expr *FirstArg = Call->getArg(0);
  6426. const Expr *SecondArg = Call->getArg(1);
  6427. const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
  6428. const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
  6429. // Only warn when exactly one argument is zero.
  6430. if (IsFirstArgZero == IsSecondArgZero) return;
  6431. SourceRange FirstRange = FirstArg->getSourceRange();
  6432. SourceRange SecondRange = SecondArg->getSourceRange();
  6433. SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
  6434. Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
  6435. << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
  6436. // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
  6437. SourceRange RemovalRange;
  6438. if (IsFirstArgZero) {
  6439. RemovalRange = SourceRange(FirstRange.getBegin(),
  6440. SecondRange.getBegin().getLocWithOffset(-1));
  6441. } else {
  6442. RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
  6443. SecondRange.getEnd());
  6444. }
  6445. Diag(Call->getExprLoc(), diag::note_remove_max_call)
  6446. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
  6447. << FixItHint::CreateRemoval(RemovalRange);
  6448. }
  6449. //===--- CHECK: Standard memory functions ---------------------------------===//
  6450. /// \brief Takes the expression passed to the size_t parameter of functions
  6451. /// such as memcmp, strncat, etc and warns if it's a comparison.
  6452. ///
  6453. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  6454. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  6455. IdentifierInfo *FnName,
  6456. SourceLocation FnLoc,
  6457. SourceLocation RParenLoc) {
  6458. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  6459. if (!Size)
  6460. return false;
  6461. // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
  6462. if (!Size->isComparisonOp() && !Size->isLogicalOp())
  6463. return false;
  6464. SourceRange SizeRange = Size->getSourceRange();
  6465. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  6466. << SizeRange << FnName;
  6467. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  6468. << FnName << FixItHint::CreateInsertion(
  6469. S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
  6470. << FixItHint::CreateRemoval(RParenLoc);
  6471. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  6472. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  6473. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  6474. ")");
  6475. return true;
  6476. }
  6477. /// \brief Determine whether the given type is or contains a dynamic class type
  6478. /// (e.g., whether it has a vtable).
  6479. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  6480. bool &IsContained) {
  6481. // Look through array types while ignoring qualifiers.
  6482. const Type *Ty = T->getBaseElementTypeUnsafe();
  6483. IsContained = false;
  6484. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  6485. RD = RD ? RD->getDefinition() : nullptr;
  6486. if (!RD || RD->isInvalidDecl())
  6487. return nullptr;
  6488. if (RD->isDynamicClass())
  6489. return RD;
  6490. // Check all the fields. If any bases were dynamic, the class is dynamic.
  6491. // It's impossible for a class to transitively contain itself by value, so
  6492. // infinite recursion is impossible.
  6493. for (auto *FD : RD->fields()) {
  6494. bool SubContained;
  6495. if (const CXXRecordDecl *ContainedRD =
  6496. getContainedDynamicClass(FD->getType(), SubContained)) {
  6497. IsContained = true;
  6498. return ContainedRD;
  6499. }
  6500. }
  6501. return nullptr;
  6502. }
  6503. /// \brief If E is a sizeof expression, returns its argument expression,
  6504. /// otherwise returns NULL.
  6505. static const Expr *getSizeOfExprArg(const Expr *E) {
  6506. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  6507. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  6508. if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
  6509. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  6510. return nullptr;
  6511. }
  6512. /// \brief If E is a sizeof expression, returns its argument type.
  6513. static QualType getSizeOfArgType(const Expr *E) {
  6514. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  6515. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  6516. if (SizeOf->getKind() == UETT_SizeOf)
  6517. return SizeOf->getTypeOfArgument();
  6518. return QualType();
  6519. }
  6520. /// \brief Check for dangerous or invalid arguments to memset().
  6521. ///
  6522. /// This issues warnings on known problematic, dangerous or unspecified
  6523. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  6524. /// function calls.
  6525. ///
  6526. /// \param Call The call expression to diagnose.
  6527. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  6528. unsigned BId,
  6529. IdentifierInfo *FnName) {
  6530. assert(BId != 0);
  6531. // It is possible to have a non-standard definition of memset. Validate
  6532. // we have enough arguments, and if not, abort further checking.
  6533. unsigned ExpectedNumArgs =
  6534. (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
  6535. if (Call->getNumArgs() < ExpectedNumArgs)
  6536. return;
  6537. unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
  6538. BId == Builtin::BIstrndup ? 1 : 2);
  6539. unsigned LenArg =
  6540. (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
  6541. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  6542. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  6543. Call->getLocStart(), Call->getRParenLoc()))
  6544. return;
  6545. // We have special checking when the length is a sizeof expression.
  6546. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  6547. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  6548. llvm::FoldingSetNodeID SizeOfArgID;
  6549. // Although widely used, 'bzero' is not a standard function. Be more strict
  6550. // with the argument types before allowing diagnostics and only allow the
  6551. // form bzero(ptr, sizeof(...)).
  6552. QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  6553. if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
  6554. return;
  6555. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  6556. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  6557. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  6558. QualType DestTy = Dest->getType();
  6559. QualType PointeeTy;
  6560. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  6561. PointeeTy = DestPtrTy->getPointeeType();
  6562. // Never warn about void type pointers. This can be used to suppress
  6563. // false positives.
  6564. if (PointeeTy->isVoidType())
  6565. continue;
  6566. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  6567. // actually comparing the expressions for equality. Because computing the
  6568. // expression IDs can be expensive, we only do this if the diagnostic is
  6569. // enabled.
  6570. if (SizeOfArg &&
  6571. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  6572. SizeOfArg->getExprLoc())) {
  6573. // We only compute IDs for expressions if the warning is enabled, and
  6574. // cache the sizeof arg's ID.
  6575. if (SizeOfArgID == llvm::FoldingSetNodeID())
  6576. SizeOfArg->Profile(SizeOfArgID, Context, true);
  6577. llvm::FoldingSetNodeID DestID;
  6578. Dest->Profile(DestID, Context, true);
  6579. if (DestID == SizeOfArgID) {
  6580. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  6581. // over sizeof(src) as well.
  6582. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  6583. StringRef ReadableName = FnName->getName();
  6584. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  6585. if (UnaryOp->getOpcode() == UO_AddrOf)
  6586. ActionIdx = 1; // If its an address-of operator, just remove it.
  6587. if (!PointeeTy->isIncompleteType() &&
  6588. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  6589. ActionIdx = 2; // If the pointee's size is sizeof(char),
  6590. // suggest an explicit length.
  6591. // If the function is defined as a builtin macro, do not show macro
  6592. // expansion.
  6593. SourceLocation SL = SizeOfArg->getExprLoc();
  6594. SourceRange DSR = Dest->getSourceRange();
  6595. SourceRange SSR = SizeOfArg->getSourceRange();
  6596. SourceManager &SM = getSourceManager();
  6597. if (SM.isMacroArgExpansion(SL)) {
  6598. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  6599. SL = SM.getSpellingLoc(SL);
  6600. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  6601. SM.getSpellingLoc(DSR.getEnd()));
  6602. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  6603. SM.getSpellingLoc(SSR.getEnd()));
  6604. }
  6605. DiagRuntimeBehavior(SL, SizeOfArg,
  6606. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  6607. << ReadableName
  6608. << PointeeTy
  6609. << DestTy
  6610. << DSR
  6611. << SSR);
  6612. DiagRuntimeBehavior(SL, SizeOfArg,
  6613. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  6614. << ActionIdx
  6615. << SSR);
  6616. break;
  6617. }
  6618. }
  6619. // Also check for cases where the sizeof argument is the exact same
  6620. // type as the memory argument, and where it points to a user-defined
  6621. // record type.
  6622. if (SizeOfArgTy != QualType()) {
  6623. if (PointeeTy->isRecordType() &&
  6624. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  6625. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  6626. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  6627. << FnName << SizeOfArgTy << ArgIdx
  6628. << PointeeTy << Dest->getSourceRange()
  6629. << LenExpr->getSourceRange());
  6630. break;
  6631. }
  6632. }
  6633. } else if (DestTy->isArrayType()) {
  6634. PointeeTy = DestTy;
  6635. }
  6636. if (PointeeTy == QualType())
  6637. continue;
  6638. // Always complain about dynamic classes.
  6639. bool IsContained;
  6640. if (const CXXRecordDecl *ContainedRD =
  6641. getContainedDynamicClass(PointeeTy, IsContained)) {
  6642. unsigned OperationType = 0;
  6643. // "overwritten" if we're warning about the destination for any call
  6644. // but memcmp; otherwise a verb appropriate to the call.
  6645. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  6646. if (BId == Builtin::BImemcpy)
  6647. OperationType = 1;
  6648. else if(BId == Builtin::BImemmove)
  6649. OperationType = 2;
  6650. else if (BId == Builtin::BImemcmp)
  6651. OperationType = 3;
  6652. }
  6653. DiagRuntimeBehavior(
  6654. Dest->getExprLoc(), Dest,
  6655. PDiag(diag::warn_dyn_class_memaccess)
  6656. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  6657. << FnName << IsContained << ContainedRD << OperationType
  6658. << Call->getCallee()->getSourceRange());
  6659. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  6660. BId != Builtin::BImemset)
  6661. DiagRuntimeBehavior(
  6662. Dest->getExprLoc(), Dest,
  6663. PDiag(diag::warn_arc_object_memaccess)
  6664. << ArgIdx << FnName << PointeeTy
  6665. << Call->getCallee()->getSourceRange());
  6666. else
  6667. continue;
  6668. DiagRuntimeBehavior(
  6669. Dest->getExprLoc(), Dest,
  6670. PDiag(diag::note_bad_memaccess_silence)
  6671. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  6672. break;
  6673. }
  6674. }
  6675. // A little helper routine: ignore addition and subtraction of integer literals.
  6676. // This intentionally does not ignore all integer constant expressions because
  6677. // we don't want to remove sizeof().
  6678. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  6679. Ex = Ex->IgnoreParenCasts();
  6680. while (true) {
  6681. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  6682. if (!BO || !BO->isAdditiveOp())
  6683. break;
  6684. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  6685. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  6686. if (isa<IntegerLiteral>(RHS))
  6687. Ex = LHS;
  6688. else if (isa<IntegerLiteral>(LHS))
  6689. Ex = RHS;
  6690. else
  6691. break;
  6692. }
  6693. return Ex;
  6694. }
  6695. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  6696. ASTContext &Context) {
  6697. // Only handle constant-sized or VLAs, but not flexible members.
  6698. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  6699. // Only issue the FIXIT for arrays of size > 1.
  6700. if (CAT->getSize().getSExtValue() <= 1)
  6701. return false;
  6702. } else if (!Ty->isVariableArrayType()) {
  6703. return false;
  6704. }
  6705. return true;
  6706. }
  6707. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  6708. // be the size of the source, instead of the destination.
  6709. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  6710. IdentifierInfo *FnName) {
  6711. // Don't crash if the user has the wrong number of arguments
  6712. unsigned NumArgs = Call->getNumArgs();
  6713. if ((NumArgs != 3) && (NumArgs != 4))
  6714. return;
  6715. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  6716. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  6717. const Expr *CompareWithSrc = nullptr;
  6718. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  6719. Call->getLocStart(), Call->getRParenLoc()))
  6720. return;
  6721. // Look for 'strlcpy(dst, x, sizeof(x))'
  6722. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  6723. CompareWithSrc = Ex;
  6724. else {
  6725. // Look for 'strlcpy(dst, x, strlen(x))'
  6726. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  6727. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  6728. SizeCall->getNumArgs() == 1)
  6729. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  6730. }
  6731. }
  6732. if (!CompareWithSrc)
  6733. return;
  6734. // Determine if the argument to sizeof/strlen is equal to the source
  6735. // argument. In principle there's all kinds of things you could do
  6736. // here, for instance creating an == expression and evaluating it with
  6737. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  6738. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  6739. if (!SrcArgDRE)
  6740. return;
  6741. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  6742. if (!CompareWithSrcDRE ||
  6743. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  6744. return;
  6745. const Expr *OriginalSizeArg = Call->getArg(2);
  6746. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  6747. << OriginalSizeArg->getSourceRange() << FnName;
  6748. // Output a FIXIT hint if the destination is an array (rather than a
  6749. // pointer to an array). This could be enhanced to handle some
  6750. // pointers if we know the actual size, like if DstArg is 'array+2'
  6751. // we could say 'sizeof(array)-2'.
  6752. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  6753. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  6754. return;
  6755. SmallString<128> sizeString;
  6756. llvm::raw_svector_ostream OS(sizeString);
  6757. OS << "sizeof(";
  6758. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  6759. OS << ")";
  6760. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  6761. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  6762. OS.str());
  6763. }
  6764. /// Check if two expressions refer to the same declaration.
  6765. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  6766. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  6767. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  6768. return D1->getDecl() == D2->getDecl();
  6769. return false;
  6770. }
  6771. static const Expr *getStrlenExprArg(const Expr *E) {
  6772. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  6773. const FunctionDecl *FD = CE->getDirectCallee();
  6774. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  6775. return nullptr;
  6776. return CE->getArg(0)->IgnoreParenCasts();
  6777. }
  6778. return nullptr;
  6779. }
  6780. // Warn on anti-patterns as the 'size' argument to strncat.
  6781. // The correct size argument should look like following:
  6782. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  6783. void Sema::CheckStrncatArguments(const CallExpr *CE,
  6784. IdentifierInfo *FnName) {
  6785. // Don't crash if the user has the wrong number of arguments.
  6786. if (CE->getNumArgs() < 3)
  6787. return;
  6788. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  6789. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  6790. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  6791. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
  6792. CE->getRParenLoc()))
  6793. return;
  6794. // Identify common expressions, which are wrongly used as the size argument
  6795. // to strncat and may lead to buffer overflows.
  6796. unsigned PatternType = 0;
  6797. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  6798. // - sizeof(dst)
  6799. if (referToTheSameDecl(SizeOfArg, DstArg))
  6800. PatternType = 1;
  6801. // - sizeof(src)
  6802. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  6803. PatternType = 2;
  6804. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  6805. if (BE->getOpcode() == BO_Sub) {
  6806. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  6807. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  6808. // - sizeof(dst) - strlen(dst)
  6809. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  6810. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  6811. PatternType = 1;
  6812. // - sizeof(src) - (anything)
  6813. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  6814. PatternType = 2;
  6815. }
  6816. }
  6817. if (PatternType == 0)
  6818. return;
  6819. // Generate the diagnostic.
  6820. SourceLocation SL = LenArg->getLocStart();
  6821. SourceRange SR = LenArg->getSourceRange();
  6822. SourceManager &SM = getSourceManager();
  6823. // If the function is defined as a builtin macro, do not show macro expansion.
  6824. if (SM.isMacroArgExpansion(SL)) {
  6825. SL = SM.getSpellingLoc(SL);
  6826. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  6827. SM.getSpellingLoc(SR.getEnd()));
  6828. }
  6829. // Check if the destination is an array (rather than a pointer to an array).
  6830. QualType DstTy = DstArg->getType();
  6831. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  6832. Context);
  6833. if (!isKnownSizeArray) {
  6834. if (PatternType == 1)
  6835. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  6836. else
  6837. Diag(SL, diag::warn_strncat_src_size) << SR;
  6838. return;
  6839. }
  6840. if (PatternType == 1)
  6841. Diag(SL, diag::warn_strncat_large_size) << SR;
  6842. else
  6843. Diag(SL, diag::warn_strncat_src_size) << SR;
  6844. SmallString<128> sizeString;
  6845. llvm::raw_svector_ostream OS(sizeString);
  6846. OS << "sizeof(";
  6847. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  6848. OS << ") - ";
  6849. OS << "strlen(";
  6850. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  6851. OS << ") - 1";
  6852. Diag(SL, diag::note_strncat_wrong_size)
  6853. << FixItHint::CreateReplacement(SR, OS.str());
  6854. }
  6855. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  6856. static const Expr *EvalVal(const Expr *E,
  6857. SmallVectorImpl<const DeclRefExpr *> &refVars,
  6858. const Decl *ParentDecl);
  6859. static const Expr *EvalAddr(const Expr *E,
  6860. SmallVectorImpl<const DeclRefExpr *> &refVars,
  6861. const Decl *ParentDecl);
  6862. /// CheckReturnStackAddr - Check if a return statement returns the address
  6863. /// of a stack variable.
  6864. static void
  6865. CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
  6866. SourceLocation ReturnLoc) {
  6867. const Expr *stackE = nullptr;
  6868. SmallVector<const DeclRefExpr *, 8> refVars;
  6869. // Perform checking for returned stack addresses, local blocks,
  6870. // label addresses or references to temporaries.
  6871. if (lhsType->isPointerType() ||
  6872. (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  6873. stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
  6874. } else if (lhsType->isReferenceType()) {
  6875. stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
  6876. }
  6877. if (!stackE)
  6878. return; // Nothing suspicious was found.
  6879. // Parameters are initialized in the calling scope, so taking the address
  6880. // of a parameter reference doesn't need a warning.
  6881. for (auto *DRE : refVars)
  6882. if (isa<ParmVarDecl>(DRE->getDecl()))
  6883. return;
  6884. SourceLocation diagLoc;
  6885. SourceRange diagRange;
  6886. if (refVars.empty()) {
  6887. diagLoc = stackE->getLocStart();
  6888. diagRange = stackE->getSourceRange();
  6889. } else {
  6890. // We followed through a reference variable. 'stackE' contains the
  6891. // problematic expression but we will warn at the return statement pointing
  6892. // at the reference variable. We will later display the "trail" of
  6893. // reference variables using notes.
  6894. diagLoc = refVars[0]->getLocStart();
  6895. diagRange = refVars[0]->getSourceRange();
  6896. }
  6897. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
  6898. // address of local var
  6899. S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
  6900. << DR->getDecl()->getDeclName() << diagRange;
  6901. } else if (isa<BlockExpr>(stackE)) { // local block.
  6902. S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  6903. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  6904. S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  6905. } else { // local temporary.
  6906. // If there is an LValue->RValue conversion, then the value of the
  6907. // reference type is used, not the reference.
  6908. if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
  6909. if (ICE->getCastKind() == CK_LValueToRValue) {
  6910. return;
  6911. }
  6912. }
  6913. S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
  6914. << lhsType->isReferenceType() << diagRange;
  6915. }
  6916. // Display the "trail" of reference variables that we followed until we
  6917. // found the problematic expression using notes.
  6918. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  6919. const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  6920. // If this var binds to another reference var, show the range of the next
  6921. // var, otherwise the var binds to the problematic expression, in which case
  6922. // show the range of the expression.
  6923. SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
  6924. : stackE->getSourceRange();
  6925. S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  6926. << VD->getDeclName() << range;
  6927. }
  6928. }
  6929. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  6930. /// check if the expression in a return statement evaluates to an address
  6931. /// to a location on the stack, a local block, an address of a label, or a
  6932. /// reference to local temporary. The recursion is used to traverse the
  6933. /// AST of the return expression, with recursion backtracking when we
  6934. /// encounter a subexpression that (1) clearly does not lead to one of the
  6935. /// above problematic expressions (2) is something we cannot determine leads to
  6936. /// a problematic expression based on such local checking.
  6937. ///
  6938. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  6939. /// the expression that they point to. Such variables are added to the
  6940. /// 'refVars' vector so that we know what the reference variable "trail" was.
  6941. ///
  6942. /// EvalAddr processes expressions that are pointers that are used as
  6943. /// references (and not L-values). EvalVal handles all other values.
  6944. /// At the base case of the recursion is a check for the above problematic
  6945. /// expressions.
  6946. ///
  6947. /// This implementation handles:
  6948. ///
  6949. /// * pointer-to-pointer casts
  6950. /// * implicit conversions from array references to pointers
  6951. /// * taking the address of fields
  6952. /// * arbitrary interplay between "&" and "*" operators
  6953. /// * pointer arithmetic from an address of a stack variable
  6954. /// * taking the address of an array element where the array is on the stack
  6955. static const Expr *EvalAddr(const Expr *E,
  6956. SmallVectorImpl<const DeclRefExpr *> &refVars,
  6957. const Decl *ParentDecl) {
  6958. if (E->isTypeDependent())
  6959. return nullptr;
  6960. // We should only be called for evaluating pointer expressions.
  6961. assert((E->getType()->isAnyPointerType() ||
  6962. E->getType()->isBlockPointerType() ||
  6963. E->getType()->isObjCQualifiedIdType()) &&
  6964. "EvalAddr only works on pointers");
  6965. E = E->IgnoreParens();
  6966. // Our "symbolic interpreter" is just a dispatch off the currently
  6967. // viewed AST node. We then recursively traverse the AST by calling
  6968. // EvalAddr and EvalVal appropriately.
  6969. switch (E->getStmtClass()) {
  6970. case Stmt::DeclRefExprClass: {
  6971. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  6972. // If we leave the immediate function, the lifetime isn't about to end.
  6973. if (DR->refersToEnclosingVariableOrCapture())
  6974. return nullptr;
  6975. if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  6976. // If this is a reference variable, follow through to the expression that
  6977. // it points to.
  6978. if (V->hasLocalStorage() &&
  6979. V->getType()->isReferenceType() && V->hasInit()) {
  6980. // Add the reference variable to the "trail".
  6981. refVars.push_back(DR);
  6982. return EvalAddr(V->getInit(), refVars, ParentDecl);
  6983. }
  6984. return nullptr;
  6985. }
  6986. case Stmt::UnaryOperatorClass: {
  6987. // The only unary operator that make sense to handle here
  6988. // is AddrOf. All others don't make sense as pointers.
  6989. const UnaryOperator *U = cast<UnaryOperator>(E);
  6990. if (U->getOpcode() == UO_AddrOf)
  6991. return EvalVal(U->getSubExpr(), refVars, ParentDecl);
  6992. return nullptr;
  6993. }
  6994. case Stmt::BinaryOperatorClass: {
  6995. // Handle pointer arithmetic. All other binary operators are not valid
  6996. // in this context.
  6997. const BinaryOperator *B = cast<BinaryOperator>(E);
  6998. BinaryOperatorKind op = B->getOpcode();
  6999. if (op != BO_Add && op != BO_Sub)
  7000. return nullptr;
  7001. const Expr *Base = B->getLHS();
  7002. // Determine which argument is the real pointer base. It could be
  7003. // the RHS argument instead of the LHS.
  7004. if (!Base->getType()->isPointerType())
  7005. Base = B->getRHS();
  7006. assert(Base->getType()->isPointerType());
  7007. return EvalAddr(Base, refVars, ParentDecl);
  7008. }
  7009. // For conditional operators we need to see if either the LHS or RHS are
  7010. // valid DeclRefExpr*s. If one of them is valid, we return it.
  7011. case Stmt::ConditionalOperatorClass: {
  7012. const ConditionalOperator *C = cast<ConditionalOperator>(E);
  7013. // Handle the GNU extension for missing LHS.
  7014. // FIXME: That isn't a ConditionalOperator, so doesn't get here.
  7015. if (const Expr *LHSExpr = C->getLHS()) {
  7016. // In C++, we can have a throw-expression, which has 'void' type.
  7017. if (!LHSExpr->getType()->isVoidType())
  7018. if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
  7019. return LHS;
  7020. }
  7021. // In C++, we can have a throw-expression, which has 'void' type.
  7022. if (C->getRHS()->getType()->isVoidType())
  7023. return nullptr;
  7024. return EvalAddr(C->getRHS(), refVars, ParentDecl);
  7025. }
  7026. case Stmt::BlockExprClass:
  7027. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  7028. return E; // local block.
  7029. return nullptr;
  7030. case Stmt::AddrLabelExprClass:
  7031. return E; // address of label.
  7032. case Stmt::ExprWithCleanupsClass:
  7033. return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  7034. ParentDecl);
  7035. // For casts, we need to handle conversions from arrays to
  7036. // pointer values, and pointer-to-pointer conversions.
  7037. case Stmt::ImplicitCastExprClass:
  7038. case Stmt::CStyleCastExprClass:
  7039. case Stmt::CXXFunctionalCastExprClass:
  7040. case Stmt::ObjCBridgedCastExprClass:
  7041. case Stmt::CXXStaticCastExprClass:
  7042. case Stmt::CXXDynamicCastExprClass:
  7043. case Stmt::CXXConstCastExprClass:
  7044. case Stmt::CXXReinterpretCastExprClass: {
  7045. const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  7046. switch (cast<CastExpr>(E)->getCastKind()) {
  7047. case CK_LValueToRValue:
  7048. case CK_NoOp:
  7049. case CK_BaseToDerived:
  7050. case CK_DerivedToBase:
  7051. case CK_UncheckedDerivedToBase:
  7052. case CK_Dynamic:
  7053. case CK_CPointerToObjCPointerCast:
  7054. case CK_BlockPointerToObjCPointerCast:
  7055. case CK_AnyPointerToBlockPointerCast:
  7056. return EvalAddr(SubExpr, refVars, ParentDecl);
  7057. case CK_ArrayToPointerDecay:
  7058. return EvalVal(SubExpr, refVars, ParentDecl);
  7059. case CK_BitCast:
  7060. if (SubExpr->getType()->isAnyPointerType() ||
  7061. SubExpr->getType()->isBlockPointerType() ||
  7062. SubExpr->getType()->isObjCQualifiedIdType())
  7063. return EvalAddr(SubExpr, refVars, ParentDecl);
  7064. else
  7065. return nullptr;
  7066. default:
  7067. return nullptr;
  7068. }
  7069. }
  7070. case Stmt::MaterializeTemporaryExprClass:
  7071. if (const Expr *Result =
  7072. EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  7073. refVars, ParentDecl))
  7074. return Result;
  7075. return E;
  7076. // Everything else: we simply don't reason about them.
  7077. default:
  7078. return nullptr;
  7079. }
  7080. }
  7081. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  7082. /// See the comments for EvalAddr for more details.
  7083. static const Expr *EvalVal(const Expr *E,
  7084. SmallVectorImpl<const DeclRefExpr *> &refVars,
  7085. const Decl *ParentDecl) {
  7086. do {
  7087. // We should only be called for evaluating non-pointer expressions, or
  7088. // expressions with a pointer type that are not used as references but
  7089. // instead
  7090. // are l-values (e.g., DeclRefExpr with a pointer type).
  7091. // Our "symbolic interpreter" is just a dispatch off the currently
  7092. // viewed AST node. We then recursively traverse the AST by calling
  7093. // EvalAddr and EvalVal appropriately.
  7094. E = E->IgnoreParens();
  7095. switch (E->getStmtClass()) {
  7096. case Stmt::ImplicitCastExprClass: {
  7097. const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  7098. if (IE->getValueKind() == VK_LValue) {
  7099. E = IE->getSubExpr();
  7100. continue;
  7101. }
  7102. return nullptr;
  7103. }
  7104. case Stmt::ExprWithCleanupsClass:
  7105. return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  7106. ParentDecl);
  7107. case Stmt::DeclRefExprClass: {
  7108. // When we hit a DeclRefExpr we are looking at code that refers to a
  7109. // variable's name. If it's not a reference variable we check if it has
  7110. // local storage within the function, and if so, return the expression.
  7111. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  7112. // If we leave the immediate function, the lifetime isn't about to end.
  7113. if (DR->refersToEnclosingVariableOrCapture())
  7114. return nullptr;
  7115. if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
  7116. // Check if it refers to itself, e.g. "int& i = i;".
  7117. if (V == ParentDecl)
  7118. return DR;
  7119. if (V->hasLocalStorage()) {
  7120. if (!V->getType()->isReferenceType())
  7121. return DR;
  7122. // Reference variable, follow through to the expression that
  7123. // it points to.
  7124. if (V->hasInit()) {
  7125. // Add the reference variable to the "trail".
  7126. refVars.push_back(DR);
  7127. return EvalVal(V->getInit(), refVars, V);
  7128. }
  7129. }
  7130. }
  7131. return nullptr;
  7132. }
  7133. case Stmt::UnaryOperatorClass: {
  7134. // The only unary operator that make sense to handle here
  7135. // is Deref. All others don't resolve to a "name." This includes
  7136. // handling all sorts of rvalues passed to a unary operator.
  7137. const UnaryOperator *U = cast<UnaryOperator>(E);
  7138. if (U->getOpcode() == UO_Deref)
  7139. return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
  7140. return nullptr;
  7141. }
  7142. case Stmt::ArraySubscriptExprClass: {
  7143. // Array subscripts are potential references to data on the stack. We
  7144. // retrieve the DeclRefExpr* for the array variable if it indeed
  7145. // has local storage.
  7146. const auto *ASE = cast<ArraySubscriptExpr>(E);
  7147. if (ASE->isTypeDependent())
  7148. return nullptr;
  7149. return EvalAddr(ASE->getBase(), refVars, ParentDecl);
  7150. }
  7151. case Stmt::OMPArraySectionExprClass: {
  7152. return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
  7153. ParentDecl);
  7154. }
  7155. case Stmt::ConditionalOperatorClass: {
  7156. // For conditional operators we need to see if either the LHS or RHS are
  7157. // non-NULL Expr's. If one is non-NULL, we return it.
  7158. const ConditionalOperator *C = cast<ConditionalOperator>(E);
  7159. // Handle the GNU extension for missing LHS.
  7160. if (const Expr *LHSExpr = C->getLHS()) {
  7161. // In C++, we can have a throw-expression, which has 'void' type.
  7162. if (!LHSExpr->getType()->isVoidType())
  7163. if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
  7164. return LHS;
  7165. }
  7166. // In C++, we can have a throw-expression, which has 'void' type.
  7167. if (C->getRHS()->getType()->isVoidType())
  7168. return nullptr;
  7169. return EvalVal(C->getRHS(), refVars, ParentDecl);
  7170. }
  7171. // Accesses to members are potential references to data on the stack.
  7172. case Stmt::MemberExprClass: {
  7173. const MemberExpr *M = cast<MemberExpr>(E);
  7174. // Check for indirect access. We only want direct field accesses.
  7175. if (M->isArrow())
  7176. return nullptr;
  7177. // Check whether the member type is itself a reference, in which case
  7178. // we're not going to refer to the member, but to what the member refers
  7179. // to.
  7180. if (M->getMemberDecl()->getType()->isReferenceType())
  7181. return nullptr;
  7182. return EvalVal(M->getBase(), refVars, ParentDecl);
  7183. }
  7184. case Stmt::MaterializeTemporaryExprClass:
  7185. if (const Expr *Result =
  7186. EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  7187. refVars, ParentDecl))
  7188. return Result;
  7189. return E;
  7190. default:
  7191. // Check that we don't return or take the address of a reference to a
  7192. // temporary. This is only useful in C++.
  7193. if (!E->isTypeDependent() && E->isRValue())
  7194. return E;
  7195. // Everything else: we simply don't reason about them.
  7196. return nullptr;
  7197. }
  7198. } while (true);
  7199. }
  7200. void
  7201. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  7202. SourceLocation ReturnLoc,
  7203. bool isObjCMethod,
  7204. const AttrVec *Attrs,
  7205. const FunctionDecl *FD) {
  7206. CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
  7207. // Check if the return value is null but should not be.
  7208. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  7209. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  7210. CheckNonNullExpr(*this, RetValExp))
  7211. Diag(ReturnLoc, diag::warn_null_ret)
  7212. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  7213. // C++11 [basic.stc.dynamic.allocation]p4:
  7214. // If an allocation function declared with a non-throwing
  7215. // exception-specification fails to allocate storage, it shall return
  7216. // a null pointer. Any other allocation function that fails to allocate
  7217. // storage shall indicate failure only by throwing an exception [...]
  7218. if (FD) {
  7219. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  7220. if (Op == OO_New || Op == OO_Array_New) {
  7221. const FunctionProtoType *Proto
  7222. = FD->getType()->castAs<FunctionProtoType>();
  7223. if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
  7224. CheckNonNullExpr(*this, RetValExp))
  7225. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  7226. << FD << getLangOpts().CPlusPlus11;
  7227. }
  7228. }
  7229. }
  7230. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  7231. /// Check for comparisons of floating point operands using != and ==.
  7232. /// Issue a warning if these are no self-comparisons, as they are not likely
  7233. /// to do what the programmer intended.
  7234. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  7235. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  7236. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  7237. // Special case: check for x == x (which is OK).
  7238. // Do not emit warnings for such cases.
  7239. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  7240. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  7241. if (DRL->getDecl() == DRR->getDecl())
  7242. return;
  7243. // Special case: check for comparisons against literals that can be exactly
  7244. // represented by APFloat. In such cases, do not emit a warning. This
  7245. // is a heuristic: often comparison against such literals are used to
  7246. // detect if a value in a variable has not changed. This clearly can
  7247. // lead to false negatives.
  7248. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  7249. if (FLL->isExact())
  7250. return;
  7251. } else
  7252. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  7253. if (FLR->isExact())
  7254. return;
  7255. // Check for comparisons with builtin types.
  7256. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  7257. if (CL->getBuiltinCallee())
  7258. return;
  7259. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  7260. if (CR->getBuiltinCallee())
  7261. return;
  7262. // Emit the diagnostic.
  7263. Diag(Loc, diag::warn_floatingpoint_eq)
  7264. << LHS->getSourceRange() << RHS->getSourceRange();
  7265. }
  7266. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  7267. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  7268. namespace {
  7269. /// Structure recording the 'active' range of an integer-valued
  7270. /// expression.
  7271. struct IntRange {
  7272. /// The number of bits active in the int.
  7273. unsigned Width;
  7274. /// True if the int is known not to have negative values.
  7275. bool NonNegative;
  7276. IntRange(unsigned Width, bool NonNegative)
  7277. : Width(Width), NonNegative(NonNegative) {}
  7278. /// Returns the range of the bool type.
  7279. static IntRange forBoolType() {
  7280. return IntRange(1, true);
  7281. }
  7282. /// Returns the range of an opaque value of the given integral type.
  7283. static IntRange forValueOfType(ASTContext &C, QualType T) {
  7284. return forValueOfCanonicalType(C,
  7285. T->getCanonicalTypeInternal().getTypePtr());
  7286. }
  7287. /// Returns the range of an opaque value of a canonical integral type.
  7288. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  7289. assert(T->isCanonicalUnqualified());
  7290. if (const VectorType *VT = dyn_cast<VectorType>(T))
  7291. T = VT->getElementType().getTypePtr();
  7292. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  7293. T = CT->getElementType().getTypePtr();
  7294. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  7295. T = AT->getValueType().getTypePtr();
  7296. if (!C.getLangOpts().CPlusPlus) {
  7297. // For enum types in C code, use the underlying datatype.
  7298. if (const EnumType *ET = dyn_cast<EnumType>(T))
  7299. T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
  7300. } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  7301. // For enum types in C++, use the known bit width of the enumerators.
  7302. EnumDecl *Enum = ET->getDecl();
  7303. // In C++11, enums can have a fixed underlying type. Use this type to
  7304. // compute the range.
  7305. if (Enum->isFixed()) {
  7306. return IntRange(C.getIntWidth(QualType(T, 0)),
  7307. !ET->isSignedIntegerOrEnumerationType());
  7308. }
  7309. unsigned NumPositive = Enum->getNumPositiveBits();
  7310. unsigned NumNegative = Enum->getNumNegativeBits();
  7311. if (NumNegative == 0)
  7312. return IntRange(NumPositive, true/*NonNegative*/);
  7313. else
  7314. return IntRange(std::max(NumPositive + 1, NumNegative),
  7315. false/*NonNegative*/);
  7316. }
  7317. const BuiltinType *BT = cast<BuiltinType>(T);
  7318. assert(BT->isInteger());
  7319. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  7320. }
  7321. /// Returns the "target" range of a canonical integral type, i.e.
  7322. /// the range of values expressible in the type.
  7323. ///
  7324. /// This matches forValueOfCanonicalType except that enums have the
  7325. /// full range of their type, not the range of their enumerators.
  7326. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  7327. assert(T->isCanonicalUnqualified());
  7328. if (const VectorType *VT = dyn_cast<VectorType>(T))
  7329. T = VT->getElementType().getTypePtr();
  7330. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  7331. T = CT->getElementType().getTypePtr();
  7332. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  7333. T = AT->getValueType().getTypePtr();
  7334. if (const EnumType *ET = dyn_cast<EnumType>(T))
  7335. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  7336. const BuiltinType *BT = cast<BuiltinType>(T);
  7337. assert(BT->isInteger());
  7338. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  7339. }
  7340. /// Returns the supremum of two ranges: i.e. their conservative merge.
  7341. static IntRange join(IntRange L, IntRange R) {
  7342. return IntRange(std::max(L.Width, R.Width),
  7343. L.NonNegative && R.NonNegative);
  7344. }
  7345. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  7346. static IntRange meet(IntRange L, IntRange R) {
  7347. return IntRange(std::min(L.Width, R.Width),
  7348. L.NonNegative || R.NonNegative);
  7349. }
  7350. };
  7351. } // namespace
  7352. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  7353. unsigned MaxWidth) {
  7354. if (value.isSigned() && value.isNegative())
  7355. return IntRange(value.getMinSignedBits(), false);
  7356. if (value.getBitWidth() > MaxWidth)
  7357. value = value.trunc(MaxWidth);
  7358. // isNonNegative() just checks the sign bit without considering
  7359. // signedness.
  7360. return IntRange(value.getActiveBits(), true);
  7361. }
  7362. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  7363. unsigned MaxWidth) {
  7364. if (result.isInt())
  7365. return GetValueRange(C, result.getInt(), MaxWidth);
  7366. if (result.isVector()) {
  7367. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  7368. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  7369. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  7370. R = IntRange::join(R, El);
  7371. }
  7372. return R;
  7373. }
  7374. if (result.isComplexInt()) {
  7375. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  7376. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  7377. return IntRange::join(R, I);
  7378. }
  7379. // This can happen with lossless casts to intptr_t of "based" lvalues.
  7380. // Assume it might use arbitrary bits.
  7381. // FIXME: The only reason we need to pass the type in here is to get
  7382. // the sign right on this one case. It would be nice if APValue
  7383. // preserved this.
  7384. assert(result.isLValue() || result.isAddrLabelDiff());
  7385. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  7386. }
  7387. static QualType GetExprType(const Expr *E) {
  7388. QualType Ty = E->getType();
  7389. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  7390. Ty = AtomicRHS->getValueType();
  7391. return Ty;
  7392. }
  7393. /// Pseudo-evaluate the given integer expression, estimating the
  7394. /// range of values it might take.
  7395. ///
  7396. /// \param MaxWidth - the width to which the value will be truncated
  7397. static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
  7398. E = E->IgnoreParens();
  7399. // Try a full evaluation first.
  7400. Expr::EvalResult result;
  7401. if (E->EvaluateAsRValue(result, C))
  7402. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  7403. // I think we only want to look through implicit casts here; if the
  7404. // user has an explicit widening cast, we should treat the value as
  7405. // being of the new, wider type.
  7406. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
  7407. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  7408. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  7409. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  7410. bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
  7411. CE->getCastKind() == CK_BooleanToSignedIntegral;
  7412. // Assume that non-integer casts can span the full range of the type.
  7413. if (!isIntegerCast)
  7414. return OutputTypeRange;
  7415. IntRange SubRange
  7416. = GetExprRange(C, CE->getSubExpr(),
  7417. std::min(MaxWidth, OutputTypeRange.Width));
  7418. // Bail out if the subexpr's range is as wide as the cast type.
  7419. if (SubRange.Width >= OutputTypeRange.Width)
  7420. return OutputTypeRange;
  7421. // Otherwise, we take the smaller width, and we're non-negative if
  7422. // either the output type or the subexpr is.
  7423. return IntRange(SubRange.Width,
  7424. SubRange.NonNegative || OutputTypeRange.NonNegative);
  7425. }
  7426. if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
  7427. // If we can fold the condition, just take that operand.
  7428. bool CondResult;
  7429. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  7430. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  7431. : CO->getFalseExpr(),
  7432. MaxWidth);
  7433. // Otherwise, conservatively merge.
  7434. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  7435. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  7436. return IntRange::join(L, R);
  7437. }
  7438. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  7439. switch (BO->getOpcode()) {
  7440. case BO_Cmp:
  7441. llvm_unreachable("builtin <=> should have class type");
  7442. // Boolean-valued operations are single-bit and positive.
  7443. case BO_LAnd:
  7444. case BO_LOr:
  7445. case BO_LT:
  7446. case BO_GT:
  7447. case BO_LE:
  7448. case BO_GE:
  7449. case BO_EQ:
  7450. case BO_NE:
  7451. return IntRange::forBoolType();
  7452. // The type of the assignments is the type of the LHS, so the RHS
  7453. // is not necessarily the same type.
  7454. case BO_MulAssign:
  7455. case BO_DivAssign:
  7456. case BO_RemAssign:
  7457. case BO_AddAssign:
  7458. case BO_SubAssign:
  7459. case BO_XorAssign:
  7460. case BO_OrAssign:
  7461. // TODO: bitfields?
  7462. return IntRange::forValueOfType(C, GetExprType(E));
  7463. // Simple assignments just pass through the RHS, which will have
  7464. // been coerced to the LHS type.
  7465. case BO_Assign:
  7466. // TODO: bitfields?
  7467. return GetExprRange(C, BO->getRHS(), MaxWidth);
  7468. // Operations with opaque sources are black-listed.
  7469. case BO_PtrMemD:
  7470. case BO_PtrMemI:
  7471. return IntRange::forValueOfType(C, GetExprType(E));
  7472. // Bitwise-and uses the *infinum* of the two source ranges.
  7473. case BO_And:
  7474. case BO_AndAssign:
  7475. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  7476. GetExprRange(C, BO->getRHS(), MaxWidth));
  7477. // Left shift gets black-listed based on a judgement call.
  7478. case BO_Shl:
  7479. // ...except that we want to treat '1 << (blah)' as logically
  7480. // positive. It's an important idiom.
  7481. if (IntegerLiteral *I
  7482. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  7483. if (I->getValue() == 1) {
  7484. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  7485. return IntRange(R.Width, /*NonNegative*/ true);
  7486. }
  7487. }
  7488. LLVM_FALLTHROUGH;
  7489. case BO_ShlAssign:
  7490. return IntRange::forValueOfType(C, GetExprType(E));
  7491. // Right shift by a constant can narrow its left argument.
  7492. case BO_Shr:
  7493. case BO_ShrAssign: {
  7494. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  7495. // If the shift amount is a positive constant, drop the width by
  7496. // that much.
  7497. llvm::APSInt shift;
  7498. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  7499. shift.isNonNegative()) {
  7500. unsigned zext = shift.getZExtValue();
  7501. if (zext >= L.Width)
  7502. L.Width = (L.NonNegative ? 0 : 1);
  7503. else
  7504. L.Width -= zext;
  7505. }
  7506. return L;
  7507. }
  7508. // Comma acts as its right operand.
  7509. case BO_Comma:
  7510. return GetExprRange(C, BO->getRHS(), MaxWidth);
  7511. // Black-list pointer subtractions.
  7512. case BO_Sub:
  7513. if (BO->getLHS()->getType()->isPointerType())
  7514. return IntRange::forValueOfType(C, GetExprType(E));
  7515. break;
  7516. // The width of a division result is mostly determined by the size
  7517. // of the LHS.
  7518. case BO_Div: {
  7519. // Don't 'pre-truncate' the operands.
  7520. unsigned opWidth = C.getIntWidth(GetExprType(E));
  7521. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  7522. // If the divisor is constant, use that.
  7523. llvm::APSInt divisor;
  7524. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  7525. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  7526. if (log2 >= L.Width)
  7527. L.Width = (L.NonNegative ? 0 : 1);
  7528. else
  7529. L.Width = std::min(L.Width - log2, MaxWidth);
  7530. return L;
  7531. }
  7532. // Otherwise, just use the LHS's width.
  7533. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  7534. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  7535. }
  7536. // The result of a remainder can't be larger than the result of
  7537. // either side.
  7538. case BO_Rem: {
  7539. // Don't 'pre-truncate' the operands.
  7540. unsigned opWidth = C.getIntWidth(GetExprType(E));
  7541. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  7542. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  7543. IntRange meet = IntRange::meet(L, R);
  7544. meet.Width = std::min(meet.Width, MaxWidth);
  7545. return meet;
  7546. }
  7547. // The default behavior is okay for these.
  7548. case BO_Mul:
  7549. case BO_Add:
  7550. case BO_Xor:
  7551. case BO_Or:
  7552. break;
  7553. }
  7554. // The default case is to treat the operation as if it were closed
  7555. // on the narrowest type that encompasses both operands.
  7556. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  7557. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  7558. return IntRange::join(L, R);
  7559. }
  7560. if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
  7561. switch (UO->getOpcode()) {
  7562. // Boolean-valued operations are white-listed.
  7563. case UO_LNot:
  7564. return IntRange::forBoolType();
  7565. // Operations with opaque sources are black-listed.
  7566. case UO_Deref:
  7567. case UO_AddrOf: // should be impossible
  7568. return IntRange::forValueOfType(C, GetExprType(E));
  7569. default:
  7570. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  7571. }
  7572. }
  7573. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
  7574. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
  7575. if (const auto *BitField = E->getSourceBitField())
  7576. return IntRange(BitField->getBitWidthValue(C),
  7577. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  7578. return IntRange::forValueOfType(C, GetExprType(E));
  7579. }
  7580. static IntRange GetExprRange(ASTContext &C, const Expr *E) {
  7581. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
  7582. }
  7583. /// Checks whether the given value, which currently has the given
  7584. /// source semantics, has the same value when coerced through the
  7585. /// target semantics.
  7586. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  7587. const llvm::fltSemantics &Src,
  7588. const llvm::fltSemantics &Tgt) {
  7589. llvm::APFloat truncated = value;
  7590. bool ignored;
  7591. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  7592. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  7593. return truncated.bitwiseIsEqual(value);
  7594. }
  7595. /// Checks whether the given value, which currently has the given
  7596. /// source semantics, has the same value when coerced through the
  7597. /// target semantics.
  7598. ///
  7599. /// The value might be a vector of floats (or a complex number).
  7600. static bool IsSameFloatAfterCast(const APValue &value,
  7601. const llvm::fltSemantics &Src,
  7602. const llvm::fltSemantics &Tgt) {
  7603. if (value.isFloat())
  7604. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  7605. if (value.isVector()) {
  7606. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  7607. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  7608. return false;
  7609. return true;
  7610. }
  7611. assert(value.isComplexFloat());
  7612. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  7613. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  7614. }
  7615. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  7616. static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
  7617. // Suppress cases where we are comparing against an enum constant.
  7618. if (const DeclRefExpr *DR =
  7619. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  7620. if (isa<EnumConstantDecl>(DR->getDecl()))
  7621. return true;
  7622. // Suppress cases where the '0' value is expanded from a macro.
  7623. if (E->getLocStart().isMacroID())
  7624. return true;
  7625. return false;
  7626. }
  7627. static bool isKnownToHaveUnsignedValue(Expr *E) {
  7628. return E->getType()->isIntegerType() &&
  7629. (!E->getType()->isSignedIntegerType() ||
  7630. !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
  7631. }
  7632. namespace {
  7633. /// The promoted range of values of a type. In general this has the
  7634. /// following structure:
  7635. ///
  7636. /// |-----------| . . . |-----------|
  7637. /// ^ ^ ^ ^
  7638. /// Min HoleMin HoleMax Max
  7639. ///
  7640. /// ... where there is only a hole if a signed type is promoted to unsigned
  7641. /// (in which case Min and Max are the smallest and largest representable
  7642. /// values).
  7643. struct PromotedRange {
  7644. // Min, or HoleMax if there is a hole.
  7645. llvm::APSInt PromotedMin;
  7646. // Max, or HoleMin if there is a hole.
  7647. llvm::APSInt PromotedMax;
  7648. PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
  7649. if (R.Width == 0)
  7650. PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
  7651. else if (R.Width >= BitWidth && !Unsigned) {
  7652. // Promotion made the type *narrower*. This happens when promoting
  7653. // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
  7654. // Treat all values of 'signed int' as being in range for now.
  7655. PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
  7656. PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
  7657. } else {
  7658. PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
  7659. .extOrTrunc(BitWidth);
  7660. PromotedMin.setIsUnsigned(Unsigned);
  7661. PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
  7662. .extOrTrunc(BitWidth);
  7663. PromotedMax.setIsUnsigned(Unsigned);
  7664. }
  7665. }
  7666. // Determine whether this range is contiguous (has no hole).
  7667. bool isContiguous() const { return PromotedMin <= PromotedMax; }
  7668. // Where a constant value is within the range.
  7669. enum ComparisonResult {
  7670. LT = 0x1,
  7671. LE = 0x2,
  7672. GT = 0x4,
  7673. GE = 0x8,
  7674. EQ = 0x10,
  7675. NE = 0x20,
  7676. InRangeFlag = 0x40,
  7677. Less = LE | LT | NE,
  7678. Min = LE | InRangeFlag,
  7679. InRange = InRangeFlag,
  7680. Max = GE | InRangeFlag,
  7681. Greater = GE | GT | NE,
  7682. OnlyValue = LE | GE | EQ | InRangeFlag,
  7683. InHole = NE
  7684. };
  7685. ComparisonResult compare(const llvm::APSInt &Value) const {
  7686. assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
  7687. Value.isUnsigned() == PromotedMin.isUnsigned());
  7688. if (!isContiguous()) {
  7689. assert(Value.isUnsigned() && "discontiguous range for signed compare");
  7690. if (Value.isMinValue()) return Min;
  7691. if (Value.isMaxValue()) return Max;
  7692. if (Value >= PromotedMin) return InRange;
  7693. if (Value <= PromotedMax) return InRange;
  7694. return InHole;
  7695. }
  7696. switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
  7697. case -1: return Less;
  7698. case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
  7699. case 1:
  7700. switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
  7701. case -1: return InRange;
  7702. case 0: return Max;
  7703. case 1: return Greater;
  7704. }
  7705. }
  7706. llvm_unreachable("impossible compare result");
  7707. }
  7708. static llvm::Optional<StringRef>
  7709. constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
  7710. if (Op == BO_Cmp) {
  7711. ComparisonResult LTFlag = LT, GTFlag = GT;
  7712. if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
  7713. if (R & EQ) return StringRef("'std::strong_ordering::equal'");
  7714. if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
  7715. if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
  7716. return llvm::None;
  7717. }
  7718. ComparisonResult TrueFlag, FalseFlag;
  7719. if (Op == BO_EQ) {
  7720. TrueFlag = EQ;
  7721. FalseFlag = NE;
  7722. } else if (Op == BO_NE) {
  7723. TrueFlag = NE;
  7724. FalseFlag = EQ;
  7725. } else {
  7726. if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
  7727. TrueFlag = LT;
  7728. FalseFlag = GE;
  7729. } else {
  7730. TrueFlag = GT;
  7731. FalseFlag = LE;
  7732. }
  7733. if (Op == BO_GE || Op == BO_LE)
  7734. std::swap(TrueFlag, FalseFlag);
  7735. }
  7736. if (R & TrueFlag)
  7737. return StringRef("true");
  7738. if (R & FalseFlag)
  7739. return StringRef("false");
  7740. return llvm::None;
  7741. }
  7742. };
  7743. }
  7744. static bool HasEnumType(Expr *E) {
  7745. // Strip off implicit integral promotions.
  7746. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  7747. if (ICE->getCastKind() != CK_IntegralCast &&
  7748. ICE->getCastKind() != CK_NoOp)
  7749. break;
  7750. E = ICE->getSubExpr();
  7751. }
  7752. return E->getType()->isEnumeralType();
  7753. }
  7754. static int classifyConstantValue(Expr *Constant) {
  7755. // The values of this enumeration are used in the diagnostics
  7756. // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
  7757. enum ConstantValueKind {
  7758. Miscellaneous = 0,
  7759. LiteralTrue,
  7760. LiteralFalse
  7761. };
  7762. if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
  7763. return BL->getValue() ? ConstantValueKind::LiteralTrue
  7764. : ConstantValueKind::LiteralFalse;
  7765. return ConstantValueKind::Miscellaneous;
  7766. }
  7767. static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
  7768. Expr *Constant, Expr *Other,
  7769. const llvm::APSInt &Value,
  7770. bool RhsConstant) {
  7771. if (S.inTemplateInstantiation())
  7772. return false;
  7773. Expr *OriginalOther = Other;
  7774. Constant = Constant->IgnoreParenImpCasts();
  7775. Other = Other->IgnoreParenImpCasts();
  7776. // Suppress warnings on tautological comparisons between values of the same
  7777. // enumeration type. There are only two ways we could warn on this:
  7778. // - If the constant is outside the range of representable values of
  7779. // the enumeration. In such a case, we should warn about the cast
  7780. // to enumeration type, not about the comparison.
  7781. // - If the constant is the maximum / minimum in-range value. For an
  7782. // enumeratin type, such comparisons can be meaningful and useful.
  7783. if (Constant->getType()->isEnumeralType() &&
  7784. S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
  7785. return false;
  7786. // TODO: Investigate using GetExprRange() to get tighter bounds
  7787. // on the bit ranges.
  7788. QualType OtherT = Other->getType();
  7789. if (const auto *AT = OtherT->getAs<AtomicType>())
  7790. OtherT = AT->getValueType();
  7791. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  7792. // Whether we're treating Other as being a bool because of the form of
  7793. // expression despite it having another type (typically 'int' in C).
  7794. bool OtherIsBooleanDespiteType =
  7795. !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
  7796. if (OtherIsBooleanDespiteType)
  7797. OtherRange = IntRange::forBoolType();
  7798. // Determine the promoted range of the other type and see if a comparison of
  7799. // the constant against that range is tautological.
  7800. PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
  7801. Value.isUnsigned());
  7802. auto Cmp = OtherPromotedRange.compare(Value);
  7803. auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
  7804. if (!Result)
  7805. return false;
  7806. // Suppress the diagnostic for an in-range comparison if the constant comes
  7807. // from a macro or enumerator. We don't want to diagnose
  7808. //
  7809. // some_long_value <= INT_MAX
  7810. //
  7811. // when sizeof(int) == sizeof(long).
  7812. bool InRange = Cmp & PromotedRange::InRangeFlag;
  7813. if (InRange && IsEnumConstOrFromMacro(S, Constant))
  7814. return false;
  7815. // If this is a comparison to an enum constant, include that
  7816. // constant in the diagnostic.
  7817. const EnumConstantDecl *ED = nullptr;
  7818. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  7819. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  7820. // Should be enough for uint128 (39 decimal digits)
  7821. SmallString<64> PrettySourceValue;
  7822. llvm::raw_svector_ostream OS(PrettySourceValue);
  7823. if (ED)
  7824. OS << '\'' << *ED << "' (" << Value << ")";
  7825. else
  7826. OS << Value;
  7827. // FIXME: We use a somewhat different formatting for the in-range cases and
  7828. // cases involving boolean values for historical reasons. We should pick a
  7829. // consistent way of presenting these diagnostics.
  7830. if (!InRange || Other->isKnownToHaveBooleanValue()) {
  7831. S.DiagRuntimeBehavior(
  7832. E->getOperatorLoc(), E,
  7833. S.PDiag(!InRange ? diag::warn_out_of_range_compare
  7834. : diag::warn_tautological_bool_compare)
  7835. << OS.str() << classifyConstantValue(Constant)
  7836. << OtherT << OtherIsBooleanDespiteType << *Result
  7837. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  7838. } else {
  7839. unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
  7840. ? (HasEnumType(OriginalOther)
  7841. ? diag::warn_unsigned_enum_always_true_comparison
  7842. : diag::warn_unsigned_always_true_comparison)
  7843. : diag::warn_tautological_constant_compare;
  7844. S.Diag(E->getOperatorLoc(), Diag)
  7845. << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
  7846. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  7847. }
  7848. return true;
  7849. }
  7850. /// Analyze the operands of the given comparison. Implements the
  7851. /// fallback case from AnalyzeComparison.
  7852. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  7853. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  7854. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  7855. }
  7856. /// \brief Implements -Wsign-compare.
  7857. ///
  7858. /// \param E the binary operator to check for warnings
  7859. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  7860. // The type the comparison is being performed in.
  7861. QualType T = E->getLHS()->getType();
  7862. // Only analyze comparison operators where both sides have been converted to
  7863. // the same type.
  7864. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  7865. return AnalyzeImpConvsInComparison(S, E);
  7866. // Don't analyze value-dependent comparisons directly.
  7867. if (E->isValueDependent())
  7868. return AnalyzeImpConvsInComparison(S, E);
  7869. Expr *LHS = E->getLHS();
  7870. Expr *RHS = E->getRHS();
  7871. if (T->isIntegralType(S.Context)) {
  7872. llvm::APSInt RHSValue;
  7873. llvm::APSInt LHSValue;
  7874. bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
  7875. bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
  7876. // We don't care about expressions whose result is a constant.
  7877. if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  7878. return AnalyzeImpConvsInComparison(S, E);
  7879. // We only care about expressions where just one side is literal
  7880. if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
  7881. // Is the constant on the RHS or LHS?
  7882. const bool RhsConstant = IsRHSIntegralLiteral;
  7883. Expr *Const = RhsConstant ? RHS : LHS;
  7884. Expr *Other = RhsConstant ? LHS : RHS;
  7885. const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
  7886. // Check whether an integer constant comparison results in a value
  7887. // of 'true' or 'false'.
  7888. if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
  7889. return AnalyzeImpConvsInComparison(S, E);
  7890. }
  7891. }
  7892. if (!T->hasUnsignedIntegerRepresentation()) {
  7893. // We don't do anything special if this isn't an unsigned integral
  7894. // comparison: we're only interested in integral comparisons, and
  7895. // signed comparisons only happen in cases we don't care to warn about.
  7896. return AnalyzeImpConvsInComparison(S, E);
  7897. }
  7898. LHS = LHS->IgnoreParenImpCasts();
  7899. RHS = RHS->IgnoreParenImpCasts();
  7900. if (!S.getLangOpts().CPlusPlus) {
  7901. // Avoid warning about comparison of integers with different signs when
  7902. // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
  7903. // the type of `E`.
  7904. if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
  7905. LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  7906. if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
  7907. RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
  7908. }
  7909. // Check to see if one of the (unmodified) operands is of different
  7910. // signedness.
  7911. Expr *signedOperand, *unsignedOperand;
  7912. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  7913. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  7914. "unsigned comparison between two signed integer expressions?");
  7915. signedOperand = LHS;
  7916. unsignedOperand = RHS;
  7917. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  7918. signedOperand = RHS;
  7919. unsignedOperand = LHS;
  7920. } else {
  7921. return AnalyzeImpConvsInComparison(S, E);
  7922. }
  7923. // Otherwise, calculate the effective range of the signed operand.
  7924. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  7925. // Go ahead and analyze implicit conversions in the operands. Note
  7926. // that we skip the implicit conversions on both sides.
  7927. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  7928. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  7929. // If the signed range is non-negative, -Wsign-compare won't fire.
  7930. if (signedRange.NonNegative)
  7931. return;
  7932. // For (in)equality comparisons, if the unsigned operand is a
  7933. // constant which cannot collide with a overflowed signed operand,
  7934. // then reinterpreting the signed operand as unsigned will not
  7935. // change the result of the comparison.
  7936. if (E->isEqualityOp()) {
  7937. unsigned comparisonWidth = S.Context.getIntWidth(T);
  7938. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  7939. // We should never be unable to prove that the unsigned operand is
  7940. // non-negative.
  7941. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  7942. if (unsignedRange.Width < comparisonWidth)
  7943. return;
  7944. }
  7945. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  7946. S.PDiag(diag::warn_mixed_sign_comparison)
  7947. << LHS->getType() << RHS->getType()
  7948. << LHS->getSourceRange() << RHS->getSourceRange());
  7949. }
  7950. /// Analyzes an attempt to assign the given value to a bitfield.
  7951. ///
  7952. /// Returns true if there was something fishy about the attempt.
  7953. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  7954. SourceLocation InitLoc) {
  7955. assert(Bitfield->isBitField());
  7956. if (Bitfield->isInvalidDecl())
  7957. return false;
  7958. // White-list bool bitfields.
  7959. QualType BitfieldType = Bitfield->getType();
  7960. if (BitfieldType->isBooleanType())
  7961. return false;
  7962. if (BitfieldType->isEnumeralType()) {
  7963. EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
  7964. // If the underlying enum type was not explicitly specified as an unsigned
  7965. // type and the enum contain only positive values, MSVC++ will cause an
  7966. // inconsistency by storing this as a signed type.
  7967. if (S.getLangOpts().CPlusPlus11 &&
  7968. !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
  7969. BitfieldEnumDecl->getNumPositiveBits() > 0 &&
  7970. BitfieldEnumDecl->getNumNegativeBits() == 0) {
  7971. S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
  7972. << BitfieldEnumDecl->getNameAsString();
  7973. }
  7974. }
  7975. if (Bitfield->getType()->isBooleanType())
  7976. return false;
  7977. // Ignore value- or type-dependent expressions.
  7978. if (Bitfield->getBitWidth()->isValueDependent() ||
  7979. Bitfield->getBitWidth()->isTypeDependent() ||
  7980. Init->isValueDependent() ||
  7981. Init->isTypeDependent())
  7982. return false;
  7983. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  7984. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  7985. llvm::APSInt Value;
  7986. if (!OriginalInit->EvaluateAsInt(Value, S.Context,
  7987. Expr::SE_AllowSideEffects)) {
  7988. // The RHS is not constant. If the RHS has an enum type, make sure the
  7989. // bitfield is wide enough to hold all the values of the enum without
  7990. // truncation.
  7991. if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
  7992. EnumDecl *ED = EnumTy->getDecl();
  7993. bool SignedBitfield = BitfieldType->isSignedIntegerType();
  7994. // Enum types are implicitly signed on Windows, so check if there are any
  7995. // negative enumerators to see if the enum was intended to be signed or
  7996. // not.
  7997. bool SignedEnum = ED->getNumNegativeBits() > 0;
  7998. // Check for surprising sign changes when assigning enum values to a
  7999. // bitfield of different signedness. If the bitfield is signed and we
  8000. // have exactly the right number of bits to store this unsigned enum,
  8001. // suggest changing the enum to an unsigned type. This typically happens
  8002. // on Windows where unfixed enums always use an underlying type of 'int'.
  8003. unsigned DiagID = 0;
  8004. if (SignedEnum && !SignedBitfield) {
  8005. DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
  8006. } else if (SignedBitfield && !SignedEnum &&
  8007. ED->getNumPositiveBits() == FieldWidth) {
  8008. DiagID = diag::warn_signed_bitfield_enum_conversion;
  8009. }
  8010. if (DiagID) {
  8011. S.Diag(InitLoc, DiagID) << Bitfield << ED;
  8012. TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
  8013. SourceRange TypeRange =
  8014. TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
  8015. S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
  8016. << SignedEnum << TypeRange;
  8017. }
  8018. // Compute the required bitwidth. If the enum has negative values, we need
  8019. // one more bit than the normal number of positive bits to represent the
  8020. // sign bit.
  8021. unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
  8022. ED->getNumNegativeBits())
  8023. : ED->getNumPositiveBits();
  8024. // Check the bitwidth.
  8025. if (BitsNeeded > FieldWidth) {
  8026. Expr *WidthExpr = Bitfield->getBitWidth();
  8027. S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
  8028. << Bitfield << ED;
  8029. S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
  8030. << BitsNeeded << ED << WidthExpr->getSourceRange();
  8031. }
  8032. }
  8033. return false;
  8034. }
  8035. unsigned OriginalWidth = Value.getBitWidth();
  8036. if (!Value.isSigned() || Value.isNegative())
  8037. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
  8038. if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
  8039. OriginalWidth = Value.getMinSignedBits();
  8040. if (OriginalWidth <= FieldWidth)
  8041. return false;
  8042. // Compute the value which the bitfield will contain.
  8043. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  8044. TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
  8045. // Check whether the stored value is equal to the original value.
  8046. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  8047. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  8048. return false;
  8049. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  8050. // therefore don't strictly fit into a signed bitfield of width 1.
  8051. if (FieldWidth == 1 && Value == 1)
  8052. return false;
  8053. std::string PrettyValue = Value.toString(10);
  8054. std::string PrettyTrunc = TruncatedValue.toString(10);
  8055. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  8056. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  8057. << Init->getSourceRange();
  8058. return true;
  8059. }
  8060. /// Analyze the given simple or compound assignment for warning-worthy
  8061. /// operations.
  8062. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  8063. // Just recurse on the LHS.
  8064. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  8065. // We want to recurse on the RHS as normal unless we're assigning to
  8066. // a bitfield.
  8067. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  8068. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  8069. E->getOperatorLoc())) {
  8070. // Recurse, ignoring any implicit conversions on the RHS.
  8071. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  8072. E->getOperatorLoc());
  8073. }
  8074. }
  8075. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  8076. }
  8077. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  8078. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  8079. SourceLocation CContext, unsigned diag,
  8080. bool pruneControlFlow = false) {
  8081. if (pruneControlFlow) {
  8082. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  8083. S.PDiag(diag)
  8084. << SourceType << T << E->getSourceRange()
  8085. << SourceRange(CContext));
  8086. return;
  8087. }
  8088. S.Diag(E->getExprLoc(), diag)
  8089. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  8090. }
  8091. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  8092. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  8093. SourceLocation CContext,
  8094. unsigned diag, bool pruneControlFlow = false) {
  8095. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  8096. }
  8097. /// Diagnose an implicit cast from a floating point value to an integer value.
  8098. static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
  8099. SourceLocation CContext) {
  8100. const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
  8101. const bool PruneWarnings = S.inTemplateInstantiation();
  8102. Expr *InnerE = E->IgnoreParenImpCasts();
  8103. // We also want to warn on, e.g., "int i = -1.234"
  8104. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  8105. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  8106. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  8107. const bool IsLiteral =
  8108. isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
  8109. llvm::APFloat Value(0.0);
  8110. bool IsConstant =
  8111. E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
  8112. if (!IsConstant) {
  8113. return DiagnoseImpCast(S, E, T, CContext,
  8114. diag::warn_impcast_float_integer, PruneWarnings);
  8115. }
  8116. bool isExact = false;
  8117. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  8118. T->hasUnsignedIntegerRepresentation());
  8119. if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
  8120. &isExact) == llvm::APFloat::opOK &&
  8121. isExact) {
  8122. if (IsLiteral) return;
  8123. return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
  8124. PruneWarnings);
  8125. }
  8126. unsigned DiagID = 0;
  8127. if (IsLiteral) {
  8128. // Warn on floating point literal to integer.
  8129. DiagID = diag::warn_impcast_literal_float_to_integer;
  8130. } else if (IntegerValue == 0) {
  8131. if (Value.isZero()) { // Skip -0.0 to 0 conversion.
  8132. return DiagnoseImpCast(S, E, T, CContext,
  8133. diag::warn_impcast_float_integer, PruneWarnings);
  8134. }
  8135. // Warn on non-zero to zero conversion.
  8136. DiagID = diag::warn_impcast_float_to_integer_zero;
  8137. } else {
  8138. if (IntegerValue.isUnsigned()) {
  8139. if (!IntegerValue.isMaxValue()) {
  8140. return DiagnoseImpCast(S, E, T, CContext,
  8141. diag::warn_impcast_float_integer, PruneWarnings);
  8142. }
  8143. } else { // IntegerValue.isSigned()
  8144. if (!IntegerValue.isMaxSignedValue() &&
  8145. !IntegerValue.isMinSignedValue()) {
  8146. return DiagnoseImpCast(S, E, T, CContext,
  8147. diag::warn_impcast_float_integer, PruneWarnings);
  8148. }
  8149. }
  8150. // Warn on evaluatable floating point expression to integer conversion.
  8151. DiagID = diag::warn_impcast_float_to_integer;
  8152. }
  8153. // FIXME: Force the precision of the source value down so we don't print
  8154. // digits which are usually useless (we don't really care here if we
  8155. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  8156. // would automatically print the shortest representation, but it's a bit
  8157. // tricky to implement.
  8158. SmallString<16> PrettySourceValue;
  8159. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  8160. precision = (precision * 59 + 195) / 196;
  8161. Value.toString(PrettySourceValue, precision);
  8162. SmallString<16> PrettyTargetValue;
  8163. if (IsBool)
  8164. PrettyTargetValue = Value.isZero() ? "false" : "true";
  8165. else
  8166. IntegerValue.toString(PrettyTargetValue);
  8167. if (PruneWarnings) {
  8168. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  8169. S.PDiag(DiagID)
  8170. << E->getType() << T.getUnqualifiedType()
  8171. << PrettySourceValue << PrettyTargetValue
  8172. << E->getSourceRange() << SourceRange(CContext));
  8173. } else {
  8174. S.Diag(E->getExprLoc(), DiagID)
  8175. << E->getType() << T.getUnqualifiedType() << PrettySourceValue
  8176. << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
  8177. }
  8178. }
  8179. static std::string PrettyPrintInRange(const llvm::APSInt &Value,
  8180. IntRange Range) {
  8181. if (!Range.Width) return "0";
  8182. llvm::APSInt ValueInRange = Value;
  8183. ValueInRange.setIsSigned(!Range.NonNegative);
  8184. ValueInRange = ValueInRange.trunc(Range.Width);
  8185. return ValueInRange.toString(10);
  8186. }
  8187. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  8188. if (!isa<ImplicitCastExpr>(Ex))
  8189. return false;
  8190. Expr *InnerE = Ex->IgnoreParenImpCasts();
  8191. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  8192. const Type *Source =
  8193. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  8194. if (Target->isDependentType())
  8195. return false;
  8196. const BuiltinType *FloatCandidateBT =
  8197. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  8198. const Type *BoolCandidateType = ToBool ? Target : Source;
  8199. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  8200. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  8201. }
  8202. static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  8203. SourceLocation CC) {
  8204. unsigned NumArgs = TheCall->getNumArgs();
  8205. for (unsigned i = 0; i < NumArgs; ++i) {
  8206. Expr *CurrA = TheCall->getArg(i);
  8207. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  8208. continue;
  8209. bool IsSwapped = ((i > 0) &&
  8210. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  8211. IsSwapped |= ((i < (NumArgs - 1)) &&
  8212. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  8213. if (IsSwapped) {
  8214. // Warn on this floating-point to bool conversion.
  8215. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  8216. CurrA->getType(), CC,
  8217. diag::warn_impcast_floating_point_to_bool);
  8218. }
  8219. }
  8220. }
  8221. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  8222. SourceLocation CC) {
  8223. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  8224. E->getExprLoc()))
  8225. return;
  8226. // Don't warn on functions which have return type nullptr_t.
  8227. if (isa<CallExpr>(E))
  8228. return;
  8229. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  8230. const Expr::NullPointerConstantKind NullKind =
  8231. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  8232. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  8233. return;
  8234. // Return if target type is a safe conversion.
  8235. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  8236. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  8237. return;
  8238. SourceLocation Loc = E->getSourceRange().getBegin();
  8239. // Venture through the macro stacks to get to the source of macro arguments.
  8240. // The new location is a better location than the complete location that was
  8241. // passed in.
  8242. Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
  8243. CC = S.SourceMgr.getTopMacroCallerLoc(CC);
  8244. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  8245. if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
  8246. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  8247. Loc, S.SourceMgr, S.getLangOpts());
  8248. if (MacroName == "NULL")
  8249. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
  8250. }
  8251. // Only warn if the null and context location are in the same macro expansion.
  8252. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  8253. return;
  8254. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  8255. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
  8256. << FixItHint::CreateReplacement(Loc,
  8257. S.getFixItZeroLiteralForType(T, Loc));
  8258. }
  8259. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  8260. ObjCArrayLiteral *ArrayLiteral);
  8261. static void
  8262. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  8263. ObjCDictionaryLiteral *DictionaryLiteral);
  8264. /// Check a single element within a collection literal against the
  8265. /// target element type.
  8266. static void checkObjCCollectionLiteralElement(Sema &S,
  8267. QualType TargetElementType,
  8268. Expr *Element,
  8269. unsigned ElementKind) {
  8270. // Skip a bitcast to 'id' or qualified 'id'.
  8271. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  8272. if (ICE->getCastKind() == CK_BitCast &&
  8273. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  8274. Element = ICE->getSubExpr();
  8275. }
  8276. QualType ElementType = Element->getType();
  8277. ExprResult ElementResult(Element);
  8278. if (ElementType->getAs<ObjCObjectPointerType>() &&
  8279. S.CheckSingleAssignmentConstraints(TargetElementType,
  8280. ElementResult,
  8281. false, false)
  8282. != Sema::Compatible) {
  8283. S.Diag(Element->getLocStart(),
  8284. diag::warn_objc_collection_literal_element)
  8285. << ElementType << ElementKind << TargetElementType
  8286. << Element->getSourceRange();
  8287. }
  8288. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  8289. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  8290. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  8291. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  8292. }
  8293. /// Check an Objective-C array literal being converted to the given
  8294. /// target type.
  8295. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  8296. ObjCArrayLiteral *ArrayLiteral) {
  8297. if (!S.NSArrayDecl)
  8298. return;
  8299. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  8300. if (!TargetObjCPtr)
  8301. return;
  8302. if (TargetObjCPtr->isUnspecialized() ||
  8303. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  8304. != S.NSArrayDecl->getCanonicalDecl())
  8305. return;
  8306. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  8307. if (TypeArgs.size() != 1)
  8308. return;
  8309. QualType TargetElementType = TypeArgs[0];
  8310. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  8311. checkObjCCollectionLiteralElement(S, TargetElementType,
  8312. ArrayLiteral->getElement(I),
  8313. 0);
  8314. }
  8315. }
  8316. /// Check an Objective-C dictionary literal being converted to the given
  8317. /// target type.
  8318. static void
  8319. checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  8320. ObjCDictionaryLiteral *DictionaryLiteral) {
  8321. if (!S.NSDictionaryDecl)
  8322. return;
  8323. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  8324. if (!TargetObjCPtr)
  8325. return;
  8326. if (TargetObjCPtr->isUnspecialized() ||
  8327. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  8328. != S.NSDictionaryDecl->getCanonicalDecl())
  8329. return;
  8330. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  8331. if (TypeArgs.size() != 2)
  8332. return;
  8333. QualType TargetKeyType = TypeArgs[0];
  8334. QualType TargetObjectType = TypeArgs[1];
  8335. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  8336. auto Element = DictionaryLiteral->getKeyValueElement(I);
  8337. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  8338. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  8339. }
  8340. }
  8341. // Helper function to filter out cases for constant width constant conversion.
  8342. // Don't warn on char array initialization or for non-decimal values.
  8343. static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
  8344. SourceLocation CC) {
  8345. // If initializing from a constant, and the constant starts with '0',
  8346. // then it is a binary, octal, or hexadecimal. Allow these constants
  8347. // to fill all the bits, even if there is a sign change.
  8348. if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
  8349. const char FirstLiteralCharacter =
  8350. S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
  8351. if (FirstLiteralCharacter == '0')
  8352. return false;
  8353. }
  8354. // If the CC location points to a '{', and the type is char, then assume
  8355. // assume it is an array initialization.
  8356. if (CC.isValid() && T->isCharType()) {
  8357. const char FirstContextCharacter =
  8358. S.getSourceManager().getCharacterData(CC)[0];
  8359. if (FirstContextCharacter == '{')
  8360. return false;
  8361. }
  8362. return true;
  8363. }
  8364. static void
  8365. CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
  8366. bool *ICContext = nullptr) {
  8367. if (E->isTypeDependent() || E->isValueDependent()) return;
  8368. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  8369. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  8370. if (Source == Target) return;
  8371. if (Target->isDependentType()) return;
  8372. // If the conversion context location is invalid don't complain. We also
  8373. // don't want to emit a warning if the issue occurs from the expansion of
  8374. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  8375. // delay this check as long as possible. Once we detect we are in that
  8376. // scenario, we just return.
  8377. if (CC.isInvalid())
  8378. return;
  8379. // Diagnose implicit casts to bool.
  8380. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  8381. if (isa<StringLiteral>(E))
  8382. // Warn on string literal to bool. Checks for string literals in logical
  8383. // and expressions, for instance, assert(0 && "error here"), are
  8384. // prevented by a check in AnalyzeImplicitConversions().
  8385. return DiagnoseImpCast(S, E, T, CC,
  8386. diag::warn_impcast_string_literal_to_bool);
  8387. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  8388. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  8389. // This covers the literal expressions that evaluate to Objective-C
  8390. // objects.
  8391. return DiagnoseImpCast(S, E, T, CC,
  8392. diag::warn_impcast_objective_c_literal_to_bool);
  8393. }
  8394. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  8395. // Warn on pointer to bool conversion that is always true.
  8396. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  8397. SourceRange(CC));
  8398. }
  8399. }
  8400. // Check implicit casts from Objective-C collection literals to specialized
  8401. // collection types, e.g., NSArray<NSString *> *.
  8402. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  8403. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  8404. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  8405. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  8406. // Strip vector types.
  8407. if (isa<VectorType>(Source)) {
  8408. if (!isa<VectorType>(Target)) {
  8409. if (S.SourceMgr.isInSystemMacro(CC))
  8410. return;
  8411. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  8412. }
  8413. // If the vector cast is cast between two vectors of the same size, it is
  8414. // a bitcast, not a conversion.
  8415. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  8416. return;
  8417. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  8418. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  8419. }
  8420. if (auto VecTy = dyn_cast<VectorType>(Target))
  8421. Target = VecTy->getElementType().getTypePtr();
  8422. // Strip complex types.
  8423. if (isa<ComplexType>(Source)) {
  8424. if (!isa<ComplexType>(Target)) {
  8425. if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
  8426. return;
  8427. return DiagnoseImpCast(S, E, T, CC,
  8428. S.getLangOpts().CPlusPlus
  8429. ? diag::err_impcast_complex_scalar
  8430. : diag::warn_impcast_complex_scalar);
  8431. }
  8432. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  8433. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  8434. }
  8435. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  8436. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  8437. // If the source is floating point...
  8438. if (SourceBT && SourceBT->isFloatingPoint()) {
  8439. // ...and the target is floating point...
  8440. if (TargetBT && TargetBT->isFloatingPoint()) {
  8441. // ...then warn if we're dropping FP rank.
  8442. // Builtin FP kinds are ordered by increasing FP rank.
  8443. if (SourceBT->getKind() > TargetBT->getKind()) {
  8444. // Don't warn about float constants that are precisely
  8445. // representable in the target type.
  8446. Expr::EvalResult result;
  8447. if (E->EvaluateAsRValue(result, S.Context)) {
  8448. // Value might be a float, a float vector, or a float complex.
  8449. if (IsSameFloatAfterCast(result.Val,
  8450. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  8451. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  8452. return;
  8453. }
  8454. if (S.SourceMgr.isInSystemMacro(CC))
  8455. return;
  8456. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  8457. }
  8458. // ... or possibly if we're increasing rank, too
  8459. else if (TargetBT->getKind() > SourceBT->getKind()) {
  8460. if (S.SourceMgr.isInSystemMacro(CC))
  8461. return;
  8462. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
  8463. }
  8464. return;
  8465. }
  8466. // If the target is integral, always warn.
  8467. if (TargetBT && TargetBT->isInteger()) {
  8468. if (S.SourceMgr.isInSystemMacro(CC))
  8469. return;
  8470. DiagnoseFloatingImpCast(S, E, T, CC);
  8471. }
  8472. // Detect the case where a call result is converted from floating-point to
  8473. // to bool, and the final argument to the call is converted from bool, to
  8474. // discover this typo:
  8475. //
  8476. // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
  8477. //
  8478. // FIXME: This is an incredibly special case; is there some more general
  8479. // way to detect this class of misplaced-parentheses bug?
  8480. if (Target->isBooleanType() && isa<CallExpr>(E)) {
  8481. // Check last argument of function call to see if it is an
  8482. // implicit cast from a type matching the type the result
  8483. // is being cast to.
  8484. CallExpr *CEx = cast<CallExpr>(E);
  8485. if (unsigned NumArgs = CEx->getNumArgs()) {
  8486. Expr *LastA = CEx->getArg(NumArgs - 1);
  8487. Expr *InnerE = LastA->IgnoreParenImpCasts();
  8488. if (isa<ImplicitCastExpr>(LastA) &&
  8489. InnerE->getType()->isBooleanType()) {
  8490. // Warn on this floating-point to bool conversion
  8491. DiagnoseImpCast(S, E, T, CC,
  8492. diag::warn_impcast_floating_point_to_bool);
  8493. }
  8494. }
  8495. }
  8496. return;
  8497. }
  8498. DiagnoseNullConversion(S, E, T, CC);
  8499. S.DiscardMisalignedMemberAddress(Target, E);
  8500. if (!Source->isIntegerType() || !Target->isIntegerType())
  8501. return;
  8502. // TODO: remove this early return once the false positives for constant->bool
  8503. // in templates, macros, etc, are reduced or removed.
  8504. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  8505. return;
  8506. IntRange SourceRange = GetExprRange(S.Context, E);
  8507. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  8508. if (SourceRange.Width > TargetRange.Width) {
  8509. // If the source is a constant, use a default-on diagnostic.
  8510. // TODO: this should happen for bitfield stores, too.
  8511. llvm::APSInt Value(32);
  8512. if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
  8513. if (S.SourceMgr.isInSystemMacro(CC))
  8514. return;
  8515. std::string PrettySourceValue = Value.toString(10);
  8516. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  8517. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  8518. S.PDiag(diag::warn_impcast_integer_precision_constant)
  8519. << PrettySourceValue << PrettyTargetValue
  8520. << E->getType() << T << E->getSourceRange()
  8521. << clang::SourceRange(CC));
  8522. return;
  8523. }
  8524. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  8525. if (S.SourceMgr.isInSystemMacro(CC))
  8526. return;
  8527. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  8528. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  8529. /* pruneControlFlow */ true);
  8530. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  8531. }
  8532. if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
  8533. SourceRange.NonNegative && Source->isSignedIntegerType()) {
  8534. // Warn when doing a signed to signed conversion, warn if the positive
  8535. // source value is exactly the width of the target type, which will
  8536. // cause a negative value to be stored.
  8537. llvm::APSInt Value;
  8538. if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
  8539. !S.SourceMgr.isInSystemMacro(CC)) {
  8540. if (isSameWidthConstantConversion(S, E, T, CC)) {
  8541. std::string PrettySourceValue = Value.toString(10);
  8542. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  8543. S.DiagRuntimeBehavior(
  8544. E->getExprLoc(), E,
  8545. S.PDiag(diag::warn_impcast_integer_precision_constant)
  8546. << PrettySourceValue << PrettyTargetValue << E->getType() << T
  8547. << E->getSourceRange() << clang::SourceRange(CC));
  8548. return;
  8549. }
  8550. }
  8551. // Fall through for non-constants to give a sign conversion warning.
  8552. }
  8553. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  8554. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  8555. SourceRange.Width == TargetRange.Width)) {
  8556. if (S.SourceMgr.isInSystemMacro(CC))
  8557. return;
  8558. unsigned DiagID = diag::warn_impcast_integer_sign;
  8559. // Traditionally, gcc has warned about this under -Wsign-compare.
  8560. // We also want to warn about it in -Wconversion.
  8561. // So if -Wconversion is off, use a completely identical diagnostic
  8562. // in the sign-compare group.
  8563. // The conditional-checking code will
  8564. if (ICContext) {
  8565. DiagID = diag::warn_impcast_integer_sign_conditional;
  8566. *ICContext = true;
  8567. }
  8568. return DiagnoseImpCast(S, E, T, CC, DiagID);
  8569. }
  8570. // Diagnose conversions between different enumeration types.
  8571. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  8572. // type, to give us better diagnostics.
  8573. QualType SourceType = E->getType();
  8574. if (!S.getLangOpts().CPlusPlus) {
  8575. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  8576. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  8577. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  8578. SourceType = S.Context.getTypeDeclType(Enum);
  8579. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  8580. }
  8581. }
  8582. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  8583. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  8584. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  8585. TargetEnum->getDecl()->hasNameForLinkage() &&
  8586. SourceEnum != TargetEnum) {
  8587. if (S.SourceMgr.isInSystemMacro(CC))
  8588. return;
  8589. return DiagnoseImpCast(S, E, SourceType, T, CC,
  8590. diag::warn_impcast_different_enum_types);
  8591. }
  8592. }
  8593. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  8594. SourceLocation CC, QualType T);
  8595. static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  8596. SourceLocation CC, bool &ICContext) {
  8597. E = E->IgnoreParenImpCasts();
  8598. if (isa<ConditionalOperator>(E))
  8599. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  8600. AnalyzeImplicitConversions(S, E, CC);
  8601. if (E->getType() != T)
  8602. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  8603. }
  8604. static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  8605. SourceLocation CC, QualType T) {
  8606. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  8607. bool Suspicious = false;
  8608. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  8609. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  8610. // If -Wconversion would have warned about either of the candidates
  8611. // for a signedness conversion to the context type...
  8612. if (!Suspicious) return;
  8613. // ...but it's currently ignored...
  8614. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  8615. return;
  8616. // ...then check whether it would have warned about either of the
  8617. // candidates for a signedness conversion to the condition type.
  8618. if (E->getType() == T) return;
  8619. Suspicious = false;
  8620. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  8621. E->getType(), CC, &Suspicious);
  8622. if (!Suspicious)
  8623. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  8624. E->getType(), CC, &Suspicious);
  8625. }
  8626. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  8627. /// Input argument E is a logical expression.
  8628. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  8629. if (S.getLangOpts().Bool)
  8630. return;
  8631. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  8632. }
  8633. /// AnalyzeImplicitConversions - Find and report any interesting
  8634. /// implicit conversions in the given expression. There are a couple
  8635. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  8636. static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
  8637. SourceLocation CC) {
  8638. QualType T = OrigE->getType();
  8639. Expr *E = OrigE->IgnoreParenImpCasts();
  8640. if (E->isTypeDependent() || E->isValueDependent())
  8641. return;
  8642. // For conditional operators, we analyze the arguments as if they
  8643. // were being fed directly into the output.
  8644. if (isa<ConditionalOperator>(E)) {
  8645. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  8646. CheckConditionalOperator(S, CO, CC, T);
  8647. return;
  8648. }
  8649. // Check implicit argument conversions for function calls.
  8650. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  8651. CheckImplicitArgumentConversions(S, Call, CC);
  8652. // Go ahead and check any implicit conversions we might have skipped.
  8653. // The non-canonical typecheck is just an optimization;
  8654. // CheckImplicitConversion will filter out dead implicit conversions.
  8655. if (E->getType() != T)
  8656. CheckImplicitConversion(S, E, T, CC);
  8657. // Now continue drilling into this expression.
  8658. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  8659. // The bound subexpressions in a PseudoObjectExpr are not reachable
  8660. // as transitive children.
  8661. // FIXME: Use a more uniform representation for this.
  8662. for (auto *SE : POE->semantics())
  8663. if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
  8664. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  8665. }
  8666. // Skip past explicit casts.
  8667. if (isa<ExplicitCastExpr>(E)) {
  8668. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  8669. return AnalyzeImplicitConversions(S, E, CC);
  8670. }
  8671. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  8672. // Do a somewhat different check with comparison operators.
  8673. if (BO->isComparisonOp())
  8674. return AnalyzeComparison(S, BO);
  8675. // And with simple assignments.
  8676. if (BO->getOpcode() == BO_Assign)
  8677. return AnalyzeAssignment(S, BO);
  8678. }
  8679. // These break the otherwise-useful invariant below. Fortunately,
  8680. // we don't really need to recurse into them, because any internal
  8681. // expressions should have been analyzed already when they were
  8682. // built into statements.
  8683. if (isa<StmtExpr>(E)) return;
  8684. // Don't descend into unevaluated contexts.
  8685. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  8686. // Now just recurse over the expression's children.
  8687. CC = E->getExprLoc();
  8688. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  8689. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  8690. for (Stmt *SubStmt : E->children()) {
  8691. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  8692. if (!ChildExpr)
  8693. continue;
  8694. if (IsLogicalAndOperator &&
  8695. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  8696. // Ignore checking string literals that are in logical and operators.
  8697. // This is a common pattern for asserts.
  8698. continue;
  8699. AnalyzeImplicitConversions(S, ChildExpr, CC);
  8700. }
  8701. if (BO && BO->isLogicalOp()) {
  8702. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  8703. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  8704. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  8705. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  8706. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  8707. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  8708. }
  8709. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
  8710. if (U->getOpcode() == UO_LNot)
  8711. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  8712. }
  8713. /// Diagnose integer type and any valid implicit convertion to it.
  8714. static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
  8715. // Taking into account implicit conversions,
  8716. // allow any integer.
  8717. if (!E->getType()->isIntegerType()) {
  8718. S.Diag(E->getLocStart(),
  8719. diag::err_opencl_enqueue_kernel_invalid_local_size_type);
  8720. return true;
  8721. }
  8722. // Potentially emit standard warnings for implicit conversions if enabled
  8723. // using -Wconversion.
  8724. CheckImplicitConversion(S, E, IntT, E->getLocStart());
  8725. return false;
  8726. }
  8727. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  8728. // Returns true when emitting a warning about taking the address of a reference.
  8729. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  8730. const PartialDiagnostic &PD) {
  8731. E = E->IgnoreParenImpCasts();
  8732. const FunctionDecl *FD = nullptr;
  8733. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  8734. if (!DRE->getDecl()->getType()->isReferenceType())
  8735. return false;
  8736. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  8737. if (!M->getMemberDecl()->getType()->isReferenceType())
  8738. return false;
  8739. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  8740. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  8741. return false;
  8742. FD = Call->getDirectCallee();
  8743. } else {
  8744. return false;
  8745. }
  8746. SemaRef.Diag(E->getExprLoc(), PD);
  8747. // If possible, point to location of function.
  8748. if (FD) {
  8749. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  8750. }
  8751. return true;
  8752. }
  8753. // Returns true if the SourceLocation is expanded from any macro body.
  8754. // Returns false if the SourceLocation is invalid, is from not in a macro
  8755. // expansion, or is from expanded from a top-level macro argument.
  8756. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  8757. if (Loc.isInvalid())
  8758. return false;
  8759. while (Loc.isMacroID()) {
  8760. if (SM.isMacroBodyExpansion(Loc))
  8761. return true;
  8762. Loc = SM.getImmediateMacroCallerLoc(Loc);
  8763. }
  8764. return false;
  8765. }
  8766. /// \brief Diagnose pointers that are always non-null.
  8767. /// \param E the expression containing the pointer
  8768. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  8769. /// compared to a null pointer
  8770. /// \param IsEqual True when the comparison is equal to a null pointer
  8771. /// \param Range Extra SourceRange to highlight in the diagnostic
  8772. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  8773. Expr::NullPointerConstantKind NullKind,
  8774. bool IsEqual, SourceRange Range) {
  8775. if (!E)
  8776. return;
  8777. // Don't warn inside macros.
  8778. if (E->getExprLoc().isMacroID()) {
  8779. const SourceManager &SM = getSourceManager();
  8780. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  8781. IsInAnyMacroBody(SM, Range.getBegin()))
  8782. return;
  8783. }
  8784. E = E->IgnoreImpCasts();
  8785. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  8786. if (isa<CXXThisExpr>(E)) {
  8787. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  8788. : diag::warn_this_bool_conversion;
  8789. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  8790. return;
  8791. }
  8792. bool IsAddressOf = false;
  8793. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  8794. if (UO->getOpcode() != UO_AddrOf)
  8795. return;
  8796. IsAddressOf = true;
  8797. E = UO->getSubExpr();
  8798. }
  8799. if (IsAddressOf) {
  8800. unsigned DiagID = IsCompare
  8801. ? diag::warn_address_of_reference_null_compare
  8802. : diag::warn_address_of_reference_bool_conversion;
  8803. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  8804. << IsEqual;
  8805. if (CheckForReference(*this, E, PD)) {
  8806. return;
  8807. }
  8808. }
  8809. auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
  8810. bool IsParam = isa<NonNullAttr>(NonnullAttr);
  8811. std::string Str;
  8812. llvm::raw_string_ostream S(Str);
  8813. E->printPretty(S, nullptr, getPrintingPolicy());
  8814. unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
  8815. : diag::warn_cast_nonnull_to_bool;
  8816. Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
  8817. << E->getSourceRange() << Range << IsEqual;
  8818. Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
  8819. };
  8820. // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
  8821. if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
  8822. if (auto *Callee = Call->getDirectCallee()) {
  8823. if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
  8824. ComplainAboutNonnullParamOrCall(A);
  8825. return;
  8826. }
  8827. }
  8828. }
  8829. // Expect to find a single Decl. Skip anything more complicated.
  8830. ValueDecl *D = nullptr;
  8831. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  8832. D = R->getDecl();
  8833. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  8834. D = M->getMemberDecl();
  8835. }
  8836. // Weak Decls can be null.
  8837. if (!D || D->isWeak())
  8838. return;
  8839. // Check for parameter decl with nonnull attribute
  8840. if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
  8841. if (getCurFunction() &&
  8842. !getCurFunction()->ModifiedNonNullParams.count(PV)) {
  8843. if (const Attr *A = PV->getAttr<NonNullAttr>()) {
  8844. ComplainAboutNonnullParamOrCall(A);
  8845. return;
  8846. }
  8847. if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  8848. auto ParamIter = llvm::find(FD->parameters(), PV);
  8849. assert(ParamIter != FD->param_end());
  8850. unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
  8851. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  8852. if (!NonNull->args_size()) {
  8853. ComplainAboutNonnullParamOrCall(NonNull);
  8854. return;
  8855. }
  8856. for (unsigned ArgNo : NonNull->args()) {
  8857. if (ArgNo == ParamNo) {
  8858. ComplainAboutNonnullParamOrCall(NonNull);
  8859. return;
  8860. }
  8861. }
  8862. }
  8863. }
  8864. }
  8865. }
  8866. QualType T = D->getType();
  8867. const bool IsArray = T->isArrayType();
  8868. const bool IsFunction = T->isFunctionType();
  8869. // Address of function is used to silence the function warning.
  8870. if (IsAddressOf && IsFunction) {
  8871. return;
  8872. }
  8873. // Found nothing.
  8874. if (!IsAddressOf && !IsFunction && !IsArray)
  8875. return;
  8876. // Pretty print the expression for the diagnostic.
  8877. std::string Str;
  8878. llvm::raw_string_ostream S(Str);
  8879. E->printPretty(S, nullptr, getPrintingPolicy());
  8880. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  8881. : diag::warn_impcast_pointer_to_bool;
  8882. enum {
  8883. AddressOf,
  8884. FunctionPointer,
  8885. ArrayPointer
  8886. } DiagType;
  8887. if (IsAddressOf)
  8888. DiagType = AddressOf;
  8889. else if (IsFunction)
  8890. DiagType = FunctionPointer;
  8891. else if (IsArray)
  8892. DiagType = ArrayPointer;
  8893. else
  8894. llvm_unreachable("Could not determine diagnostic.");
  8895. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  8896. << Range << IsEqual;
  8897. if (!IsFunction)
  8898. return;
  8899. // Suggest '&' to silence the function warning.
  8900. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  8901. << FixItHint::CreateInsertion(E->getLocStart(), "&");
  8902. // Check to see if '()' fixit should be emitted.
  8903. QualType ReturnType;
  8904. UnresolvedSet<4> NonTemplateOverloads;
  8905. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  8906. if (ReturnType.isNull())
  8907. return;
  8908. if (IsCompare) {
  8909. // There are two cases here. If there is null constant, the only suggest
  8910. // for a pointer return type. If the null is 0, then suggest if the return
  8911. // type is a pointer or an integer type.
  8912. if (!ReturnType->isPointerType()) {
  8913. if (NullKind == Expr::NPCK_ZeroExpression ||
  8914. NullKind == Expr::NPCK_ZeroLiteral) {
  8915. if (!ReturnType->isIntegerType())
  8916. return;
  8917. } else {
  8918. return;
  8919. }
  8920. }
  8921. } else { // !IsCompare
  8922. // For function to bool, only suggest if the function pointer has bool
  8923. // return type.
  8924. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  8925. return;
  8926. }
  8927. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  8928. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
  8929. }
  8930. /// Diagnoses "dangerous" implicit conversions within the given
  8931. /// expression (which is a full expression). Implements -Wconversion
  8932. /// and -Wsign-compare.
  8933. ///
  8934. /// \param CC the "context" location of the implicit conversion, i.e.
  8935. /// the most location of the syntactic entity requiring the implicit
  8936. /// conversion
  8937. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  8938. // Don't diagnose in unevaluated contexts.
  8939. if (isUnevaluatedContext())
  8940. return;
  8941. // Don't diagnose for value- or type-dependent expressions.
  8942. if (E->isTypeDependent() || E->isValueDependent())
  8943. return;
  8944. // Check for array bounds violations in cases where the check isn't triggered
  8945. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  8946. // ArraySubscriptExpr is on the RHS of a variable initialization.
  8947. CheckArrayAccess(E);
  8948. // This is not the right CC for (e.g.) a variable initialization.
  8949. AnalyzeImplicitConversions(*this, E, CC);
  8950. }
  8951. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  8952. /// Input argument E is a logical expression.
  8953. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  8954. ::CheckBoolLikeConversion(*this, E, CC);
  8955. }
  8956. /// Diagnose when expression is an integer constant expression and its evaluation
  8957. /// results in integer overflow
  8958. void Sema::CheckForIntOverflow (Expr *E) {
  8959. // Use a work list to deal with nested struct initializers.
  8960. SmallVector<Expr *, 2> Exprs(1, E);
  8961. do {
  8962. Expr *E = Exprs.pop_back_val();
  8963. if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
  8964. E->IgnoreParenCasts()->EvaluateForOverflow(Context);
  8965. continue;
  8966. }
  8967. if (auto InitList = dyn_cast<InitListExpr>(E))
  8968. Exprs.append(InitList->inits().begin(), InitList->inits().end());
  8969. if (isa<ObjCBoxedExpr>(E))
  8970. E->IgnoreParenCasts()->EvaluateForOverflow(Context);
  8971. } while (!Exprs.empty());
  8972. }
  8973. namespace {
  8974. /// \brief Visitor for expressions which looks for unsequenced operations on the
  8975. /// same object.
  8976. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  8977. using Base = EvaluatedExprVisitor<SequenceChecker>;
  8978. /// \brief A tree of sequenced regions within an expression. Two regions are
  8979. /// unsequenced if one is an ancestor or a descendent of the other. When we
  8980. /// finish processing an expression with sequencing, such as a comma
  8981. /// expression, we fold its tree nodes into its parent, since they are
  8982. /// unsequenced with respect to nodes we will visit later.
  8983. class SequenceTree {
  8984. struct Value {
  8985. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  8986. unsigned Parent : 31;
  8987. unsigned Merged : 1;
  8988. };
  8989. SmallVector<Value, 8> Values;
  8990. public:
  8991. /// \brief A region within an expression which may be sequenced with respect
  8992. /// to some other region.
  8993. class Seq {
  8994. friend class SequenceTree;
  8995. unsigned Index = 0;
  8996. explicit Seq(unsigned N) : Index(N) {}
  8997. public:
  8998. Seq() = default;
  8999. };
  9000. SequenceTree() { Values.push_back(Value(0)); }
  9001. Seq root() const { return Seq(0); }
  9002. /// \brief Create a new sequence of operations, which is an unsequenced
  9003. /// subset of \p Parent. This sequence of operations is sequenced with
  9004. /// respect to other children of \p Parent.
  9005. Seq allocate(Seq Parent) {
  9006. Values.push_back(Value(Parent.Index));
  9007. return Seq(Values.size() - 1);
  9008. }
  9009. /// \brief Merge a sequence of operations into its parent.
  9010. void merge(Seq S) {
  9011. Values[S.Index].Merged = true;
  9012. }
  9013. /// \brief Determine whether two operations are unsequenced. This operation
  9014. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  9015. /// should have been merged into its parent as appropriate.
  9016. bool isUnsequenced(Seq Cur, Seq Old) {
  9017. unsigned C = representative(Cur.Index);
  9018. unsigned Target = representative(Old.Index);
  9019. while (C >= Target) {
  9020. if (C == Target)
  9021. return true;
  9022. C = Values[C].Parent;
  9023. }
  9024. return false;
  9025. }
  9026. private:
  9027. /// \brief Pick a representative for a sequence.
  9028. unsigned representative(unsigned K) {
  9029. if (Values[K].Merged)
  9030. // Perform path compression as we go.
  9031. return Values[K].Parent = representative(Values[K].Parent);
  9032. return K;
  9033. }
  9034. };
  9035. /// An object for which we can track unsequenced uses.
  9036. using Object = NamedDecl *;
  9037. /// Different flavors of object usage which we track. We only track the
  9038. /// least-sequenced usage of each kind.
  9039. enum UsageKind {
  9040. /// A read of an object. Multiple unsequenced reads are OK.
  9041. UK_Use,
  9042. /// A modification of an object which is sequenced before the value
  9043. /// computation of the expression, such as ++n in C++.
  9044. UK_ModAsValue,
  9045. /// A modification of an object which is not sequenced before the value
  9046. /// computation of the expression, such as n++.
  9047. UK_ModAsSideEffect,
  9048. UK_Count = UK_ModAsSideEffect + 1
  9049. };
  9050. struct Usage {
  9051. Expr *Use = nullptr;
  9052. SequenceTree::Seq Seq;
  9053. Usage() = default;
  9054. };
  9055. struct UsageInfo {
  9056. Usage Uses[UK_Count];
  9057. /// Have we issued a diagnostic for this variable already?
  9058. bool Diagnosed = false;
  9059. UsageInfo() = default;
  9060. };
  9061. using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
  9062. Sema &SemaRef;
  9063. /// Sequenced regions within the expression.
  9064. SequenceTree Tree;
  9065. /// Declaration modifications and references which we have seen.
  9066. UsageInfoMap UsageMap;
  9067. /// The region we are currently within.
  9068. SequenceTree::Seq Region;
  9069. /// Filled in with declarations which were modified as a side-effect
  9070. /// (that is, post-increment operations).
  9071. SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
  9072. /// Expressions to check later. We defer checking these to reduce
  9073. /// stack usage.
  9074. SmallVectorImpl<Expr *> &WorkList;
  9075. /// RAII object wrapping the visitation of a sequenced subexpression of an
  9076. /// expression. At the end of this process, the side-effects of the evaluation
  9077. /// become sequenced with respect to the value computation of the result, so
  9078. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  9079. /// UK_ModAsValue.
  9080. struct SequencedSubexpression {
  9081. SequencedSubexpression(SequenceChecker &Self)
  9082. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  9083. Self.ModAsSideEffect = &ModAsSideEffect;
  9084. }
  9085. ~SequencedSubexpression() {
  9086. for (auto &M : llvm::reverse(ModAsSideEffect)) {
  9087. UsageInfo &U = Self.UsageMap[M.first];
  9088. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  9089. Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
  9090. SideEffectUsage = M.second;
  9091. }
  9092. Self.ModAsSideEffect = OldModAsSideEffect;
  9093. }
  9094. SequenceChecker &Self;
  9095. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  9096. SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
  9097. };
  9098. /// RAII object wrapping the visitation of a subexpression which we might
  9099. /// choose to evaluate as a constant. If any subexpression is evaluated and
  9100. /// found to be non-constant, this allows us to suppress the evaluation of
  9101. /// the outer expression.
  9102. class EvaluationTracker {
  9103. public:
  9104. EvaluationTracker(SequenceChecker &Self)
  9105. : Self(Self), Prev(Self.EvalTracker) {
  9106. Self.EvalTracker = this;
  9107. }
  9108. ~EvaluationTracker() {
  9109. Self.EvalTracker = Prev;
  9110. if (Prev)
  9111. Prev->EvalOK &= EvalOK;
  9112. }
  9113. bool evaluate(const Expr *E, bool &Result) {
  9114. if (!EvalOK || E->isValueDependent())
  9115. return false;
  9116. EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
  9117. return EvalOK;
  9118. }
  9119. private:
  9120. SequenceChecker &Self;
  9121. EvaluationTracker *Prev;
  9122. bool EvalOK = true;
  9123. } *EvalTracker = nullptr;
  9124. /// \brief Find the object which is produced by the specified expression,
  9125. /// if any.
  9126. Object getObject(Expr *E, bool Mod) const {
  9127. E = E->IgnoreParenCasts();
  9128. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  9129. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  9130. return getObject(UO->getSubExpr(), Mod);
  9131. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9132. if (BO->getOpcode() == BO_Comma)
  9133. return getObject(BO->getRHS(), Mod);
  9134. if (Mod && BO->isAssignmentOp())
  9135. return getObject(BO->getLHS(), Mod);
  9136. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  9137. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  9138. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  9139. return ME->getMemberDecl();
  9140. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  9141. // FIXME: If this is a reference, map through to its value.
  9142. return DRE->getDecl();
  9143. return nullptr;
  9144. }
  9145. /// \brief Note that an object was modified or used by an expression.
  9146. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  9147. Usage &U = UI.Uses[UK];
  9148. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  9149. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  9150. ModAsSideEffect->push_back(std::make_pair(O, U));
  9151. U.Use = Ref;
  9152. U.Seq = Region;
  9153. }
  9154. }
  9155. /// \brief Check whether a modification or use conflicts with a prior usage.
  9156. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  9157. bool IsModMod) {
  9158. if (UI.Diagnosed)
  9159. return;
  9160. const Usage &U = UI.Uses[OtherKind];
  9161. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  9162. return;
  9163. Expr *Mod = U.Use;
  9164. Expr *ModOrUse = Ref;
  9165. if (OtherKind == UK_Use)
  9166. std::swap(Mod, ModOrUse);
  9167. SemaRef.Diag(Mod->getExprLoc(),
  9168. IsModMod ? diag::warn_unsequenced_mod_mod
  9169. : diag::warn_unsequenced_mod_use)
  9170. << O << SourceRange(ModOrUse->getExprLoc());
  9171. UI.Diagnosed = true;
  9172. }
  9173. void notePreUse(Object O, Expr *Use) {
  9174. UsageInfo &U = UsageMap[O];
  9175. // Uses conflict with other modifications.
  9176. checkUsage(O, U, Use, UK_ModAsValue, false);
  9177. }
  9178. void notePostUse(Object O, Expr *Use) {
  9179. UsageInfo &U = UsageMap[O];
  9180. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  9181. addUsage(U, O, Use, UK_Use);
  9182. }
  9183. void notePreMod(Object O, Expr *Mod) {
  9184. UsageInfo &U = UsageMap[O];
  9185. // Modifications conflict with other modifications and with uses.
  9186. checkUsage(O, U, Mod, UK_ModAsValue, true);
  9187. checkUsage(O, U, Mod, UK_Use, false);
  9188. }
  9189. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  9190. UsageInfo &U = UsageMap[O];
  9191. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  9192. addUsage(U, O, Use, UK);
  9193. }
  9194. public:
  9195. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  9196. : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
  9197. Visit(E);
  9198. }
  9199. void VisitStmt(Stmt *S) {
  9200. // Skip all statements which aren't expressions for now.
  9201. }
  9202. void VisitExpr(Expr *E) {
  9203. // By default, just recurse to evaluated subexpressions.
  9204. Base::VisitStmt(E);
  9205. }
  9206. void VisitCastExpr(CastExpr *E) {
  9207. Object O = Object();
  9208. if (E->getCastKind() == CK_LValueToRValue)
  9209. O = getObject(E->getSubExpr(), false);
  9210. if (O)
  9211. notePreUse(O, E);
  9212. VisitExpr(E);
  9213. if (O)
  9214. notePostUse(O, E);
  9215. }
  9216. void VisitBinComma(BinaryOperator *BO) {
  9217. // C++11 [expr.comma]p1:
  9218. // Every value computation and side effect associated with the left
  9219. // expression is sequenced before every value computation and side
  9220. // effect associated with the right expression.
  9221. SequenceTree::Seq LHS = Tree.allocate(Region);
  9222. SequenceTree::Seq RHS = Tree.allocate(Region);
  9223. SequenceTree::Seq OldRegion = Region;
  9224. {
  9225. SequencedSubexpression SeqLHS(*this);
  9226. Region = LHS;
  9227. Visit(BO->getLHS());
  9228. }
  9229. Region = RHS;
  9230. Visit(BO->getRHS());
  9231. Region = OldRegion;
  9232. // Forget that LHS and RHS are sequenced. They are both unsequenced
  9233. // with respect to other stuff.
  9234. Tree.merge(LHS);
  9235. Tree.merge(RHS);
  9236. }
  9237. void VisitBinAssign(BinaryOperator *BO) {
  9238. // The modification is sequenced after the value computation of the LHS
  9239. // and RHS, so check it before inspecting the operands and update the
  9240. // map afterwards.
  9241. Object O = getObject(BO->getLHS(), true);
  9242. if (!O)
  9243. return VisitExpr(BO);
  9244. notePreMod(O, BO);
  9245. // C++11 [expr.ass]p7:
  9246. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  9247. // only once.
  9248. //
  9249. // Therefore, for a compound assignment operator, O is considered used
  9250. // everywhere except within the evaluation of E1 itself.
  9251. if (isa<CompoundAssignOperator>(BO))
  9252. notePreUse(O, BO);
  9253. Visit(BO->getLHS());
  9254. if (isa<CompoundAssignOperator>(BO))
  9255. notePostUse(O, BO);
  9256. Visit(BO->getRHS());
  9257. // C++11 [expr.ass]p1:
  9258. // the assignment is sequenced [...] before the value computation of the
  9259. // assignment expression.
  9260. // C11 6.5.16/3 has no such rule.
  9261. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  9262. : UK_ModAsSideEffect);
  9263. }
  9264. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  9265. VisitBinAssign(CAO);
  9266. }
  9267. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  9268. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  9269. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  9270. Object O = getObject(UO->getSubExpr(), true);
  9271. if (!O)
  9272. return VisitExpr(UO);
  9273. notePreMod(O, UO);
  9274. Visit(UO->getSubExpr());
  9275. // C++11 [expr.pre.incr]p1:
  9276. // the expression ++x is equivalent to x+=1
  9277. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  9278. : UK_ModAsSideEffect);
  9279. }
  9280. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  9281. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  9282. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  9283. Object O = getObject(UO->getSubExpr(), true);
  9284. if (!O)
  9285. return VisitExpr(UO);
  9286. notePreMod(O, UO);
  9287. Visit(UO->getSubExpr());
  9288. notePostMod(O, UO, UK_ModAsSideEffect);
  9289. }
  9290. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  9291. void VisitBinLOr(BinaryOperator *BO) {
  9292. // The side-effects of the LHS of an '&&' are sequenced before the
  9293. // value computation of the RHS, and hence before the value computation
  9294. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  9295. // as if they were unconditionally sequenced.
  9296. EvaluationTracker Eval(*this);
  9297. {
  9298. SequencedSubexpression Sequenced(*this);
  9299. Visit(BO->getLHS());
  9300. }
  9301. bool Result;
  9302. if (Eval.evaluate(BO->getLHS(), Result)) {
  9303. if (!Result)
  9304. Visit(BO->getRHS());
  9305. } else {
  9306. // Check for unsequenced operations in the RHS, treating it as an
  9307. // entirely separate evaluation.
  9308. //
  9309. // FIXME: If there are operations in the RHS which are unsequenced
  9310. // with respect to operations outside the RHS, and those operations
  9311. // are unconditionally evaluated, diagnose them.
  9312. WorkList.push_back(BO->getRHS());
  9313. }
  9314. }
  9315. void VisitBinLAnd(BinaryOperator *BO) {
  9316. EvaluationTracker Eval(*this);
  9317. {
  9318. SequencedSubexpression Sequenced(*this);
  9319. Visit(BO->getLHS());
  9320. }
  9321. bool Result;
  9322. if (Eval.evaluate(BO->getLHS(), Result)) {
  9323. if (Result)
  9324. Visit(BO->getRHS());
  9325. } else {
  9326. WorkList.push_back(BO->getRHS());
  9327. }
  9328. }
  9329. // Only visit the condition, unless we can be sure which subexpression will
  9330. // be chosen.
  9331. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  9332. EvaluationTracker Eval(*this);
  9333. {
  9334. SequencedSubexpression Sequenced(*this);
  9335. Visit(CO->getCond());
  9336. }
  9337. bool Result;
  9338. if (Eval.evaluate(CO->getCond(), Result))
  9339. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  9340. else {
  9341. WorkList.push_back(CO->getTrueExpr());
  9342. WorkList.push_back(CO->getFalseExpr());
  9343. }
  9344. }
  9345. void VisitCallExpr(CallExpr *CE) {
  9346. // C++11 [intro.execution]p15:
  9347. // When calling a function [...], every value computation and side effect
  9348. // associated with any argument expression, or with the postfix expression
  9349. // designating the called function, is sequenced before execution of every
  9350. // expression or statement in the body of the function [and thus before
  9351. // the value computation of its result].
  9352. SequencedSubexpression Sequenced(*this);
  9353. Base::VisitCallExpr(CE);
  9354. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  9355. }
  9356. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  9357. // This is a call, so all subexpressions are sequenced before the result.
  9358. SequencedSubexpression Sequenced(*this);
  9359. if (!CCE->isListInitialization())
  9360. return VisitExpr(CCE);
  9361. // In C++11, list initializations are sequenced.
  9362. SmallVector<SequenceTree::Seq, 32> Elts;
  9363. SequenceTree::Seq Parent = Region;
  9364. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  9365. E = CCE->arg_end();
  9366. I != E; ++I) {
  9367. Region = Tree.allocate(Parent);
  9368. Elts.push_back(Region);
  9369. Visit(*I);
  9370. }
  9371. // Forget that the initializers are sequenced.
  9372. Region = Parent;
  9373. for (unsigned I = 0; I < Elts.size(); ++I)
  9374. Tree.merge(Elts[I]);
  9375. }
  9376. void VisitInitListExpr(InitListExpr *ILE) {
  9377. if (!SemaRef.getLangOpts().CPlusPlus11)
  9378. return VisitExpr(ILE);
  9379. // In C++11, list initializations are sequenced.
  9380. SmallVector<SequenceTree::Seq, 32> Elts;
  9381. SequenceTree::Seq Parent = Region;
  9382. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  9383. Expr *E = ILE->getInit(I);
  9384. if (!E) continue;
  9385. Region = Tree.allocate(Parent);
  9386. Elts.push_back(Region);
  9387. Visit(E);
  9388. }
  9389. // Forget that the initializers are sequenced.
  9390. Region = Parent;
  9391. for (unsigned I = 0; I < Elts.size(); ++I)
  9392. Tree.merge(Elts[I]);
  9393. }
  9394. };
  9395. } // namespace
  9396. void Sema::CheckUnsequencedOperations(Expr *E) {
  9397. SmallVector<Expr *, 8> WorkList;
  9398. WorkList.push_back(E);
  9399. while (!WorkList.empty()) {
  9400. Expr *Item = WorkList.pop_back_val();
  9401. SequenceChecker(*this, Item, WorkList);
  9402. }
  9403. }
  9404. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  9405. bool IsConstexpr) {
  9406. CheckImplicitConversions(E, CheckLoc);
  9407. if (!E->isInstantiationDependent())
  9408. CheckUnsequencedOperations(E);
  9409. if (!IsConstexpr && !E->isValueDependent())
  9410. CheckForIntOverflow(E);
  9411. DiagnoseMisalignedMembers();
  9412. }
  9413. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  9414. FieldDecl *BitField,
  9415. Expr *Init) {
  9416. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  9417. }
  9418. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  9419. SourceLocation Loc) {
  9420. if (!PType->isVariablyModifiedType())
  9421. return;
  9422. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  9423. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  9424. return;
  9425. }
  9426. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  9427. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  9428. return;
  9429. }
  9430. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  9431. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  9432. return;
  9433. }
  9434. const ArrayType *AT = S.Context.getAsArrayType(PType);
  9435. if (!AT)
  9436. return;
  9437. if (AT->getSizeModifier() != ArrayType::Star) {
  9438. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  9439. return;
  9440. }
  9441. S.Diag(Loc, diag::err_array_star_in_function_definition);
  9442. }
  9443. /// CheckParmsForFunctionDef - Check that the parameters of the given
  9444. /// function are appropriate for the definition of a function. This
  9445. /// takes care of any checks that cannot be performed on the
  9446. /// declaration itself, e.g., that the types of each of the function
  9447. /// parameters are complete.
  9448. bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
  9449. bool CheckParameterNames) {
  9450. bool HasInvalidParm = false;
  9451. for (ParmVarDecl *Param : Parameters) {
  9452. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  9453. // function declarator that is part of a function definition of
  9454. // that function shall not have incomplete type.
  9455. //
  9456. // This is also C++ [dcl.fct]p6.
  9457. if (!Param->isInvalidDecl() &&
  9458. RequireCompleteType(Param->getLocation(), Param->getType(),
  9459. diag::err_typecheck_decl_incomplete_type)) {
  9460. Param->setInvalidDecl();
  9461. HasInvalidParm = true;
  9462. }
  9463. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  9464. // declaration of each parameter shall include an identifier.
  9465. if (CheckParameterNames &&
  9466. Param->getIdentifier() == nullptr &&
  9467. !Param->isImplicit() &&
  9468. !getLangOpts().CPlusPlus)
  9469. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  9470. // C99 6.7.5.3p12:
  9471. // If the function declarator is not part of a definition of that
  9472. // function, parameters may have incomplete type and may use the [*]
  9473. // notation in their sequences of declarator specifiers to specify
  9474. // variable length array types.
  9475. QualType PType = Param->getOriginalType();
  9476. // FIXME: This diagnostic should point the '[*]' if source-location
  9477. // information is added for it.
  9478. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  9479. // If the parameter is a c++ class type and it has to be destructed in the
  9480. // callee function, declare the destructor so that it can be called by the
  9481. // callee function. Do not perfom any direct access check on the dtor here.
  9482. if (!Param->isInvalidDecl()) {
  9483. if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
  9484. if (!ClassDecl->isInvalidDecl() &&
  9485. !ClassDecl->hasIrrelevantDestructor() &&
  9486. !ClassDecl->isDependentContext() &&
  9487. Context.isParamDestroyedInCallee(Param->getType())) {
  9488. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  9489. MarkFunctionReferenced(Param->getLocation(), Destructor);
  9490. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  9491. }
  9492. }
  9493. }
  9494. // Parameters with the pass_object_size attribute only need to be marked
  9495. // constant at function definitions. Because we lack information about
  9496. // whether we're on a declaration or definition when we're instantiating the
  9497. // attribute, we need to check for constness here.
  9498. if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
  9499. if (!Param->getType().isConstQualified())
  9500. Diag(Param->getLocation(), diag::err_attribute_pointers_only)
  9501. << Attr->getSpelling() << 1;
  9502. }
  9503. return HasInvalidParm;
  9504. }
  9505. /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
  9506. /// or MemberExpr.
  9507. static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
  9508. ASTContext &Context) {
  9509. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  9510. return Context.getDeclAlign(DRE->getDecl());
  9511. if (const auto *ME = dyn_cast<MemberExpr>(E))
  9512. return Context.getDeclAlign(ME->getMemberDecl());
  9513. return TypeAlign;
  9514. }
  9515. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  9516. /// pointer cast increases the alignment requirements.
  9517. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  9518. // This is actually a lot of work to potentially be doing on every
  9519. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  9520. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  9521. return;
  9522. // Ignore dependent types.
  9523. if (T->isDependentType() || Op->getType()->isDependentType())
  9524. return;
  9525. // Require that the destination be a pointer type.
  9526. const PointerType *DestPtr = T->getAs<PointerType>();
  9527. if (!DestPtr) return;
  9528. // If the destination has alignment 1, we're done.
  9529. QualType DestPointee = DestPtr->getPointeeType();
  9530. if (DestPointee->isIncompleteType()) return;
  9531. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  9532. if (DestAlign.isOne()) return;
  9533. // Require that the source be a pointer type.
  9534. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  9535. if (!SrcPtr) return;
  9536. QualType SrcPointee = SrcPtr->getPointeeType();
  9537. // Whitelist casts from cv void*. We already implicitly
  9538. // whitelisted casts to cv void*, since they have alignment 1.
  9539. // Also whitelist casts involving incomplete types, which implicitly
  9540. // includes 'void'.
  9541. if (SrcPointee->isIncompleteType()) return;
  9542. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  9543. if (auto *CE = dyn_cast<CastExpr>(Op)) {
  9544. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  9545. SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
  9546. } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
  9547. if (UO->getOpcode() == UO_AddrOf)
  9548. SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
  9549. }
  9550. if (SrcAlign >= DestAlign) return;
  9551. Diag(TRange.getBegin(), diag::warn_cast_align)
  9552. << Op->getType() << T
  9553. << static_cast<unsigned>(SrcAlign.getQuantity())
  9554. << static_cast<unsigned>(DestAlign.getQuantity())
  9555. << TRange << Op->getSourceRange();
  9556. }
  9557. /// \brief Check whether this array fits the idiom of a size-one tail padded
  9558. /// array member of a struct.
  9559. ///
  9560. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  9561. /// commonly used to emulate flexible arrays in C89 code.
  9562. static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
  9563. const NamedDecl *ND) {
  9564. if (Size != 1 || !ND) return false;
  9565. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  9566. if (!FD) return false;
  9567. // Don't consider sizes resulting from macro expansions or template argument
  9568. // substitution to form C89 tail-padded arrays.
  9569. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  9570. while (TInfo) {
  9571. TypeLoc TL = TInfo->getTypeLoc();
  9572. // Look through typedefs.
  9573. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  9574. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  9575. TInfo = TDL->getTypeSourceInfo();
  9576. continue;
  9577. }
  9578. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  9579. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  9580. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  9581. return false;
  9582. }
  9583. break;
  9584. }
  9585. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  9586. if (!RD) return false;
  9587. if (RD->isUnion()) return false;
  9588. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  9589. if (!CRD->isStandardLayout()) return false;
  9590. }
  9591. // See if this is the last field decl in the record.
  9592. const Decl *D = FD;
  9593. while ((D = D->getNextDeclInContext()))
  9594. if (isa<FieldDecl>(D))
  9595. return false;
  9596. return true;
  9597. }
  9598. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  9599. const ArraySubscriptExpr *ASE,
  9600. bool AllowOnePastEnd, bool IndexNegated) {
  9601. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  9602. if (IndexExpr->isValueDependent())
  9603. return;
  9604. const Type *EffectiveType =
  9605. BaseExpr->getType()->getPointeeOrArrayElementType();
  9606. BaseExpr = BaseExpr->IgnoreParenCasts();
  9607. const ConstantArrayType *ArrayTy =
  9608. Context.getAsConstantArrayType(BaseExpr->getType());
  9609. if (!ArrayTy)
  9610. return;
  9611. llvm::APSInt index;
  9612. if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
  9613. return;
  9614. if (IndexNegated)
  9615. index = -index;
  9616. const NamedDecl *ND = nullptr;
  9617. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  9618. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  9619. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  9620. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  9621. if (index.isUnsigned() || !index.isNegative()) {
  9622. llvm::APInt size = ArrayTy->getSize();
  9623. if (!size.isStrictlyPositive())
  9624. return;
  9625. const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
  9626. if (BaseType != EffectiveType) {
  9627. // Make sure we're comparing apples to apples when comparing index to size
  9628. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  9629. uint64_t array_typesize = Context.getTypeSize(BaseType);
  9630. // Handle ptrarith_typesize being zero, such as when casting to void*
  9631. if (!ptrarith_typesize) ptrarith_typesize = 1;
  9632. if (ptrarith_typesize != array_typesize) {
  9633. // There's a cast to a different size type involved
  9634. uint64_t ratio = array_typesize / ptrarith_typesize;
  9635. // TODO: Be smarter about handling cases where array_typesize is not a
  9636. // multiple of ptrarith_typesize
  9637. if (ptrarith_typesize * ratio == array_typesize)
  9638. size *= llvm::APInt(size.getBitWidth(), ratio);
  9639. }
  9640. }
  9641. if (size.getBitWidth() > index.getBitWidth())
  9642. index = index.zext(size.getBitWidth());
  9643. else if (size.getBitWidth() < index.getBitWidth())
  9644. size = size.zext(index.getBitWidth());
  9645. // For array subscripting the index must be less than size, but for pointer
  9646. // arithmetic also allow the index (offset) to be equal to size since
  9647. // computing the next address after the end of the array is legal and
  9648. // commonly done e.g. in C++ iterators and range-based for loops.
  9649. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  9650. return;
  9651. // Also don't warn for arrays of size 1 which are members of some
  9652. // structure. These are often used to approximate flexible arrays in C89
  9653. // code.
  9654. if (IsTailPaddedMemberArray(*this, size, ND))
  9655. return;
  9656. // Suppress the warning if the subscript expression (as identified by the
  9657. // ']' location) and the index expression are both from macro expansions
  9658. // within a system header.
  9659. if (ASE) {
  9660. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  9661. ASE->getRBracketLoc());
  9662. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  9663. SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
  9664. IndexExpr->getLocStart());
  9665. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  9666. return;
  9667. }
  9668. }
  9669. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  9670. if (ASE)
  9671. DiagID = diag::warn_array_index_exceeds_bounds;
  9672. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  9673. PDiag(DiagID) << index.toString(10, true)
  9674. << size.toString(10, true)
  9675. << (unsigned)size.getLimitedValue(~0U)
  9676. << IndexExpr->getSourceRange());
  9677. } else {
  9678. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  9679. if (!ASE) {
  9680. DiagID = diag::warn_ptr_arith_precedes_bounds;
  9681. if (index.isNegative()) index = -index;
  9682. }
  9683. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  9684. PDiag(DiagID) << index.toString(10, true)
  9685. << IndexExpr->getSourceRange());
  9686. }
  9687. if (!ND) {
  9688. // Try harder to find a NamedDecl to point at in the note.
  9689. while (const ArraySubscriptExpr *ASE =
  9690. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  9691. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  9692. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  9693. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  9694. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  9695. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  9696. }
  9697. if (ND)
  9698. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  9699. PDiag(diag::note_array_index_out_of_bounds)
  9700. << ND->getDeclName());
  9701. }
  9702. void Sema::CheckArrayAccess(const Expr *expr) {
  9703. int AllowOnePastEnd = 0;
  9704. while (expr) {
  9705. expr = expr->IgnoreParenImpCasts();
  9706. switch (expr->getStmtClass()) {
  9707. case Stmt::ArraySubscriptExprClass: {
  9708. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  9709. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  9710. AllowOnePastEnd > 0);
  9711. return;
  9712. }
  9713. case Stmt::OMPArraySectionExprClass: {
  9714. const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
  9715. if (ASE->getLowerBound())
  9716. CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
  9717. /*ASE=*/nullptr, AllowOnePastEnd > 0);
  9718. return;
  9719. }
  9720. case Stmt::UnaryOperatorClass: {
  9721. // Only unwrap the * and & unary operators
  9722. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  9723. expr = UO->getSubExpr();
  9724. switch (UO->getOpcode()) {
  9725. case UO_AddrOf:
  9726. AllowOnePastEnd++;
  9727. break;
  9728. case UO_Deref:
  9729. AllowOnePastEnd--;
  9730. break;
  9731. default:
  9732. return;
  9733. }
  9734. break;
  9735. }
  9736. case Stmt::ConditionalOperatorClass: {
  9737. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  9738. if (const Expr *lhs = cond->getLHS())
  9739. CheckArrayAccess(lhs);
  9740. if (const Expr *rhs = cond->getRHS())
  9741. CheckArrayAccess(rhs);
  9742. return;
  9743. }
  9744. case Stmt::CXXOperatorCallExprClass: {
  9745. const auto *OCE = cast<CXXOperatorCallExpr>(expr);
  9746. for (const auto *Arg : OCE->arguments())
  9747. CheckArrayAccess(Arg);
  9748. return;
  9749. }
  9750. default:
  9751. return;
  9752. }
  9753. }
  9754. }
  9755. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  9756. namespace {
  9757. struct RetainCycleOwner {
  9758. VarDecl *Variable = nullptr;
  9759. SourceRange Range;
  9760. SourceLocation Loc;
  9761. bool Indirect = false;
  9762. RetainCycleOwner() = default;
  9763. void setLocsFrom(Expr *e) {
  9764. Loc = e->getExprLoc();
  9765. Range = e->getSourceRange();
  9766. }
  9767. };
  9768. } // namespace
  9769. /// Consider whether capturing the given variable can possibly lead to
  9770. /// a retain cycle.
  9771. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  9772. // In ARC, it's captured strongly iff the variable has __strong
  9773. // lifetime. In MRR, it's captured strongly if the variable is
  9774. // __block and has an appropriate type.
  9775. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  9776. return false;
  9777. owner.Variable = var;
  9778. if (ref)
  9779. owner.setLocsFrom(ref);
  9780. return true;
  9781. }
  9782. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  9783. while (true) {
  9784. e = e->IgnoreParens();
  9785. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  9786. switch (cast->getCastKind()) {
  9787. case CK_BitCast:
  9788. case CK_LValueBitCast:
  9789. case CK_LValueToRValue:
  9790. case CK_ARCReclaimReturnedObject:
  9791. e = cast->getSubExpr();
  9792. continue;
  9793. default:
  9794. return false;
  9795. }
  9796. }
  9797. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  9798. ObjCIvarDecl *ivar = ref->getDecl();
  9799. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  9800. return false;
  9801. // Try to find a retain cycle in the base.
  9802. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  9803. return false;
  9804. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  9805. owner.Indirect = true;
  9806. return true;
  9807. }
  9808. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  9809. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  9810. if (!var) return false;
  9811. return considerVariable(var, ref, owner);
  9812. }
  9813. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  9814. if (member->isArrow()) return false;
  9815. // Don't count this as an indirect ownership.
  9816. e = member->getBase();
  9817. continue;
  9818. }
  9819. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  9820. // Only pay attention to pseudo-objects on property references.
  9821. ObjCPropertyRefExpr *pre
  9822. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  9823. ->IgnoreParens());
  9824. if (!pre) return false;
  9825. if (pre->isImplicitProperty()) return false;
  9826. ObjCPropertyDecl *property = pre->getExplicitProperty();
  9827. if (!property->isRetaining() &&
  9828. !(property->getPropertyIvarDecl() &&
  9829. property->getPropertyIvarDecl()->getType()
  9830. .getObjCLifetime() == Qualifiers::OCL_Strong))
  9831. return false;
  9832. owner.Indirect = true;
  9833. if (pre->isSuperReceiver()) {
  9834. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  9835. if (!owner.Variable)
  9836. return false;
  9837. owner.Loc = pre->getLocation();
  9838. owner.Range = pre->getSourceRange();
  9839. return true;
  9840. }
  9841. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  9842. ->getSourceExpr());
  9843. continue;
  9844. }
  9845. // Array ivars?
  9846. return false;
  9847. }
  9848. }
  9849. namespace {
  9850. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  9851. ASTContext &Context;
  9852. VarDecl *Variable;
  9853. Expr *Capturer = nullptr;
  9854. bool VarWillBeReased = false;
  9855. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  9856. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  9857. Context(Context), Variable(variable) {}
  9858. void VisitDeclRefExpr(DeclRefExpr *ref) {
  9859. if (ref->getDecl() == Variable && !Capturer)
  9860. Capturer = ref;
  9861. }
  9862. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  9863. if (Capturer) return;
  9864. Visit(ref->getBase());
  9865. if (Capturer && ref->isFreeIvar())
  9866. Capturer = ref;
  9867. }
  9868. void VisitBlockExpr(BlockExpr *block) {
  9869. // Look inside nested blocks
  9870. if (block->getBlockDecl()->capturesVariable(Variable))
  9871. Visit(block->getBlockDecl()->getBody());
  9872. }
  9873. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  9874. if (Capturer) return;
  9875. if (OVE->getSourceExpr())
  9876. Visit(OVE->getSourceExpr());
  9877. }
  9878. void VisitBinaryOperator(BinaryOperator *BinOp) {
  9879. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  9880. return;
  9881. Expr *LHS = BinOp->getLHS();
  9882. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  9883. if (DRE->getDecl() != Variable)
  9884. return;
  9885. if (Expr *RHS = BinOp->getRHS()) {
  9886. RHS = RHS->IgnoreParenCasts();
  9887. llvm::APSInt Value;
  9888. VarWillBeReased =
  9889. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  9890. }
  9891. }
  9892. }
  9893. };
  9894. } // namespace
  9895. /// Check whether the given argument is a block which captures a
  9896. /// variable.
  9897. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  9898. assert(owner.Variable && owner.Loc.isValid());
  9899. e = e->IgnoreParenCasts();
  9900. // Look through [^{...} copy] and Block_copy(^{...}).
  9901. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  9902. Selector Cmd = ME->getSelector();
  9903. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  9904. e = ME->getInstanceReceiver();
  9905. if (!e)
  9906. return nullptr;
  9907. e = e->IgnoreParenCasts();
  9908. }
  9909. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  9910. if (CE->getNumArgs() == 1) {
  9911. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  9912. if (Fn) {
  9913. const IdentifierInfo *FnI = Fn->getIdentifier();
  9914. if (FnI && FnI->isStr("_Block_copy")) {
  9915. e = CE->getArg(0)->IgnoreParenCasts();
  9916. }
  9917. }
  9918. }
  9919. }
  9920. BlockExpr *block = dyn_cast<BlockExpr>(e);
  9921. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  9922. return nullptr;
  9923. FindCaptureVisitor visitor(S.Context, owner.Variable);
  9924. visitor.Visit(block->getBlockDecl()->getBody());
  9925. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  9926. }
  9927. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  9928. RetainCycleOwner &owner) {
  9929. assert(capturer);
  9930. assert(owner.Variable && owner.Loc.isValid());
  9931. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  9932. << owner.Variable << capturer->getSourceRange();
  9933. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  9934. << owner.Indirect << owner.Range;
  9935. }
  9936. /// Check for a keyword selector that starts with the word 'add' or
  9937. /// 'set'.
  9938. static bool isSetterLikeSelector(Selector sel) {
  9939. if (sel.isUnarySelector()) return false;
  9940. StringRef str = sel.getNameForSlot(0);
  9941. while (!str.empty() && str.front() == '_') str = str.substr(1);
  9942. if (str.startswith("set"))
  9943. str = str.substr(3);
  9944. else if (str.startswith("add")) {
  9945. // Specially whitelist 'addOperationWithBlock:'.
  9946. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  9947. return false;
  9948. str = str.substr(3);
  9949. }
  9950. else
  9951. return false;
  9952. if (str.empty()) return true;
  9953. return !isLowercase(str.front());
  9954. }
  9955. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  9956. ObjCMessageExpr *Message) {
  9957. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  9958. Message->getReceiverInterface(),
  9959. NSAPI::ClassId_NSMutableArray);
  9960. if (!IsMutableArray) {
  9961. return None;
  9962. }
  9963. Selector Sel = Message->getSelector();
  9964. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  9965. S.NSAPIObj->getNSArrayMethodKind(Sel);
  9966. if (!MKOpt) {
  9967. return None;
  9968. }
  9969. NSAPI::NSArrayMethodKind MK = *MKOpt;
  9970. switch (MK) {
  9971. case NSAPI::NSMutableArr_addObject:
  9972. case NSAPI::NSMutableArr_insertObjectAtIndex:
  9973. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  9974. return 0;
  9975. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  9976. return 1;
  9977. default:
  9978. return None;
  9979. }
  9980. return None;
  9981. }
  9982. static
  9983. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  9984. ObjCMessageExpr *Message) {
  9985. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  9986. Message->getReceiverInterface(),
  9987. NSAPI::ClassId_NSMutableDictionary);
  9988. if (!IsMutableDictionary) {
  9989. return None;
  9990. }
  9991. Selector Sel = Message->getSelector();
  9992. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  9993. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  9994. if (!MKOpt) {
  9995. return None;
  9996. }
  9997. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  9998. switch (MK) {
  9999. case NSAPI::NSMutableDict_setObjectForKey:
  10000. case NSAPI::NSMutableDict_setValueForKey:
  10001. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  10002. return 0;
  10003. default:
  10004. return None;
  10005. }
  10006. return None;
  10007. }
  10008. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  10009. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  10010. Message->getReceiverInterface(),
  10011. NSAPI::ClassId_NSMutableSet);
  10012. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  10013. Message->getReceiverInterface(),
  10014. NSAPI::ClassId_NSMutableOrderedSet);
  10015. if (!IsMutableSet && !IsMutableOrderedSet) {
  10016. return None;
  10017. }
  10018. Selector Sel = Message->getSelector();
  10019. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  10020. if (!MKOpt) {
  10021. return None;
  10022. }
  10023. NSAPI::NSSetMethodKind MK = *MKOpt;
  10024. switch (MK) {
  10025. case NSAPI::NSMutableSet_addObject:
  10026. case NSAPI::NSOrderedSet_setObjectAtIndex:
  10027. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  10028. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  10029. return 0;
  10030. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  10031. return 1;
  10032. }
  10033. return None;
  10034. }
  10035. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  10036. if (!Message->isInstanceMessage()) {
  10037. return;
  10038. }
  10039. Optional<int> ArgOpt;
  10040. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  10041. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  10042. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  10043. return;
  10044. }
  10045. int ArgIndex = *ArgOpt;
  10046. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  10047. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  10048. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  10049. }
  10050. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  10051. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  10052. if (ArgRE->isObjCSelfExpr()) {
  10053. Diag(Message->getSourceRange().getBegin(),
  10054. diag::warn_objc_circular_container)
  10055. << ArgRE->getDecl()->getName() << StringRef("super");
  10056. }
  10057. }
  10058. } else {
  10059. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  10060. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  10061. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  10062. }
  10063. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  10064. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  10065. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  10066. ValueDecl *Decl = ReceiverRE->getDecl();
  10067. Diag(Message->getSourceRange().getBegin(),
  10068. diag::warn_objc_circular_container)
  10069. << Decl->getName() << Decl->getName();
  10070. if (!ArgRE->isObjCSelfExpr()) {
  10071. Diag(Decl->getLocation(),
  10072. diag::note_objc_circular_container_declared_here)
  10073. << Decl->getName();
  10074. }
  10075. }
  10076. }
  10077. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  10078. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  10079. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  10080. ObjCIvarDecl *Decl = IvarRE->getDecl();
  10081. Diag(Message->getSourceRange().getBegin(),
  10082. diag::warn_objc_circular_container)
  10083. << Decl->getName() << Decl->getName();
  10084. Diag(Decl->getLocation(),
  10085. diag::note_objc_circular_container_declared_here)
  10086. << Decl->getName();
  10087. }
  10088. }
  10089. }
  10090. }
  10091. }
  10092. /// Check a message send to see if it's likely to cause a retain cycle.
  10093. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  10094. // Only check instance methods whose selector looks like a setter.
  10095. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  10096. return;
  10097. // Try to find a variable that the receiver is strongly owned by.
  10098. RetainCycleOwner owner;
  10099. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  10100. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  10101. return;
  10102. } else {
  10103. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  10104. owner.Variable = getCurMethodDecl()->getSelfDecl();
  10105. owner.Loc = msg->getSuperLoc();
  10106. owner.Range = msg->getSuperLoc();
  10107. }
  10108. // Check whether the receiver is captured by any of the arguments.
  10109. const ObjCMethodDecl *MD = msg->getMethodDecl();
  10110. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
  10111. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
  10112. // noescape blocks should not be retained by the method.
  10113. if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
  10114. continue;
  10115. return diagnoseRetainCycle(*this, capturer, owner);
  10116. }
  10117. }
  10118. }
  10119. /// Check a property assign to see if it's likely to cause a retain cycle.
  10120. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  10121. RetainCycleOwner owner;
  10122. if (!findRetainCycleOwner(*this, receiver, owner))
  10123. return;
  10124. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  10125. diagnoseRetainCycle(*this, capturer, owner);
  10126. }
  10127. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  10128. RetainCycleOwner Owner;
  10129. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  10130. return;
  10131. // Because we don't have an expression for the variable, we have to set the
  10132. // location explicitly here.
  10133. Owner.Loc = Var->getLocation();
  10134. Owner.Range = Var->getSourceRange();
  10135. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  10136. diagnoseRetainCycle(*this, Capturer, Owner);
  10137. }
  10138. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  10139. Expr *RHS, bool isProperty) {
  10140. // Check if RHS is an Objective-C object literal, which also can get
  10141. // immediately zapped in a weak reference. Note that we explicitly
  10142. // allow ObjCStringLiterals, since those are designed to never really die.
  10143. RHS = RHS->IgnoreParenImpCasts();
  10144. // This enum needs to match with the 'select' in
  10145. // warn_objc_arc_literal_assign (off-by-1).
  10146. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  10147. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  10148. return false;
  10149. S.Diag(Loc, diag::warn_arc_literal_assign)
  10150. << (unsigned) Kind
  10151. << (isProperty ? 0 : 1)
  10152. << RHS->getSourceRange();
  10153. return true;
  10154. }
  10155. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  10156. Qualifiers::ObjCLifetime LT,
  10157. Expr *RHS, bool isProperty) {
  10158. // Strip off any implicit cast added to get to the one ARC-specific.
  10159. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  10160. if (cast->getCastKind() == CK_ARCConsumeObject) {
  10161. S.Diag(Loc, diag::warn_arc_retained_assign)
  10162. << (LT == Qualifiers::OCL_ExplicitNone)
  10163. << (isProperty ? 0 : 1)
  10164. << RHS->getSourceRange();
  10165. return true;
  10166. }
  10167. RHS = cast->getSubExpr();
  10168. }
  10169. if (LT == Qualifiers::OCL_Weak &&
  10170. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  10171. return true;
  10172. return false;
  10173. }
  10174. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  10175. QualType LHS, Expr *RHS) {
  10176. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  10177. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  10178. return false;
  10179. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  10180. return true;
  10181. return false;
  10182. }
  10183. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  10184. Expr *LHS, Expr *RHS) {
  10185. QualType LHSType;
  10186. // PropertyRef on LHS type need be directly obtained from
  10187. // its declaration as it has a PseudoType.
  10188. ObjCPropertyRefExpr *PRE
  10189. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  10190. if (PRE && !PRE->isImplicitProperty()) {
  10191. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  10192. if (PD)
  10193. LHSType = PD->getType();
  10194. }
  10195. if (LHSType.isNull())
  10196. LHSType = LHS->getType();
  10197. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  10198. if (LT == Qualifiers::OCL_Weak) {
  10199. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  10200. getCurFunction()->markSafeWeakUse(LHS);
  10201. }
  10202. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  10203. return;
  10204. // FIXME. Check for other life times.
  10205. if (LT != Qualifiers::OCL_None)
  10206. return;
  10207. if (PRE) {
  10208. if (PRE->isImplicitProperty())
  10209. return;
  10210. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  10211. if (!PD)
  10212. return;
  10213. unsigned Attributes = PD->getPropertyAttributes();
  10214. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  10215. // when 'assign' attribute was not explicitly specified
  10216. // by user, ignore it and rely on property type itself
  10217. // for lifetime info.
  10218. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  10219. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  10220. LHSType->isObjCRetainableType())
  10221. return;
  10222. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  10223. if (cast->getCastKind() == CK_ARCConsumeObject) {
  10224. Diag(Loc, diag::warn_arc_retained_property_assign)
  10225. << RHS->getSourceRange();
  10226. return;
  10227. }
  10228. RHS = cast->getSubExpr();
  10229. }
  10230. }
  10231. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  10232. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  10233. return;
  10234. }
  10235. }
  10236. }
  10237. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  10238. static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  10239. SourceLocation StmtLoc,
  10240. const NullStmt *Body) {
  10241. // Do not warn if the body is a macro that expands to nothing, e.g:
  10242. //
  10243. // #define CALL(x)
  10244. // if (condition)
  10245. // CALL(0);
  10246. if (Body->hasLeadingEmptyMacro())
  10247. return false;
  10248. // Get line numbers of statement and body.
  10249. bool StmtLineInvalid;
  10250. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  10251. &StmtLineInvalid);
  10252. if (StmtLineInvalid)
  10253. return false;
  10254. bool BodyLineInvalid;
  10255. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  10256. &BodyLineInvalid);
  10257. if (BodyLineInvalid)
  10258. return false;
  10259. // Warn if null statement and body are on the same line.
  10260. if (StmtLine != BodyLine)
  10261. return false;
  10262. return true;
  10263. }
  10264. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  10265. const Stmt *Body,
  10266. unsigned DiagID) {
  10267. // Since this is a syntactic check, don't emit diagnostic for template
  10268. // instantiations, this just adds noise.
  10269. if (CurrentInstantiationScope)
  10270. return;
  10271. // The body should be a null statement.
  10272. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  10273. if (!NBody)
  10274. return;
  10275. // Do the usual checks.
  10276. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  10277. return;
  10278. Diag(NBody->getSemiLoc(), DiagID);
  10279. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  10280. }
  10281. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  10282. const Stmt *PossibleBody) {
  10283. assert(!CurrentInstantiationScope); // Ensured by caller
  10284. SourceLocation StmtLoc;
  10285. const Stmt *Body;
  10286. unsigned DiagID;
  10287. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  10288. StmtLoc = FS->getRParenLoc();
  10289. Body = FS->getBody();
  10290. DiagID = diag::warn_empty_for_body;
  10291. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  10292. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  10293. Body = WS->getBody();
  10294. DiagID = diag::warn_empty_while_body;
  10295. } else
  10296. return; // Neither `for' nor `while'.
  10297. // The body should be a null statement.
  10298. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  10299. if (!NBody)
  10300. return;
  10301. // Skip expensive checks if diagnostic is disabled.
  10302. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  10303. return;
  10304. // Do the usual checks.
  10305. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  10306. return;
  10307. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  10308. // noise level low, emit diagnostics only if for/while is followed by a
  10309. // CompoundStmt, e.g.:
  10310. // for (int i = 0; i < n; i++);
  10311. // {
  10312. // a(i);
  10313. // }
  10314. // or if for/while is followed by a statement with more indentation
  10315. // than for/while itself:
  10316. // for (int i = 0; i < n; i++);
  10317. // a(i);
  10318. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  10319. if (!ProbableTypo) {
  10320. bool BodyColInvalid;
  10321. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  10322. PossibleBody->getLocStart(),
  10323. &BodyColInvalid);
  10324. if (BodyColInvalid)
  10325. return;
  10326. bool StmtColInvalid;
  10327. unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
  10328. S->getLocStart(),
  10329. &StmtColInvalid);
  10330. if (StmtColInvalid)
  10331. return;
  10332. if (BodyCol > StmtCol)
  10333. ProbableTypo = true;
  10334. }
  10335. if (ProbableTypo) {
  10336. Diag(NBody->getSemiLoc(), DiagID);
  10337. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  10338. }
  10339. }
  10340. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  10341. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  10342. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  10343. SourceLocation OpLoc) {
  10344. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  10345. return;
  10346. if (inTemplateInstantiation())
  10347. return;
  10348. // Strip parens and casts away.
  10349. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  10350. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  10351. // Check for a call expression
  10352. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  10353. if (!CE || CE->getNumArgs() != 1)
  10354. return;
  10355. // Check for a call to std::move
  10356. if (!CE->isCallToStdMove())
  10357. return;
  10358. // Get argument from std::move
  10359. RHSExpr = CE->getArg(0);
  10360. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  10361. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  10362. // Two DeclRefExpr's, check that the decls are the same.
  10363. if (LHSDeclRef && RHSDeclRef) {
  10364. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  10365. return;
  10366. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  10367. RHSDeclRef->getDecl()->getCanonicalDecl())
  10368. return;
  10369. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  10370. << LHSExpr->getSourceRange()
  10371. << RHSExpr->getSourceRange();
  10372. return;
  10373. }
  10374. // Member variables require a different approach to check for self moves.
  10375. // MemberExpr's are the same if every nested MemberExpr refers to the same
  10376. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  10377. // the base Expr's are CXXThisExpr's.
  10378. const Expr *LHSBase = LHSExpr;
  10379. const Expr *RHSBase = RHSExpr;
  10380. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  10381. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  10382. if (!LHSME || !RHSME)
  10383. return;
  10384. while (LHSME && RHSME) {
  10385. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  10386. RHSME->getMemberDecl()->getCanonicalDecl())
  10387. return;
  10388. LHSBase = LHSME->getBase();
  10389. RHSBase = RHSME->getBase();
  10390. LHSME = dyn_cast<MemberExpr>(LHSBase);
  10391. RHSME = dyn_cast<MemberExpr>(RHSBase);
  10392. }
  10393. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  10394. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  10395. if (LHSDeclRef && RHSDeclRef) {
  10396. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  10397. return;
  10398. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  10399. RHSDeclRef->getDecl()->getCanonicalDecl())
  10400. return;
  10401. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  10402. << LHSExpr->getSourceRange()
  10403. << RHSExpr->getSourceRange();
  10404. return;
  10405. }
  10406. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  10407. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  10408. << LHSExpr->getSourceRange()
  10409. << RHSExpr->getSourceRange();
  10410. }
  10411. //===--- Layout compatibility ----------------------------------------------//
  10412. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  10413. /// \brief Check if two enumeration types are layout-compatible.
  10414. static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  10415. // C++11 [dcl.enum] p8:
  10416. // Two enumeration types are layout-compatible if they have the same
  10417. // underlying type.
  10418. return ED1->isComplete() && ED2->isComplete() &&
  10419. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  10420. }
  10421. /// \brief Check if two fields are layout-compatible.
  10422. static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
  10423. FieldDecl *Field2) {
  10424. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  10425. return false;
  10426. if (Field1->isBitField() != Field2->isBitField())
  10427. return false;
  10428. if (Field1->isBitField()) {
  10429. // Make sure that the bit-fields are the same length.
  10430. unsigned Bits1 = Field1->getBitWidthValue(C);
  10431. unsigned Bits2 = Field2->getBitWidthValue(C);
  10432. if (Bits1 != Bits2)
  10433. return false;
  10434. }
  10435. return true;
  10436. }
  10437. /// \brief Check if two standard-layout structs are layout-compatible.
  10438. /// (C++11 [class.mem] p17)
  10439. static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
  10440. RecordDecl *RD2) {
  10441. // If both records are C++ classes, check that base classes match.
  10442. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  10443. // If one of records is a CXXRecordDecl we are in C++ mode,
  10444. // thus the other one is a CXXRecordDecl, too.
  10445. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  10446. // Check number of base classes.
  10447. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  10448. return false;
  10449. // Check the base classes.
  10450. for (CXXRecordDecl::base_class_const_iterator
  10451. Base1 = D1CXX->bases_begin(),
  10452. BaseEnd1 = D1CXX->bases_end(),
  10453. Base2 = D2CXX->bases_begin();
  10454. Base1 != BaseEnd1;
  10455. ++Base1, ++Base2) {
  10456. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  10457. return false;
  10458. }
  10459. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  10460. // If only RD2 is a C++ class, it should have zero base classes.
  10461. if (D2CXX->getNumBases() > 0)
  10462. return false;
  10463. }
  10464. // Check the fields.
  10465. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  10466. Field2End = RD2->field_end(),
  10467. Field1 = RD1->field_begin(),
  10468. Field1End = RD1->field_end();
  10469. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  10470. if (!isLayoutCompatible(C, *Field1, *Field2))
  10471. return false;
  10472. }
  10473. if (Field1 != Field1End || Field2 != Field2End)
  10474. return false;
  10475. return true;
  10476. }
  10477. /// \brief Check if two standard-layout unions are layout-compatible.
  10478. /// (C++11 [class.mem] p18)
  10479. static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
  10480. RecordDecl *RD2) {
  10481. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  10482. for (auto *Field2 : RD2->fields())
  10483. UnmatchedFields.insert(Field2);
  10484. for (auto *Field1 : RD1->fields()) {
  10485. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  10486. I = UnmatchedFields.begin(),
  10487. E = UnmatchedFields.end();
  10488. for ( ; I != E; ++I) {
  10489. if (isLayoutCompatible(C, Field1, *I)) {
  10490. bool Result = UnmatchedFields.erase(*I);
  10491. (void) Result;
  10492. assert(Result);
  10493. break;
  10494. }
  10495. }
  10496. if (I == E)
  10497. return false;
  10498. }
  10499. return UnmatchedFields.empty();
  10500. }
  10501. static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
  10502. RecordDecl *RD2) {
  10503. if (RD1->isUnion() != RD2->isUnion())
  10504. return false;
  10505. if (RD1->isUnion())
  10506. return isLayoutCompatibleUnion(C, RD1, RD2);
  10507. else
  10508. return isLayoutCompatibleStruct(C, RD1, RD2);
  10509. }
  10510. /// \brief Check if two types are layout-compatible in C++11 sense.
  10511. static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  10512. if (T1.isNull() || T2.isNull())
  10513. return false;
  10514. // C++11 [basic.types] p11:
  10515. // If two types T1 and T2 are the same type, then T1 and T2 are
  10516. // layout-compatible types.
  10517. if (C.hasSameType(T1, T2))
  10518. return true;
  10519. T1 = T1.getCanonicalType().getUnqualifiedType();
  10520. T2 = T2.getCanonicalType().getUnqualifiedType();
  10521. const Type::TypeClass TC1 = T1->getTypeClass();
  10522. const Type::TypeClass TC2 = T2->getTypeClass();
  10523. if (TC1 != TC2)
  10524. return false;
  10525. if (TC1 == Type::Enum) {
  10526. return isLayoutCompatible(C,
  10527. cast<EnumType>(T1)->getDecl(),
  10528. cast<EnumType>(T2)->getDecl());
  10529. } else if (TC1 == Type::Record) {
  10530. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  10531. return false;
  10532. return isLayoutCompatible(C,
  10533. cast<RecordType>(T1)->getDecl(),
  10534. cast<RecordType>(T2)->getDecl());
  10535. }
  10536. return false;
  10537. }
  10538. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  10539. /// \brief Given a type tag expression find the type tag itself.
  10540. ///
  10541. /// \param TypeExpr Type tag expression, as it appears in user's code.
  10542. ///
  10543. /// \param VD Declaration of an identifier that appears in a type tag.
  10544. ///
  10545. /// \param MagicValue Type tag magic value.
  10546. static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  10547. const ValueDecl **VD, uint64_t *MagicValue) {
  10548. while(true) {
  10549. if (!TypeExpr)
  10550. return false;
  10551. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  10552. switch (TypeExpr->getStmtClass()) {
  10553. case Stmt::UnaryOperatorClass: {
  10554. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  10555. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  10556. TypeExpr = UO->getSubExpr();
  10557. continue;
  10558. }
  10559. return false;
  10560. }
  10561. case Stmt::DeclRefExprClass: {
  10562. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  10563. *VD = DRE->getDecl();
  10564. return true;
  10565. }
  10566. case Stmt::IntegerLiteralClass: {
  10567. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  10568. llvm::APInt MagicValueAPInt = IL->getValue();
  10569. if (MagicValueAPInt.getActiveBits() <= 64) {
  10570. *MagicValue = MagicValueAPInt.getZExtValue();
  10571. return true;
  10572. } else
  10573. return false;
  10574. }
  10575. case Stmt::BinaryConditionalOperatorClass:
  10576. case Stmt::ConditionalOperatorClass: {
  10577. const AbstractConditionalOperator *ACO =
  10578. cast<AbstractConditionalOperator>(TypeExpr);
  10579. bool Result;
  10580. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  10581. if (Result)
  10582. TypeExpr = ACO->getTrueExpr();
  10583. else
  10584. TypeExpr = ACO->getFalseExpr();
  10585. continue;
  10586. }
  10587. return false;
  10588. }
  10589. case Stmt::BinaryOperatorClass: {
  10590. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  10591. if (BO->getOpcode() == BO_Comma) {
  10592. TypeExpr = BO->getRHS();
  10593. continue;
  10594. }
  10595. return false;
  10596. }
  10597. default:
  10598. return false;
  10599. }
  10600. }
  10601. }
  10602. /// \brief Retrieve the C type corresponding to type tag TypeExpr.
  10603. ///
  10604. /// \param TypeExpr Expression that specifies a type tag.
  10605. ///
  10606. /// \param MagicValues Registered magic values.
  10607. ///
  10608. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  10609. /// kind.
  10610. ///
  10611. /// \param TypeInfo Information about the corresponding C type.
  10612. ///
  10613. /// \returns true if the corresponding C type was found.
  10614. static bool GetMatchingCType(
  10615. const IdentifierInfo *ArgumentKind,
  10616. const Expr *TypeExpr, const ASTContext &Ctx,
  10617. const llvm::DenseMap<Sema::TypeTagMagicValue,
  10618. Sema::TypeTagData> *MagicValues,
  10619. bool &FoundWrongKind,
  10620. Sema::TypeTagData &TypeInfo) {
  10621. FoundWrongKind = false;
  10622. // Variable declaration that has type_tag_for_datatype attribute.
  10623. const ValueDecl *VD = nullptr;
  10624. uint64_t MagicValue;
  10625. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  10626. return false;
  10627. if (VD) {
  10628. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  10629. if (I->getArgumentKind() != ArgumentKind) {
  10630. FoundWrongKind = true;
  10631. return false;
  10632. }
  10633. TypeInfo.Type = I->getMatchingCType();
  10634. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  10635. TypeInfo.MustBeNull = I->getMustBeNull();
  10636. return true;
  10637. }
  10638. return false;
  10639. }
  10640. if (!MagicValues)
  10641. return false;
  10642. llvm::DenseMap<Sema::TypeTagMagicValue,
  10643. Sema::TypeTagData>::const_iterator I =
  10644. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  10645. if (I == MagicValues->end())
  10646. return false;
  10647. TypeInfo = I->second;
  10648. return true;
  10649. }
  10650. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  10651. uint64_t MagicValue, QualType Type,
  10652. bool LayoutCompatible,
  10653. bool MustBeNull) {
  10654. if (!TypeTagForDatatypeMagicValues)
  10655. TypeTagForDatatypeMagicValues.reset(
  10656. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  10657. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  10658. (*TypeTagForDatatypeMagicValues)[Magic] =
  10659. TypeTagData(Type, LayoutCompatible, MustBeNull);
  10660. }
  10661. static bool IsSameCharType(QualType T1, QualType T2) {
  10662. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  10663. if (!BT1)
  10664. return false;
  10665. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  10666. if (!BT2)
  10667. return false;
  10668. BuiltinType::Kind T1Kind = BT1->getKind();
  10669. BuiltinType::Kind T2Kind = BT2->getKind();
  10670. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  10671. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  10672. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  10673. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  10674. }
  10675. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  10676. const ArrayRef<const Expr *> ExprArgs,
  10677. SourceLocation CallSiteLoc) {
  10678. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  10679. bool IsPointerAttr = Attr->getIsPointer();
  10680. // Retrieve the argument representing the 'type_tag'.
  10681. if (Attr->getTypeTagIdx() >= ExprArgs.size()) {
  10682. // Add 1 to display the user's specified value.
  10683. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  10684. << 0 << Attr->getTypeTagIdx() + 1;
  10685. return;
  10686. }
  10687. const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
  10688. bool FoundWrongKind;
  10689. TypeTagData TypeInfo;
  10690. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  10691. TypeTagForDatatypeMagicValues.get(),
  10692. FoundWrongKind, TypeInfo)) {
  10693. if (FoundWrongKind)
  10694. Diag(TypeTagExpr->getExprLoc(),
  10695. diag::warn_type_tag_for_datatype_wrong_kind)
  10696. << TypeTagExpr->getSourceRange();
  10697. return;
  10698. }
  10699. // Retrieve the argument representing the 'arg_idx'.
  10700. if (Attr->getArgumentIdx() >= ExprArgs.size()) {
  10701. // Add 1 to display the user's specified value.
  10702. Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
  10703. << 1 << Attr->getArgumentIdx() + 1;
  10704. return;
  10705. }
  10706. const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
  10707. if (IsPointerAttr) {
  10708. // Skip implicit cast of pointer to `void *' (as a function argument).
  10709. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  10710. if (ICE->getType()->isVoidPointerType() &&
  10711. ICE->getCastKind() == CK_BitCast)
  10712. ArgumentExpr = ICE->getSubExpr();
  10713. }
  10714. QualType ArgumentType = ArgumentExpr->getType();
  10715. // Passing a `void*' pointer shouldn't trigger a warning.
  10716. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  10717. return;
  10718. if (TypeInfo.MustBeNull) {
  10719. // Type tag with matching void type requires a null pointer.
  10720. if (!ArgumentExpr->isNullPointerConstant(Context,
  10721. Expr::NPC_ValueDependentIsNotNull)) {
  10722. Diag(ArgumentExpr->getExprLoc(),
  10723. diag::warn_type_safety_null_pointer_required)
  10724. << ArgumentKind->getName()
  10725. << ArgumentExpr->getSourceRange()
  10726. << TypeTagExpr->getSourceRange();
  10727. }
  10728. return;
  10729. }
  10730. QualType RequiredType = TypeInfo.Type;
  10731. if (IsPointerAttr)
  10732. RequiredType = Context.getPointerType(RequiredType);
  10733. bool mismatch = false;
  10734. if (!TypeInfo.LayoutCompatible) {
  10735. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  10736. // C++11 [basic.fundamental] p1:
  10737. // Plain char, signed char, and unsigned char are three distinct types.
  10738. //
  10739. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  10740. // char' depending on the current char signedness mode.
  10741. if (mismatch)
  10742. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  10743. RequiredType->getPointeeType())) ||
  10744. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  10745. mismatch = false;
  10746. } else
  10747. if (IsPointerAttr)
  10748. mismatch = !isLayoutCompatible(Context,
  10749. ArgumentType->getPointeeType(),
  10750. RequiredType->getPointeeType());
  10751. else
  10752. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  10753. if (mismatch)
  10754. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  10755. << ArgumentType << ArgumentKind
  10756. << TypeInfo.LayoutCompatible << RequiredType
  10757. << ArgumentExpr->getSourceRange()
  10758. << TypeTagExpr->getSourceRange();
  10759. }
  10760. void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
  10761. CharUnits Alignment) {
  10762. MisalignedMembers.emplace_back(E, RD, MD, Alignment);
  10763. }
  10764. void Sema::DiagnoseMisalignedMembers() {
  10765. for (MisalignedMember &m : MisalignedMembers) {
  10766. const NamedDecl *ND = m.RD;
  10767. if (ND->getName().empty()) {
  10768. if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
  10769. ND = TD;
  10770. }
  10771. Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
  10772. << m.MD << ND << m.E->getSourceRange();
  10773. }
  10774. MisalignedMembers.clear();
  10775. }
  10776. void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
  10777. E = E->IgnoreParens();
  10778. if (!T->isPointerType() && !T->isIntegerType())
  10779. return;
  10780. if (isa<UnaryOperator>(E) &&
  10781. cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
  10782. auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  10783. if (isa<MemberExpr>(Op)) {
  10784. auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
  10785. MisalignedMember(Op));
  10786. if (MA != MisalignedMembers.end() &&
  10787. (T->isIntegerType() ||
  10788. (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
  10789. Context.getTypeAlignInChars(
  10790. T->getPointeeType()) <= MA->Alignment))))
  10791. MisalignedMembers.erase(MA);
  10792. }
  10793. }
  10794. }
  10795. void Sema::RefersToMemberWithReducedAlignment(
  10796. Expr *E,
  10797. llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
  10798. Action) {
  10799. const auto *ME = dyn_cast<MemberExpr>(E);
  10800. if (!ME)
  10801. return;
  10802. // No need to check expressions with an __unaligned-qualified type.
  10803. if (E->getType().getQualifiers().hasUnaligned())
  10804. return;
  10805. // For a chain of MemberExpr like "a.b.c.d" this list
  10806. // will keep FieldDecl's like [d, c, b].
  10807. SmallVector<FieldDecl *, 4> ReverseMemberChain;
  10808. const MemberExpr *TopME = nullptr;
  10809. bool AnyIsPacked = false;
  10810. do {
  10811. QualType BaseType = ME->getBase()->getType();
  10812. if (ME->isArrow())
  10813. BaseType = BaseType->getPointeeType();
  10814. RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
  10815. if (RD->isInvalidDecl())
  10816. return;
  10817. ValueDecl *MD = ME->getMemberDecl();
  10818. auto *FD = dyn_cast<FieldDecl>(MD);
  10819. // We do not care about non-data members.
  10820. if (!FD || FD->isInvalidDecl())
  10821. return;
  10822. AnyIsPacked =
  10823. AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
  10824. ReverseMemberChain.push_back(FD);
  10825. TopME = ME;
  10826. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
  10827. } while (ME);
  10828. assert(TopME && "We did not compute a topmost MemberExpr!");
  10829. // Not the scope of this diagnostic.
  10830. if (!AnyIsPacked)
  10831. return;
  10832. const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
  10833. const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
  10834. // TODO: The innermost base of the member expression may be too complicated.
  10835. // For now, just disregard these cases. This is left for future
  10836. // improvement.
  10837. if (!DRE && !isa<CXXThisExpr>(TopBase))
  10838. return;
  10839. // Alignment expected by the whole expression.
  10840. CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
  10841. // No need to do anything else with this case.
  10842. if (ExpectedAlignment.isOne())
  10843. return;
  10844. // Synthesize offset of the whole access.
  10845. CharUnits Offset;
  10846. for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
  10847. I++) {
  10848. Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
  10849. }
  10850. // Compute the CompleteObjectAlignment as the alignment of the whole chain.
  10851. CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
  10852. ReverseMemberChain.back()->getParent()->getTypeForDecl());
  10853. // The base expression of the innermost MemberExpr may give
  10854. // stronger guarantees than the class containing the member.
  10855. if (DRE && !TopME->isArrow()) {
  10856. const ValueDecl *VD = DRE->getDecl();
  10857. if (!VD->getType()->isReferenceType())
  10858. CompleteObjectAlignment =
  10859. std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
  10860. }
  10861. // Check if the synthesized offset fulfills the alignment.
  10862. if (Offset % ExpectedAlignment != 0 ||
  10863. // It may fulfill the offset it but the effective alignment may still be
  10864. // lower than the expected expression alignment.
  10865. CompleteObjectAlignment < ExpectedAlignment) {
  10866. // If this happens, we want to determine a sensible culprit of this.
  10867. // Intuitively, watching the chain of member expressions from right to
  10868. // left, we start with the required alignment (as required by the field
  10869. // type) but some packed attribute in that chain has reduced the alignment.
  10870. // It may happen that another packed structure increases it again. But if
  10871. // we are here such increase has not been enough. So pointing the first
  10872. // FieldDecl that either is packed or else its RecordDecl is,
  10873. // seems reasonable.
  10874. FieldDecl *FD = nullptr;
  10875. CharUnits Alignment;
  10876. for (FieldDecl *FDI : ReverseMemberChain) {
  10877. if (FDI->hasAttr<PackedAttr>() ||
  10878. FDI->getParent()->hasAttr<PackedAttr>()) {
  10879. FD = FDI;
  10880. Alignment = std::min(
  10881. Context.getTypeAlignInChars(FD->getType()),
  10882. Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
  10883. break;
  10884. }
  10885. }
  10886. assert(FD && "We did not find a packed FieldDecl!");
  10887. Action(E, FD->getParent(), FD, Alignment);
  10888. }
  10889. }
  10890. void Sema::CheckAddressOfPackedMember(Expr *rhs) {
  10891. using namespace std::placeholders;
  10892. RefersToMemberWithReducedAlignment(
  10893. rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
  10894. _2, _3, _4));
  10895. }